userver: userver/ydb/builder.hpp Source File
Loading...
Searching...
No Matches
builder.hpp
1#pragma once
2
3#include <ydb-cpp-sdk/client/params/params.h>
4
5#include <string>
6#include <type_traits>
7#include <utility>
8
9#include <userver/ydb/impl/cast.hpp>
10#include <userver/ydb/io/traits.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace ydb {
15
16class TableClient;
17class Transaction;
18
19class PreparedArgsBuilder final {
20 public:
21 PreparedArgsBuilder(PreparedArgsBuilder&&) noexcept = default;
22 PreparedArgsBuilder& operator=(PreparedArgsBuilder&&) = delete;
23
24 /// Supported types and required includes are documented in:
25 /// <userver/ydb/io/supported_types.hpp>
26 template <typename T>
27 void Add(const std::string& name, T&& value);
28
29 /// @cond
30 // For internal use only.
31 explicit PreparedArgsBuilder(NYdb::TParamsBuilder&& builder)
32 : builder_(std::move(builder)) {}
33
34 // For internal use only.
35 template <typename... NamesValues>
36 void AddParams(NamesValues&&... names_values);
37 /// @endcond
38
39 private:
40 friend class Transaction;
41 friend class TableClient;
42 struct PreparedArgsWithKey;
43
44 NYdb::TParams Build() && { return std::move(builder_).Build(); }
45
46 PreparedArgsWithKey operator<<(const std::string& key);
47
48 NYdb::TParamsBuilder builder_;
49};
50
51template <typename T>
52void PreparedArgsBuilder::Add(const std::string& name, T&& value) {
53 auto& param_builder = builder_.AddParam(impl::ToString(name));
54 Write(param_builder, std::forward<T>(value));
55 param_builder.Build();
56}
57
58template <typename... NamesValues>
59void PreparedArgsBuilder::AddParams(NamesValues&&... names_values) {
60 [[maybe_unused]] decltype(auto) result =
61 (*this << ... << std::forward<NamesValues>(names_values));
62 static_assert(std::is_same_v<decltype(result), PreparedArgsBuilder&>);
63}
64
65struct PreparedArgsBuilder::PreparedArgsWithKey final {
66 PreparedArgsBuilder& builder;
67 const std::string& key;
68
69 template <typename T>
70 PreparedArgsBuilder& operator<<(T&& value) const {
71 builder.Add(key, std::forward<T>(value));
72 return builder;
73 }
74};
75
76inline auto PreparedArgsBuilder::operator<<(const std::string& key)
77 -> PreparedArgsWithKey {
78 return PreparedArgsWithKey{*this, key};
79}
80
81} // namespace ydb
82
83USERVER_NAMESPACE_END