userver: userver/ydb/io/traits.hpp Source File
Loading...
Searching...
No Matches
traits.hpp
1#pragma once
2
3#include <string_view>
4#include <type_traits>
5
6namespace NYdb {
7class TType;
8class TValue;
9class TValueParser;
10class TValueBuilder;
11class TParamValueBuilder;
12
13template <typename Builder>
14class TValueBuilderBase;
15} // namespace NYdb
16
17USERVER_NAMESPACE_BEGIN
18
19namespace ydb {
20
21/// Used for error reporting in ydb::ValueTraits::Parse.
22struct ParseContext final {
23 std::string_view column_name;
24};
25
26template <typename T, typename Enable = void>
27struct ValueTraits {
28 /// Parses an element of type `T` from `parser`. `context` may be used
29 /// for diagnostic messages.
30 static T Parse([[maybe_unused]] NYdb::TValueParser& parser,
31 [[maybe_unused]] const ParseContext& context) {
32 static_assert(!sizeof(T),
33 "Cannot convert from YDB value. No ValueTraits defined for "
34 "this type. userver/ydb/io/supported_types.hpp "
35 "contains all known definitions");
36 return T{};
37 }
38
39 /// Writes an element of type `T` to `builder`.
40 template <typename Builder>
41 static void Write([[maybe_unused]] NYdb::TValueBuilderBase<Builder>& builder,
42 [[maybe_unused]] const T& value) {
43 static_assert(!sizeof(T),
44 "Cannot convert to YDB value. No ValueTraits defined for "
45 "this type. userver/ydb/io/supported_types.hpp "
46 "contains all known definitions");
47 }
48
49 /// Uses NYdb::TTypeBuilder to create a representation of `T` type.
50 static NYdb::TType MakeType() = delete;
51};
52
53/// A shorthand for calling ydb::ValueTraits<T>::Parse.
54template <typename T>
55inline constexpr auto Parse =
56 [](NYdb::TValueParser& parser, const ParseContext& context) -> T {
57 // Note: using a CPO instead of a global function to avoid ADL.
58 // Customization should be performed using ValueTraits.
59 return ValueTraits<T>::Parse(parser, context);
60};
61
62/// A shorthand for calling ydb::ValueTraits<T>::Write.
63inline constexpr auto Write = [](auto& builder, auto&& value) {
64 // Note: using a CPO instead of a global function to avoid ADL.
65 // Customization should be performed using ValueTraits.
66 using RawValueType =
67 std::remove_const_t<std::remove_reference_t<decltype(value)>>;
68 using ValueType =
69 std::conditional_t<std::is_convertible_v<RawValueType, std::string_view>,
70 std::string, RawValueType>;
71 ValueTraits<ValueType>::Write(builder, value);
72};
73
74} // namespace ydb
75
76USERVER_NAMESPACE_END