5#if defined(_WIN32) || defined(_WIN64)
9#include <Lightweight/Lightweight.hpp>
11#include <catch2/catch_session.hpp>
12#include <catch2/catch_test_macros.hpp>
26#if __has_include(<stacktrace>)
36using WideChar = std::conditional_t<
sizeof(wchar_t) == 2,
wchar_t,
char16_t>;
37using WideString = std::basic_string<WideChar>;
38using WideStringView = std::basic_string_view<WideChar>;
40#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
52 #define WTEXT(x) (u##x)
54 #define WTEXT(x) (L##x)
57#define UNSUPPORTED_DATABASE(stmt, dbType) \
58 if ((stmt).Connection().ServerType() == (dbType)) \
60 WARN(std::format("TODO({}): This database is currently unsupported on this test.", dbType)); \
65struct std::formatter<std::u8string>: std::formatter<std::string>
67 auto format(std::u8string
const& value, std::format_context& ctx)
const -> std::format_context::iterator
69 return std::formatter<std::string>::format(
70 std::format(
"{}", (
char const*) value.c_str()),
81template <
typename W
ideStringT>
82 requires(Lightweight::detail::OneOf<WideStringT,
89ostream&
operator<<(ostream& os, WideStringT
const& str)
91 auto constexpr BitsPerChar =
sizeof(
typename WideStringT::value_type) * 8;
93 return os <<
"UTF-" << BitsPerChar <<
'{' <<
"length: " << str.size() <<
", characters: " <<
'"'
94 << string_view((
char const*) u8String.data(), u8String.size()) <<
'"' <<
'}';
99 return os << format(
"SqlGuid({})", guid);
106template <std::
size_t Precision, std::
size_t Scale>
109 return os << std::format(
"SqlNumeric<{}, {}>({}, {}, {}, {})",
113 value.sqlValue.precision,
114 value.sqlValue.scale,
129 .value = std::format(
"DRIVER={};Database={}",
130#
if defined(_WIN32) || defined(_WIN64)
131 "SQLite3 ODBC Driver",
138class TestSuiteSqlLogger:
public Lightweight::SqlLogger::Null
141 mutable std::mutex m_mutex;
142 std::string m_lastPreparedQuery;
144 void WriteRawInfo(std::string_view message);
146 template <
typename... Args>
147 void WriteInfo(std::format_string<Args...>
const& fmt, Args&&... args)
149 auto message = std::format(fmt, std::forward<Args>(args)...);
150 message = std::format(
"[{}] {}",
"Lightweight", message);
151 WriteRawInfo(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 std::lock_guard lock(m_mutex);
193 m_lastPreparedQuery = query;
196 void OnExecute(std::string_view
const& query)
override
198 WriteInfo(
"Execute: {}", query);
201 void OnExecuteBatch()
override
203 std::lock_guard lock(m_mutex);
204 WriteInfo(
"ExecuteBatch: {}", m_lastPreparedQuery);
207 void OnFetchRow()
override
209 WriteInfo(
"Fetched row");
212 void OnFetchEnd()
override
218 void WriteDetails(std::source_location sourceLocation)
220 std::lock_guard lock(m_mutex);
221 WriteInfo(
" Source: {}:{}", sourceLocation.file_name(), sourceLocation.line());
222 if (!m_lastPreparedQuery.empty())
223 WriteInfo(
" Query: {}", m_lastPreparedQuery);
224 WriteInfo(
" Stack trace:");
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]);
235class ScopedSqlNullLogger:
public Lightweight::SqlLogger::Null
238 SqlLogger& m_previousLogger = SqlLogger::GetLogger();
241 ScopedSqlNullLogger()
243 SqlLogger::SetLogger(*
this);
246 ~ScopedSqlNullLogger()
override
248 SqlLogger::SetLogger(m_previousLogger);
252template <
typename Getter,
typename Callable>
253constexpr void FixedPointIterate(Getter
const& getter, Callable
const& callable)
270 static inline std::string testDatabaseName =
"LightweightTest";
271 static inline bool odbcTrace =
false;
272 static inline std::atomic<bool> running =
false;
274 using MainProgramArgs = std::tuple<int, char**>;
276 static std::variant<MainProgramArgs, int> Initialize(
int argc,
char** argv)
280 using namespace std::string_view_literals;
282 for (; i < argc; ++i)
284 if (argv[i] ==
"--trace-sql"sv)
286 else if (argv[i] ==
"--trace-odbc"sv)
288 else if (argv[i] ==
"--help"sv || argv[i] ==
"-h"sv)
290 std::println(
"{} [--trace-sql] [--trace-odbc] [[--] [Catch2 flags ...]]", argv[0]);
291 return { EXIT_SUCCESS };
293 else if (argv[i] ==
"--"sv)
303 argv[i - 1] = argv[0];
306 char* envBuffer =
nullptr;
307 size_t envBufferLen = 0;
308 _dupenv_s(&envBuffer, &envBufferLen,
"ODBC_CONNECTION_STRING");
309 if (
auto const* s = envBuffer; s && *s)
311 if (
auto const* s = std::getenv(
"ODBC_CONNECTION_STRING"); s && *s)
315 std::println(
"Using ODBC connection string: '{}'", Lightweight::SqlConnectionString::SanitizePwd(s));
321 std::println(
"Using default ODBC connection string: '{}'", DefaultTestConnectionString.value);
328 if (!sqlConnection.IsAlive())
330 std::println(
"Failed to connect to the database: {}", sqlConnection.LastError());
334 std::println(
"Running test cases against: {} ({}) (identified as: {})",
335 sqlConnection.ServerName(),
336 sqlConnection.ServerVersion(),
337 sqlConnection.ServerType());
339 return MainProgramArgs { argc - (i - 1), argv + (i - 1) };
346 auto const traceFile = []() -> std::string_view {
347#if !defined(_WIN32) && !defined(_WIN64)
348 return "/dev/stdout";
355 SQLSetConnectAttrA(handle, SQL_ATTR_TRACEFILE, (SQLPOINTER) traceFile.data(), SQL_NTS);
356 SQLSetConnectAttrA(handle, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_ON, SQL_IS_UINTEGER);
359 using Lightweight::SqlServerType;
362 case SqlServerType::SQLITE: {
365 stmt.ExecuteDirect(
"PRAGMA foreign_keys = ON");
368 case SqlServerType::MICROSOFT_SQL:
369 case SqlServerType::POSTGRESQL:
370 case SqlServerType::ORACLE:
371 case SqlServerType::MYSQL:
372 case SqlServerType::UNKNOWN:
381 REQUIRE(stmt.IsAlive());
385 SQLSMALLINT dbNameLen {};
386 SQLGetInfo(stmt.Connection().NativeHandle(), SQL_DATABASE_NAME, dbName,
sizeof(dbName), &dbNameLen);
388 testDatabaseName = dbName;
389 else if (stmt.Connection().ServerType() == Lightweight::SqlServerType::ORACLE)
390 testDatabaseName =
"FREEPDB1";
392 DropAllTablesInDatabase(stmt);
395 virtual ~SqlTestFixture()
401 static std::string ToString(std::vector<std::string>
const& values, std::string_view separator)
403 auto result = std::string {};
404 for (
auto const& value: values)
414 Lightweight::SqlSchema::FullyQualifiedTableName
const& table)
416 auto const dependantTables = Lightweight::SqlSchema::AllForeignKeysTo(stmt, table);
417 for (
auto const& dependantTable: dependantTables)
418 DropTableRecursively(stmt, dependantTable.foreignKey.table);
419 stmt.
ExecuteDirect(std::format(
"DROP TABLE IF EXISTS \"{}\"", table.table));
424 using Lightweight::SqlServerType;
427 case SqlServerType::MICROSOFT_SQL:
428 case SqlServerType::MYSQL:
429 stmt.
ExecuteDirect(std::format(
"USE \"{}\"", testDatabaseName));
431 case SqlServerType::SQLITE:
432 case SqlServerType::ORACLE:
433 case SqlServerType::UNKNOWN: {
434 auto const tableNames = GetAllTableNames(stmt);
435 for (
auto const& tableName: tableNames)
437 if (tableName ==
"sqlite_sequence")
440 DropTableRecursively(stmt,
441 Lightweight::SqlSchema::FullyQualifiedTableName {
449 case SqlServerType::POSTGRESQL:
450 if (m_createdTables.empty())
451 m_createdTables = GetAllTableNames(stmt);
452 for (
auto& createdTable: std::views::reverse(m_createdTables))
453 stmt.ExecuteDirect(std::format(
"DROP TABLE IF EXISTS \"{}\" CASCADE", createdTable));
456 m_createdTables.clear();
462 auto result = std::vector<std::string> {};
463 stmt.
Prepare(R
"SQL(SELECT table_name
465 WHERE table_name NOT LIKE '%$%'
466 AND table_name NOT IN ('SCHEDULER_JOB_ARGS_TBL', 'SCHEDULER_PROGRAM_ARGS_TBL', 'SQLPLUS_PRODUCT_PROFILE')
467 ORDER BY table_name)SQL");
471 result.emplace_back(stmt.
GetColumn<std::string>(1));
479 return GetAllTableNamesForOracle(stmt);
481 using namespace std::string_literals;
482 auto result = std::vector<std::string>();
483 auto const schemaName = [&] {
486 case Lightweight::SqlServerType::MICROSOFT_SQL:
493 (SQLCHAR*) testDatabaseName.data(),
494 (SQLSMALLINT) testDatabaseName.size(),
495 (SQLCHAR*) schemaName.data(),
496 (SQLSMALLINT) schemaName.size(),
501 if (SQL_SUCCEEDED(sqlResult))
505 result.emplace_back(stmt.
GetColumn<std::string>(3));
511 static inline std::vector<std::string> m_createdTables;
517 return os << std::format(
"SqlText({})", value.value);
522 auto const ymd = date.
value();
523 return os << std::format(
"SqlDate {{ {}-{}-{} }}", ymd.year(), ymd.month(), ymd.day());
528 auto const value = time.value();
529 return os << std::format(
"SqlTime {{ {:02}:{:02}:{:02}.{:06} }}",
530 value.hours().count(),
531 value.minutes().count(),
532 value.seconds().count(),
533 value.subseconds().count());
538 auto const value = datetime.
value();
539 auto const totalDays = std::chrono::floor<std::chrono::days>(value);
540 auto const ymd = std::chrono::year_month_day { totalDays };
542 std::chrono::hh_mm_ss<std::chrono::nanoseconds> { std::chrono::floor<std::chrono::nanoseconds>(value - totalDays) };
543 return os << std::format(
"SqlDateTime {{ {:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} }}",
545 (
unsigned) ymd.month(),
546 (
unsigned) ymd.day(),
548 hms.minutes().count(),
549 hms.seconds().count(),
550 hms.subseconds().count());
553template <std::
size_t N,
typename T, Lightweight::SqlFixedStringMode Mode>
556 if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE)
557 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
558 else if constexpr (Mode == Lightweight::SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
559 return os << std::format(
"SqlTrimmedFixedString<{}> {{ '{}' }}", N, value.data());
560 else if constexpr (Mode == Lightweight::SqlFixedStringMode::VARIABLE_SIZE)
562 if constexpr (std::same_as<T, char>)
563 return os << std::format(
"SqlVariableString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.data());
566 auto u8String =
ToUtf8(std::basic_string_view<T>(value.data(), value.
size()));
567 return os << std::format(
"SqlVariableString<{}, {}> {{ size: {}, '{}' }}",
569 Reflection::TypeNameOf<T>,
571 (
char const*) u8String.c_str());
575 return os << std::format(
"SqlFixedString<{}> {{ size: {}, data: '{}' }}", N, value.
size(), value.data());
578template <std::
size_t N,
typename T>
581 if constexpr (std::same_as<T, char>)
582 return os << std::format(
"SqlDynamicString<{}> {{ size: {}, '{}' }}", N, value.
size(), value.
data());
585 auto u8String =
ToUtf8(std::basic_string_view<T>(value.
data(), value.
size()));
586 return os << std::format(
"SqlDynamicString<{}, {}> {{ size: {}, '{}' }}",
588 Reflection::TypeNameOf<T>,
590 (
char const*) u8String.c_str());
594[[nodiscard]]
inline std::string NormalizeText(std::string_view
const& text)
596 auto result = std::string(text);
599 result.erase(std::unique(result.begin(),
601 [](
char a,
char b) { return std::isspace(a) && std::isspace(b); }),
605 while (!result.empty() && std::isspace(result.front()))
606 result.erase(result.begin());
608 while (!result.empty() && std::isspace(result.back()))
614[[nodiscard]]
inline std::string NormalizeText(std::vector<std::string>
const& texts)
616 auto result = std::string {};
617 for (
auto const& text: texts)
621 result += NormalizeText(text);
629 std::source_location location = std::source_location::current())
634 .PrimaryKeyWithAutoIncrement(
"EmployeeID")
635 .RequiredColumn(
"FirstName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
636 .Column(
"LastName", Lightweight::SqlColumnTypeDefinitions::Varchar { 50 })
637 .RequiredColumn(
"Salary", Lightweight::SqlColumnTypeDefinitions::Integer {});
646 for (
char c =
'A'; c <=
'Z'; ++c)
648 table.
Column(std::string(1, c), Lightweight::SqlColumnTypeDefinitions::Varchar { 50 });
657 .Set(
"FirstName", Lightweight::SqlWildcard)
658 .Set(
"LastName", Lightweight::SqlWildcard)
659 .Set(
"Salary", Lightweight::SqlWildcard));
660 stmt.
Execute(
"Alice",
"Smith", 50'000);
661 stmt.
Execute(
"Bob",
"Johnson", 60'000);
662 stmt.
Execute(
"Charlie",
"Brown", 70'000);
665template <
typename T =
char>
666inline auto MakeLargeText(
size_t size)
668 auto text = std::basic_string<T>(size, {});
669 std::ranges::generate(text, [i = 0]()
mutable {
return static_cast<T
>(
'A' + (i++ % 26)); });
673inline bool IsGithubActions()
675#if defined(_WIN32) || defined(_WIN64)
676 char envBuffer[32] {};
677 size_t requiredCount = 0;
678 return getenv_s(&requiredCount, envBuffer,
sizeof(envBuffer),
"GITHUB_ACTIONS") == 0
679 && std::string_view(envBuffer) ==
"true" == 0;
681 return std::getenv(
"GITHUB_ACTIONS") !=
nullptr
682 && std::string_view(std::getenv(
"GITHUB_ACTIONS")) ==
"true";
690ostream& operator<<(ostream& os, optional<T>
const& opt)
695 return os <<
"nullopt";
700template <
typename T, auto P1, auto P2>
701std::ostream& operator<<(std::ostream& os,
Lightweight::Field<std::optional<T>, P1, P2>
const& field)
704 return os << std::format(
"Field<{}> {{ {}, {} }}",
705 Reflection::TypeNameOf<T>,
707 field.IsModified() ?
"modified" :
"not modified");
712template <
typename T, auto P1, auto P2>
715 return os << std::format(
"Field<{}> {{ ", Reflection::TypeNameOf<T>) <<
"value: " << field.
Value() <<
"; "
716 << (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)
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.