7#include "Async/Fwd.hpp"
8#include "SqlConnectInfo.hpp"
10#include "SqlLogger.hpp"
11#include "SqlOdbcPrelude.hpp"
12#include "SqlRetryPolicy.hpp"
13#include "SqlServerType.hpp"
25#include <system_error>
43class SqlMigrationQueryBuilder;
44class SqlQueryFormatter;
45class SqlPreparedStatementCache;
109inline constexpr std::chrono::milliseconds SqliteBusyTimeoutDefault { 60'000 };
166 LIGHTWEIGHT_API
explicit SqlConnection(std::optional<SqlConnectionString> connectInfo);
265 return m_stringTruncationMode;
354 return m_connectionId;
364 LIGHTWEIGHT_API
void Close() noexcept;
395 [[nodiscard]] LIGHTWEIGHT_API std::
string UserName() const;
398 [[nodiscard]] LIGHTWEIGHT_API std::
string ServerName() const;
404 [[nodiscard]] SqlServerType
ServerType() const noexcept;
407 [[nodiscard]] std::
string const&
DriverName() const noexcept;
557 std::string_view
const& tableAlias)
const;
581 [[nodiscard]] LIGHTWEIGHT_API
bool IsAlive() const noexcept;
593 [[nodiscard]] LIGHTWEIGHT_API std::chrono::steady_clock::time_point
LastUsed() const noexcept;
596 LIGHTWEIGHT_API
void SetLastUsed(std::chrono::steady_clock::time_point lastUsed) noexcept;
600 std::source_location sourceLocation = std::source_location::current()) const;
617 LIGHTWEIGHT_API
void EnableAsync(Async::IExecutor& dbWorkers, Async::IResumeScheduler& resume);
627 LIGHTWEIGHT_API
void EnableAsync(std::unique_ptr<Async::IAsyncBackend> backend);
669 void EnsureHandlesAllocated();
673 [[nodiscard]]
bool PostConnect();
679 [[nodiscard]] std::expected<void, SqlErrorInfo> ConnectOnce() noexcept;
683 template <typename Attempt>
684 [[nodiscard]]
bool ConnectWithRetry(Attempt const& attempt) noexcept;
689 [[nodiscard]] std::expected<
void,
SqlErrorInfo> ApplySqliteSettings();
692 void ApplyPreparedStatementCacheCapacity() noexcept;
696 void ApplyStringTruncationMode();
700 void ReadStringTruncationMode();
707 uint64_t m_connectionId;
708 SqlServerType m_serverType = SqlServerType::UNKNOWN;
709 SqlQueryFormatter
const* m_queryFormatter {};
710 std::string m_driverName;
711 bool m_acceptsWideQueryText =
true;
731 return m_acceptsWideQueryText;
736 return *m_queryFormatter;
746 case SqlServerType::MICROSOFT_SQL:
747 case SqlServerType::POSTGRESQL:
748 case SqlServerType::SQLITE:
750 case SqlServerType::MYSQL:
751 case SqlServerType::UNKNOWN:
764 case SqlServerType::MICROSOFT_SQL:
765 case SqlServerType::POSTGRESQL:
766 case SqlServerType::SQLITE:
768 case SqlServerType::MYSQL:
769 case SqlServerType::UNKNOWN:
787 case SqlServerType::MICROSOFT_SQL:
788 case SqlServerType::POSTGRESQL:
789 case SqlServerType::SQLITE:
791 case SqlServerType::MYSQL:
792 case SqlServerType::UNKNOWN:
807 case SqlServerType::MICROSOFT_SQL:
808 case SqlServerType::SQLITE:
810 case SqlServerType::POSTGRESQL:
811 case SqlServerType::MYSQL:
812 case SqlServerType::UNKNOWN:
Represents a connection to a SQL database.
LIGHTWEIGHT_API void RequireSuccess(SQLRETURN sqlResult, std::source_location sourceLocation=std::source_location::current()) const
Checks the result of an SQL operation, and throws an exception if it is not successful.
static LIGHTWEIGHT_API void ResetPostConnectedHook()
Resets the post connected hook.
LIGHTWEIGHT_API std::expected< void, SqlErrorInfo > SetSqliteSettings(SqliteConnectionSettings const &settings)
Changes this connection's SQLite settings, applying them immediately when the connection is open to a...
LIGHTWEIGHT_API void DisableAsync() noexcept
static LIGHTWEIGHT_API void SetDefaultConnectRetrySettings(SqlRetrySettings const &settings)
Sets the connect-retry settings newly constructed connections adopt.
LIGHTWEIGHT_API std::string ServerName() const
Retrieves the name of the server.
SqlServerType ServerType() const noexcept
Retrieves the type of the server.
LIGHTWEIGHT_API SqlMigrationQueryBuilder Migration() const
Creates a new migration query builder, compatible the current connection.
LIGHTWEIGHT_API bool TransactionActive() const noexcept
Tests if a transaction is active.
LIGHTWEIGHT_API SqlPreparedStatementCache & PreparedStatementCache() noexcept
Retrieves this connection's prepared-statement cache.
static LIGHTWEIGHT_API void SetDefaultSqliteSettings(SqliteConnectionSettings const &settings)
Sets the SQLite settings newly constructed connections adopt.
LIGHTWEIGHT_API std::size_t PreparedStatementCacheCapacity() const noexcept
The capacity of this connection's prepared-statement cache.
LIGHTWEIGHT_API bool IsAlive() const noexcept
Tests if the connection is still active.
LIGHTWEIGHT_API SqlQueryBuilder Query(std::string_view const &table={}) const
static LIGHTWEIGHT_API SqlConnection Borrow(SQLHDBC connectedHandle)
Wraps an ODBC connection handle that another component allocated, connected and keeps owning.
LIGHTWEIGHT_API SqlQueryBuilder QueryAs(std::string_view const &table, std::string_view const &tableAlias) const
LIGHTWEIGHT_API void SetConnectRetrySettings(SqlRetrySettings const &settings, SqlRetrySleeper *sleeper=nullptr) noexcept
Changes how this connection's Connect() retries a connect that failed transiently.
static LIGHTWEIGHT_API SqlStringTruncationMode DefaultStringTruncationMode() noexcept
LIGHTWEIGHT_API SqlRetrySettings const & ConnectRetrySettings() const noexcept
This connection's connect-retry settings.
LIGHTWEIGHT_API SqlConnection(std::optional< SqlConnectionString > connectInfo)
Constructs a new SQL connection to the given connect informaton.
static LIGHTWEIGHT_API std::uint32_t DefaultConnectionStringGeneration() noexcept
LIGHTWEIGHT_API void SetPreparedStatementCacheCapacity(std::size_t capacity) noexcept
Enables (or resizes) this connection's prepared-statement cache.
LIGHTWEIGHT_API bool TransactionsAllowed() const noexcept
Tests if transactions are allowed.
LIGHTWEIGHT_API void ClearPreparedStatementCache() noexcept
Frees every pooled prepared statement handle, e.g. after DDL invalidated the cached query plans.
uint64_t ConnectionId() const noexcept
Retrieves the connection ID.
SqlStringTruncationMode StringTruncationMode() const noexcept
This connection's string-truncation mode. See SqlStringTruncationMode.
static bool RoundTripsNarrowTextByteExact(SqlServerType serverType) noexcept
Whether serverType's driver round-trips narrow (SQL_C_CHAR) character data byte-exact,...
SqlQueryFormatter const & QueryFormatter() const noexcept
Retrieves a query formatter suitable for the SQL server being connected.
bool SupportsNativeRowArrayFetch() const noexcept
Whether this connection's ODBC driver supports native row-array fetching (SQL_ATTR_ROW_ARRAY_SIZE > 1...
static LIGHTWEIGHT_API SqlConnectionString const & DefaultConnectionString()
LIGHTWEIGHT_API void SetLastUsed(std::chrono::steady_clock::time_point lastUsed) noexcept
Sets the last time the connection was used.
static LIGHTWEIGHT_API SqliteConnectionSettings DefaultSqliteSettings()
The SQLite settings a newly constructed connection adopts.
LIGHTWEIGHT_API void Close() noexcept
LIGHTWEIGHT_API bool IsAsyncEnabled() const noexcept
LIGHTWEIGHT_API Async::IAsyncBackend & AsyncBackend()
LIGHTWEIGHT_API SqlConnection(std::optional< SqlConnectionString > connectInfo, SqliteConnectionSettings sqliteSettings)
Constructs a new SQL connection with explicit SQLite connection settings.
static LIGHTWEIGHT_API void SetDefaultConnectionString(SqlConnectionString const &connectionString)
bool AcceptsWideQueryText() const noexcept
LIGHTWEIGHT_API void SetDefaultPrefetchDepth(std::size_t depth) noexcept
Sets the default block-prefetch depth for statements created on this connection.
LIGHTWEIGHT_API SqlErrorInfo LastError() const
Retrieves the last error information with respect to this SQL connection handle.
LIGHTWEIGHT_API SqlConnection()
Constructs a new SQL connection to the default connection.
LIGHTWEIGHT_API SqlConnection(SqlConnection &&) noexcept
Move constructor.
static LIGHTWEIGHT_API void SetDefaultStringTruncationMode(SqlStringTruncationMode mode) noexcept
LIGHTWEIGHT_API bool RollbackOpenTransaction() noexcept
LIGHTWEIGHT_API std::string DatabaseName() const
Retrieves the name of the database in use.
bool SupportsNativeRowBatch() const noexcept
Whether this connection's ODBC driver supports native parameter-array binding (SQL_ATTR_PARAMSET_SIZE...
LIGHTWEIGHT_API std::size_t DefaultPrefetchDepth() const noexcept
The default block-prefetch depth applied to statements created on this connection.
LIGHTWEIGHT_API std::chrono::steady_clock::time_point LastUsed() const noexcept
Retrieves the last time the connection was used.
LIGHTWEIGHT_API bool RequiresTableRebuildForSchemaChange() const noexcept
Whether this backend must rebuild a table to apply an ALTER TABLE schema change it cannot express in ...
LIGHTWEIGHT_API SqlHandleOwnership HandleOwnership() const noexcept
Tells whether this connection owns its ODBC handles or borrowed them (see Borrow).
LIGHTWEIGHT_API void SetStringTruncationMode(SqlStringTruncationMode mode)
SQLHDBC NativeHandle() const noexcept
Retrieves the native handle.
bool SupportsPreparedStatementReuse() const noexcept
Whether this connection's backend supports reusing an already-prepared statement handle for a later e...
LIGHTWEIGHT_API std::string ServerVersion() const
Retrieves the reported server version.
LIGHTWEIGHT_API SqlConnectionString const & ConnectionString() const noexcept
Retrieves the connection information.
std::string const & DriverName() const noexcept
Retrieves the name of the driver used for this connection.
static LIGHTWEIGHT_API void SetDefaultDataSource(SqlConnectionDataSource const &dataSource)
LIGHTWEIGHT_API SqliteConnectionSettings const & SqliteSettings() const noexcept
This connection's SQLite settings.
LIGHTWEIGHT_API std::string UserName() const
Retrieves the name of the user.
static LIGHTWEIGHT_API SqlRetrySettings DefaultConnectRetrySettings()
The connect-retry settings a newly constructed connection adopts.
static LIGHTWEIGHT_API void SetPostConnectedHook(std::function< void(SqlConnection &)> hook)
Sets a callback to be called after each connection being established.
LIGHTWEIGHT_API void EnableAsync(Async::IExecutor &dbWorkers, Async::IResumeScheduler &resume)
LIGHTWEIGHT_API bool Connect(SqlConnectionDataSource const &info) noexcept
Query builder for building SQL migration queries.
A bounded LRU pool of already-prepared ODBC statement handles, owned by a SqlConnection.
API Entry point for building SQL queries.
Supplies the wait between retries.
SqliteJournalMode
The SQLite journal mode a connection requests when it is established.
SqlStringTruncationMode
How a connection treats a string or binary value written into a column too small to hold it.
SqlHandleOwnership
How a connection relates to its ODBC handles.
@ Memory
PRAGMA journal_mode=MEMORY — the rollback journal, kept in memory.
@ Persist
PRAGMA journal_mode=PERSIST — the rollback journal, kept and its header zeroed.
@ Owned
The connection allocated its handles, connects them and frees them on Close().
Represents an ODBC SQL error.
Connection-level settings applied when a connection to a SQLite database is established.
std::chrono::milliseconds busyTimeout
How long a statement waits on a locked database file before failing, applied via PRAGMA busy_timeout.
bool operator==(SqliteConnectionSettings const &) const noexcept=default
Equality comparison operator.
SqliteJournalMode journalMode
The journal mode to switch the database to, see SqliteJournalMode.