userver: userver/storages/sqlite/cursor_result_set.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
cursor_result_set.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/sqlite/cursor_result_set.hpp
4
5#include <userver/storages/sqlite/result_set.hpp>
6
7USERVER_NAMESPACE_BEGIN
8
9namespace storages::sqlite {
10
11/// @brief A wrapper for read-only cursor.
12///
13/// You should always retrieve it from `storages::sqlite::Client` for correct
14/// behavior.
15template <typename T>
16class CursorResultSet final {
17public:
18 explicit CursorResultSet(ResultSet&& result_set, size_t batch_size);
19 ~CursorResultSet();
20
21 CursorResultSet(const CursorResultSet& other) = delete;
22 CursorResultSet(CursorResultSet&& other) noexcept;
23
24 /// @brief Fetches all the rows from cursor and for each new row executes
25 /// row_callback.
26 ///
27 /// Usable when the result set is expected to be big enough to put too
28 /// much memory pressure if fetched as a whole.
29 template <typename RowCallback>
30 void ForEach(RowCallback&& row_callback) &&;
31
32private:
33 ResultSet result_set_;
34 size_t batch_size_;
35};
36
37template <typename T>
38CursorResultSet<T>::CursorResultSet(ResultSet&& result_set, size_t batch_size)
39 : result_set_{std::move(result_set)}, batch_size_{batch_size} {}
40
41template <typename T>
42CursorResultSet<T>::CursorResultSet(CursorResultSet<T>&& other) noexcept = default;
43
44template <typename T>
45CursorResultSet<T>::~CursorResultSet() = default;
46
47template <typename T>
48template <typename RowCallback>
49void CursorResultSet<T>::ForEach(RowCallback&& row_callback) && {
50 using IntermediateStorage = std::vector<T>;
51
52 bool keep_going = true;
53 impl::TypedExtractor<T, RowTag> extractor{*result_set_.pimpl_};
54
55 while (keep_going) {
56 keep_going = result_set_.FetchResult(extractor, batch_size_);
57
58 IntermediateStorage data{extractor.ExtractData()};
59 for (auto&& row : data) {
60 row_callback(std::move(row));
61 }
62 }
63}
64
65} // namespace storages::sqlite
66
67USERVER_NAMESPACE_END