Lightweight 0.20250904.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//
124auto inline const DefaultTestConnectionString = Lightweight::SqlConnectionString {
125 .value = std::format("DRIVER={};Database={}",
126#if defined(_WIN32) || defined(_WIN64)
127 "SQLite3 ODBC Driver",
128#else
129 "SQLite3",
130#endif
131 "test.db"),
132};
133
134class TestSuiteSqlLogger: public Lightweight::SqlLogger::Null
135{
136 private:
137 std::string m_lastPreparedQuery;
138
139 template <typename... Args>
140 void WriteInfo(std::format_string<Args...> const& fmt, Args&&... args)
141 {
142 auto message = std::format(fmt, std::forward<Args>(args)...);
143 message = std::format("[{}] {}", "Lightweight", message);
144 try
145 {
146 UNSCOPED_INFO(message);
147 }
148 catch (...)
149 {
150 std::println("{}", message);
151 }
152 }
153
154 template <typename... Args>
155 void WriteWarning(std::format_string<Args...> const& fmt, Args&&... args)
156 {
157 WARN(std::format(fmt, std::forward<Args>(args)...));
158 }
159
160 public:
161 static TestSuiteSqlLogger& GetLogger() noexcept
162 {
163 static TestSuiteSqlLogger theLogger;
164 return theLogger;
165 }
166
167 void OnError(Lightweight::SqlError error, std::source_location sourceLocation) override
168 {
169 WriteWarning("SQL Error: {}", error);
170 WriteDetails(sourceLocation);
171 }
172
173 void OnError(Lightweight::SqlErrorInfo const& errorInfo, std::source_location sourceLocation) override
174 {
175 WriteWarning("SQL Error: {}", errorInfo);
176 WriteDetails(sourceLocation);
177 }
178
179 void OnWarning(std::string_view const& message) override
180 {
181 WriteWarning("{}", message);
182 WriteDetails(std::source_location::current());
183 }
184
185 void OnExecuteDirect(std::string_view const& query) override
186 {
187 WriteInfo("ExecuteDirect: {}", query);
188 }
189
190 void OnPrepare(std::string_view const& query) override
191 {
192 m_lastPreparedQuery = query;
193 }
194
195 void OnExecute(std::string_view const& query) override
196 {
197 WriteInfo("Execute: {}", query);
198 }
199
200 void OnExecuteBatch() override
201 {
202 WriteInfo("ExecuteBatch: {}", m_lastPreparedQuery);
203 }
204
205 void OnFetchRow() override
206 {
207 WriteInfo("Fetched row");
208 }
209
210 void OnFetchEnd() override
211 {
212 WriteInfo("Fetch end");
213 }
214
215 private:
216 void WriteDetails(std::source_location sourceLocation)
217 {
218 WriteInfo(" Source: {}:{}", sourceLocation.file_name(), sourceLocation.line());
219 if (!m_lastPreparedQuery.empty())
220 WriteInfo(" Query: {}", m_lastPreparedQuery);
221 WriteInfo(" Stack trace:");
222
223#if __has_include(<stacktrace>)
224 auto stackTrace = std::stacktrace::current(1, 25);
225 for (std::size_t const i: std::views::iota(std::size_t(0), stackTrace.size()))
226 WriteInfo(" [{:>2}] {}", i, stackTrace[i]);
227#endif
228 }
229};
230
231// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
232class ScopedSqlNullLogger: public Lightweight::SqlLogger::Null
233{
234 private:
235 SqlLogger& m_previousLogger = SqlLogger::GetLogger();
236
237 public:
238 ScopedSqlNullLogger()
239 {
240 SqlLogger::SetLogger(*this);
241 }
242
243 ~ScopedSqlNullLogger() override
244 {
245 SqlLogger::SetLogger(m_previousLogger);
246 }
247};
248
249template <typename Getter, typename Callable>
250constexpr void FixedPointIterate(Getter const& getter, Callable const& callable)
251{
252 auto a = getter();
253 for (;;)
254 {
255 callable(a);
256 auto b = getter();
257 if (a == b)
258 break;
259 a = std::move(b);
260 }
261}
262
263// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
264class SqlTestFixture
265{
266 public:
267 static inline std::string testDatabaseName = "LightweightTest";
268 static inline bool odbcTrace = false;
269
270 using MainProgramArgs = std::tuple<int, char**>;
271
272 static std::variant<MainProgramArgs, int> Initialize(int argc, char** argv)
273 {
274 Lightweight::SqlLogger::SetLogger(TestSuiteSqlLogger::GetLogger());
275
276 using namespace std::string_view_literals;
277 int i = 1;
278 for (; i < argc; ++i)
279 {
280 if (argv[i] == "--trace-sql"sv)
282 else if (argv[i] == "--trace-odbc"sv)
283 odbcTrace = true;
284 else if (argv[i] == "--help"sv || argv[i] == "-h"sv)
285 {
286 std::println("{} [--trace-sql] [--trace-odbc] [[--] [Catch2 flags ...]]", argv[0]);
287 return { EXIT_SUCCESS };
288 }
289 else if (argv[i] == "--"sv)
290 {
291 ++i;
292 break;
293 }
294 else
295 break;
296 }
297
298 if (i < argc)
299 argv[i - 1] = argv[0];
300
301#if defined(_MSC_VER)
302 char* envBuffer = nullptr;
303 size_t envBufferLen = 0;
304 _dupenv_s(&envBuffer, &envBufferLen, "ODBC_CONNECTION_STRING");
305 if (auto const* s = envBuffer; s && *s)
306#else
307 if (auto const* s = std::getenv("ODBC_CONNECTION_STRING"); s && *s)
308#endif
309
310 {
311 std::println("Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(s));
313 }
314 else
315 {
316 // Use an in-memory SQLite3 database by default (for testing purposes)
317 std::println("Using default ODBC connection string: '{}'", DefaultTestConnectionString.value);
319 }
320
321 Lightweight::SqlConnection::SetPostConnectedHook(&SqlTestFixture::PostConnectedHook);
322
323 auto sqlConnection = Lightweight::SqlConnection();
324 if (!sqlConnection.IsAlive())
325 {
326 std::println("Failed to connect to the database: {}", sqlConnection.LastError());
327 std::abort();
328 }
329
330 std::println("Running test cases against: {} ({}) (identified as: {})",
331 sqlConnection.ServerName(),
332 sqlConnection.ServerVersion(),
333 sqlConnection.ServerType());
334
335 return MainProgramArgs { argc - (i - 1), argv + (i - 1) };
336 }
337
338 static void PostConnectedHook(Lightweight::SqlConnection& connection)
339 {
340 if (odbcTrace)
341 {
342 auto const traceFile = []() -> std::string_view {
343#if !defined(_WIN32) && !defined(_WIN64)
344 return "/dev/stdout";
345#else
346 return "CONOUT$";
347#endif
348 }();
349
350 SQLHDBC handle = connection.NativeHandle();
351 SQLSetConnectAttrA(handle, SQL_ATTR_TRACEFILE, (SQLPOINTER) traceFile.data(), SQL_NTS);
352 SQLSetConnectAttrA(handle, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_ON, SQL_IS_UINTEGER);
353 }
354
355 using Lightweight::SqlServerType;
356 switch (connection.ServerType())
357 {
358 case SqlServerType::SQLITE: {
359 auto stmt = Lightweight::SqlStatement { connection };
360 // Enable foreign key constraints for SQLite
361 stmt.ExecuteDirect("PRAGMA foreign_keys = ON");
362 break;
363 }
364 case SqlServerType::MICROSOFT_SQL:
365 case SqlServerType::POSTGRESQL:
366 case SqlServerType::ORACLE:
367 case SqlServerType::MYSQL:
368 case SqlServerType::UNKNOWN:
369 break;
370 }
371 }
372
373 SqlTestFixture()
374 {
375 auto stmt = Lightweight::SqlStatement();
376 REQUIRE(stmt.IsAlive());
377
378 // On Github CI, we use the pre-created database "FREEPDB1" for Oracle
379 char dbName[100]; // Buffer to store the database name
380 SQLSMALLINT dbNameLen {};
381 SQLGetInfo(stmt.Connection().NativeHandle(), SQL_DATABASE_NAME, dbName, sizeof(dbName), &dbNameLen);
382 if (dbNameLen > 0)
383 testDatabaseName = dbName;
384 else if (stmt.Connection().ServerType() == Lightweight::SqlServerType::ORACLE)
385 testDatabaseName = "FREEPDB1";
386
387 DropAllTablesInDatabase(stmt);
388 }
389
390 virtual ~SqlTestFixture() = default;
391
392 static std::string ToString(std::vector<std::string> const& values, std::string_view separator)
393 {
394 auto result = std::string {};
395 for (auto const& value: values)
396 {
397 if (!result.empty())
398 result += separator;
399 result += value;
400 }
401 return result;
402 }
403
404 static void DropTableRecursively(Lightweight::SqlStatement& stmt,
405 Lightweight::SqlSchema::FullyQualifiedTableName const& table)
406 {
407 auto const dependantTables = Lightweight::SqlSchema::AllForeignKeysTo(stmt, table);
408 for (auto const& dependantTable: dependantTables)
409 DropTableRecursively(stmt, dependantTable.foreignKey.table);
410 stmt.ExecuteDirect(std::format("DROP TABLE IF EXISTS \"{}\"", table.table));
411 }
412
413 static void DropAllTablesInDatabase(Lightweight::SqlStatement& stmt)
414 {
415 using Lightweight::SqlServerType;
416 switch (stmt.Connection().ServerType())
417 {
418 case SqlServerType::MICROSOFT_SQL:
419 case SqlServerType::MYSQL:
420 stmt.ExecuteDirect(std::format("USE \"{}\"", testDatabaseName));
421 [[fallthrough]];
422 case SqlServerType::SQLITE:
423 case SqlServerType::ORACLE:
424 case SqlServerType::UNKNOWN: {
425 auto const tableNames = GetAllTableNames(stmt);
426 for (auto const& tableName: tableNames)
427 {
428 if (tableName == "sqlite_sequence")
429 continue;
430
431 DropTableRecursively(stmt,
432 Lightweight::SqlSchema::FullyQualifiedTableName {
433 .catalog = {},
434 .schema = {},
435 .table = tableName,
436 });
437 }
438 break;
439 }
440 case SqlServerType::POSTGRESQL:
441 if (m_createdTables.empty())
442 m_createdTables = GetAllTableNames(stmt);
443 for (auto& createdTable: std::views::reverse(m_createdTables))
444 stmt.ExecuteDirect(std::format("DROP TABLE IF EXISTS \"{}\" CASCADE", createdTable));
445 break;
446 }
447 m_createdTables.clear();
448 }
449
450 private:
451 static std::vector<std::string> GetAllTableNamesForOracle(Lightweight::SqlStatement& stmt)
452 {
453 auto result = std::vector<std::string> {};
454 stmt.Prepare(R"SQL(SELECT table_name
455 FROM user_tables
456 WHERE table_name NOT LIKE '%$%'
457 AND table_name NOT IN ('SCHEDULER_JOB_ARGS_TBL', 'SCHEDULER_PROGRAM_ARGS_TBL', 'SQLPLUS_PRODUCT_PROFILE')
458 ORDER BY table_name)SQL");
459 stmt.Execute();
460 while (stmt.FetchRow())
461 {
462 result.emplace_back(stmt.GetColumn<std::string>(1));
463 }
464 return result;
465 }
466
467 static std::vector<std::string> GetAllTableNames(Lightweight::SqlStatement& stmt)
468 {
469 if (stmt.Connection().ServerType() == Lightweight::SqlServerType::ORACLE)
470 return GetAllTableNamesForOracle(stmt);
471
472 using namespace std::string_literals;
473 auto result = std::vector<std::string>();
474 auto const schemaName = [&] {
475 switch (stmt.Connection().ServerType())
476 {
477 case Lightweight::SqlServerType::MICROSOFT_SQL:
478 return "dbo"s;
479 default:
480 return ""s;
481 }
482 }();
483 auto const sqlResult = SQLTables(stmt.NativeHandle(),
484 (SQLCHAR*) testDatabaseName.data(),
485 (SQLSMALLINT) testDatabaseName.size(),
486 (SQLCHAR*) schemaName.data(),
487 (SQLSMALLINT) schemaName.size(),
488 nullptr,
489 0,
490 (SQLCHAR*) "TABLE",
491 SQL_NTS);
492 if (SQL_SUCCEEDED(sqlResult))
493 {
494 while (stmt.FetchRow())
495 {
496 result.emplace_back(stmt.GetColumn<std::string>(3)); // table name
497 }
498 }
499 return result;
500 }
501
502 static inline std::vector<std::string> m_createdTables;
503};
504
505// {{{ ostream support for Lightweight, for debugging purposes
506inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlText const& value)
507{
508 return os << std::format("SqlText({})", value.value);
509}
510
511inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlDate const& date)
512{
513 auto const ymd = date.value();
514 return os << std::format("SqlDate {{ {}-{}-{} }}", ymd.year(), ymd.month(), ymd.day());
515}
516
517inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlTime const& time)
518{
519 auto const value = time.value();
520 return os << std::format("SqlTime {{ {:02}:{:02}:{:02}.{:06} }}",
521 value.hours().count(),
522 value.minutes().count(),
523 value.seconds().count(),
524 value.subseconds().count());
525}
526
527inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlDateTime const& datetime)
528{
529 auto const value = datetime.value();
530 auto const totalDays = std::chrono::floor<std::chrono::days>(value);
531 auto const ymd = std::chrono::year_month_day { totalDays };
532 auto const hms =
533 std::chrono::hh_mm_ss<std::chrono::nanoseconds> { std::chrono::floor<std::chrono::nanoseconds>(value - totalDays) };
534 return os << std::format("SqlDateTime {{ {:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} }}",
535 (int) ymd.year(),
536 (unsigned) ymd.month(),
537 (unsigned) ymd.day(),
538 hms.hours().count(),
539 hms.minutes().count(),
540 hms.seconds().count(),
541 hms.subseconds().count());
542}
543
544template <std::size_t N, typename T, Lightweight::SqlFixedStringMode Mode>
545inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlFixedString<N, T, Mode> const& value)
546{
547 if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE)
548 return os << std::format("SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.size(), value.data());
549 else if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
550 return os << std::format("SqlTrimmedFixedString<{}> {{ '{}' }}", N, value.data());
551 else if constexpr (Mode == Lightweight::SqlFixedStringMode::VARIABLE_SIZE)
552 {
553 if constexpr (std::same_as<T, char>)
554 return os << std::format("SqlVariableString<{}> {{ size: {}, '{}' }}", N, value.size(), value.data());
555 else
556 {
557 auto u8String = ToUtf8(std::basic_string_view<T>(value.data(), value.size()));
558 return os << std::format("SqlVariableString<{}, {}> {{ size: {}, '{}' }}",
559 N,
560 Reflection::TypeNameOf<T>,
561 value.size(),
562 (char const*) u8String.c_str()); // NOLINT(readability-redundant-string-cstr)
563 }
564 }
565 else
566 return os << std::format("SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.size(), value.data());
567}
568
569template <std::size_t N, typename T>
570inline std::ostream& operator<<(std::ostream& os, Lightweight::SqlDynamicString<N, T> const& value)
571{
572 if constexpr (std::same_as<T, char>)
573 return os << std::format("SqlDynamicString<{}> {{ size: {}, '{}' }}", N, value.size(), value.data());
574 else
575 {
576 auto u8String = ToUtf8(std::basic_string_view<T>(value.data(), value.size()));
577 return os << std::format("SqlDynamicString<{}, {}> {{ size: {}, '{}' }}",
578 N,
579 Reflection::TypeNameOf<T>,
580 value.size(),
581 (char const*) u8String.c_str()); // NOLINT(readability-redundant-string-cstr)
582 }
583}
584
585[[nodiscard]] inline std::string NormalizeText(std::string_view const& text)
586{
587 auto result = std::string(text);
588
589 // Remove any newlines and reduce all whitespace to a single space
590 result.erase(std::unique(result.begin(), // NOLINT(modernize-use-ranges)
591 result.end(),
592 [](char a, char b) { return std::isspace(a) && std::isspace(b); }),
593 result.end());
594
595 // trim lading and trailing whitespace
596 while (!result.empty() && std::isspace(result.front()))
597 result.erase(result.begin());
598
599 while (!result.empty() && std::isspace(result.back()))
600 result.pop_back();
601
602 return result;
603}
604
605[[nodiscard]] inline std::string NormalizeText(std::vector<std::string> const& texts)
606{
607 auto result = std::string {};
608 for (auto const& text: texts)
609 {
610 if (!result.empty())
611 result += '\n';
612 result += NormalizeText(text);
613 }
614 return result;
615}
616
617// }}}
618
619inline void CreateEmployeesTable(Lightweight::SqlStatement& stmt,
620 std::source_location location = std::source_location::current())
621{
622 stmt.MigrateDirect(
624 migration.CreateTable("Employees")
625 .PrimaryKeyWithAutoIncrement("EmployeeID")
626 .RequiredColumn("FirstName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
627 .Column("LastName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
628 .RequiredColumn("Salary", Lightweight::SqlColumnTypeDefinitions::Integer {});
629 },
630 location);
631}
632
633inline void CreateLargeTable(Lightweight::SqlStatement& stmt)
634{
636 auto table = migration.CreateTable("LargeTable");
637 for (char c = 'A'; c <= 'Z'; ++c)
638 {
639 table.Column(std::string(1, c), Lightweight::SqlColumnTypeDefinitions::Varchar { 50 });
640 }
641 });
642}
643
644inline void FillEmployeesTable(Lightweight::SqlStatement& stmt)
645{
646 stmt.Prepare(stmt.Query("Employees")
647 .Insert()
648 .Set("FirstName", Lightweight::SqlWildcard)
649 .Set("LastName", Lightweight::SqlWildcard)
650 .Set("Salary", Lightweight::SqlWildcard));
651 stmt.Execute("Alice", "Smith", 50'000);
652 stmt.Execute("Bob", "Johnson", 60'000);
653 stmt.Execute("Charlie", "Brown", 70'000);
654}
655
656template <typename T = char>
657inline auto MakeLargeText(size_t size)
658{
659 auto text = std::basic_string<T>(size, {});
660 std::ranges::generate(text, [i = 0]() mutable { return static_cast<T>('A' + (i++ % 26)); });
661 return text;
662}
663
664inline bool IsGithubActions()
665{
666#if defined(_WIN32) || defined(_WIN64)
667 char envBuffer[32] {};
668 size_t requiredCount = 0;
669 return getenv_s(&requiredCount, envBuffer, sizeof(envBuffer), "GITHUB_ACTIONS") == 0
670 && std::string_view(envBuffer) == "true" == 0;
671#else
672 return std::getenv("GITHUB_ACTIONS") != nullptr && std::string_view(std::getenv("GITHUB_ACTIONS")) == "true";
673#endif
674}
675
676namespace std
677{
678
679template <typename T>
680ostream& operator<<(ostream& os, optional<T> const& opt)
681{
682 if (opt.has_value())
683 return os << *opt;
684 else
685 return os << "nullopt";
686}
687
688} // namespace std
689
690template <typename T, auto P1, auto P2>
691std::ostream& operator<<(std::ostream& os, Lightweight::Field<std::optional<T>, P1, P2> const& field)
692{
693 if (field.Value())
694 return os << std::format("Field<{}> {{ {}, {} }}",
695 Reflection::TypeNameOf<T>,
696 *field.Value(),
697 field.IsModified() ? "modified" : "not modified");
698 else
699 return os << "NULL";
700}
701
702template <typename T, auto P1, auto P2>
703std::ostream& operator<<(std::ostream& os, Lightweight::Field<T, P1, P2> const& field)
704{
705 return os << std::format("Field<{}> {{ ", Reflection::TypeNameOf<T>) << "value: " << field.Value() << "; "
706 << (field.IsModified() ? "modified" : "not modified") << " }";
707}
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:292
constexpr T const & Value() const noexcept
Returns the value of the field.
Definition Field.hpp:298
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
SQL_NUMERIC_STRUCT sqlValue
The value is stored as a string to avoid floating point precision issues.
constexpr LIGHTWEIGHT_FORCE_INLINE auto ToUnscaledValue() const noexcept
Converts the numeric to an unscaled integer value.