Lightweight 0.20250904.0
Loading...
Searching...
No Matches
SqlConnectInfo.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include "Api.hpp"
6
7#include <chrono>
8#include <format>
9#include <map>
10#include <string>
11#include <variant>
12
13namespace Lightweight
14{
15
16/// Represents an ODBC connection string.
18{
19 std::string value;
20
21 LIGHTWEIGHT_API auto operator<=>(SqlConnectionString const&) const noexcept = default;
22
23 [[nodiscard]] LIGHTWEIGHT_API std::string Sanitized() const;
24
25 LIGHTWEIGHT_API static std::string SanitizePwd(std::string_view input);
26};
27
28using SqlConnectionStringMap = std::map<std::string, std::string>;
29
30/// Parses an ODBC connection string into a map.
31LIGHTWEIGHT_API SqlConnectionStringMap ParseConnectionString(SqlConnectionString const& connectionString);
32
33/// Builds an ODBC connection string from a map.
34LIGHTWEIGHT_API SqlConnectionString BuildConnectionString(SqlConnectionStringMap const& map);
35
36/// Represents a connection data source as a DSN, username, password, and timeout.
37struct [[nodiscard]] SqlConnectionDataSource
38{
39 std::string datasource;
40 std::string username;
41 std::string password;
42 std::chrono::seconds timeout { 5 };
43
44 LIGHTWEIGHT_API static SqlConnectionDataSource FromConnectionString(SqlConnectionString const& value);
45
46 [[nodiscard]] SqlConnectionString ToConnectionString() const
47 {
48 return SqlConnectionString {
49 .value = std::format("DSN={};UID={};PWD={};TIMEOUT={}", datasource, username, password, timeout.count())
50 };
51 }
52
53 LIGHTWEIGHT_API auto operator<=>(SqlConnectionDataSource const&) const noexcept = default;
54};
55
56using SqlConnectInfo = std::variant<SqlConnectionDataSource, SqlConnectionString>;
57
58} // namespace Lightweight
59
60template <>
61struct std::formatter<Lightweight::SqlConnectInfo>: std::formatter<std::string>
62{
63 auto format(Lightweight::SqlConnectInfo const& info, format_context& ctx) const -> format_context::iterator
64 {
65 if (auto const* dsn = std::get_if<Lightweight::SqlConnectionDataSource>(&info))
66 {
67 return formatter<string>::format(
68 std::format(
69 "DSN={};UID={};PWD={};TIMEOUT={}", dsn->datasource, dsn->username, dsn->password, dsn->timeout.count()),
70 ctx);
71 }
72 else if (auto const* connectionString = std::get_if<Lightweight::SqlConnectionString>(&info))
73 {
74 return formatter<string>::format(connectionString->value, ctx);
75 }
76 else
77 {
78 return formatter<string>::format("Invalid connection info", ctx);
79 }
80 }
81};
Represents a connection data source as a DSN, username, password, and timeout.
Represents an ODBC connection string.