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