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