Lightweight 0.20260303.0
Loading...
Searching...
No Matches
SqlScopedTraceLogger.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include "Api.hpp"
6#include "SqlConnection.hpp"
7#include "SqlOdbcWide.hpp"
8#include "SqlStatement.hpp"
9
10#include <filesystem>
11
12namespace Lightweight
13{
14
15/// @brief Enables protocol-level ODBC trace logging for the given connection.
16///
17/// The trace logging is active for the lifetime of this object.
18///
19/// The logging output is sent to the standard output stream.
20class LIGHTWEIGHT_API SqlScopedTraceLogger
21{
22 SQLHDBC m_nativeConnection;
23
24 public:
25 /// Constructs a scoped trace logger for the given SQL connection, logging to standard output.
26 explicit SqlScopedTraceLogger(SqlConnection& connection):
27 SqlScopedTraceLogger(connection.NativeHandle(),
28#if defined(_WIN32) || defined(_WIN64)
29 "CONOUT$"
30#else
31 "/dev/stdout"
32#endif
33 )
34 {
35 }
36
37 /// Constructs a scoped trace logger for the given SQL statement, logging to standard output.
39 SqlScopedTraceLogger(stmt.Connection().NativeHandle(),
40#if defined(_WIN32) || defined(_WIN64)
41 "CONOUT$"
42#else
43 "/dev/stdout"
44#endif
45 )
46 {
47 }
48
49 /// Constructs a scoped trace logger for the given native ODBC handle, logging to the specified file.
50 explicit SqlScopedTraceLogger(SQLHDBC hDbc, std::filesystem::path const& logFile):
51 m_nativeConnection { hDbc }
52 {
53 // Stay on the W path: the rest of the library puts the DBC handle into Unicode-app
54 // mode at connect time, so passing an ANSI trace-file name here would mix variants
55 // unnecessarily. `path::u16string()` does the platform-correct conversion (UTF-16
56 // is path's native form on Windows; UTF-8 → UTF-16 on POSIX).
57 auto wLogFile = logFile.u16string();
58 SQLSetConnectAttrW(m_nativeConnection, SQL_ATTR_TRACEFILE, detail::AsSqlWChar(wLogFile.data()), SQL_NTS);
59 SQLSetConnectAttrW(m_nativeConnection, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_ON, SQL_IS_UINTEGER);
60 }
61
63 SqlScopedTraceLogger& operator=(SqlScopedTraceLogger&&) = delete;
65 SqlScopedTraceLogger& operator=(SqlScopedTraceLogger const&) = delete;
66
68 {
69 SQLSetConnectAttrW(m_nativeConnection, SQL_ATTR_TRACE, (SQLPOINTER) SQL_OPT_TRACE_OFF, SQL_IS_UINTEGER);
70 }
71};
72
73} // namespace Lightweight
Represents a connection to a SQL database.
Enables protocol-level ODBC trace logging for the given connection.
SqlScopedTraceLogger(SQLHDBC hDbc, std::filesystem::path const &logFile)
Constructs a scoped trace logger for the given native ODBC handle, logging to the specified file.
SqlScopedTraceLogger(SqlStatement &stmt)
Constructs a scoped trace logger for the given SQL statement, logging to standard output.
SqlScopedTraceLogger(SqlConnection &connection)
Constructs a scoped trace logger for the given SQL connection, logging to standard output.
High level API for (prepared) raw SQL statements.