|
Lightweight 0.20260921.0
|
Represents a connection to a SQL database. More...
#include <SqlConnection.hpp>
Public Member Functions | |
| LIGHTWEIGHT_API | SqlConnection () |
| Constructs a new SQL connection to the default connection. | |
| LIGHTWEIGHT_API | SqlConnection (std::optional< SqlConnectionString > connectInfo) |
| Constructs a new SQL connection to the given connect informaton. | |
| LIGHTWEIGHT_API | SqlConnection (SqlConnection &&) noexcept |
| Move constructor. | |
| LIGHTWEIGHT_API SqlConnection & | operator= (SqlConnection &&) noexcept |
| Move assignment operator. | |
| SqlConnection (SqlConnection const &)=delete | |
| SqlConnection & | operator= (SqlConnection const &)=delete |
| LIGHTWEIGHT_API | ~SqlConnection () noexcept |
| Destructs this SQL connection object,. | |
| SqlStringTruncationMode | StringTruncationMode () const noexcept |
| This connection's string-truncation mode. See SqlStringTruncationMode. | |
| LIGHTWEIGHT_API void | SetStringTruncationMode (SqlStringTruncationMode mode) |
| uint64_t | ConnectionId () const noexcept |
| Retrieves the connection ID. | |
| LIGHTWEIGHT_API void | Close () noexcept |
| LIGHTWEIGHT_API bool | Connect (SqlConnectionDataSource const &info) noexcept |
| LIGHTWEIGHT_API bool | Connect (SqlConnectionString sqlConnectionString) noexcept |
| LIGHTWEIGHT_API SqlErrorInfo | LastError () const |
| Retrieves the last error information with respect to this SQL connection handle. | |
| LIGHTWEIGHT_API std::string | DatabaseName () const |
| Retrieves the name of the database in use. | |
| LIGHTWEIGHT_API std::string | UserName () const |
| Retrieves the name of the user. | |
| LIGHTWEIGHT_API std::string | ServerName () const |
| Retrieves the name of the server. | |
| LIGHTWEIGHT_API std::string | ServerVersion () const |
| Retrieves the reported server version. | |
| SqlServerType | ServerType () const noexcept |
| Retrieves the type of the server. | |
| std::string const & | DriverName () const noexcept |
| Retrieves the name of the driver used for this connection. | |
| SqlQueryFormatter const & | QueryFormatter () const noexcept |
| Retrieves a query formatter suitable for the SQL server being connected. | |
| LIGHTWEIGHT_API bool | RequiresTableRebuildForSchemaChange () const noexcept |
Whether this backend must rebuild a table to apply an ALTER TABLE schema change it cannot express in place (foreign-key add/drop, or column type/nullability change). | |
| bool | SupportsNativeRowBatch () const noexcept |
Whether this connection's ODBC driver supports native parameter-array binding (SQL_ATTR_PARAMSET_SIZE > 1) for batched row-wise execution. | |
| bool | SupportsNativeRowArrayFetch () const noexcept |
Whether this connection's ODBC driver supports native row-array fetching (SQL_ATTR_ROW_ARRAY_SIZE > 1 with SQLFetchScroll) for block result retrieval. | |
| LIGHTWEIGHT_API std::size_t | DefaultPrefetchDepth () const noexcept |
| The default block-prefetch depth applied to statements created on this connection. | |
| LIGHTWEIGHT_API void | SetDefaultPrefetchDepth (std::size_t depth) noexcept |
| Sets the default block-prefetch depth for statements created on this connection. | |
| bool | SupportsPreparedStatementReuse () const noexcept |
| Whether this connection's backend supports reusing an already-prepared statement handle for a later execution of the same SQL text. | |
| LIGHTWEIGHT_API std::size_t | PreparedStatementCacheCapacity () const noexcept |
| The capacity of this connection's prepared-statement cache. | |
| LIGHTWEIGHT_API void | SetPreparedStatementCacheCapacity (std::size_t capacity) noexcept |
| Enables (or resizes) this connection's prepared-statement cache. | |
| LIGHTWEIGHT_API void | ClearPreparedStatementCache () noexcept |
| Frees every pooled prepared statement handle, e.g. after DDL invalidated the cached query plans. | |
| LIGHTWEIGHT_API SqlPreparedStatementCache & | PreparedStatementCache () noexcept |
| Retrieves this connection's prepared-statement cache. | |
| LIGHTWEIGHT_API SqlQueryBuilder | Query (std::string_view const &table={}) const |
| LIGHTWEIGHT_API SqlQueryBuilder | QueryAs (std::string_view const &table, std::string_view const &tableAlias) const |
| 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 bool | TransactionsAllowed () const noexcept |
| Tests if transactions are allowed. | |
| LIGHTWEIGHT_API bool | IsAlive () const noexcept |
| Tests if the connection is still active. | |
| LIGHTWEIGHT_API SqlConnectionString const & | ConnectionString () const noexcept |
| Retrieves the connection information. | |
| SQLHDBC | NativeHandle () const noexcept |
| Retrieves the native handle. | |
| LIGHTWEIGHT_API std::chrono::steady_clock::time_point | LastUsed () const noexcept |
| Retrieves the last time the connection was used. | |
| LIGHTWEIGHT_API void | SetLastUsed (std::chrono::steady_clock::time_point lastUsed) noexcept |
| Sets the last time the connection was used. | |
| 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. | |
| LIGHTWEIGHT_API void | EnableAsync (Async::IExecutor &dbWorkers, Async::IResumeScheduler &resume) |
| LIGHTWEIGHT_API void | EnableAsync (std::unique_ptr< Async::IAsyncBackend > backend) |
| LIGHTWEIGHT_API void | DisableAsync () noexcept |
| LIGHTWEIGHT_API bool | IsAsyncEnabled () const noexcept |
| LIGHTWEIGHT_API Async::IAsyncBackend & | AsyncBackend () |
Static Public Member Functions | |
| static LIGHTWEIGHT_API SqlConnectionString const & | DefaultConnectionString () noexcept |
| Retrieves the default connection information. | |
| static LIGHTWEIGHT_API void | SetDefaultConnectionString (SqlConnectionString const &connectionString) noexcept |
| static LIGHTWEIGHT_API void | SetDefaultDataSource (SqlConnectionDataSource const &dataSource) noexcept |
| Sets the default connection information as SqlConnectionDataSource. | |
| static LIGHTWEIGHT_API void | SetPostConnectedHook (std::function< void(SqlConnection &)> hook) |
| Sets a callback to be called after each connection being established. | |
| static LIGHTWEIGHT_API void | ResetPostConnectedHook () |
| Resets the post connected hook. | |
| static LIGHTWEIGHT_API SqlStringTruncationMode | DefaultStringTruncationMode () noexcept |
| static LIGHTWEIGHT_API void | SetDefaultStringTruncationMode (SqlStringTruncationMode mode) noexcept |
| static bool | SupportsNativeRowArrayFetch (SqlServerType serverType) noexcept |
Server-type overload of SupportsNativeRowArrayFetch, for callers that hold only the server type (e.g. the DataMapper result reader) and not the connection. Keeps the single source of truth for this capability on the connection rather than scattering a switch (serverType) into business logic. | |
| static bool | RoundTripsNarrowTextByteExact (SqlServerType serverType) noexcept |
Whether serverType's driver round-trips narrow (SQL_C_CHAR) character data byte-exact, so a fixed-capacity char string may be array-bound narrow on the row-wise fetch path. | |
| static bool | SupportsPreparedStatementReuse (SqlServerType serverType) noexcept |
| Server-type overload of SupportsPreparedStatementReuse, for callers that hold only the server type rather than a live connection. | |
Represents a connection to a SQL database.
Definition at line 70 of file SqlConnection.hpp.
| LIGHTWEIGHT_API Lightweight::SqlConnection::SqlConnection | ( | ) |
Constructs a new SQL connection to the default connection.
The default connection is set via SetDefaultConnectInfo. In case the default connection is not set, the connection will fail. And in case the connection fails, the last error will be set.
|
explicit |
Constructs a new SQL connection to the given connect informaton.
| connectInfo | The connection information to use. If std::nullopt, no connection is established and the object is left in an unconnected state — use Connect(...) later. If a value is provided and the connection fails, SqlException is thrown carrying the ODBC diagnostic read from the DBC handle. |
|
staticnoexcept |
Sets the default connection information.
| connectionString | The connection information to use. |
|
staticnoexcept |
The string-truncation mode a newly established connection adopts. Defaults to SqlStringTruncationMode::Truncate.
|
staticnoexcept |
Sets the string-truncation mode newly established connections adopt. Existing connections are unaffected; use SetStringTruncationMode on those.
|
inlinenoexcept |
This connection's string-truncation mode. See SqlStringTruncationMode.
Definition at line 126 of file SqlConnection.hpp.
| LIGHTWEIGHT_API void Lightweight::SqlConnection::SetStringTruncationMode | ( | SqlStringTruncationMode | mode | ) |
Sets this connection's string-truncation mode, applying it immediately when the connection is open (a no-op on backends other than Microsoft SQL Server).
|
inlinenoexcept |
Retrieves the connection ID.
This is a unique identifier for the connection, which is useful for debugging purposes. Note, this ID will not change if the connection is moved nor when it is reused via the connection pool.
Definition at line 139 of file SqlConnection.hpp.
|
noexcept |
Closes the connection, freeing the underlying ODBC handles.
This does not return the connection to any pool: SqlConnection owns its handles outright. Connection pooling is provided separately by Lightweight::Pool in DataMapper/Pool.hpp, which recycles pooled DataMapper instances.
|
noexcept |
Connects to the given database with the given username and password.
This method can be called on a connection that has been closed via Close(). If the ODBC handles have been freed, they will be automatically reallocated.
| true | if the connection was successful. |
| false | if the connection failed. Use LastError() to retrieve the error information. |
|
noexcept |
Connects to the given database with the given connection string.
This method can be called on a connection that has been closed via Close(). If the ODBC handles have been freed, they will be automatically reallocated.
| true | if the connection was successful. |
| false | if the connection failed. Use LastError() to retrieve the error information. |
|
inlinenoexcept |
Retrieves the type of the server.
Definition at line 442 of file SqlConnection.hpp.
Referenced by Lightweight::DataMapper::CreateTable(), Lightweight::DataMapper::Query(), Lightweight::DataMapper::Query(), Lightweight::DataMapper::Query(), Lightweight::DataMapper::QuerySingle(), SupportsNativeRowArrayFetch(), SupportsNativeRowBatch(), and SupportsPreparedStatementReuse().
|
inlinenoexcept |
Retrieves the name of the driver used for this connection.
Definition at line 447 of file SqlConnection.hpp.
|
inlinenoexcept |
Retrieves a query formatter suitable for the SQL server being connected.
Definition at line 452 of file SqlConnection.hpp.
Referenced by Lightweight::SqlStatement::MigrateDirect(), and Lightweight::DataMapper::Query().
|
noexcept |
Whether this backend must rebuild a table to apply an ALTER TABLE schema change it cannot express in place (foreign-key add/drop, or column type/nullability change).
The migration executor consults this to decide whether a -- LIGHTWEIGHT_SQLITE_GUARD: sentinel must be turned into a table rebuild (true for SQLite) or executed directly. Exposed on the connection so capability decisions go through the backend, delegating the dialect knowledge to the query formatter.
|
inlinenoexcept |
Whether this connection's ODBC driver supports native parameter-array binding (SQL_ATTR_PARAMSET_SIZE > 1) for batched row-wise execution.
The batched SqlStatement::ExecuteBatch(rows, accessors...) consults this to decide whether it may submit the whole batch in a single row-wise SQLExecute, or must fall back to a single prepare followed by consecutive per-row executes. This is a driver/backend capability — not a SQL-dialect concern — so it belongs to the connection, which knows both the server type and the driver name (either of which a future carve-out can branch on).
true if the driver honours parameter arrays. Definition at line 457 of file SqlConnection.hpp.
References ServerType().
|
inlinenoexcept |
Whether this connection's ODBC driver supports native row-array fetching (SQL_ATTR_ROW_ARRAY_SIZE > 1 with SQLFetchScroll) for block result retrieval.
The fast retrieval path in SqlStatement::FetchAllRowWise consults this to decide whether it may bind the result columns row-wise over a record block and materialize whole row blocks per SQLFetchScroll round-trip, or must fall back to the per-row SQLFetch path. Like SupportsNativeRowBatch this is a driver/backend capability — not a SQL-dialect concern — so it lives on the connection. Kept distinct from the parameter-array flag so a backend that honours one but not the other can be carved out independently.
true if the driver honours row-array fetching. Definition at line 516 of file SqlConnection.hpp.
References ServerType(), and SupportsNativeRowArrayFetch().
Referenced by SupportsNativeRowArrayFetch().
|
inlinestaticnoexcept |
Server-type overload of SupportsNativeRowArrayFetch, for callers that hold only the server type (e.g. the DataMapper result reader) and not the connection. Keeps the single source of truth for this capability on the connection rather than scattering a switch (serverType) into business logic.
| serverType | The backend server type to test. |
true if that backend honours row-array fetching. Definition at line 498 of file SqlConnection.hpp.
|
inlinestaticnoexcept |
Whether serverType's driver round-trips narrow (SQL_C_CHAR) character data byte-exact, so a fixed-capacity char string may be array-bound narrow on the row-wise fetch path.
PostgreSQL's psqlODBC transcodes SQL_C_CHAR through the client codepage (cp1252 on Windows), mangling non-ASCII bytes — its single-row binder therefore reads narrow strings via SQL_C_WCHAR. That wide round-trip needs an external per-cell buffer + conversion, which cannot be expressed as an in-place row-wise array bind, so a record carrying a fixed-capacity string falls back to the per-row path on PostgreSQL. MS SQL Server and SQLite read SQL_C_CHAR verbatim and stay on the fast path.
| serverType | The backend server type to test. |
true if narrow character data round-trips byte-exact on that backend. Definition at line 521 of file SqlConnection.hpp.
|
noexcept |
The default block-prefetch depth applied to statements created on this connection.
Classic per-row fetch loops (while (cursor.FetchRow()) ..., SqlRowIterator, SqlVariantRowCursor) transparently request this many rows per SQLFetchScroll round-trip instead of issuing one SQLFetch per row. A value <= 1 disables prefetch. Effective only when SupportsNativeRowArrayFetch is true; otherwise statements fall back to per-row fetching.
PrefetchDepthDefault).
|
noexcept |
Sets the default block-prefetch depth for statements created on this connection.
| depth | Rows to request per SQLFetchScroll round-trip on the transparent prefetch path; a value <= 1 disables prefetch (restoring one SQLFetch per row). |
|
inlinenoexcept |
Whether this connection's backend supports reusing an already-prepared statement handle for a later execution of the same SQL text.
Gates the prepared-statement cache: a backend not known to keep a prepared statement re-executable across an intervening cursor close never pools handles, no matter what capacity was configured. Like SupportsNativeRowBatch this is a driver/backend capability rather than a SQL-dialect concern, so it lives on the connection instead of a switch in the caller.
true if prepared handles may be pooled and re-executed on this backend. Definition at line 493 of file SqlConnection.hpp.
References ServerType(), and SupportsPreparedStatementReuse().
Referenced by SupportsPreparedStatementReuse().
|
inlinestaticnoexcept |
Server-type overload of SupportsPreparedStatementReuse, for callers that hold only the server type rather than a live connection.
| serverType | The backend to answer for. |
true if prepared handles may be pooled and re-executed on serverType. Definition at line 475 of file SqlConnection.hpp.
|
noexcept |
The capacity of this connection's prepared-statement cache.
0 when the cache is disabled (the default).
|
noexcept |
Enables (or resizes) this connection's prepared-statement cache.
With a non-zero capacity, SqlStatement::Prepare() on this connection first looks for an idle handle already prepared for the same SQL text and reuses it, skipping the driver's SQLPrepare round-trip. Handles return to the cache when the statement is re-prepared or destroyed, and are evicted least-recently-used first once the bound is exceeded. Every layer built on SqlStatement — DataMapper, the query builders — benefits without call-site changes; a single statement can opt out via SqlStatement::SetPreparedStatementCaching.
A capacity request on a backend without SupportsPreparedStatementReuse is kept but stays inactive, so the same setup code is safe to run against any DBMS.
SqlStatement::MigrateDirect already do so.| capacity | Maximum number of idle prepared handles to keep; 0 disables and clears the cache. PreparedStatementCacheCapacitySuggested is a reasonable starting point. |
|
noexcept |
Retrieves this connection's prepared-statement cache.
Non-const because acquiring and releasing pooled handles mutates the cache. Mostly of interest for its SqlPreparedStatementCache::Stats counters.
| LIGHTWEIGHT_API SqlQueryBuilder Lightweight::SqlConnection::Query | ( | std::string_view const & | table = {} | ) | const |
Creates a new query builder for the given table, compatible with the current connection.
| table | The table to query. If not provided, the query will be a generic query builder. |
Referenced by Lightweight::DataMapper::CreateAll(), Lightweight::DataMapper::Delete(), Lightweight::DataMapper::FromTable(), Lightweight::DataMapper::QuerySingle(), Lightweight::DataMapper::Update(), and Lightweight::DataMapper::UpdateAll().
| LIGHTWEIGHT_API SqlQueryBuilder Lightweight::SqlConnection::QueryAs | ( | std::string_view const & | table, |
| std::string_view const & | tableAlias | ||
| ) | const |
Creates a new query builder for the given table with an alias, compatible with the current connection.
| table | The table to query. |
| tableAlias | The alias to use for the table. |
|
inlinenoexcept |
Retrieves the native handle.
Definition at line 346 of file SqlConnection.hpp.
Referenced by Lightweight::SqlTransaction::TryCommit().
| LIGHTWEIGHT_API void Lightweight::SqlConnection::EnableAsync | ( | Async::IExecutor & | dbWorkers, |
| Async::IResumeScheduler & | resume | ||
| ) |
Enables coroutine-based asynchronous methods on this connection.
Wires the connection to an injected execution context: blocking ODBC work is offloaded to dbWorkers (serialized per connection so the ODBC handle is only ever used by one thread at a time) and the awaiting coroutine is resumed via resume (typically the application's run loop). A native driver-async backend is selected when the driver advertises support; otherwise the portable thread-offload backend is used.
Both executors must outlive this connection and every coroutine driven through it. Must not be called while asynchronous operations are in flight on this connection (it replaces the backend); the connection pool calls DisableAsync on return so each re-acquire is a fresh enable rather than a live replacement.
| dbWorkers | The worker-thread pool used to run blocking ODBC calls. |
| resume | The scheduler used to resume coroutines after a blocking step completes. |
| LIGHTWEIGHT_API void Lightweight::SqlConnection::EnableAsync | ( | std::unique_ptr< Async::IAsyncBackend > | backend | ) |
Enables the asynchronous API on this connection using an explicitly provided backend.
This is the dependency-injection seam behind the convenience overload above: callers and tests can supply any Async::IAsyncBackend implementation (a fake/inline backend for tests, or a future native event backend) instead of the default thread-offload backend. The same in-flight / lifetime constraints as the convenience overload apply.
| backend | The async execution backend to install (consumed); must not be null. |
|
noexcept |
Tears down the asynchronous backend, returning the connection to a non-async state.
Called by the connection pool when a mapper is returned, so a recycled connection never carries a stale backend that references executors which may have been destroyed. Safe to call when async was never enabled.
DataMapper).
|
noexcept |
| LIGHTWEIGHT_API Async::IAsyncBackend & Lightweight::SqlConnection::AsyncBackend | ( | ) |
Retrieves the connection's asynchronous execution backend.
Non-const because using the backend schedules and serializes real ODBC work (via its strand and resume scheduler), which is an observable mutation of the connection's execution state.
| std::logic_error | if async has not been enabled (programmer error, fail-fast). |
Referenced by Lightweight::DataMapper::CreateAsync(), Lightweight::DataMapper::DeleteAsync(), Lightweight::DataMapper::LoadRelationsAsync(), Lightweight::DataMapper::QuerySingleAsync(), and Lightweight::DataMapper::UpdateAsync().