userver: userver/storages/mysql/tests/utils.hpp Source File
Loading...
Searching...
No Matches
utils.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/mysql/tests/utils.hpp
4/// @brief Utilities for testing logic working with MySQL.
5
6#include <userver/clients/dns/resolver.hpp>
7#include <userver/engine/deadline.hpp>
8#include <userver/utils/uuid4.hpp>
9
10#include <userver/storages/mysql.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace storages::mysql::tests {
15
16std::uint32_t GetMysqlPort();
17
18std::chrono::system_clock::time_point ToMariaDBPrecision(std::chrono::system_clock::time_point tp);
19
20class ClusterWrapper final {
21public:
22 ClusterWrapper();
23 ~ClusterWrapper();
24
25 storages::mysql::Cluster& operator*() const;
26 storages::mysql::Cluster* operator->() const;
27
28 engine::Deadline GetDeadline() const;
29
30 template <typename... Args>
31 StatementResultSet DefaultExecute(const std::string& query, const Args&... args) const;
32
33private:
34 clients::dns::Resolver resolver_;
35 std::shared_ptr<storages::mysql::Cluster> cluster_;
36
37 engine::Deadline deadline_;
38};
39
40template <typename... Args>
41StatementResultSet ClusterWrapper::DefaultExecute(const std::string& query, const Args&... args) const {
42 return cluster_->Execute(ClusterHostType::kPrimary, query, args...);
43}
44
45class TmpTable final {
46public:
47 explicit TmpTable(std::string_view definition);
48 TmpTable(ClusterWrapper& cluster, std::string_view definition);
49 ~TmpTable();
50
51 template <typename... Args>
52 std::string FormatWithTableName(std::string_view source, const Args&... args) const;
53
54 template <typename... Args>
55 StatementResultSet DefaultExecute(std::string_view source, const Args&... args);
56
57 ClusterWrapper& GetCluster() const;
58
59 Transaction Begin();
60
61 engine::Deadline GetDeadline() const;
62
63private:
64 static constexpr std::string_view kCreateTableQueryTemplate = "CREATE TABLE {} ({})";
65
66 void CreateTable(std::string_view definition);
67
68 std::optional<ClusterWrapper> owned_cluster_;
69 ClusterWrapper& cluster_;
70 std::string table_name_;
71};
72
73template <typename... Args>
74std::string TmpTable::FormatWithTableName(std::string_view source, const Args&... args) const {
75 return fmt::format(fmt::runtime(source), table_name_, args...);
76}
77
78template <typename... Args>
79StatementResultSet TmpTable::DefaultExecute(std::string_view source, const Args&... args) {
80 return cluster_.DefaultExecute(FormatWithTableName(source, table_name_), args...);
81}
82
83} // namespace storages::mysql::tests
84
85USERVER_NAMESPACE_END