5#if defined(_WIN32) || defined(_WIN64)
9#include <Lightweight/Lightweight.hpp>
11#include <catch2/catch_session.hpp>
12#include <catch2/catch_test_macros.hpp>
25#if __has_include(<stacktrace>)
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>;
39#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
51 #define WTEXT(x) (u##x)
53 #define WTEXT(x) (L##x)
56#define UNSUPPORTED_DATABASE(stmt, dbType) \
57 if ((stmt).Connection().ServerType() == (dbType)) \
59 WARN(std::format("TODO({}): This database is currently unsupported on this test.", dbType)); \
64struct std::formatter<std::u8string>: std::formatter<std::string>
66 auto format(std::u8string
const& value, std::format_context& ctx)
const -> std::format_context::iterator
68 return std::formatter<std::string>::format(
69 std::format(
"{}", (
char const*) value.c_str()),
80template <
typename W
ideStringT>
81 requires(Lightweight::detail::OneOf<WideStringT,
88ostream&
operator<<(ostream& os, WideStringT
const& str)
90 auto constexpr BitsPerChar =
sizeof(
typename WideStringT::value_type) * 8;
92 return os <<
"UTF-" << BitsPerChar <<
'{' <<
"length: " << str.size() <<
", characters: " <<
'"'
93 << string_view((
char const*) u8String.data(), u8String.size()) <<
'"' <<
'}';
98 return os << format(
"SqlGuid({})", guid);
105template <std::
size_t Precision, std::
size_t Scale>
108 return os << std::format(
"SqlNumeric<{}, {}>({}, {}, {}, {})",
125 .value = std::format(
"DRIVER={};Database={}",
126#
if defined(_WIN32) || defined(_WIN64)
127 "SQLite3 ODBC Driver",
134class TestSuiteSqlLogger:
public Lightweight::SqlLogger::Null
137 std::string m_lastPreparedQuery;
139 template <
typename... Args>
140 void WriteInfo(std::format_string<Args...>
const& fmt, Args&&... args)
142 auto message = std::format(fmt, std::forward<Args>(args)...);
143 message = std::format(
"[{}] {}",
"Lightweight", message);
146 UNSCOPED_INFO(message);
150 std::println(
"{}", message);
154 template <
typename... Args>
155 void WriteWarning(std::format_string<Args...>
const& fmt, Args&&... args)
157 WARN(std::format(fmt, std::forward<Args>(args)...));
161 static TestSuiteSqlLogger& GetLogger() noexcept
163 static TestSuiteSqlLogger theLogger;
167 void OnError(Lightweight::SqlError error, std::source_location sourceLocation)
override
169 WriteWarning(
"SQL Error: {}", error);
170 WriteDetails(sourceLocation);
175 WriteWarning(
"SQL Error: {}", errorInfo);
176 WriteDetails(sourceLocation);
179 void OnWarning(std::string_view
const& message)
override
181 WriteWarning(
"{}", message);
182 WriteDetails(std::source_location::current());
185 void OnExecuteDirect(std::string_view
const& query)
override
187 WriteInfo(
"ExecuteDirect: {}", query);
190 void OnPrepare(std::string_view
const& query)
override
192 m_lastPreparedQuery = query;
195 void OnExecute(std::string_view
const& query)
override
197 WriteInfo(
"Execute: {}", query);
200 void OnExecuteBatch()
override
202 WriteInfo(
"ExecuteBatch: {}", m_lastPreparedQuery);
205 void OnFetchRow()
override
207 WriteInfo(
"Fetched row");
210 void OnFetchEnd()
override
212 WriteInfo(
"Fetch end");
216 void WriteDetails(std::source_location sourceLocation)
218 WriteInfo(
" Source: {}:{}", sourceLocation.file_name(), sourceLocation.line());
219 if (!m_lastPreparedQuery.empty())
220 WriteInfo(
" Query: {}", m_lastPreparedQuery);
221 WriteInfo(
" Stack trace:");
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]);
232class ScopedSqlNullLogger:
public Lightweight::SqlLogger::Null
235 SqlLogger& m_previousLogger = SqlLogger::GetLogger();
238 ScopedSqlNullLogger()
240 SqlLogger::SetLogger(*
this);
243 ~ScopedSqlNullLogger()
override
245 SqlLogger::SetLogger(m_previousLogger);
249template <
typename Getter,
typename Callable>
250constexpr void FixedPointIterate(Getter
const& getter, Callable
const& callable)
267 static inline std::string testDatabaseName =
"LightweightTest";
268 static inline bool odbcTrace =
false;
270 using MainProgramArgs = std::tuple<int, char**>;
272 static std::variant<MainProgramArgs, int> Initialize(
int argc,
char** argv)
276 using namespace std::string_view_literals;
278 for (; i < argc; ++i)
280 if (argv[i] ==
"--trace-sql"sv)
282 else if (argv[i] ==
"--trace-odbc"sv)
284 else if (argv[i] ==
"--help"sv || argv[i] ==
"-h"sv)
286 std::println(
"{} [--trace-sql] [--trace-odbc] [[--] [Catch2 flags ...]]", argv[0]);
287 return { EXIT_SUCCESS };
289 else if (argv[i] ==
"--"sv)
299 argv[i - 1] = argv[0];
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)
307 if (
auto const* s = std::getenv(
"ODBC_CONNECTION_STRING"); s && *s)
311 std::println(
"Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(s));
317 std::println(
"Using default ODBC connection string: '{}'", DefaultTestConnectionString.value);
324 if (!sqlConnection.IsAlive())
326 std::println(
"Failed to connect to the database: {}", sqlConnection.LastError());
330 std::println(
"Running test cases against: {} ({}) (identified as: {})",
331 sqlConnection.ServerName(),
332 sqlConnection.ServerVersion(),
333 sqlConnection.ServerType());
335 return MainProgramArgs { argc - (i - 1), argv + (i - 1) };
342 auto const traceFile = []() -> std::string_view {
343#if !defined(_WIN32) && !defined(_WIN64)
344 return "/dev/stdout";
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);
355 using Lightweight::SqlServerType;
358 case SqlServerType::SQLITE: {
361 stmt.ExecuteDirect(
"PRAGMA foreign_keys = ON");
364 case SqlServerType::MICROSOFT_SQL:
365 case SqlServerType::POSTGRESQL:
366 case SqlServerType::ORACLE:
367 case SqlServerType::MYSQL:
368 case SqlServerType::UNKNOWN:
376 REQUIRE(stmt.IsAlive());
380 SQLSMALLINT dbNameLen {};
381 SQLGetInfo(stmt.Connection().NativeHandle(), SQL_DATABASE_NAME, dbName,
sizeof(dbName), &dbNameLen);
383 testDatabaseName = dbName;
384 else if (stmt.Connection().ServerType() == Lightweight::SqlServerType::ORACLE)
385 testDatabaseName =
"FREEPDB1";
387 DropAllTablesInDatabase(stmt);
390 virtual ~SqlTestFixture() =
default;
392 static std::string ToString(std::vector<std::string>
const& values, std::string_view separator)
394 auto result = std::string {};
395 for (
auto const& value: values)
405 Lightweight::SqlSchema::FullyQualifiedTableName
const& table)
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));
415 using Lightweight::SqlServerType;
418 case SqlServerType::MICROSOFT_SQL:
419 case SqlServerType::MYSQL:
420 stmt.
ExecuteDirect(std::format(
"USE \"{}\"", testDatabaseName));
422 case SqlServerType::SQLITE:
423 case SqlServerType::ORACLE:
424 case SqlServerType::UNKNOWN: {
425 auto const tableNames = GetAllTableNames(stmt);
426 for (
auto const& tableName: tableNames)
428 if (tableName ==
"sqlite_sequence")
431 DropTableRecursively(stmt,
432 Lightweight::SqlSchema::FullyQualifiedTableName {
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));
447 m_createdTables.clear();
453 auto result = std::vector<std::string> {};
454 stmt.
Prepare(R
"SQL(SELECT table_name
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");
462 result.emplace_back(stmt.
GetColumn<std::string>(1));
470 return GetAllTableNamesForOracle(stmt);
472 using namespace std::string_literals;
473 auto result = std::vector<std::string>();
474 auto const schemaName = [&] {
477 case Lightweight::SqlServerType::MICROSOFT_SQL:
484 (SQLCHAR*) testDatabaseName.data(),
485 (SQLSMALLINT) testDatabaseName.size(),
486 (SQLCHAR*) schemaName.data(),
487 (SQLSMALLINT) schemaName.size(),
492 if (SQL_SUCCEEDED(sqlResult))
496 result.emplace_back(stmt.
GetColumn<std::string>(3));
502 static inline std::vector<std::string> m_createdTables;
508 return os << std::format(
"SqlText({})", value.value);
513 auto const ymd = date.
value();
514 return os << std::format(
"SqlDate {{ {}-{}-{} }}", ymd.year(), ymd.month(), ymd.day());
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());
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 };
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} }}",
536 (
unsigned) ymd.month(),
537 (
unsigned) ymd.day(),
539 hms.minutes().count(),
540 hms.seconds().count(),
541 hms.subseconds().count());
544template <std::
size_t N,
typename T, Lightweight::SqlFixedStringMode Mode>
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)
553 if constexpr (std::same_as<T, char>)
554 return os << std::format(
"SqlVariableString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.data());
557 auto u8String =
ToUtf8(std::basic_string_view<T>(value.data(), value.
size()));
558 return os << std::format(
"SqlVariableString<{}, {}> {{ size: {}, '{}' }}",
560 Reflection::TypeNameOf<T>,
562 (
char const*) u8String.c_str());
566 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
569template <std::
size_t N,
typename T>
572 if constexpr (std::same_as<T, char>)
573 return os << std::format(
"SqlDynamicString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.
data());
576 auto u8String =
ToUtf8(std::basic_string_view<T>(value.
data(), value.
size()));
577 return os << std::format(
"SqlDynamicString<{}, {}> {{ size: {}, '{}' }}",
579 Reflection::TypeNameOf<T>,
581 (
char const*) u8String.c_str());
585[[nodiscard]]
inline std::string NormalizeText(std::string_view
const& text)
587 auto result = std::string(text);
590 result.erase(std::unique(result.begin(),
592 [](
char a,
char b) { return std::isspace(a) && std::isspace(b); }),
596 while (!result.empty() && std::isspace(result.front()))
597 result.erase(result.begin());
599 while (!result.empty() && std::isspace(result.back()))
605[[nodiscard]]
inline std::string NormalizeText(std::vector<std::string>
const& texts)
607 auto result = std::string {};
608 for (
auto const& text: texts)
612 result += NormalizeText(text);
620 std::source_location location = std::source_location::current())
625 .PrimaryKeyWithAutoIncrement(
"EmployeeID")
626 .RequiredColumn(
"FirstName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
627 .Column(
"LastName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
628 .RequiredColumn(
"Salary", Lightweight::SqlColumnTypeDefinitions::Integer {});
637 for (
char c =
'A'; c <=
'Z'; ++c)
639 table.
Column(std::string(1, c), Lightweight::SqlColumnTypeDefinitions::Varchar { 50 });
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);
656template <
typename T =
char>
657inline auto MakeLargeText(
size_t size)
659 auto text = std::basic_string<T>(size, {});
660 std::ranges::generate(text, [i = 0]()
mutable {
return static_cast<T
>(
'A' + (i++ % 26)); });
664inline bool IsGithubActions()
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;
672 return std::getenv(
"GITHUB_ACTIONS") !=
nullptr && std::string_view(std::getenv(
"GITHUB_ACTIONS")) ==
"true";
680ostream& operator<<(ostream& os, optional<T>
const& opt)
685 return os <<
"nullopt";
690template <
typename T, auto P1, auto P2>
691std::ostream& operator<<(std::ostream& os,
Lightweight::Field<std::optional<T>, P1, P2>
const& field)
694 return os << std::format(
"Field<{}> {{ {}, {} }}",
695 Reflection::TypeNameOf<T>,
697 field.IsModified() ?
"modified" :
"not modified");
702template <
typename T, auto P1, auto P2>
705 return os << std::format(
"Field<{}> {{ ", Reflection::TypeNameOf<T>) <<
"value: " << field.
Value() <<
"; "
706 << (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 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.
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.
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.