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, [[maybe_unused]] const ParseContext& context) {
31 static_assert(
32 !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 );
37 return T{};
38 }
39
40 /// Writes an element of type `T` to `builder`.
41 template <typename Builder>
42 static void Write([[maybe_unused]] NYdb::TValueBuilderBase<Builder>& builder, [[maybe_unused]] const T& value) {
43 static_assert(
44 !sizeof(T),
45 "Cannot convert to YDB value. No ValueTraits defined for "
46 "this type. userver/ydb/io/supported_types.hpp "
47 "contains all known definitions"
48 );
49 }
50
51 /// Uses NYdb::TTypeBuilder to create a representation of `T` type.
52 static NYdb::TType MakeType() = delete;
53};
54
55/// A shorthand for calling ydb::ValueTraits<T>::Parse.
56template <typename T>
57inline constexpr auto Parse = [](NYdb::TValueParser& parser, const ParseContext& context) -> T {
58 // Note: using a CPO instead of a global function to avoid ADL.
59 // Customization should be performed using ValueTraits.
60 return ValueTraits<T>::Parse(parser, context);
61};
62
63/// A shorthand for calling ydb::ValueTraits<T>::Write.
64inline constexpr auto Write = [](auto& builder, auto&& value) {
65 // Note: using a CPO instead of a global function to avoid ADL.
66 // Customization should be performed using ValueTraits.
67 using RawValueType = 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>, std::string, RawValueType>;
70 ValueTraits<ValueType>::Write(builder, value);
71};
72
73} // namespace ydb
74
75USERVER_NAMESPACE_END