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