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 Oid GetTypeOid() const;
247 const io::TypeBufferCategory& GetTypeBufferCategories() const;
248
249 template <typename T>
250 size_type ReadNullable(const io::FieldBuffer& fb, T&& val, std::true_type) const {
251 using ValueType = typename std::decay<T>::type;
252 using NullSetter = io::traits::GetSetNull<ValueType>;
253 if (fb.is_null) {
254 NullSetter::SetNull(val);
255 } else {
256 Read(fb, std::forward<T>(val));
257 }
258 return fb.length;
259 }
260
261 template <typename T>
262 size_type ReadNullable(const io::FieldBuffer& buffer, T&& val, std::false_type) const {
263 if (buffer.is_null) {
264 throw FieldValueIsNull{field_index_, Name(), val};
265 } else {
266 Read(buffer, std::forward<T>(val));
267 }
268 return buffer.length;
269 }
270
271 template <typename T>
272 void Read(const io::FieldBuffer& buffer, T&& val) const {
273 using ValueType = typename std::decay<T>::type;
274 io::traits::CheckParser<ValueType>();
275 try {
276 io::ReadBuffer(buffer, std::forward<T>(val), GetTypeBufferCategories());
277 } catch (InvalidInputBufferSize& ex) {
278 // InvalidInputBufferSize is not descriptive. Enriching with OID information and C++ types info
279 ex.AddMsgPrefix(fmt::format(
280 "Error while reading field #{0} '{1}' which database type {2} as a C++ type '{3}'. Refer to "
281 "the 'Supported data types' in the documentation to make sure that the database type is actually "
282 "representable as a C++ type '{3}'. Error details: ",
283 field_index_,
284 Name(),
285 impl::OidPrettyPrint(GetTypeOid()),
286 compiler::GetTypeName<T>()
287 ));
288 UASSERT_MSG(false, ex.what());
289 throw;
290 } catch (ResultSetError& ex) {
291 ex.AddMsgSuffix(fmt::format(" (ResultSet error while reading field #{} name `{}`)", field_index_, Name()));
292 throw;
293 }
294 }
295
296 const detail::ResultWrapper& res_;
297 const size_type row_index_;
298 const size_type field_index_;
299};
300
301/// @brief Accessor to a single field in a result set's row
302class Field {
303public:
304 using size_type = std::size_t;
305
306 size_type RowIndex() const { return row_index_; }
307 size_type FieldIndex() const { return field_index_; }
308
309 //@{
310 /** @name Field metadata */
311 /// Field name as named in query
313 FieldDescription Description() const;
314
315 Oid GetTypeOid() const;
316 //@}
317
318 //@{
319 /** @name Data access */
320 bool IsNull() const;
321
322 /// Read the field's buffer into user-provided variable.
323 /// @throws FieldValueIsNull If the field is null and the C++ type is
324 /// not nullable.
325 template <typename T>
326 size_type To(T&& val) const {
327 return FieldView{*res_, row_index_, field_index_}.To(std::forward<T>(val));
328 }
329
330 /// Read the field's buffer into user-provided variable.
331 /// If the field is null, set the variable to the default value.
332 template <typename T>
333 void Coalesce(T& val, const T& default_val) const {
334 if (!IsNull())
335 To(val);
336 else
337 val = default_val;
338 }
339
340 /// Convert the field's buffer into a C++ type.
341 /// @throws FieldValueIsNull If the field is null and the C++ type is
342 /// not nullable.
343 template <typename T>
344 typename std::decay<T>::type As() const {
345 T val{};
346 To(val);
347 return val;
348 }
349
350 /// Convert the field's buffer into a C++ type.
351 /// If the field is null, return default value.
352 template <typename T>
353 typename std::decay<T>::type Coalesce(const T& default_val) const {
354 if (IsNull()) return default_val;
355 return As<T>();
356 }
357 //@}
358 const io::TypeBufferCategory& GetTypeBufferCategories() const;
359
360protected:
361 friend class Row;
362
363 Field() = default;
364
365 Field(detail::ResultWrapperPtr res, size_type row, size_type col)
366 : res_{std::move(res)}, row_index_{row}, field_index_{col} {}
367
368 //@{
369 /** @name Iteration support */
370 bool IsValid() const;
371 int Compare(const Field& rhs) const;
372 std::ptrdiff_t Distance(const Field& rhs) const;
373 Field& Advance(std::ptrdiff_t);
374 //@}
375
376private:
377 detail::ResultWrapperPtr res_;
378 size_type row_index_{0};
379 size_type field_index_{0};
380};
381
382/// @brief Iterator over fields in a result set's row
385public:
386 ConstFieldIterator() = default;
387
388private:
389 friend class Row;
390
391 ConstFieldIterator(detail::ResultWrapperPtr res, size_type row, size_type col)
392 : ConstDataIterator(std::move(res), row, col) {}
393};
394
395/// @brief Reverse iterator over fields in a result set's row
398public:
399 ReverseConstFieldIterator() = default;
400
401private:
402 friend class Row;
403
404 ReverseConstFieldIterator(detail::ResultWrapperPtr res, size_type row, size_type col)
405 : ConstDataIterator(std::move(res), row, col) {}
406};
407
408/// Data row in a result set
409/// This class is a mere accessor to underlying result set data buffer,
410/// must not be used outside of result set life scope.
411///
412/// Mimics field container
413class Row {
414public:
415 //@{
416 /** @name Field container concept */
417 using size_type = std::size_t;
418 using const_iterator = ConstFieldIterator;
419 using const_reverse_iterator = ReverseConstFieldIterator;
420
421 using value_type = Field;
422 using reference = Field;
423 using pointer = const_iterator;
424 //@}
425
426 size_type RowIndex() const { return row_index_; }
427
428 RowDescription GetDescription() const { return {res_}; }
429 //@{
430 /** @name Field container interface */
431 /// Number of fields
432 size_type Size() const;
433
434 //@{
435 /** @name Forward iteration */
436 const_iterator cbegin() const;
437 const_iterator begin() const { return cbegin(); }
438 const_iterator cend() const;
439 const_iterator end() const { return cend(); }
440 //@}
441 //@{
442 /** @name Reverse iteration */
443 const_reverse_iterator crbegin() const;
444 const_reverse_iterator rbegin() const { return crbegin(); }
445 const_reverse_iterator crend() const;
446 const_reverse_iterator rend() const { return crend(); }
447 //@}
448
449 /// @brief Field access by index
450 /// @throws FieldIndexOutOfBounds if index is out of bounds
451 reference operator[](size_type index) const;
452 /// @brief Field access field by name
453 /// @throws FieldNameDoesntExist if the result set doesn't contain
454 /// such a field
455 reference operator[](const std::string& name) const;
456 //@}
457
458 //@{
459 /** @name Access to row's data */
460 /// Read the contents of the row to a user's row type or read the first
461 /// column into the value.
462 ///
463 /// If the user tries to read the first column into a variable, it must be the
464 /// only column in the result set. If the result set contains more than one
465 /// column, the function will throw NonSingleColumnResultSet. If the result
466 /// set is OK to contain more than one columns, the first column value should
467 /// be accessed via `row[0].To/As`.
468 ///
469 /// If the type is a 'row' type, the function will read the fields of the row
470 /// into the type's data members.
471 ///
472 /// If the type can be treated as both a row type and a composite type (the
473 /// type is mapped to a PostgreSQL type), the function will treat the type
474 /// as a type for the first (and the only) column.
475 ///
476 /// To read the all fields of the row as a row type, the To(T&&, RowTag)
477 /// should be used.
478 template <typename T>
479 void To(T&& val) const;
480
481 /// Function to disambiguate reading the row to a user's row type (values
482 /// of the row initialize user's type data members)
483 template <typename T>
484 void To(T&& val, RowTag) const;
485
486 /// Function to disambiguate reading the first column to a user's composite
487 /// type (PostgreSQL composite type in the row initializes user's type).
488 /// The same as calling To(T&& val) for a T mapped to a PostgreSQL type.
489 template <typename T>
490 void To(T&& val, FieldTag) const;
491
492 /// Read fields into variables in order of their appearance in the row
493 template <typename... T>
494 void To(T&&... val) const;
495
496 /// @brief Parse values from the row and return the result.
497 ///
498 /// If there are more than one type arguments to the function, it will
499 /// return a tuple of those types.
500 ///
501 /// If there is a single type argument to the function, it will read the first
502 /// and the only column of the row or the whole row to the row type (depending
503 /// on C++ to PosgreSQL mapping presence) and return plain value of this type.
504 ///
505 /// @see To(T&&)
506 template <typename T, typename... Y>
507 auto As() const;
508
509 /// @brief Returns T initialized with values of the row.
510 /// @snippet storages/postgres/tests/typed_rows_pgtest.cpp RowTagSippet
511 template <typename T>
512 T As(RowTag) const {
513 T val{};
514 To(val, kRowTag);
515 return val;
516 }
517
518 /// @brief Returns T initialized with a single column value of the row.
519 /// @snippet storages/postgres/tests/composite_types_pgtest.cpp FieldTagSippet
520 template <typename T>
521 T As(FieldTag) const {
522 T val{};
523 To(val, kFieldTag);
524 return val;
525 }
526
527 /// Read fields into variables in order of their names in the first argument
528 template <typename... T>
529 void To(const std::initializer_list<std::string>& names, T&&... val) const;
530 template <typename... T>
531 std::tuple<T...> As(const std::initializer_list<std::string>& names) const;
532
533 /// Read fields into variables in order of their indexes in the first
534 /// argument
535 template <typename... T>
536 void To(const std::initializer_list<size_type>& indexes, T&&... val) const;
537 template <typename... T>
538 std::tuple<T...> As(const std::initializer_list<size_type>& indexes) const;
539 //@}
540
541 size_type IndexOfName(const std::string&) const;
542
543 FieldView GetFieldView(size_type index) const;
544
545protected:
546 friend class ResultSet;
547
548 Row() = default;
549
550 Row(detail::ResultWrapperPtr res, size_type row) : res_{std::move(res)}, row_index_{row} {}
551
552 //@{
553 /** @name Iteration support */
554 bool IsValid() const;
555 int Compare(const Row& rhs) const;
556 std::ptrdiff_t Distance(const Row& rhs) const;
557 Row& Advance(std::ptrdiff_t);
558 //@}
559private:
560 detail::ResultWrapperPtr res_;
561 size_type row_index_{0};
562};
563
564/// @name Iterator over rows in a result set
566public:
567 ConstRowIterator() = default;
568
569private:
570 friend class ResultSet;
571
572 ConstRowIterator(detail::ResultWrapperPtr res, size_type row) : ConstDataIterator(std::move(res), row) {}
573};
574
575/// @name Reverse iterator over rows in a result set
578public:
579 ReverseConstRowIterator() = default;
580
581private:
582 friend class ResultSet;
583
584 ReverseConstRowIterator(detail::ResultWrapperPtr res, size_type row) : ConstDataIterator(std::move(res), row) {}
585};
586
587/// @brief PostgreSQL result set
588///
589/// Provides random access to rows via indexing operations
590/// and bidirectional iteration via iterators.
591///
592/// ## Usage synopsis
593/// ```
594/// auto trx = ...;
595/// auto res = trx.Execute("select a, b from table");
596/// for (auto row : res) {
597/// // Process row data
598/// }
599/// ```
601public:
602 using size_type = std::size_t;
603 using difference_type = std::ptrdiff_t;
604 static constexpr size_type npos = std::numeric_limits<size_type>::max();
605
606 //@{
607 /** @name Row container concept */
608 using const_iterator = ConstRowIterator;
609 using const_reverse_iterator = ReverseConstRowIterator;
610
611 using value_type = Row;
612 using reference = value_type;
613 using pointer = const_iterator;
614 //@}
615
616 explicit ResultSet(std::shared_ptr<detail::ResultWrapper> pimpl) : pimpl_{std::move(pimpl)} {}
617
618 /// Number of rows in the result set
619 size_type Size() const;
620 bool IsEmpty() const { return Size() == 0; }
621
622 size_type RowsAffected() const;
623 std::string CommandStatus() const;
624
625 //@{
626 /** @name Row container interface */
627 //@{
628 /** @name Forward iteration */
629 const_iterator cbegin() const&;
630 const_iterator begin() const& { return cbegin(); }
631 const_iterator cend() const&;
632 const_iterator end() const& { return cend(); }
633
634 // One should store ResultSet before using its accessors
635 const_iterator cbegin() const&& = delete;
636 const_iterator begin() const&& = delete;
637 const_iterator cend() const&& = delete;
638 const_iterator end() const&& = delete;
639 //@}
640 //@{
641 /** @name Reverse iteration */
642 const_reverse_iterator crbegin() const&;
643 const_reverse_iterator rbegin() const& { return crbegin(); }
644 const_reverse_iterator crend() const&;
645 const_reverse_iterator rend() const& { return crend(); }
646 // One should store ResultSet before using its accessors
647 const_reverse_iterator crbegin() const&& = delete;
648 const_reverse_iterator rbegin() const&& = delete;
649 const_reverse_iterator crend() const&& = delete;
650 const_reverse_iterator rend() const&& = delete;
651 //@}
652
653 reference Front() const&;
654 reference Back() const&;
655 // One should store ResultSet before using its accessors
656 reference Front() const&& = delete;
657 reference Back() const&& = delete;
658
659 /// @brief Access a row by index
660 /// @throws RowIndexOutOfBounds if index is out of bounds
661 reference operator[](size_type index) const&;
662 // One should store ResultSet before using its accessors
663 reference operator[](size_type index) const&& = delete;
664 //@}
665
666 //@{
667 /** @name ResultSet metadata access */
668 // TODO ResultSet metadata access interface
669 size_type FieldCount() const;
670 RowDescription GetRowDescription() const& { return {pimpl_}; }
671 // One should store ResultSet before using its accessors
672 RowDescription GetRowDescription() const&& = delete;
673 //@}
674
675 //@{
676 /** @name Typed results */
677 /// @brief Get a wrapper for iterating over a set of typed results.
678 /// For more information see @ref psql_typed_results
679 template <typename T>
680 auto AsSetOf() const;
681 template <typename T>
682 auto AsSetOf(RowTag) const;
683 template <typename T>
684 auto AsSetOf(FieldTag) const;
685
686 /// @brief Extract data into a container.
687 /// For more information see @ref psql_typed_results
688 template <typename Container>
689 Container AsContainer() const;
690 template <typename Container>
691 Container AsContainer(RowTag) const;
692
693 /// @brief Extract first row into user type.
694 /// A single row result set is expected, will throw an exception when result
695 /// set size != 1
696 template <typename T>
697 auto AsSingleRow() const;
698 template <typename T>
699 auto AsSingleRow(RowTag) const;
700 template <typename T>
701 auto AsSingleRow(FieldTag) const;
702
703 /// @brief Extract first row into user type.
704 /// @returns A single row result set if non empty result was returned, empty
705 /// std::optional otherwise
706 /// @throws exception when result set size > 1
707 template <typename T>
708 std::optional<T> AsOptionalSingleRow() const;
709 template <typename T>
710 std::optional<T> AsOptionalSingleRow(RowTag) const;
711 template <typename T>
712 std::optional<T> AsOptionalSingleRow(FieldTag) const;
713 //@}
714private:
715 friend class detail::ConnectionImpl;
716 void FillBufferCategories(const UserTypes& types);
717 void SetBufferCategoriesFrom(const ResultSet&);
718
719 template <typename T, typename Tag>
720 friend class TypedResultSet;
721 friend class ConnectionImpl;
722
723 std::shared_ptr<detail::ResultWrapper> pimpl_;
724};
725
726namespace detail {
727
728template <typename T>
729struct IsOptionalFromOptional : std::false_type {};
730
731template <typename T>
732struct IsOptionalFromOptional<std::optional<std::optional<T>>> : std::true_type {};
733
734template <typename T>
735struct IsOneVariant : std::false_type {};
736
737template <typename T>
738struct IsOneVariant<std::variant<T>> : std::true_type {};
739
740template <typename... Args>
741constexpr void AssertSaneTypeToDeserialize() {
742 static_assert(
743 !(IsOptionalFromOptional<std::remove_const_t<std::remove_reference_t<Args>>>::value || ...),
744 "Attempt to get an optional<optional<T>> was detected. Such "
745 "optional-from-optional types are very error prone, obfuscate code and "
746 "are ambiguous to deserialize. Change the type to just optional<T>"
747 );
748 static_assert(
749 !(IsOneVariant<std::remove_const_t<std::remove_reference_t<Args>>>::value || ...),
750 "Attempt to get an variant<T> was detected. Such variant from one type "
751 "obfuscates code. Change the type to just T"
752 );
753}
754
755//@{
756/** @name Sequental field extraction */
757template <typename IndexTuple, typename... T>
758struct RowDataExtractorBase;
759
760template <std::size_t... Indexes, typename... T>
761struct RowDataExtractorBase<std::index_sequence<Indexes...>, T...> {
762 static void ExtractValues(const Row& row, 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(std::forward<decltype(arg)>(arg)); };
767 (perform(std::forward<T>(val)), ...);
768 }
769 static void ExtractTuple(const Row& row, std::tuple<T...>& val) {
770 static_assert(sizeof...(Indexes) == sizeof...(T));
771
772 std::size_t field_index = 0;
773 const auto perform = [&](auto& arg) { row.GetFieldView(field_index++).To(arg); };
774 (perform(std::get<Indexes>(val)), ...);
775 }
776 static void ExtractTuple(const Row& row, std::tuple<T...>&& val) {
777 static_assert(sizeof...(Indexes) == sizeof...(T));
778
779 std::size_t field_index = 0;
780 const auto perform = [&](auto& arg) { row.GetFieldView(field_index++).To(arg); };
781 (perform(std::get<Indexes>(val)), ...);
782 }
783
784 static void ExtractValues(const Row& row, const std::initializer_list<std::string>& names, T&&... val) {
785 (row[*(names.begin() + Indexes)].To(std::forward<T>(val)), ...);
786 }
787 static void ExtractTuple(const Row& row, const std::initializer_list<std::string>& names, std::tuple<T...>& val) {
788 std::tuple<T...> tmp{row[*(names.begin() + Indexes)].template As<T>()...};
789 tmp.swap(val);
790 }
791
792 static void ExtractValues(const Row& row, const std::initializer_list<std::size_t>& indexes, T&&... val) {
793 (row[*(indexes.begin() + Indexes)].To(std::forward<T>(val)), ...);
794 }
795 static void ExtractTuple(const Row& row, const std::initializer_list<std::size_t>& indexes, std::tuple<T...>& val) {
796 std::tuple<T...> tmp{row[*(indexes.begin() + Indexes)].template As<T>()...};
797 tmp.swap(val);
798 }
799};
800
801template <typename... T>
802struct RowDataExtractor : RowDataExtractorBase<std::index_sequence_for<T...>, T...> {};
803
804template <typename T>
805struct TupleDataExtractor;
806template <typename... T>
807struct TupleDataExtractor<std::tuple<T...>> : RowDataExtractorBase<std::index_sequence_for<T...>, T...> {};
808//@}
809
810template <typename RowType>
811constexpr void AssertRowTypeIsMappedToPgOrIsCompositeType() {
812 // composite types can be parsed without an explicit mapping
813 static_assert(
814 io::traits::kIsMappedToPg<RowType> || io::traits::kIsCompositeType<RowType>,
815 "Row type must be mapped to pg type(CppToUserPg) or one of the "
816 "following: "
817 "1. primitive type. "
818 "2. std::tuple. "
819 "3. Aggregation type. See std::aggregation. "
820 "4. Has a Introspect method that makes the std::tuple from your "
821 "class/struct. "
822 "For more info see `uPg: Typed PostgreSQL results` chapter in docs."
823 );
824}
825
826} // namespace detail
827
828template <typename T>
829void Row::To(T&& val) const {
830 To(std::forward<T>(val), kFieldTag);
831}
832
833template <typename T>
834void Row::To(T&& val, RowTag) const {
835 detail::AssertSaneTypeToDeserialize<T>();
836 // Convert the val into a writable tuple and extract the data
837 using ValueType = std::decay_t<T>;
838 io::traits::AssertIsValidRowType<ValueType>();
839 using RowType = io::RowType<ValueType>;
840 using TupleType = typename RowType::TupleType;
841 constexpr auto tuple_size = RowType::size;
842 if (tuple_size > Size()) {
843 throw InvalidTupleSizeRequested(Size(), tuple_size);
844 } else if (tuple_size < Size()) {
845 LOG_LIMITED_WARNING() << "Row size is greater that the number of data members in "
846 "C++ user datatype "
847 << compiler::GetTypeName<T>();
848 }
849
850 detail::TupleDataExtractor<TupleType>::ExtractTuple(*this, RowType::GetTuple(std::forward<T>(val)));
851}
852
853template <typename T>
854void Row::To(T&& val, FieldTag) const {
855 detail::AssertSaneTypeToDeserialize<T>();
856 using ValueType = std::decay_t<T>;
857 detail::AssertRowTypeIsMappedToPgOrIsCompositeType<ValueType>();
858 // Read the first field into the type
859 if (Size() < 1) {
861 }
862 if (Size() > 1) {
863 throw NonSingleColumnResultSet{Size(), compiler::GetTypeName<T>(), "As"};
864 }
865 (*this)[0].To(std::forward<T>(val));
866}
867
868template <typename... T>
869void Row::To(T&&... val) const {
870 detail::AssertSaneTypeToDeserialize<T...>();
871 if (sizeof...(T) > Size()) {
872 throw InvalidTupleSizeRequested(Size(), sizeof...(T));
873 }
874 detail::RowDataExtractor<T...>::ExtractValues(*this, std::forward<T>(val)...);
875}
876
877template <typename T, typename... Y>
878auto Row::As() const {
879 if constexpr (sizeof...(Y) > 0) {
880 std::tuple<T, Y...> res;
881 To(res, kRowTag);
882 return res;
883 } else {
884 return As<T>(kFieldTag);
885 }
886}
887
888template <typename... T>
889void Row::To(const std::initializer_list<std::string>& names, T&&... val) const {
890 detail::AssertSaneTypeToDeserialize<T...>();
891 if (sizeof...(T) != names.size()) {
892 throw FieldTupleMismatch(names.size(), sizeof...(T));
893 }
894 detail::RowDataExtractor<T...>::ExtractValues(*this, names, std::forward<T>(val)...);
895}
896
897template <typename... T>
898std::tuple<T...> Row::As(const std::initializer_list<std::string>& names) const {
899 if (sizeof...(T) != names.size()) {
900 throw FieldTupleMismatch(names.size(), sizeof...(T));
901 }
902 std::tuple<T...> res;
903 detail::RowDataExtractor<T...>::ExtractTuple(*this, names, res);
904 return res;
905}
906
907template <typename... T>
908void Row::To(const std::initializer_list<size_type>& indexes, T&&... val) const {
909 detail::AssertSaneTypeToDeserialize<T...>();
910 if (sizeof...(T) != indexes.size()) {
911 throw FieldTupleMismatch(indexes.size(), sizeof...(T));
912 }
913 detail::RowDataExtractor<T...>::ExtractValues(*this, indexes, std::forward<T>(val)...);
914}
915
916template <typename... T>
917std::tuple<T...> Row::As(const std::initializer_list<size_type>& indexes) const {
918 if (sizeof...(T) != indexes.size()) {
919 throw FieldTupleMismatch(indexes.size(), sizeof...(T));
920 }
921 std::tuple<T...> res;
922 detail::RowDataExtractor<T...>::ExtractTuple(*this, indexes, res);
923 return res;
924}
925
926template <typename T>
927auto ResultSet::AsSetOf() const {
928 return AsSetOf<T>(kFieldTag);
929}
930
931template <typename T>
932auto ResultSet::AsSetOf(RowTag) const {
933 detail::AssertSaneTypeToDeserialize<T>();
934 using ValueType = std::decay_t<T>;
935 io::traits::AssertIsValidRowType<ValueType>();
936 return TypedResultSet<T, RowTag>{*this};
937}
938
939template <typename T>
940auto ResultSet::AsSetOf(FieldTag) const {
941 detail::AssertSaneTypeToDeserialize<T>();
942 using ValueType = std::decay_t<T>;
943 detail::AssertRowTypeIsMappedToPgOrIsCompositeType<ValueType>();
944 if (FieldCount() > 1) {
945 throw NonSingleColumnResultSet{FieldCount(), compiler::GetTypeName<T>(), "AsSetOf"};
946 }
947 return TypedResultSet<T, FieldTag>{*this};
948}
949
950template <typename Container>
951Container ResultSet::AsContainer() const {
952 detail::AssertSaneTypeToDeserialize<Container>();
953 using ValueType = typename Container::value_type;
954 Container c;
955 if constexpr (io::traits::kCanReserve<Container>) {
956 c.reserve(Size());
957 }
958 auto res = AsSetOf<ValueType>();
959
960 auto inserter = io::traits::Inserter(c);
961 auto row_it = res.begin();
962 for (std::size_t i = 0; i < res.Size(); ++i, ++row_it, ++inserter) {
963 *inserter = *row_it;
964 }
965
966 return c;
967}
968
969template <typename Container>
970Container ResultSet::AsContainer(RowTag) const {
971 detail::AssertSaneTypeToDeserialize<Container>();
972 using ValueType = typename Container::value_type;
973 Container c;
974 if constexpr (io::traits::kCanReserve<Container>) {
975 c.reserve(Size());
976 }
977 auto res = AsSetOf<ValueType>(kRowTag);
978
979 auto inserter = io::traits::Inserter(c);
980 auto row_it = res.begin();
981 for (std::size_t i = 0; i < res.Size(); ++i, ++row_it, ++inserter) {
982 *inserter = *row_it;
983 }
984
985 return c;
986}
987
988template <typename T>
989auto ResultSet::AsSingleRow() const {
990 return AsSingleRow<T>(kFieldTag);
991}
992
993template <typename T>
994auto ResultSet::AsSingleRow(RowTag) const {
995 detail::AssertSaneTypeToDeserialize<T>();
996 if (Size() != 1) {
998 }
999 return Front().As<T>(kRowTag);
1000}
1001
1002template <typename T>
1003auto ResultSet::AsSingleRow(FieldTag) const {
1004 detail::AssertSaneTypeToDeserialize<T>();
1005 if (Size() != 1) {
1007 }
1008 return Front().As<T>(kFieldTag);
1009}
1010
1011template <typename T>
1012std::optional<T> ResultSet::AsOptionalSingleRow() const {
1013 return AsOptionalSingleRow<T>(kFieldTag);
1014}
1015
1016template <typename T>
1017std::optional<T> ResultSet::AsOptionalSingleRow(RowTag) const {
1018 return IsEmpty() ? std::nullopt : std::optional<T>{AsSingleRow<T>(kRowTag)};
1019}
1020
1021template <typename T>
1022std::optional<T> ResultSet::AsOptionalSingleRow(FieldTag) const {
1023 return IsEmpty() ? std::nullopt : std::optional<T>{AsSingleRow<T>(kFieldTag)};
1024}
1025
1026} // namespace storages::postgres
1027
1028USERVER_NAMESPACE_END
1029
1030#include <userver/storages/postgres/typed_result_set.hpp>