userver: userver/storages/postgres/result_set.hpp Source File
Loading...
Searching...
No Matches
result_set.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/postgres/result_set.hpp
4/// @brief Result accessors
5
6#include <initializer_list>
7#include <limits>
8#include <memory>
9#include <optional>
10#include <tuple>
11#include <type_traits>
12#include <utility>
13#include <variant>
14
15#include <fmt/format.h>
16
17#include <userver/storages/postgres/exceptions.hpp>
18#include <userver/storages/postgres/io/supported_types.hpp>
19#include <userver/storages/postgres/postgres_fwd.hpp>
20
21#include <userver/storages/postgres/detail/const_data_iterator.hpp>
22
23#include <userver/compiler/demangle.hpp>
24#include <userver/logging/log.hpp>
25
26USERVER_NAMESPACE_BEGIN
27
28namespace storages::postgres {
29
30/// @page pg_process_results uPg: Working with result sets
31///
32/// A result set returned from Execute function is a thin read only wrapper
33/// around the libpq result. It can be copied around as it contains only a
34/// smart pointer to the underlying result set.
35///
36/// The result set's lifetime is not limited by the transaction in which it was
37/// created. In can be used after the transaction is committed or rolled back.
38///
39/// @par Iterating result set's rows
40///
41/// The ResultSet provides interface for range-based iteration over its rows.
42/// @code
43/// auto result = trx.Execute("select foo, bar from foobar");
44/// for (auto row : result) {
45/// // Process row data here
46/// }
47/// @endcode
48///
49/// Also rows can be accessed via indexing operators.
50/// @code
51/// auto result = trx.Execute("select foo, bar from foobar");
52/// for (auto idx = 0; idx < result.Size(); ++idx) {
53/// auto row = result[idx];
54/// // process row data here
55/// }
56/// @endcode
57///
58/// @par Accessing fields in a row
59///
60/// Fields in a row can be accessed by their index, by field name and can be
61/// iterated over. Invalid index or name will throw an exception.
62/// @code
63/// auto f1 = row[0];
64/// auto f2 = row["foo"];
65/// auto f3 = row[1];
66/// auto f4 = row["bar"];
67///
68/// for (auto f : row) {
69/// // Process field here
70/// }
71/// @endcode
72///
73/// @par Extracting field's data to variables
74///
75/// A Field object provides an interface to convert underlying buffer to a
76/// C++ variable of supported type. Please see @ref pg_types for more
77/// information on supported types.
78///
79/// Functions Field::As and Field::To can throw an exception if the field
80/// value is `null`. Their Field::Coalesce counterparts instead set the result
81/// to default value.
82///
83/// All data extraction functions can throw parsing errors (descendants of
84/// ResultSetError).
85///
86/// @code
87/// auto foo = row["foo"].As<int>();
88/// auto bar = row["bar"].As<std::string>();
89///
90/// foo = row["foo"].Coalesce(42);
91/// // There is no parser for char*, so a string object must be passed here.
92/// bar = row["bar"].Coalesce(std::string{"bar"});
93///
94/// row["foo"].To(foo);
95/// row["bar"].To(bar);
96///
97/// row["foo"].Coalesce(foo, 42);
98/// // The type is deduced by the first argument, so the second will be also
99/// // treated as std::string
100/// row["bar"].Coalesce(bar, "baz");
101/// @endcode
102///
103/// @par Extracting data directly from a Row object
104///
105/// Data can be extracted straight from a Row object to a pack or a tuple of
106/// user variables. The number of user variables cannot exceed the number of
107/// fields in the result. If it does, an exception will be thrown.
108///
109/// When used without additional parameters, the field values are extracted
110/// in the order of their appearance.
111///
112/// When a subset of the fields is needed, the fields can be specified by their
113/// indexes or names.
114///
115/// Row's data extraction functions throw exceptions as the field extraction
116/// functions. Also a FieldIndexOutOfBounds or FieldNameDoesntExist can be
117/// thrown.
118///
119/// Statements that return user-defined PostgreSQL type may be called as
120/// returning either one-column row with the whole type in it or as multi-column
121/// row with every column representing a field in the type. For the purpose of
122/// disambiguation, kRowTag may be used.
123///
124/// When a first column is extracted, it is expected that the result set
125/// contains the only column, otherwise an exception will be thrown.
126///
127/// @code
128/// auto [foo, bar] = row.As<int, std::string>();
129/// row.To(foo, bar);
130///
131/// auto [bar, foo] = row.As<std::string, int>({1, 0});
132/// row.To({1, 0}, bar, foo);
133///
134/// auto [bar, foo] = row.As<std::string, int>({"bar", "foo"});
135/// row.To({"bar", "foo"}, bar, foo);
136///
137/// // extract the whole row into a row-type structure.
138/// // The FooBar type must not have the C++ to PostgreSQL mapping in this case
139/// auto foobar = row.As<FooBar>();
140/// row.To(foobar);
141/// // If the FooBar type does have the mapping, the function call must be
142/// // disambiguated.
143/// foobar = row.As<FooBar>(kRowTag);
144/// row.To(foobar, kRowTag);
145/// @endcode
146///
147/// In the following example it is assumed that the row has a single column
148/// and the FooBar type is mapped to a PostgreSQL type.
149///
150/// @note The row is used to extract different types, it doesn't mean it will
151/// actually work with incompatible types.
152///
153/// @code
154/// auto foobar = row.As<FooBar>();
155/// row.To(foobar);
156///
157/// auto str = row.As<std::string>();
158/// auto i = row.As<int>();
159/// @endcode
160///
161///
162/// @par Converting a Row to a user row type
163///
164/// A row can be converted to a user type (tuple, structure, class), for more
165/// information on data type requirements see @ref pg_user_row_types
166///
167/// @todo Interface for converting rows to arbitrary user types
168///
169/// @par Converting ResultSet to a result set with user row types
170///
171/// A result set can be represented as a set of user row types or extracted to
172/// a container. For more information see @ref pg_user_row_types
173///
174/// @todo Interface for copying a ResultSet to an output iterator.
175///
176/// @par Non-select query results
177///
178/// @todo Process non-select result and provide interface. Do the docs.
179///
180///
181/// ----------
182///
183/// @htmlonly <div class="bottom-nav"> @endhtmlonly
184/// ⇦ @ref pg_run_queries | @ref pg_types ⇨
185/// @htmlonly </div> @endhtmlonly
186
188 /// Index of the field in the result set
189 std::size_t index;
190 /// @brief The object ID of the field's data type.
192 /// @brief The field name.
193 // TODO string_view
194 std::string name;
195 /// @brief If the field can be identified as a column of a specific table,
196 /// the object ID of the table; otherwise zero.
198 /// @brief If the field can be identified as a column of a specific table,
199 /// the attribute number of the column; otherwise zero.
201 /// @brief The data type size (see pg_type.typlen). Note that negative
202 /// values denote variable-width types.
203 Integer type_size;
204 /// @brief The type modifier (see pg_attribute.atttypmod). The meaning of
205 /// the modifier is type-specific.
207};
208
209/// @brief A wrapper for PGresult to access field descriptions.
211 public:
212 RowDescription(detail::ResultWrapperPtr res) : res_{std::move(res)} {}
213
214 /// Check that all fields can be read in binary format
215 /// @throw NoBinaryParser if any of the fields doesn't have a binary parser
216 void CheckBinaryFormat(const UserTypes& types) const;
217
218 // TODO interface for iterating field descriptions
219 private:
220 detail::ResultWrapperPtr res_;
221};
222
223class Row;
224class ResultSet;
225template <typename T, typename ExtractionTag>
226class TypedResultSet;
227
228class FieldView final {
229 public:
230 using size_type = std::size_t;
231
232 FieldView(const detail::ResultWrapper& res, size_type row_index,
233 size_type field_index)
234 : res_{res}, row_index_{row_index}, field_index_{field_index} {}
235
236 template <typename T>
237 size_type To(T&& val) const {
238 using ValueType = typename std::decay<T>::type;
239 auto fb = GetBuffer();
240 return ReadNullable(fb, std::forward<T>(val),
241 io::traits::IsNullable<ValueType>{});
242 }
243
244 private:
245 io::FieldBuffer GetBuffer() const;
246 std::string_view Name() const;
247 const io::TypeBufferCategory& GetTypeBufferCategories() const;
248
249 template <typename T>
250 size_type ReadNullable(const io::FieldBuffer& fb, T&& val,
251 std::true_type) const {
252 using ValueType = typename std::decay<T>::type;
253 using NullSetter = io::traits::GetSetNull<ValueType>;
254 if (fb.is_null) {
255 NullSetter::SetNull(val);
256 } else {
257 Read(fb, std::forward<T>(val));
258 }
259 return fb.length;
260 }
261
262 template <typename T>
263 size_type ReadNullable(const io::FieldBuffer& buffer, T&& val,
264 std::false_type) const {
265 if (buffer.is_null) {
266 throw FieldValueIsNull{field_index_, Name(), val};
267 } else {
268 Read(buffer, std::forward<T>(val));
269 }
270 return buffer.length;
271 }
272
273 template <typename T>
274 void Read(const io::FieldBuffer& buffer, T&& val) const {
275 using ValueType = typename std::decay<T>::type;
276 io::traits::CheckParser<ValueType>();
277 try {
278 io::ReadBuffer(buffer, std::forward<T>(val), GetTypeBufferCategories());
279 } catch (ResultSetError& ex) {
280 ex.AddMsgSuffix(
281 fmt::format(" (ResultSet error while reading field #{} name `{}`)",
282 field_index_, Name()));
283 throw;
284 }
285 }
286
287 const detail::ResultWrapper& res_;
288 const size_type row_index_;
289 const size_type field_index_;
290};
291
292/// @brief Accessor to a single field in a result set's row
293class Field {
294 public:
295 using size_type = std::size_t;
296
297 size_type RowIndex() const { return row_index_; }
298 size_type FieldIndex() const { return field_index_; }
299
300 //@{
301 /** @name Field metadata */
302 /// Field name as named in query
304 FieldDescription Description() const;
305
306 Oid GetTypeOid() const;
307 //@}
308
309 //@{
310 /** @name Data access */
311 bool IsNull() const;
312
313 /// Read the field's buffer into user-provided variable.
314 /// @throws FieldValueIsNull If the field is null and the C++ type is
315 /// not nullable.
316 template <typename T>
317 size_type To(T&& val) const {
318 return FieldView{*res_, row_index_, field_index_}.To(std::forward<T>(val));
319 }
320
321 /// Read the field's buffer into user-provided variable.
322 /// If the field is null, set the variable to the default value.
323 template <typename T>
324 void Coalesce(T& val, const T& default_val) const {
325 if (!IsNull())
326 To(val);
327 else
328 val = default_val;
329 }
330
331 /// Convert the field's buffer into a C++ type.
332 /// @throws FieldValueIsNull If the field is null and the C++ type is
333 /// not nullable.
334 template <typename T>
335 typename std::decay<T>::type As() const {
336 T val{};
337 To(val);
338 return val;
339 }
340
341 /// Convert the field's buffer into a C++ type.
342 /// If the field is null, return default value.
343 template <typename T>
344 typename std::decay<T>::type Coalesce(const T& default_val) const {
345 if (IsNull()) return default_val;
346 return As<T>();
347 }
348 //@}
349 const io::TypeBufferCategory& GetTypeBufferCategories() const;
350
351 protected:
352 friend class Row;
353
354 Field(detail::ResultWrapperPtr res, size_type row, size_type col)
355 : res_{std::move(res)}, row_index_{row}, field_index_{col} {}
356
357 //@{
358 /** @name Iteration support */
359 bool IsValid() const;
360 int Compare(const Field& rhs) const;
361 std::ptrdiff_t Distance(const Field& rhs) const;
362 Field& Advance(std::ptrdiff_t);
363 //@}
364
365 private:
366 detail::ResultWrapperPtr res_;
367 size_type row_index_;
368 size_type field_index_;
369};
370
371/// @brief Iterator over fields in a result set's row
375 friend class Row;
376
377 ConstFieldIterator(detail::ResultWrapperPtr res, size_type row, size_type col)
378 : ConstDataIterator(std::move(res), row, col) {}
379};
380
381/// @brief Reverse iterator over fields in a result set's row
385 friend class Row;
386
387 ReverseConstFieldIterator(detail::ResultWrapperPtr res, size_type row,
388 size_type col)
389 : ConstDataIterator(std::move(res), row, col) {}
390};
391
392/// Data row in a result set
393/// This class is a mere accessor to underlying result set data buffer,
394/// must not be used outside of result set life scope.
395///
396/// Mimics field container
397class Row {
398 public:
399 //@{
400 /** @name Field container concept */
401 using size_type = std::size_t;
402 using const_iterator = ConstFieldIterator;
403 using const_reverse_iterator = ReverseConstFieldIterator;
404
405 using value_type = Field;
406 using reference = Field;
407 using pointer = const_iterator;
408 //@}
409
410 size_type RowIndex() const { return row_index_; }
411
412 RowDescription GetDescription() const { return {res_}; }
413 //@{
414 /** @name Field container interface */
415 /// Number of fields
416 size_type Size() const;
417
418 //@{
419 /** @name Forward iteration */
420 const_iterator cbegin() const;
421 const_iterator begin() const { return cbegin(); }
422 const_iterator cend() const;
423 const_iterator end() const { return cend(); }
424 //@}
425 //@{
426 /** @name Reverse iteration */
427 const_reverse_iterator crbegin() const;
428 const_reverse_iterator rbegin() const { return crbegin(); }
429 const_reverse_iterator crend() const;
430 const_reverse_iterator rend() const { return crend(); }
431 //@}
432
433 /// @brief Field access by index
434 /// @throws FieldIndexOutOfBounds if index is out of bounds
435 reference operator[](size_type index) const;
436 /// @brief Field access field by name
437 /// @throws FieldNameDoesntExist if the result set doesn't contain
438 /// such a field
439 reference operator[](const std::string& name) const;
440 //@}
441
442 //@{
443 /** @name Access to row's data */
444 /// Read the contents of the row to a user's row type or read the first
445 /// column into the value.
446 ///
447 /// If the user tries to read the first column into a variable, it must be the
448 /// only column in the result set. If the result set contains more than one
449 /// column, the function will throw NonSingleColumnResultSet. If the result
450 /// set is OK to contain more than one columns, the first column value should
451 /// be accessed via `row[0].To/As`.
452 ///
453 /// If the type is a 'row' type, the function will read the fields of the row
454 /// into the type's data members.
455 ///
456 /// If the type can be treated as both a row type and a composite type (the
457 /// type is mapped to a PostgreSQL type), the function will treat the type
458 /// as a type for the first (and the only) column.
459 ///
460 /// To read the all fields of the row as a row type, the To(T&&, RowTag)
461 /// should be used.
462 template <typename T>
463 void To(T&& val) const;
464
465 /// Function to disambiguate reading the row to a user's row type (values
466 /// of the row initialize user's type data members)
467 template <typename T>
468 void To(T&& val, RowTag) const;
469
470 /// Function to disambiguate reading the first column to a user's composite
471 /// type (PostgreSQL composite type in the row initializes user's type).
472 /// The same as calling To(T&& val) for a T mapped to a PostgreSQL type.
473 template <typename T>
474 void To(T&& val, FieldTag) const;
475
476 /// Read fields into variables in order of their appearance in the row
477 template <typename... T>
478 void To(T&&... val) const;
479
480 /// @brief Parse values from the row and return the result.
481 ///
482 /// If there are more than one type arguments to the function, it will
483 /// return a tuple of those types.
484 ///
485 /// If there is a single type argument to the function, it will read the first
486 /// and the only column of the row or the whole row to the row type (depending
487 /// on C++ to PosgreSQL mapping presence) and return plain value of this type.
488 ///
489 /// @see To(T&&)
490 template <typename T, typename... Y>
491 auto As() const;
492
493 /// @brief Returns T initialized with values of the row.
494 /// @snippet storages/postgres/tests/typed_rows_pgtest.cpp RowTagSippet
495 template <typename T>
496 T As(RowTag) const {
497 T val{};
498 To(val, kRowTag);
499 return val;
500 }
501
502 /// @brief Returns T initialized with a single column value of the row.
503 /// @snippet storages/postgres/tests/composite_types_pgtest.cpp FieldTagSippet
504 template <typename T>
505 T As(FieldTag) const {
506 T val{};
507 To(val, kFieldTag);
508 return val;
509 }
510
511 /// Read fields into variables in order of their names in the first argument
512 template <typename... T>
513 void To(const std::initializer_list<std::string>& names, T&&... val) const;
514 template <typename... T>
515 std::tuple<T...> As(const std::initializer_list<std::string>& names) const;
516
517 /// Read fields into variables in order of their indexes in the first
518 /// argument
519 template <typename... T>
520 void To(const std::initializer_list<size_type>& indexes, T&&... val) const;
521 template <typename... T>
522 std::tuple<T...> As(const std::initializer_list<size_type>& indexes) const;
523 //@}
524
525 size_type IndexOfName(const std::string&) const;
526
527 FieldView GetFieldView(size_type index) const;
528
529 protected:
530 friend class ResultSet;
531
532 Row(detail::ResultWrapperPtr res, size_type row)
533 : res_{std::move(res)}, row_index_{row} {}
534
535 //@{
536 /** @name Iteration support */
537 bool IsValid() const;
538 int Compare(const Row& rhs) const;
539 std::ptrdiff_t Distance(const Row& rhs) const;
540 Row& Advance(std::ptrdiff_t);
541 //@}
542 private:
543 detail::ResultWrapperPtr res_;
544 size_type row_index_;
545};
546
547/// @name Iterator over rows in a result set
551 friend class ResultSet;
552
553 ConstRowIterator(detail::ResultWrapperPtr res, size_type row)
554 : ConstDataIterator(std::move(res), row) {}
555};
556
557/// @name Reverse iterator over rows in a result set
561 friend class ResultSet;
562
563 ReverseConstRowIterator(detail::ResultWrapperPtr res, size_type row)
564 : ConstDataIterator(std::move(res), row) {}
565};
566
567/// @brief PostgreSQL result set
568///
569/// Provides random access to rows via indexing operations
570/// and bidirectional iteration via iterators.
571///
572/// ## Usage synopsis
573/// ```
574/// auto trx = ...;
575/// auto res = trx.Execute("select a, b from table");
576/// for (auto row : res) {
577/// // Process row data
578/// }
579/// ```
581 public:
582 using size_type = std::size_t;
583 using difference_type = std::ptrdiff_t;
584 static constexpr size_type npos = std::numeric_limits<size_type>::max();
585
586 //@{
587 /** @name Row container concept */
588 using const_iterator = ConstRowIterator;
589 using const_reverse_iterator = ReverseConstRowIterator;
590
591 using value_type = Row;
592 using reference = value_type;
593 using pointer = const_iterator;
594 //@}
595
596 explicit ResultSet(std::shared_ptr<detail::ResultWrapper> pimpl)
597 : pimpl_{std::move(pimpl)} {}
598
599 /// Number of rows in the result set
600 size_type Size() const;
601 bool IsEmpty() const { return Size() == 0; }
602
603 size_type RowsAffected() const;
604 std::string CommandStatus() const;
605
606 //@{
607 /** @name Row container interface */
608 //@{
609 /** @name Forward iteration */
610 const_iterator cbegin() const&;
611 const_iterator begin() const& { return cbegin(); }
612 const_iterator cend() const&;
613 const_iterator end() const& { return cend(); }
614
615 // One should store ResultSet before using its accessors
616 const_iterator cbegin() const&& = delete;
617 const_iterator begin() const&& = delete;
618 const_iterator cend() const&& = delete;
619 const_iterator end() const&& = delete;
620 //@}
621 //@{
622 /** @name Reverse iteration */
623 const_reverse_iterator crbegin() const&;
624 const_reverse_iterator rbegin() const& { return crbegin(); }
625 const_reverse_iterator crend() const&;
626 const_reverse_iterator rend() const& { return crend(); }
627 // One should store ResultSet before using its accessors
628 const_reverse_iterator crbegin() const&& = delete;
629 const_reverse_iterator rbegin() const&& = delete;
630 const_reverse_iterator crend() const&& = delete;
631 const_reverse_iterator rend() const&& = delete;
632 //@}
633
634 reference Front() const&;
635 reference Back() const&;
636 // One should store ResultSet before using its accessors
637 reference Front() const&& = delete;
638 reference Back() const&& = delete;
639
640 /// @brief Access a row by index
641 /// @throws RowIndexOutOfBounds if index is out of bounds
642 reference operator[](size_type index) const&;
643 // One should store ResultSet before using its accessors
644 reference operator[](size_type index) const&& = delete;
645 //@}
646
647 //@{
648 /** @name ResultSet metadata access */
649 // TODO ResultSet metadata access interface
650 size_type FieldCount() const;
651 RowDescription GetRowDescription() const& { return {pimpl_}; }
652 // One should store ResultSet before using its accessors
653 RowDescription GetRowDescription() const&& = delete;
654 //@}
655
656 //@{
657 /** @name Typed results */
658 /// @brief Get a wrapper for iterating over a set of typed results.
659 /// For more information see @ref psql_typed_results
660 template <typename T>
661 auto AsSetOf() const;
662 template <typename T>
663 auto AsSetOf(RowTag) const;
664 template <typename T>
665 auto AsSetOf(FieldTag) const;
666
667 /// @brief Extract data into a container.
668 /// For more information see @ref psql_typed_results
669 template <typename Container>
670 Container AsContainer() const;
671 template <typename Container>
672 Container AsContainer(RowTag) const;
673
674 /// @brief Extract first row into user type.
675 /// A single row result set is expected, will throw an exception when result
676 /// set size != 1
677 template <typename T>
678 auto AsSingleRow() const;
679 template <typename T>
680 auto AsSingleRow(RowTag) const;
681 template <typename T>
682 auto AsSingleRow(FieldTag) const;
683
684 /// @brief Extract first row into user type.
685 /// @returns A single row result set if non empty result was returned, empty
686 /// std::optional otherwise
687 /// @throws exception when result set size > 1
688 template <typename T>
689 std::optional<T> AsOptionalSingleRow() const;
690 template <typename T>
691 std::optional<T> AsOptionalSingleRow(RowTag) const;
692 template <typename T>
693 std::optional<T> AsOptionalSingleRow(FieldTag) const;
694 //@}
695 private:
696 friend class detail::ConnectionImpl;
697 void FillBufferCategories(const UserTypes& types);
698 void SetBufferCategoriesFrom(const ResultSet&);
699
700 template <typename T, typename Tag>
701 friend class TypedResultSet;
702 friend class ConnectionImpl;
703
704 std::shared_ptr<detail::ResultWrapper> pimpl_;
705};
706
707namespace detail {
708
709template <typename T>
710struct IsOptionalFromOptional : std::false_type {};
711
712template <typename T>
713struct IsOptionalFromOptional<std::optional<std::optional<T>>>
714 : std::true_type {};
715
716template <typename T>
717struct IsOneVariant : std::false_type {};
718
719template <typename T>
720struct IsOneVariant<std::variant<T>> : std::true_type {};
721
722template <typename... Args>
723constexpr void AssertSaneTypeToDeserialize() {
724 static_assert(
725 !(IsOptionalFromOptional<
726 std::remove_const_t<std::remove_reference_t<Args>>>::value ||
727 ...),
728 "Attempt to get an optional<optional<T>> was detected. Such "
729 "optional-from-optional types are very error prone, obfuscate code and "
730 "are ambiguous to deserialize. Change the type to just optional<T>");
731 static_assert(
732 !(IsOneVariant<
733 std::remove_const_t<std::remove_reference_t<Args>>>::value ||
734 ...),
735 "Attempt to get an variant<T> was detected. Such variant from one type "
736 "obfuscates code. Change the type to just T");
737}
738
739//@{
740/** @name Sequental field extraction */
741template <typename IndexTuple, typename... T>
742struct RowDataExtractorBase;
743
744template <std::size_t... Indexes, typename... T>
745struct RowDataExtractorBase<std::index_sequence<Indexes...>, T...> {
746 static void ExtractValues(const Row& row, T&&... val) {
747 static_assert(sizeof...(Indexes) == sizeof...(T));
748
749 std::size_t field_index = 0;
750 const auto perform = [&](auto&& arg) {
751 row.GetFieldView(field_index++).To(std::forward<decltype(arg)>(arg));
752 };
753 (perform(std::forward<T>(val)), ...);
754 }
755 static void ExtractTuple(const Row& row, std::tuple<T...>& val) {
756 static_assert(sizeof...(Indexes) == sizeof...(T));
757
758 std::size_t field_index = 0;
759 const auto perform = [&](auto& arg) {
760 row.GetFieldView(field_index++).To(arg);
761 };
762 (perform(std::get<Indexes>(val)), ...);
763 }
764 static void ExtractTuple(const Row& row, std::tuple<T...>&& val) {
765 static_assert(sizeof...(Indexes) == sizeof...(T));
766
767 std::size_t field_index = 0;
768 const auto perform = [&](auto& arg) {
769 row.GetFieldView(field_index++).To(arg);
770 };
771 (perform(std::get<Indexes>(val)), ...);
772 }
773
774 static void ExtractValues(const Row& row,
775 const std::initializer_list<std::string>& names,
776 T&&... val) {
777 (row[*(names.begin() + Indexes)].To(std::forward<T>(val)), ...);
778 }
779 static void ExtractTuple(const Row& row,
780 const std::initializer_list<std::string>& names,
781 std::tuple<T...>& val) {
782 std::tuple<T...> tmp{row[*(names.begin() + Indexes)].template As<T>()...};
783 tmp.swap(val);
784 }
785
786 static void ExtractValues(const Row& row,
787 const std::initializer_list<std::size_t>& indexes,
788 T&&... val) {
789 (row[*(indexes.begin() + Indexes)].To(std::forward<T>(val)), ...);
790 }
791 static void ExtractTuple(const Row& row,
792 const std::initializer_list<std::size_t>& indexes,
793 std::tuple<T...>& val) {
794 std::tuple<T...> tmp{row[*(indexes.begin() + Indexes)].template As<T>()...};
795 tmp.swap(val);
796 }
797};
798
799template <typename... T>
800struct RowDataExtractor
801 : RowDataExtractorBase<std::index_sequence_for<T...>, T...> {};
802
803template <typename T>
804struct TupleDataExtractor;
805template <typename... T>
806struct TupleDataExtractor<std::tuple<T...>>
807 : RowDataExtractorBase<std::index_sequence_for<T...>, T...> {};
808//@}
809
810} // namespace detail
811
812template <typename T>
813void Row::To(T&& val) const {
814 To(std::forward<T>(val), kFieldTag);
815}
816
817template <typename T>
818void Row::To(T&& val, RowTag) const {
819 detail::AssertSaneTypeToDeserialize<T>();
820 // Convert the val into a writable tuple and extract the data
821 using ValueType = std::decay_t<T>;
822 static_assert(io::traits::kIsRowType<ValueType>,
823 "This type cannot be used as a row type");
824 using RowType = io::RowType<ValueType>;
825 using TupleType = typename RowType::TupleType;
826 constexpr auto tuple_size = RowType::size;
827 if (tuple_size > Size()) {
828 throw InvalidTupleSizeRequested(Size(), tuple_size);
829 } else if (tuple_size < Size()) {
831 << "Row size is greater that the number of data members in "
832 "C++ user datatype "
833 << compiler::GetTypeName<T>();
834 }
835
836 detail::TupleDataExtractor<TupleType>::ExtractTuple(
837 *this, RowType::GetTuple(std::forward<T>(val)));
838}
839
840template <typename T>
841void Row::To(T&& val, FieldTag) const {
842 detail::AssertSaneTypeToDeserialize<T>();
843 using ValueType = std::decay_t<T>;
844 // composite types can be parsed without an explicit mapping
845 static_assert(io::traits::kIsMappedToPg<ValueType> ||
846 io::traits::kIsCompositeType<ValueType>,
847 "This type is not mapped to a PostgreSQL type");
848 // Read the first field into the type
849 if (Size() < 1) {
851 }
852 if (Size() > 1) {
853 throw NonSingleColumnResultSet{Size(), compiler::GetTypeName<T>(), "As"};
854 }
855 (*this)[0].To(std::forward<T>(val));
856}
857
858template <typename... T>
859void Row::To(T&&... val) const {
860 detail::AssertSaneTypeToDeserialize<T...>();
861 if (sizeof...(T) > Size()) {
862 throw InvalidTupleSizeRequested(Size(), sizeof...(T));
863 }
864 detail::RowDataExtractor<T...>::ExtractValues(*this, std::forward<T>(val)...);
865}
866
867template <typename T, typename... Y>
868auto Row::As() const {
869 if constexpr (sizeof...(Y) > 0) {
870 std::tuple<T, Y...> res;
871 To(res, kRowTag);
872 return res;
873 } else {
874 return As<T>(kFieldTag);
875 }
876}
877
878template <typename... T>
879void Row::To(const std::initializer_list<std::string>& names,
880 T&&... val) const {
881 detail::AssertSaneTypeToDeserialize<T...>();
882 if (sizeof...(T) != names.size()) {
883 throw FieldTupleMismatch(names.size(), sizeof...(T));
884 }
885 detail::RowDataExtractor<T...>::ExtractValues(*this, names,
886 std::forward<T>(val)...);
887}
888
889template <typename... T>
890std::tuple<T...> Row::As(
891 const std::initializer_list<std::string>& names) const {
892 if (sizeof...(T) != names.size()) {
893 throw FieldTupleMismatch(names.size(), sizeof...(T));
894 }
895 std::tuple<T...> res;
896 detail::RowDataExtractor<T...>::ExtractTuple(*this, names, res);
897 return res;
898}
899
900template <typename... T>
901void Row::To(const std::initializer_list<size_type>& indexes,
902 T&&... val) const {
903 detail::AssertSaneTypeToDeserialize<T...>();
904 if (sizeof...(T) != indexes.size()) {
905 throw FieldTupleMismatch(indexes.size(), sizeof...(T));
906 }
907 detail::RowDataExtractor<T...>::ExtractValues(*this, indexes,
908 std::forward<T>(val)...);
909}
910
911template <typename... T>
912std::tuple<T...> Row::As(
913 const std::initializer_list<size_type>& indexes) const {
914 if (sizeof...(T) != indexes.size()) {
915 throw FieldTupleMismatch(indexes.size(), sizeof...(T));
916 }
917 std::tuple<T...> res;
918 detail::RowDataExtractor<T...>::ExtractTuple(*this, indexes, res);
919 return res;
920}
921
922template <typename T>
923auto ResultSet::AsSetOf() const {
924 return AsSetOf<T>(kFieldTag);
925}
926
927template <typename T>
928auto ResultSet::AsSetOf(RowTag) const {
929 detail::AssertSaneTypeToDeserialize<T>();
930 using ValueType = std::decay_t<T>;
931 static_assert(io::traits::kIsRowType<ValueType>,
932 "This type cannot be used as a row type");
933 return TypedResultSet<T, RowTag>{*this};
934}
935
936template <typename T>
937auto ResultSet::AsSetOf(FieldTag) const {
938 detail::AssertSaneTypeToDeserialize<T>();
939 using ValueType = std::decay_t<T>;
940 // composite types can be parsed without an explicit mapping
941 static_assert(io::traits::kIsMappedToPg<ValueType> ||
942 io::traits::kIsCompositeType<ValueType>,
943 "This type is not mapped to a PostgreSQL type");
944 if (FieldCount() > 1) {
945 throw NonSingleColumnResultSet{FieldCount(), compiler::GetTypeName<T>(),
946 "AsSetOf"};
947 }
948 return TypedResultSet<T, FieldTag>{*this};
949}
950
951template <typename Container>
952Container ResultSet::AsContainer() const {
953 detail::AssertSaneTypeToDeserialize<Container>();
954 using ValueType = typename Container::value_type;
955 Container c;
956 if constexpr (io::traits::kCanReserve<Container>) {
957 c.reserve(Size());
958 }
959 auto res = AsSetOf<ValueType>();
960
961 auto inserter = io::traits::Inserter(c);
962 auto row_it = res.begin();
963 for (std::size_t i = 0; i < res.Size(); ++i, ++row_it, ++inserter) {
964 *inserter = *row_it;
965 }
966
967 return c;
968}
969
970template <typename Container>
971Container ResultSet::AsContainer(RowTag) const {
972 detail::AssertSaneTypeToDeserialize<Container>();
973 using ValueType = typename Container::value_type;
974 Container c;
975 if constexpr (io::traits::kCanReserve<Container>) {
976 c.reserve(Size());
977 }
978 auto res = AsSetOf<ValueType>(kRowTag);
979
980 auto inserter = io::traits::Inserter(c);
981 auto row_it = res.begin();
982 for (std::size_t i = 0; i < res.Size(); ++i, ++row_it, ++inserter) {
983 *inserter = *row_it;
984 }
985
986 return c;
987}
988
989template <typename T>
990auto ResultSet::AsSingleRow() const {
991 return AsSingleRow<T>(kFieldTag);
992}
993
994template <typename T>
995auto ResultSet::AsSingleRow(RowTag) const {
996 detail::AssertSaneTypeToDeserialize<T>();
997 if (Size() != 1) {
999 }
1000 return Front().As<T>(kRowTag);
1001}
1002
1003template <typename T>
1004auto ResultSet::AsSingleRow(FieldTag) const {
1005 detail::AssertSaneTypeToDeserialize<T>();
1006 if (Size() != 1) {
1008 }
1009 return Front().As<T>(kFieldTag);
1010}
1011
1012template <typename T>
1013std::optional<T> ResultSet::AsOptionalSingleRow() const {
1014 return AsOptionalSingleRow<T>(kFieldTag);
1015}
1016
1017template <typename T>
1018std::optional<T> ResultSet::AsOptionalSingleRow(RowTag) const {
1019 return IsEmpty() ? std::nullopt : std::optional<T>{AsSingleRow<T>(kRowTag)};
1020}
1021
1022template <typename T>
1023std::optional<T> ResultSet::AsOptionalSingleRow(FieldTag) const {
1024 return IsEmpty() ? std::nullopt : std::optional<T>{AsSingleRow<T>(kFieldTag)};
1025}
1026
1027} // namespace storages::postgres
1028
1029USERVER_NAMESPACE_END
1030
1031#include <userver/storages/postgres/typed_result_set.hpp>