Lightweight 0.20251104.0
Loading...
Searching...
No Matches
Utils.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#if defined(_WIN32) || defined(_WIN64)
6 #include <Windows.h>
7#endif
8
9#include <Lightweight/Lightweight.hpp>
10
11#include <catch2/catch_session.hpp>
12#include <catch2/catch_test_macros.hpp>
13
14#include <algorithm>
15#include <chrono>
16#include <format>
17#include <ostream>
18#include <ranges>
19#include <string>
20#include <string_view>
21#include <tuple>
22#include <variant>
23#include <vector>
24
25#if __has_include(<stacktrace>)
26 #include <stacktrace>
27#endif
28
29#include <sql.h>
30#include <sqlext.h>
31#include <sqlspi.h>
32#include <sqltypes.h>
33
34// NOTE: I've done this preprocessor stuff only to have a single test for UTF-16 (UCS-2) regardless of platform.
35using WideChar = std::conditional_t<sizeof(wchar_t) == 2, wchar_t, char16_t>;
36using WideString = std::basic_string<WideChar>;
37using WideStringView = std::basic_string_view<WideChar>;
38
39#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
40 /// @brief marco to define a member to the structure, in case of C++26 reflection this
41 /// will create reflection, in case of C++20 reflection this will create a member pointer
42 #define Member(x) ^^x
43
44#else
45 /// @brief marco to define a member to the structure, in case of C++26 reflection this
46 /// will create reflection, in case of C++20 reflection this will create a member pointer
47 #define Member(x) &x
48#endif
49
50#if !defined(_WIN32)
51 #define WTEXT(x) (u##x)
52#else
53 #define WTEXT(x) (L##x)
54#endif
55
56#define UNSUPPORTED_DATABASE(stmt, dbType) \
57 if ((stmt).Connection().ServerType() == (dbType)) \
58 { \
59 WARN(std::format("TODO({}): This database is currently unsupported on this test.", dbType)); \
60 return; \
61 }
62
63template <>
64struct std::formatter<std::u8string>: std::formatter<std::string>
65{
66 auto format(std::u8string const& value, std::format_context& ctx) const -> std::format_context::iterator
67 {
68 return std::formatter<std::string>::format(
69 std::format("{}", (char const*) value.c_str()), // NOLINT(readability-redundant-string-cstr)
70 ctx);
71 }
72};
73
74namespace std
75{
76
77// Add support for std::basic_string<WideChar> and std::basic_string_view<WideChar> to std::ostream,
78// so that we can get them pretty-printed in REQUIRE() and CHECK() macros.
79
80template <typename WideStringT>
81 requires(Lightweight::detail::OneOf<WideStringT,
82 std::wstring,
83 std::wstring_view,
84 std::u16string,
85 std::u16string_view,
86 std::u32string,
87 std::u32string_view>)
88ostream& operator<<(ostream& os, WideStringT const& str)
89{
90 auto constexpr BitsPerChar = sizeof(typename WideStringT::value_type) * 8;
91 auto const u8String = Lightweight::ToUtf8(str);
92 return os << "UTF-" << BitsPerChar << '{' << "length: " << str.size() << ", characters: " << '"'
93 << string_view((char const*) u8String.data(), u8String.size()) << '"' << '}';
94}
95
96inline ostream& operator<<(ostream& os, Lightweight::SqlGuid const& guid)
97{
98 return os << format("SqlGuid({})", guid);
99}
100
101} // namespace std
102
103namespace std
104{
105template <std::size_t Precision, std::size_t Scale>
106std::ostream& operator<<(std::ostream& os, Lightweight::SqlNumeric<Precision, Scale> const& value)
107{
108 return os << std::format("SqlNumeric<{}, {}>({}, {}, {}, {})",
109 Precision,
110 Scale,
111 value.sqlValue.sign,
112 value.sqlValue.precision,
113 value.sqlValue.scale,
114 value.ToUnscaledValue());
115}
116} // namespace std
117
118// Refer to an in-memory SQLite database (and assuming the sqliteodbc driver is installed)
119// See:
120// - https://www.sqlite.org/inmemorydb.html
121// - http://www.ch-werner.de/sqliteodbc/
122// - https://github.com/softace/sqliteodbc
123//
124
125// clang-format off
126auto inline const DefaultTestConnectionString = Lightweight::SqlConnectionString { //NOLINT(bugprone-throwing-static-initialization)
127 // clang-format on
128 .value = std::format("DRIVER={};Database={}",
129#if defined(_WIN32) || defined(_WIN64)
130 "SQLite3 ODBC Driver",
131#else
132 "SQLite3",
133#endif
134 "test.db"),
135};
136
137class TestSuiteSqlLogger: public Lightweight::SqlLogger::Null
138{
139 private:
140 std::string m_lastPreparedQuery;
141
142 template <typename... Args>
143 void WriteInfo(std::format_string<Args...> const& fmt, Args&&... args)
144 {
145 auto message = std::format(fmt, std::forward<Args>(args)...);
146 message = std::format("[{}] {}", "Lightweight", message);
147 try
148 {
149 UNSCOPED_INFO(message);
150 }
151 catch (...)
152 {
153 std::println("{}", message);
154 }
155 }
156
157 template <typename... Args>
158 void WriteWarning(std::format_string<Args...> const& fmt, Args&&... args)
159 {
160 WARN(std::format(fmt, std::forward<Args>(args)...));
161 }
162
163 public:
164 static TestSuiteSqlLogger& GetLogger() noexcept
165 {
166 static TestSuiteSqlLogger theLogger;
167 return theLogger;
168 }
169
170 void OnError(Lightweight::SqlError error, std::source_location sourceLocation) override
171 {
172 WriteWarning("SQL Error: {}", error);
173 WriteDetails(sourceLocation);
174 }
175
176 void OnError(Lightweight::SqlErrorInfo const& errorInfo, std::source_location sourceLocation) override
177 {
178 WriteWarning("SQL Error: {}", errorInfo);
179 WriteDetails(sourceLocation);
180 }
181
182 void OnWarning(std::string_view const& message) override
183 {
184 WriteWarning("{}", message);
185 WriteDetails(std::source_location::current());
186 }
187
188 void OnExecuteDirect(std::string_view const& query) override
189 {
190 WriteInfo("ExecuteDirect: {}", query);
191 }
192
193 void OnPrepare(std::string_view const& query) override
194 {
195 m_lastPreparedQuery = query;
196 }
197
198 void OnExecute(std::string_view const& query) override
199 {
200 WriteInfo("Execute: {}", query);
201 }
202
203 void OnExecuteBatch() override
204 {
205 WriteInfo("ExecuteBatch: {}", m_lastPreparedQuery);
206 }
207
208 void OnFetchRow() override
209 {
210 WriteInfo("Fetched row");
211 }
212
213 void OnFetchEnd() override
214 {
215 WriteInfo("Fetch end");
216 }
217
218 private:
219 void WriteDetails(std::source_location sourceLocation)
220 {
221 WriteInfo(" Source: {}:{}", sourceLocation.file_name(), sourceLocation.line());
222 if (!m_lastPreparedQuery.empty())
223 WriteInfo(" Query: {}", m_lastPreparedQuery);
224 WriteInfo(" Stack trace:");
225
226#if __has_include(<stacktrace>)
227 auto stackTrace = std::stacktrace::current(1, 25);
228 for (std::size_t const i: std::views::iota(std::size_t(0), stackTrace.size()))
229 WriteInfo(" [{:>2}] {}", i, stackTrace[i]);
230#endif
231 }
232};
233
234// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
235class ScopedSqlNullLogger: public Lightweight::SqlLogger::Null
236{
237 private:
238 SqlLogger& m_previousLogger = SqlLogger::GetLogger();
239
240 public:
241 ScopedSqlNullLogger()
242 {
243 SqlLogger::SetLogger(*this);
244 }
245
246 ~ScopedSqlNullLogger() override
247 {
248 SqlLogger::SetLogger(m_previousLogger);
249 }
250};
251
252template <typename Getter, typename Callable>
253constexpr void FixedPointIterate(Getter const& getter, Callable const& callable)
254{
255 auto a = getter();
256 for (;;)
257 {
258 callable(a);
259 auto b = getter();
260 if (a == b)
261 break;
262 a = std::move(b);
263 }
264}
265
266// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
267class SqlTestFixture
268{
269 public:
270 static inline std::string testDatabaseName = "LightweightTest"; // NOLINT(bugprone-throwing-static-initialization)
271 static inline bool odbcTrace = false;
272
273 using MainProgramArgs = std::tuple<int, char**>;
274
275 static std::variant<MainProgramArgs, int> Initialize(int argc, char** argv)
276 {
277 Lightweight::SqlLogger::SetLogger(TestSuiteSqlLogger::GetLogger());
278
279 using namespace std::string_view_literals;
280 int i = 1;
281 for (; i < argc; ++i)
282 {
283 if (argv[i] == "--trace-sql"sv)
285 else if (argv[i] == "--trace-odbc"sv)
286 odbcTrace = true;
287 else if (argv[i] == "--help"sv || argv[i] == "-h"sv)
288 {
289 std::println("{} [--trace-sql] [--trace-odbc] [[--] [Catch2 flags ...]]", argv[0]);
290 return { EXIT_SUCCESS };
291 }
292 else if (argv[i] == "--"sv)
293 {
294 ++i;
295 break;
296 }
297 else
298 break;
299 }
300
301 if (i < argc)
302 argv[i - 1] = argv[0];
303
304#if defined(_MSC_VER)
305 char* envBuffer = nullptr;
306 size_t envBufferLen = 0;
307 _dupenv_s(&envBuffer, &envBufferLen, "ODBC_CONNECTION_STRING");
308 if (auto const* s = envBuffer; s && *s)
309#else
310 if (auto const* s = std::getenv("ODBC_CONNECTION_STRING"); s && *s)
311#endif
312
313 {
314 std::println("Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(s));
316 }
317 else
318 {
319 // Use an in-memory SQLite3 database by default (for testing purposes)
320 std::println("Using default ODBC connection string: '{}'", DefaultTestConnectionString.value);
322 }
323
324 Lightweight::SqlConnection::SetPostConnectedHook(&SqlTestFixture::PostConnectedHook);
325
326 auto sqlConnection = Lightweight::SqlConnection();
327 if (!sqlConnection.IsAlive())
328 {
329 std::println("Failed to connect to the database: {}", sqlConnection.LastError());
330 std::abort();
331 }
332
333 std::println("Running test cases against: {} ({}) (identified as: {})",
334 sqlConnection.ServerName(),
335 sqlConnection.ServerVersion(),
336 sqlConnection.ServerType());
337
338 return MainProgramArgs { argc - (i - 1), argv + (i - 1) };
339 }
340
341 static void PostConnectedHook(Lightweight::SqlConnection& connection)
342 {
343 if (odbcTrace)
344 {
345 auto const traceFile = []() -> std::string_view {
346#if !defined(_WIN32) && !defined(_WIN64)
347 return "/dev/stdout";
348#else
349 return "CONOUT$";
350#endif
351 }();
352
353 SQLHDBC handle = connection.NativeHandle();
354 SQLSetConnectAttrA(handle, SQL_ATTR_TRACEFILE, (SQLPOINTER) traceFile.data(), SQL_NTS);
355 SQLSetConnectAttrA(handle, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_ON, SQL_IS_UINTEGER);
356 }
357
358 using Lightweight::SqlServerType;
359 switch (connection.ServerType())
360 {
361 case SqlServerType::SQLITE: {
362 auto stmt = Lightweight::SqlStatement { connection };
363 // Enable foreign key constraints for SQLite
364 stmt.ExecuteDirect("PRAGMA foreign_keys = ON");
365 break;
366 }
367 case SqlServerType::MICROSOFT_SQL:
368 case SqlServerType::POSTGRESQL:
369 case SqlServerType::ORACLE:
370 case SqlServerType::MYSQL:
371 case SqlServerType::UNKNOWN:
372 break;
373 }
374 }
375
376 SqlTestFixture()
377 {
378 auto stmt = Lightweight::SqlStatement();
379 REQUIRE(stmt.IsAlive());
380
381 // On Github CI, we use the pre-created database "FREEPDB1" for Oracle
382 char dbName[100]; // Buffer to store the database name
383 SQLSMALLINT dbNameLen {};
384 SQLGetInfo(stmt.Connection().NativeHandle(), SQL_DATABASE_NAME, dbName, sizeof(dbName), &dbNameLen);
385 if (dbNameLen > 0)
386 testDatabaseName = dbName;
387 else if (stmt.Connection().ServerType() == Lightweight::SqlServerType::ORACLE)
388 testDatabaseName = "FREEPDB1";
389
390 DropAllTablesInDatabase(stmt);
391 }
392
393 virtual ~SqlTestFixture() = default;
394
395 static std::string ToString(std::vector<std::string> const& values, std::string_view separator)
396 {
397 auto result = std::string {};
398 for (auto const& value: values)
399 {
400 if (!result.empty())
401 result += separator;
402 result += value;
403 }
404 return result;
405 }
406
407 static void DropTableRecursively(Lightweight::SqlStatement& stmt,
408 Lightweight::SqlSchema::FullyQualifiedTableName const& table)
409 {
410 auto const dependantTables = Lightweight::SqlSchema::AllForeignKeysTo(stmt, table);
411 for (auto const& dependantTable: dependantTables)
412 DropTableRecursively(stmt, dependantTable.foreignKey.table);
413 stmt.ExecuteDirect(std::format("DROP TABLE IF EXISTS \"{}\"", table.table));
414 }
415
416 static void DropAllTablesInDatabase(Lightweight::SqlStatement& stmt)
417 {
418 using Lightweight::SqlServerType;
419 switch (stmt.Connection().ServerType())
420 {
421 case SqlServerType::MICROSOFT_SQL:
422 case SqlServerType::MYSQL:
423 stmt.ExecuteDirect(std::format("USE \"{}\"", testDatabaseName));
424 [[fallthrough]];
425 case SqlServerType::SQLITE:
426 case SqlServerType::ORACLE:
427 case SqlServerType::UNKNOWN: {
428 auto const tableNames = GetAllTableNames(stmt);
429 for (auto const& tableName: tableNames)
430 {
431 if (tableName == "sqlite_sequence")
432 continue;
433
434 DropTableRecursively(stmt,
435 Lightweight::SqlSchema::FullyQualifiedTableName {
436 .catalog = {},
437 .schema = {},
438 .table = tableName,
439 });
440 }
441 break;
442 }
443 case SqlServerType::POSTGRESQL:
444 if (m_createdTables.empty())
445 m_createdTables = GetAllTableNames(stmt);
446 for (auto& createdTable: std::views::reverse(m_createdTables))
447 stmt.ExecuteDirect(std::format("DROP TABLE IF EXISTS \"{}\" CASCADE", createdTable));
448 break;
449 }
450 m_createdTables.clear();
451 }
452
453 private:
454 static std::vector<std::string> GetAllTableNamesForOracle(Lightweight::SqlStatement& stmt)
455 {
456 auto result = std::vector<std::string> {};
457 stmt.Prepare(R"SQL(SELECT table_name
458 FROM user_tables
459 WHERE table_name NOT LIKE '%$%'
460 AND table_name NOT IN ('SCHEDULER_JOB_ARGS_TBL', 'SCHEDULER_PROGRAM_ARGS_TBL', 'SQLPLUS_PRODUCT_PROFILE')
461 ORDER BY table_name)SQL");
462 stmt.Execute();
463 while (stmt.FetchRow())
464 {
465 result.emplace_back(stmt.GetColumn<std::string>(1));
466 }
467 return result;
468 }
469
470 static std::vector<std::string> GetAllTableNames(Lightweight::SqlStatement& stmt)
471 {
472 if (stmt.Connection().ServerType() == Lightweight::SqlServerType::ORACLE)
473 return GetAllTableNamesForOracle(stmt);
474
475 using namespace std::string_literals;
476 auto result = std::vector<std::string>();
477 auto const schemaName = [&] {
478 switch (stmt.Connection().ServerType())
479 {
480 case Lightweight::SqlServerType::MICROSOFT_SQL:
481 return "dbo"s;
482 default:
483 return ""s;
484 }
485 }();
486 auto const sqlResult = SQLTables(stmt.NativeHandle(),
487 (SQLCHAR*) testDatabaseName.data(),
488 (SQLSMALLINT) testDatabaseName.size(),
489 (SQLCHAR*) schemaName.data(),
490 (SQLSMALLINT) schemaName.size(),
491 nullptr,
492 0,
493 (SQLCHAR*) "TABLE",
494 SQL_NTS);
495 if (SQL_SUCCEEDED(sqlResult))
496 {
497 while (stmt.FetchRow())
498 {
499 result.emplace_back(stmt.GetColumn<std::string>(3)); // table name
500 }
501 }
502 return result;
503 }
504
505 static inline std::vector<std::string> m_createdTables;
506};
507
508// {{{ ostream support for Lightweight, for debugging purposes
509inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlText const& value)
510{
511 return os << std::format("SqlText({})", value.value);
512}
513
514inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlDate const& date)
515{
516 auto const ymd = date.value();
517 return os << std::format("SqlDate {{ {}-{}-{} }}", ymd.year(), ymd.month(), ymd.day());
518}
519
520inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlTime const& time)
521{
522 auto const value = time.value();
523 return os << std::format("SqlTime {{ {:02}:{:02}:{:02}.{:06} }}",
524 value.hours().count(),
525 value.minutes().count(),
526 value.seconds().count(),
527 value.subseconds().count());
528}
529
530inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlDateTime const& datetime)
531{
532 auto const value = datetime.value();
533 auto const totalDays = std::chrono::floor<std::chrono::days>(value);
534 auto const ymd = std::chrono::year_month_day { totalDays };
535 auto const hms =
536 std::chrono::hh_mm_ss<std::chrono::nanoseconds> { std::chrono::floor<std::chrono::nanoseconds>(value - totalDays) };
537 return os << std::format("SqlDateTime {{ {:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} }}",
538 (int) ymd.year(),
539 (unsigned) ymd.month(),
540 (unsigned) ymd.day(),
541 hms.hours().count(),
542 hms.minutes().count(),
543 hms.seconds().count(),
544 hms.subseconds().count());
545}
546
547template <std::size_t N, typename T, Lightweight::SqlFixedStringMode Mode>
548inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlFixedString<N, T, Mode> const& value)
549{
550 if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE)
551 return os << std::format("SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.size(), value.data());
552 else if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
553 return os << std::format("SqlTrimmedFixedString<{}> {{ '{}' }}", N, value.data());
554 else if constexpr (Mode == Lightweight::SqlFixedStringMode::VARIABLE_SIZE)
555 {
556 if constexpr (std::same_as<T, char>)
557 return os << std::format("SqlVariableString<{}> {{ size: {}, '{}' }}", N, value.size(), value.data());
558 else
559 {
560 auto u8String = ToUtf8(std::basic_string_view<T>(value.data(), value.size()));
561 return os << std::format("SqlVariableString<{}, {}> {{ size: {}, '{}' }}",
562 N,
563 Reflection::TypeNameOf<T>,
564 value.size(),
565 (char const*) u8String.c_str()); // NOLINT(readability-redundant-string-cstr)
566 }
567 }
568 else
569 return os << std::format("SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.size(), value.data());
570}
571
572template <std::size_t N, typename T>
573inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlDynamicString<N, T> const& value)
574{
575 if constexpr (std::same_as<T, char>)
576 return os << std::format("SqlDynamicString<{}> {{ size: {}, '{}' }}", N, value.size(), value.data());
577 else
578 {
579 auto u8String = ToUtf8(std::basic_string_view<T>(value.data(), value.size()));
580 return os << std::format("SqlDynamicString<{}, {}> {{ size: {}, '{}' }}",
581 N,
582 Reflection::TypeNameOf<T>,
583 value.size(),
584 (char const*) u8String.c_str()); // NOLINT(readability-redundant-string-cstr)
585 }
586}
587
588[[nodiscard]] inline std::string NormalizeText(std::string_view const& text)
589{
590 auto result = std::string(text);
591
592 // Remove any newlines and reduce all whitespace to a single space
593 result.erase(std::unique(result.begin(), // NOLINT(modernize-use-ranges)
594 result.end(),
595 [](char a, char b) { return std::isspace(a) && std::isspace(b); }),
596 result.end());
597
598 // trim lading and trailing whitespace
599 while (!result.empty() && std::isspace(result.front()))
600 result.erase(result.begin());
601
602 while (!result.empty() && std::isspace(result.back()))
603 result.pop_back();
604
605 return result;
606}
607
608[[nodiscard]] inline std::string NormalizeText(std::vector<std::string> const& texts)
609{
610 auto result = std::string {};
611 for (auto const& text: texts)
612 {
613 if (!result.empty())
614 result += '\n';
615 result += NormalizeText(text);
616 }
617 return result;
618}
619
620// }}}
621
622inline void CreateEmployeesTable(Lightweight::SqlStatement& stmt,
623 std::source_location location = std::source_location::current())
624{
625 stmt.MigrateDirect(
627 migration.CreateTable("Employees")
628 .PrimaryKeyWithAutoIncrement("EmployeeID")
629 .RequiredColumn("FirstName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
630 .Column("LastName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
631 .RequiredColumn("Salary", Lightweight::SqlColumnTypeDefinitions::Integer {});
632 },
633 location);
634}
635
636inline void CreateLargeTable(Lightweight::SqlStatement& stmt)
637{
639 auto table = migration.CreateTable("LargeTable");
640 for (char c = 'A'; c <= 'Z'; ++c)
641 {
642 table.Column(std::string(1, c), Lightweight::SqlColumnTypeDefinitions::Varchar { 50 });
643 }
644 });
645}
646
647inline void FillEmployeesTable(Lightweight::SqlStatement& stmt)
648{
649 stmt.Prepare(stmt.Query("Employees")
650 .Insert()
651 .Set("FirstName", Lightweight::SqlWildcard)
652 .Set("LastName", Lightweight::SqlWildcard)
653 .Set("Salary", Lightweight::SqlWildcard));
654 stmt.Execute("Alice", "Smith", 50'000);
655 stmt.Execute("Bob", "Johnson", 60'000);
656 stmt.Execute("Charlie", "Brown", 70'000);
657}
658
659template <typename T = char>
660inline auto MakeLargeText(size_t size)
661{
662 auto text = std::basic_string<T>(size, {});
663 std::ranges::generate(text, [i = 0]() mutable { return static_cast<T>('A' + (i++ % 26)); });
664 return text;
665}
666
667inline bool IsGithubActions()
668{
669#if defined(_WIN32) || defined(_WIN64)
670 char envBuffer[32] {};
671 size_t requiredCount = 0;
672 return getenv_s(&requiredCount, envBuffer, sizeof(envBuffer), "GITHUB_ACTIONS") == 0
673 && std::string_view(envBuffer) == "true" == 0;
674#else
675 return std::getenv("GITHUB_ACTIONS") != nullptr
676 && std::string_view(std::getenv("GITHUB_ACTIONS")) == "true"; // NOLINT(clang-analyzer-core.NonNullParamChecker)
677#endif
678}
679
680namespace std
681{
682
683template <typename T>
684ostream& operator<<(ostream& os, optional<T> const& opt)
685{
686 if (opt.has_value())
687 return os << *opt;
688 else
689 return os << "nullopt";
690}
691
692} // namespace std
693
694template <typename T, auto P1, auto P2>
695std::ostream& operator<<(std::ostream& os, Lightweight::Field<std::optional<T>, P1, P2> const& field)
696{
697 if (field.Value())
698 return os << std::format("Field<{}> {{ {}, {} }}",
699 Reflection::TypeNameOf<T>,
700 *field.Value(),
701 field.IsModified() ? "modified" : "not modified");
702 else
703 return os << "NULL";
704}
705
706template <typename T, auto P1, auto P2>
707std::ostream& operator<<(std::ostream& os, Lightweight::Field<T, P1, P2> const& field)
708{
709 return os << std::format("Field<{}> {{ ", Reflection::TypeNameOf<T>) << "value: " << field.Value() << "; "
710 << (field.IsModified() ? "modified" : "not modified") << " }";
711}
Represents a connection to a SQL database.
SqlServerType ServerType() const noexcept
Retrieves the type of the server.
static LIGHTWEIGHT_API void SetDefaultConnectionString(SqlConnectionString const &connectionString) noexcept
SQLHDBC NativeHandle() const noexcept
Retrieves the native handle.
static LIGHTWEIGHT_API void SetPostConnectedHook(std::function< void(SqlConnection &)> hook)
Sets a callback to be called after each connection being established.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & Column(SqlColumnDeclaration column)
Adds a new column to the table.
LIGHTWEIGHT_FORCE_INLINE std::size_t size() const noexcept
Retrieves the string's size.
LIGHTWEIGHT_FORCE_INLINE T const * data() const noexcept
Retrieves the string's inner value (as T const*).
LIGHTWEIGHT_FORCE_INLINE constexpr std::size_t size() const noexcept
Returns the size of the string.
static LIGHTWEIGHT_API SqlLogger & TraceLogger()
Retrieves a logger that logs to the trace logger.
static LIGHTWEIGHT_API void SetLogger(SqlLogger &logger)
Query builder for building SQL migration queries.
Definition Migrate.hpp:185
LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTable(std::string_view tableName)
Creates a new table.
LIGHTWEIGHT_API SqlInsertQueryBuilder Insert(std::vector< SqlVariant > *boundInputs=nullptr) noexcept
High level API for (prepared) raw SQL statements.
LIGHTWEIGHT_API void Prepare(std::string_view query) &
LIGHTWEIGHT_API SQLHSTMT NativeHandle() const noexcept
Retrieves the native handle of the statement.
void MigrateDirect(Callable const &callable, std::source_location location=std::source_location::current())
Executes an SQL migration query, as created b the callback.
LIGHTWEIGHT_API SqlConnection & Connection() noexcept
Retrieves the connection associated with this statement.
void Execute(Args const &... args)
Binds the given arguments to the prepared statement and executes it.
bool GetColumn(SQLUSMALLINT column, T *result) const
LIGHTWEIGHT_API SqlQueryBuilder Query(std::string_view const &table={}) const
Creates a new query builder for the given table, compatible with the SQL server being connected.
LIGHTWEIGHT_API void ExecuteDirect(std::string_view const &query, std::source_location location=std::source_location::current())
Executes the given query directly.
LIGHTWEIGHT_API bool FetchRow()
LIGHTWEIGHT_API std::u8string ToUtf8(std::u32string_view u32InputString)
Represents a single column in a table.
Definition Field.hpp:84
constexpr bool IsModified() const noexcept
Checks if the field has been modified.
Definition Field.hpp:299
constexpr T const & Value() const noexcept
Returns the value of the field.
Definition Field.hpp:305
Represents an ODBC connection string.
constexpr LIGHTWEIGHT_FORCE_INLINE native_type value() const noexcept
Returns the current date and time.
LIGHTWEIGHT_FORCE_INLINE constexpr std::chrono::year_month_day value() const noexcept
Returns the current date.
Definition SqlDate.hpp:29
Represents an ODBC SQL error.
Definition SqlError.hpp:33
constexpr LIGHTWEIGHT_FORCE_INLINE auto ToUnscaledValue() const noexcept
Converts the numeric to an unscaled integer value.