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 (
auto const& entry: stackTrace)
251 WriteInfo(
" {}", entry);
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**>;
324 static std::variant<MainProgramArgs, int> Initialize(
int argc,
char** argv)
328 using namespace std::string_view_literals;
329 std::optional<std::string> testEnvName;
331 for (; i < argc; ++i)
333 if (argv[i] ==
"--trace-sql"sv)
335 else if (argv[i] ==
"--trace-odbc"sv)
337 else if (std::string_view(argv[i]).starts_with(
"--test-env="))
338 testEnvName = std::string_view(argv[i]).substr(11);
339 else if (argv[i] ==
"--help"sv || argv[i] ==
"-h"sv)
341 std::println(
"{} [--test-env=NAME] [--trace-sql] [--trace-odbc] [[--] [Catch2 flags ...]]", argv[0]);
343 std::println(
"Options:");
344 std::println(
" --test-env=NAME Use connection string from .test-env.yml (e.g., pgsql, mssql, sqlite)");
345 std::println(
" --trace-sql Enable SQL tracing");
346 std::println(
" --trace-odbc Enable ODBC tracing");
347 return { EXIT_SUCCESS };
349 else if (argv[i] ==
"--"sv)
359 argv[i - 1] = argv[0];
368 auto configPath = FindTestEnvFile();
372 "Error: .test-env.yml not found (searched from '{}' to project root)",
373 std::filesystem::current_path().
string());
374 return { EXIT_FAILURE };
379 YAML::Node config = YAML::LoadFile(configPath->string());
380 auto connectionStrings = config[
"ODBC_CONNECTION_STRING"];
381 if (!connectionStrings || !connectionStrings[*testEnvName])
383 std::println(stderr,
"Error: Key '{}' not found in ODBC_CONNECTION_STRING", *testEnvName);
384 if (connectionStrings && connectionStrings.IsMap())
386 std::print(stderr,
"Available environments:");
387 for (
auto const& entry: connectionStrings)
388 std::print(stderr,
" {}", entry.first.as<std::string>());
389 std::println(stderr,
"");
391 return { EXIT_FAILURE };
393 auto connStr = connectionStrings[*testEnvName].as<std::string>();
396 std::println(stderr,
"Error: Connection string for '{}' is empty", *testEnvName);
397 return { EXIT_FAILURE };
399 std::println(
"Using test environment '{}' from: {}", *testEnvName, configPath->string());
400 std::println(
"Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(connStr));
403 catch (YAML::Exception
const& e)
405 std::println(stderr,
"Error parsing {}: {}", configPath->string(), e.what());
406 return { EXIT_FAILURE };
412 char* envBuffer =
nullptr;
413 size_t envBufferLen = 0;
414 _dupenv_s(&envBuffer, &envBufferLen,
"ODBC_CONNECTION_STRING");
415 if (
auto const* s = envBuffer; s && *s)
417 if (
auto const* s = std::getenv(
"ODBC_CONNECTION_STRING"); s && *s)
421 std::println(
"Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(s));
427 std::println(
"Using default ODBC connection string: '{}'", DefaultTestConnectionString.value);
435 if (!sqlConnection.IsAlive())
437 std::println(
"Failed to connect to the database: {}", sqlConnection.LastError());
441 std::println(
"Running test cases against: {} ({}) (identified as: {})",
442 sqlConnection.ServerName(),
443 sqlConnection.ServerVersion(),
444 sqlConnection.ServerType());
446 return MainProgramArgs { argc - (i - 1), argv + (i - 1) };
453 auto const traceFile = []() -> std::string_view {
454#if !defined(_WIN32) && !defined(_WIN64)
455 return "/dev/stdout";
462 SQLSetConnectAttrA(handle, SQL_ATTR_TRACEFILE, (SQLPOINTER) traceFile.data(), SQL_NTS);
463 SQLSetConnectAttrA(handle, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_ON, SQL_IS_UINTEGER);
466 using Lightweight::SqlServerType;
469 case SqlServerType::SQLITE: {
472 stmt.ExecuteDirect(
"PRAGMA foreign_keys = ON");
475 case SqlServerType::MICROSOFT_SQL:
476 case SqlServerType::POSTGRESQL:
477 case SqlServerType::MYSQL:
478 case SqlServerType::UNKNOWN:
487 REQUIRE(stmt.IsAlive());
490 SQLSMALLINT dbNameLen {};
491 SQLGetInfo(stmt.Connection().NativeHandle(), SQL_DATABASE_NAME, dbName,
sizeof(dbName), &dbNameLen);
493 testDatabaseName = dbName;
495 DropAllTablesInDatabase(stmt);
498 virtual ~SqlTestFixture()
504 static std::string ToString(std::vector<std::string>
const& values, std::string_view separator)
506 auto result = std::string {};
507 for (
auto const& value: values)
517 Lightweight::SqlSchema::FullyQualifiedTableName
const& table)
519 auto const dependantTables = Lightweight::SqlSchema::AllForeignKeysTo(stmt, table);
520 for (
auto const& dependantTable: dependantTables)
521 DropTableRecursively(stmt, dependantTable.foreignKey.table);
522 stmt.
ExecuteDirect(std::format(
"DROP TABLE IF EXISTS \"{}\"", table.table));
530 stmt.
ExecuteDirect(std::format(
"DROP TABLE IF EXISTS {}", tableName));
540 using Lightweight::SqlServerType;
543 case SqlServerType::MICROSOFT_SQL:
544 case SqlServerType::MYSQL:
545 stmt.
ExecuteDirect(std::format(
"USE \"{}\"", testDatabaseName));
547 case SqlServerType::SQLITE:
548 case SqlServerType::UNKNOWN: {
549 auto const tableNames = GetAllTableNames(stmt);
550 for (
auto const& tableName: tableNames)
552 if (tableName ==
"sqlite_sequence")
555 DropTableRecursively(stmt,
556 Lightweight::SqlSchema::FullyQualifiedTableName {
564 case SqlServerType::POSTGRESQL:
565 if (m_createdTables.empty())
566 m_createdTables = GetAllTableNames(stmt);
567 for (
auto& createdTable: std::views::reverse(m_createdTables))
568 stmt.ExecuteDirect(std::format(
"DROP TABLE IF EXISTS \"{}\" CASCADE", createdTable));
571 m_createdTables.clear();
576 using namespace std::string_literals;
579 case Lightweight::SqlServerType::MICROSOFT_SQL:
589 using namespace std::string_literals;
590 auto result = std::vector<std::string>();
591 auto const schemaName = GetDefaultSchemaName(stmt.
Connection());
593 (SQLCHAR*) testDatabaseName.data(),
594 (SQLSMALLINT) testDatabaseName.size(),
595 (SQLCHAR*) schemaName.data(),
596 (SQLSMALLINT) schemaName.size(),
601 if (SQL_SUCCEEDED(sqlResult))
605 result.emplace_back(stmt.
GetColumn<std::string>(3));
611 static inline std::vector<std::string> m_createdTables;
617 return os << std::format(
"SqlText({})", value.value);
622 auto const ymd = date.
value();
623 return os << std::format(
"SqlDate {{ {}-{}-{} }}", ymd.year(), ymd.month(), ymd.day());
628 auto const value = time.value();
629 return os << std::format(
"SqlTime {{ {:02}:{:02}:{:02}.{:06} }}",
630 value.hours().count(),
631 value.minutes().count(),
632 value.seconds().count(),
633 value.subseconds().count());
638 auto const value = datetime.
value();
639 auto const totalDays = std::chrono::floor<std::chrono::days>(value);
640 auto const ymd = std::chrono::year_month_day { totalDays };
642 std::chrono::hh_mm_ss<std::chrono::nanoseconds> { std::chrono::floor<std::chrono::nanoseconds>(value - totalDays) };
643 return os << std::format(
"SqlDateTime {{ {:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} }}",
645 (
unsigned) ymd.month(),
646 (
unsigned) ymd.day(),
648 hms.minutes().count(),
649 hms.seconds().count(),
650 hms.subseconds().count());
653template <std::
size_t N,
typename T, Lightweight::SqlFixedStringMode Mode>
656 if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE)
657 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
658 else if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
659 return os << std::format(
"SqlTrimmedFixedString<{}> {{ '{}' }}", N, value.data());
660 else if constexpr (Mode == Lightweight::SqlFixedStringMode::VARIABLE_SIZE)
662 if constexpr (std::same_as<T, char>)
663 return os << std::format(
"SqlVariableString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.data());
666 auto u8String =
ToUtf8(std::basic_string_view<T>(value.data(), value.
size()));
667 return os << std::format(
"SqlVariableString<{}, {}> {{ size: {}, '{}' }}",
669 Reflection::TypeNameOf<T>,
671 (
char const*) u8String.c_str());
675 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
678template <std::
size_t N,
typename T>
681 if constexpr (std::same_as<T, char>)
682 return os << std::format(
"SqlDynamicString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.
data());
685 auto u8String =
ToUtf8(std::basic_string_view<T>(value.
data(), value.
size()));
686 return os << std::format(
"SqlDynamicString<{}, {}> {{ size: {}, '{}' }}",
688 Reflection::TypeNameOf<T>,
690 (
char const*) u8String.c_str());
694[[nodiscard]]
inline std::string NormalizeText(std::string_view
const& text)
696 auto result = std::string(text);
699 result.erase(std::unique(result.begin(),
701 [](
char a,
char b) { return std::isspace(a) && std::isspace(b); }),
705 while (!result.empty() && std::isspace(result.front()))
706 result.erase(result.begin());
708 while (!result.empty() && std::isspace(result.back()))
714[[nodiscard]]
inline std::string NormalizeText(std::vector<std::string>
const& texts)
716 auto result = std::string {};
717 for (
auto const& text: texts)
721 result += NormalizeText(text);
731 if (conn.
ServerType() == Lightweight::SqlServerType::SQLITE)
741 if (conn.
ServerType() == Lightweight::SqlServerType::SQLITE)
750template <
typename Func>
755 stmt.
ExecuteDirect(std::format(
"SET IDENTITY_INSERT \"{}\" ON", tableName));
758 std::forward<Func>(func)();
759 stmt.
ExecuteDirect(std::format(
"SET IDENTITY_INSERT \"{}\" OFF", tableName));
763 stmt.
ExecuteDirect(std::format(
"SET IDENTITY_INSERT \"{}\" OFF", tableName));
769 std::forward<Func>(func)();
774 std::source_location location = std::source_location::current())
779 .PrimaryKeyWithAutoIncrement(
"EmployeeID")
780 .RequiredColumn(
"FirstName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
781 .Column(
"LastName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
782 .RequiredColumn(
"Salary", Lightweight::SqlColumnTypeDefinitions::Integer {});
791 for (
char c =
'A'; c <=
'Z'; ++c)
793 table.
Column(std::string(1, c), Lightweight::SqlColumnTypeDefinitions::Varchar { 50 });
802 .Set(
"FirstName", Lightweight::SqlWildcard)
803 .Set(
"LastName", Lightweight::SqlWildcard)
804 .Set(
"Salary", Lightweight::SqlWildcard));
805 stmt.
Execute(
"Alice",
"Smith", 50'000);
806 stmt.
Execute(
"Bob",
"Johnson", 60'000);
807 stmt.
Execute(
"Charlie",
"Brown", 70'000);
810template <
typename T =
char>
811inline auto MakeLargeText(
size_t size)
813 auto text = std::basic_string<T>(size, {});
814 std::ranges::generate(text, [i = 0]()
mutable {
return static_cast<T
>(
'A' + (i++ % 26)); });
818inline bool IsGithubActions()
820#if defined(_WIN32) || defined(_WIN64)
821 char envBuffer[32] {};
822 size_t requiredCount = 0;
823 return getenv_s(&requiredCount, envBuffer,
sizeof(envBuffer),
"GITHUB_ACTIONS") == 0
824 && std::string_view(envBuffer) ==
"true" == 0;
826 return std::getenv(
"GITHUB_ACTIONS") !=
nullptr
827 && std::string_view(std::getenv(
"GITHUB_ACTIONS")) ==
"true";
835ostream& operator<<(ostream& os, optional<T>
const& opt)
840 return os <<
"nullopt";
845template <
typename T, auto P1, auto P2>
846std::ostream& operator<<(std::ostream& os,
Lightweight::Field<std::optional<T>, P1, P2>
const& field)
849 return os << std::format(
"Field<{}> {{ {}, {} }}",
850 Reflection::TypeNameOf<T>,
852 field.IsModified() ?
"modified" :
"not modified");
857template <
typename T, auto P1, auto P2>
860 return os << std::format(
"Field<{}> {{ ", Reflection::TypeNameOf<T>) <<
"value: " << field.
Value() <<
"; "
861 << (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.