5#if defined(_WIN32) || defined(_WIN64)
9#include <Lightweight/Lightweight.hpp>
11#include <catch2/catch_session.hpp>
12#include <catch2/catch_test_macros.hpp>
13#include <yaml-cpp/yaml.h>
28#if __has_include(<stacktrace>)
38using WideChar = std::conditional_t<
sizeof(wchar_t) == 2,
wchar_t,
char16_t>;
39using WideString = std::basic_string<WideChar>;
40using WideStringView = std::basic_string_view<WideChar>;
42#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
54 #define WTEXT(x) (u##x)
56 #define WTEXT(x) (L##x)
59#define UNSUPPORTED_DATABASE(stmt, dbType) \
60 if ((stmt).Connection().ServerType() == (dbType)) \
62 WARN(std::format("TODO({}): This database is currently unsupported on this test.", dbType)); \
67struct std::formatter<std::u8string>: std::formatter<std::string>
69 auto format(std::u8string
const& value, std::format_context& ctx)
const -> std::format_context::iterator
71 return std::formatter<std::string>::format(
72 std::format(
"{}", (
char const*) value.c_str()),
83template <
typename W
ideStringT>
84 requires(Lightweight::detail::OneOf<WideStringT,
91ostream&
operator<<(ostream& os, WideStringT
const& str)
93 auto constexpr BitsPerChar =
sizeof(
typename WideStringT::value_type) * 8;
95 return os <<
"UTF-" << BitsPerChar <<
'{' <<
"length: " << str.size() <<
", characters: " <<
'"'
96 << string_view((
char const*) u8String.data(), u8String.size()) <<
'"' <<
'}';
101 return os << format(
"SqlGuid({})", guid);
104inline std::string EscapedBinaryText(std::string_view binary)
106 std::string hexEncodedString;
107 for (
auto const& b: binary)
110 hexEncodedString +=
static_cast<char>(b);
112 hexEncodedString += std::format(
"\\x{:02x}",
static_cast<unsigned char>(b));
114 return hexEncodedString;
120 auto const hexEncodedString = EscapedBinaryText(std::string_view((
char const*) binary.
data(), binary.
size()));
121 return os << std::format(
"SqlDynamicBinary<{}>(length: {}, characters: {})", N, binary.
size(), hexEncodedString);
128template <std::
size_t Precision, std::
size_t Scale>
131 return os << std::format(
"SqlNumeric<{}, {}>({}, {}, {}, {})",
135 value.sqlValue.precision,
136 value.sqlValue.scale,
151 .value = std::format(
"DRIVER={};Database={}",
152#
if defined(_WIN32) || defined(_WIN64)
153 "SQLite3 ODBC Driver",
160class TestSuiteSqlLogger:
public Lightweight::SqlLogger::Null
163 mutable std::mutex m_mutex;
164 std::string m_lastPreparedQuery;
166 void WriteRawInfo(std::string_view message);
168 template <
typename... Args>
169 void WriteInfo(std::format_string<Args...>
const& fmt, Args&&... args)
171 auto message = std::format(fmt, std::forward<Args>(args)...);
172 message = std::format(
"[{}] {}",
"Lightweight", message);
173 WriteRawInfo(message);
176 template <
typename... Args>
177 void WriteWarning(std::format_string<Args...>
const& fmt, Args&&... args)
179 WARN(std::format(fmt, std::forward<Args>(args)...));
183 static TestSuiteSqlLogger& GetLogger() noexcept
185 static TestSuiteSqlLogger theLogger;
189 void OnError(Lightweight::SqlError error, std::source_location sourceLocation)
override
191 WriteWarning(
"SQL Error: {}", error);
192 WriteDetails(sourceLocation);
197 WriteWarning(
"SQL Error: {}", errorInfo);
198 WriteDetails(sourceLocation);
201 void OnWarning(std::string_view
const& message)
override
203 WriteWarning(
"{}", message);
204 WriteDetails(std::source_location::current());
207 void OnExecuteDirect(std::string_view
const& query)
override
209 WriteInfo(
"ExecuteDirect: {}", query);
212 void OnPrepare(std::string_view
const& query)
override
214 std::scoped_lock lock(m_mutex);
215 m_lastPreparedQuery = query;
218 void OnExecute(std::string_view
const& query)
override
220 WriteInfo(
"Execute: {}", query);
223 void OnExecuteBatch()
override
225 std::scoped_lock lock(m_mutex);
226 WriteInfo(
"ExecuteBatch: {}", m_lastPreparedQuery);
229 void OnFetchRow()
override
231 WriteInfo(
"Fetched row");
234 void OnFetchEnd()
override
240 void WriteDetails(std::source_location sourceLocation)
242 std::scoped_lock lock(m_mutex);
243 WriteInfo(
" Source: {}:{}", sourceLocation.file_name(), sourceLocation.line());
244 if (!m_lastPreparedQuery.empty())
245 WriteInfo(
" Query: {}", m_lastPreparedQuery);
246 WriteInfo(
" Stack trace:");
248#if __has_include(<stacktrace>)
249 auto stackTrace = std::stacktrace::current(1, 25);
250 for (std::size_t
const i: std::views::iota(std::size_t(0), stackTrace.size()))
251 WriteInfo(
" [{:>2}] {}", i, stackTrace[i]);
257class ScopedSqlNullLogger:
public Lightweight::SqlLogger::Null
260 SqlLogger& m_previousLogger = SqlLogger::GetLogger();
263 ScopedSqlNullLogger()
265 SqlLogger::SetLogger(*
this);
268 ~ScopedSqlNullLogger()
override
270 SqlLogger::SetLogger(m_previousLogger);
274template <
typename Getter,
typename Callable>
275constexpr void FixedPointIterate(Getter
const& getter, Callable
const& callable)
290inline std::optional<std::filesystem::path> FindTestEnvFile()
292 auto currentDir = std::filesystem::current_path();
296 auto testEnvPath = currentDir /
".test-env.yml";
297 if (std::filesystem::exists(testEnvPath))
301 auto gitPath = currentDir /
".git";
302 if (std::filesystem::exists(gitPath))
305 auto parentDir = currentDir.parent_path();
306 if (parentDir == currentDir)
309 currentDir = parentDir;
317 static inline std::string testDatabaseName =
"LightweightTest";
318 static inline bool odbcTrace =
false;
319 static inline std::atomic<bool> running =
false;
321 using MainProgramArgs = std::tuple<int, char**>;
323 static std::variant<MainProgramArgs, int> Initialize(
int argc,
char** argv)
327 using namespace std::string_view_literals;
328 std::optional<std::string> testEnvName;
330 for (; i < argc; ++i)
332 if (argv[i] ==
"--trace-sql"sv)
334 else if (argv[i] ==
"--trace-odbc"sv)
336 else if (std::string_view(argv[i]).starts_with(
"--test-env="))
337 testEnvName = std::string_view(argv[i]).substr(11);
338 else if (argv[i] ==
"--help"sv || argv[i] ==
"-h"sv)
340 std::println(
"{} [--test-env=NAME] [--trace-sql] [--trace-odbc] [[--] [Catch2 flags ...]]", argv[0]);
342 std::println(
"Options:");
343 std::println(
" --test-env=NAME Use connection string from .test-env.yml (e.g., pgsql, mssql, sqlite)");
344 std::println(
" --trace-sql Enable SQL tracing");
345 std::println(
" --trace-odbc Enable ODBC tracing");
346 return { EXIT_SUCCESS };
348 else if (argv[i] ==
"--"sv)
358 argv[i - 1] = argv[0];
367 auto configPath = FindTestEnvFile();
371 "Error: .test-env.yml not found (searched from '{}' to project root)",
372 std::filesystem::current_path().
string());
373 return { EXIT_FAILURE };
378 YAML::Node config = YAML::LoadFile(configPath->string());
379 auto connectionStrings = config[
"ODBC_CONNECTION_STRING"];
380 if (!connectionStrings || !connectionStrings[*testEnvName])
382 std::println(stderr,
"Error: Key '{}' not found in ODBC_CONNECTION_STRING", *testEnvName);
383 if (connectionStrings && connectionStrings.IsMap())
385 std::print(stderr,
"Available environments:");
386 for (
auto const& entry: connectionStrings)
387 std::print(stderr,
" {}", entry.first.as<std::string>());
388 std::println(stderr,
"");
390 return { EXIT_FAILURE };
392 auto connStr = connectionStrings[*testEnvName].as<std::string>();
395 std::println(stderr,
"Error: Connection string for '{}' is empty", *testEnvName);
396 return { EXIT_FAILURE };
398 std::println(
"Using test environment '{}' from: {}", *testEnvName, configPath->string());
399 std::println(
"Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(connStr));
402 catch (YAML::Exception
const& e)
404 std::println(stderr,
"Error parsing {}: {}", configPath->string(), e.what());
405 return { EXIT_FAILURE };
411 char* envBuffer =
nullptr;
412 size_t envBufferLen = 0;
413 _dupenv_s(&envBuffer, &envBufferLen,
"ODBC_CONNECTION_STRING");
414 if (
auto const* s = envBuffer; s && *s)
416 if (
auto const* s = std::getenv(
"ODBC_CONNECTION_STRING"); s && *s)
420 std::println(
"Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(s));
426 std::println(
"Using default ODBC connection string: '{}'", DefaultTestConnectionString.value);
434 if (!sqlConnection.IsAlive())
436 std::println(
"Failed to connect to the database: {}", sqlConnection.LastError());
440 std::println(
"Running test cases against: {} ({}) (identified as: {})",
441 sqlConnection.ServerName(),
442 sqlConnection.ServerVersion(),
443 sqlConnection.ServerType());
445 return MainProgramArgs { argc - (i - 1), argv + (i - 1) };
452 auto const traceFile = []() -> std::string_view {
453#if !defined(_WIN32) && !defined(_WIN64)
454 return "/dev/stdout";
461 SQLSetConnectAttrA(handle, SQL_ATTR_TRACEFILE, (SQLPOINTER) traceFile.data(), SQL_NTS);
462 SQLSetConnectAttrA(handle, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_ON, SQL_IS_UINTEGER);
465 using Lightweight::SqlServerType;
468 case SqlServerType::SQLITE: {
471 stmt.ExecuteDirect(
"PRAGMA foreign_keys = ON");
474 case SqlServerType::MICROSOFT_SQL:
475 case SqlServerType::POSTGRESQL:
476 case SqlServerType::MYSQL:
477 case SqlServerType::UNKNOWN:
486 REQUIRE(stmt.IsAlive());
489 SQLSMALLINT dbNameLen {};
490 SQLGetInfo(stmt.Connection().NativeHandle(), SQL_DATABASE_NAME, dbName,
sizeof(dbName), &dbNameLen);
492 testDatabaseName = dbName;
494 DropAllTablesInDatabase(stmt);
497 virtual ~SqlTestFixture()
503 static std::string ToString(std::vector<std::string>
const& values, std::string_view separator)
505 auto result = std::string {};
506 for (
auto const& value: values)
516 Lightweight::SqlSchema::FullyQualifiedTableName
const& table)
518 auto const dependantTables = Lightweight::SqlSchema::AllForeignKeysTo(stmt, table);
519 for (
auto const& dependantTable: dependantTables)
520 DropTableRecursively(stmt, dependantTable.foreignKey.table);
521 stmt.
ExecuteDirect(std::format(
"DROP TABLE IF EXISTS \"{}\"", table.table));
529 stmt.
ExecuteDirect(std::format(
"DROP TABLE IF EXISTS {}", tableName));
539 using Lightweight::SqlServerType;
542 case SqlServerType::MICROSOFT_SQL:
543 case SqlServerType::MYSQL:
544 stmt.
ExecuteDirect(std::format(
"USE \"{}\"", testDatabaseName));
546 case SqlServerType::SQLITE:
547 case SqlServerType::UNKNOWN: {
548 auto const tableNames = GetAllTableNames(stmt);
549 for (
auto const& tableName: tableNames)
551 if (tableName ==
"sqlite_sequence")
554 DropTableRecursively(stmt,
555 Lightweight::SqlSchema::FullyQualifiedTableName {
563 case SqlServerType::POSTGRESQL:
564 if (m_createdTables.empty())
565 m_createdTables = GetAllTableNames(stmt);
566 for (
auto& createdTable: std::views::reverse(m_createdTables))
567 stmt.ExecuteDirect(std::format(
"DROP TABLE IF EXISTS \"{}\" CASCADE", createdTable));
570 m_createdTables.clear();
575 using namespace std::string_literals;
578 case Lightweight::SqlServerType::MICROSOFT_SQL:
588 using namespace std::string_literals;
589 auto result = std::vector<std::string>();
590 auto const schemaName = GetDefaultSchemaName(stmt.
Connection());
592 (SQLCHAR*) testDatabaseName.data(),
593 (SQLSMALLINT) testDatabaseName.size(),
594 (SQLCHAR*) schemaName.data(),
595 (SQLSMALLINT) schemaName.size(),
600 if (SQL_SUCCEEDED(sqlResult))
604 result.emplace_back(stmt.
GetColumn<std::string>(3));
610 static inline std::vector<std::string> m_createdTables;
616 return os << std::format(
"SqlText({})", value.value);
621 auto const ymd = date.
value();
622 return os << std::format(
"SqlDate {{ {}-{}-{} }}", ymd.year(), ymd.month(), ymd.day());
627 auto const value = time.value();
628 return os << std::format(
"SqlTime {{ {:02}:{:02}:{:02}.{:06} }}",
629 value.hours().count(),
630 value.minutes().count(),
631 value.seconds().count(),
632 value.subseconds().count());
637 auto const value = datetime.
value();
638 auto const totalDays = std::chrono::floor<std::chrono::days>(value);
639 auto const ymd = std::chrono::year_month_day { totalDays };
641 std::chrono::hh_mm_ss<std::chrono::nanoseconds> { std::chrono::floor<std::chrono::nanoseconds>(value - totalDays) };
642 return os << std::format(
"SqlDateTime {{ {:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} }}",
644 (
unsigned) ymd.month(),
645 (
unsigned) ymd.day(),
647 hms.minutes().count(),
648 hms.seconds().count(),
649 hms.subseconds().count());
652template <std::
size_t N,
typename T, Lightweight::SqlFixedStringMode Mode>
655 if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE)
656 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
657 else if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
658 return os << std::format(
"SqlTrimmedFixedString<{}> {{ '{}' }}", N, value.data());
659 else if constexpr (Mode == Lightweight::SqlFixedStringMode::VARIABLE_SIZE)
661 if constexpr (std::same_as<T, char>)
662 return os << std::format(
"SqlVariableString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.data());
665 auto u8String =
ToUtf8(std::basic_string_view<T>(value.data(), value.
size()));
666 return os << std::format(
"SqlVariableString<{}, {}> {{ size: {}, '{}' }}",
668 Reflection::TypeNameOf<T>,
670 (
char const*) u8String.c_str());
674 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
677template <std::
size_t N,
typename T>
680 if constexpr (std::same_as<T, char>)
681 return os << std::format(
"SqlDynamicString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.
data());
684 auto u8String =
ToUtf8(std::basic_string_view<T>(value.
data(), value.
size()));
685 return os << std::format(
"SqlDynamicString<{}, {}> {{ size: {}, '{}' }}",
687 Reflection::TypeNameOf<T>,
689 (
char const*) u8String.c_str());
693[[nodiscard]]
inline std::string NormalizeText(std::string_view
const& text)
695 auto result = std::string(text);
698 result.erase(std::unique(result.begin(),
700 [](
char a,
char b) { return std::isspace(a) && std::isspace(b); }),
704 while (!result.empty() && std::isspace(result.front()))
705 result.erase(result.begin());
707 while (!result.empty() && std::isspace(result.back()))
713[[nodiscard]]
inline std::string NormalizeText(std::vector<std::string>
const& texts)
715 auto result = std::string {};
716 for (
auto const& text: texts)
720 result += NormalizeText(text);
730 if (conn.
ServerType() == Lightweight::SqlServerType::SQLITE)
740 if (conn.
ServerType() == Lightweight::SqlServerType::SQLITE)
749template <
typename Func>
754 stmt.
ExecuteDirect(std::format(
"SET IDENTITY_INSERT \"{}\" ON", tableName));
757 std::forward<Func>(func)();
758 stmt.
ExecuteDirect(std::format(
"SET IDENTITY_INSERT \"{}\" OFF", tableName));
762 stmt.
ExecuteDirect(std::format(
"SET IDENTITY_INSERT \"{}\" OFF", tableName));
768 std::forward<Func>(func)();
773 std::source_location location = std::source_location::current())
778 .PrimaryKeyWithAutoIncrement(
"EmployeeID")
779 .RequiredColumn(
"FirstName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
780 .Column(
"LastName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
781 .RequiredColumn(
"Salary", Lightweight::SqlColumnTypeDefinitions::Integer {});
790 for (
char c =
'A'; c <=
'Z'; ++c)
792 table.
Column(std::string(1, c), Lightweight::SqlColumnTypeDefinitions::Varchar { 50 });
801 .Set(
"FirstName", Lightweight::SqlWildcard)
802 .Set(
"LastName", Lightweight::SqlWildcard)
803 .Set(
"Salary", Lightweight::SqlWildcard));
804 stmt.
Execute(
"Alice",
"Smith", 50'000);
805 stmt.
Execute(
"Bob",
"Johnson", 60'000);
806 stmt.
Execute(
"Charlie",
"Brown", 70'000);
809template <
typename T =
char>
810inline auto MakeLargeText(
size_t size)
812 auto text = std::basic_string<T>(size, {});
813 std::ranges::generate(text, [i = 0]()
mutable {
return static_cast<T
>(
'A' + (i++ % 26)); });
817inline bool IsGithubActions()
819#if defined(_WIN32) || defined(_WIN64)
820 char envBuffer[32] {};
821 size_t requiredCount = 0;
822 return getenv_s(&requiredCount, envBuffer,
sizeof(envBuffer),
"GITHUB_ACTIONS") == 0
823 && std::string_view(envBuffer) ==
"true" == 0;
825 return std::getenv(
"GITHUB_ACTIONS") !=
nullptr
826 && std::string_view(std::getenv(
"GITHUB_ACTIONS")) ==
"true";
834ostream& operator<<(ostream& os, optional<T>
const& opt)
839 return os <<
"nullopt";
844template <
typename T, auto P1, auto P2>
845std::ostream& operator<<(std::ostream& os,
Lightweight::Field<std::optional<T>, P1, P2>
const& field)
848 return os << std::format(
"Field<{}> {{ {}, {} }}",
849 Reflection::TypeNameOf<T>,
851 field.IsModified() ?
"modified" :
"not modified");
856template <
typename T, auto P1, auto P2>
859 return os << std::format(
"Field<{}> {{ ", Reflection::TypeNameOf<T>) <<
"value: " << field.
Value() <<
"; "
860 << (field.
IsModified() ?
"modified" :
"not modified") <<
" }";
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 constexpr decltype(auto) data(this auto &&self) noexcept
Retrieves the pointer to the string data.
LIGHTWEIGHT_FORCE_INLINE constexpr std::size_t size() const noexcept
Retrieves the size of the string.
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)
static LIGHTWEIGHT_API SqlLogger & StandardLogger()
Retrieves a logger that logs to standard output.
Query builder for building SQL migration queries.
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.
constexpr bool IsModified() const noexcept
Checks if the field has been modified.
constexpr T const & Value() const noexcept
Returns the value of the field.
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.
Represents an ODBC SQL error.
constexpr LIGHTWEIGHT_FORCE_INLINE auto ToUnscaledValue() const noexcept
Converts the numeric to an unscaled integer value.