|
Lightweight 0.20261105.1
|
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 (std::optional< SqlConnectionString > connectInfo, SqliteConnectionSettings sqliteSettings) |
| Constructs a new SQL connection with explicit SQLite connection settings. | |
| 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,. | |
| LIGHTWEIGHT_API SqlHandleOwnership | HandleOwnership () const noexcept |
| Tells whether this connection owns its ODBC handles or borrowed them (see Borrow). | |
| SqlStringTruncationMode | StringTruncationMode () const noexcept |
| This connection's string-truncation mode. See SqlStringTruncationMode. | |
| LIGHTWEIGHT_API void | SetStringTruncationMode (SqlStringTruncationMode mode) |
| LIGHTWEIGHT_API SqliteConnectionSettings const & | SqliteSettings () const noexcept |
| This connection's SQLite settings. | |
| 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 SQLite database. | |
| LIGHTWEIGHT_API SqlRetrySettings const & | ConnectRetrySettings () const noexcept |
| This connection's connect-retry settings. | |
| LIGHTWEIGHT_API void | SetConnectRetrySettings (SqlRetrySettings const &settings, SqlRetrySleeper *sleeper=nullptr) noexcept |
| Changes how this connection's Connect() retries a connect that failed transiently. | |
| 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. | |
| bool | AcceptsWideQueryText () const noexcept |
| 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 | RollbackOpenTransaction () noexcept |
| 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 SqlConnection | Borrow (SQLHDBC connectedHandle) |
| Wraps an ODBC connection handle that another component allocated, connected and keeps owning. | |
| static LIGHTWEIGHT_API SqlConnectionString const & | DefaultConnectionString () |
| static LIGHTWEIGHT_API std::uint32_t | DefaultConnectionStringGeneration () noexcept |
| static LIGHTWEIGHT_API void | SetDefaultConnectionString (SqlConnectionString const &connectionString) |
| static LIGHTWEIGHT_API void | SetDefaultDataSource (SqlConnectionDataSource const &dataSource) |
| 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 LIGHTWEIGHT_API SqliteConnectionSettings | DefaultSqliteSettings () |
| The SQLite settings a newly constructed connection adopts. | |
| static LIGHTWEIGHT_API void | SetDefaultSqliteSettings (SqliteConnectionSettings const &settings) |
| Sets the SQLite settings newly constructed connections adopt. | |
| static LIGHTWEIGHT_API SqlRetrySettings | DefaultConnectRetrySettings () |
| The connect-retry settings a newly constructed connection adopts. | |
| static LIGHTWEIGHT_API void | SetDefaultConnectRetrySettings (SqlRetrySettings const &settings) |
| Sets the connect-retry settings newly constructed connections adopt. | |
| 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 148 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. |
| LIGHTWEIGHT_API Lightweight::SqlConnection::SqlConnection | ( | std::optional< SqlConnectionString > | connectInfo, |
| SqliteConnectionSettings | sqliteSettings | ||
| ) |
Constructs a new SQL connection with explicit SQLite connection settings.
Behaves like the single-argument constructor, except that the connection uses sqliteSettings instead of a snapshot of DefaultSqliteSettings. The settings are applied as part of establishing the connection, so the first statement already runs under them.
| connectInfo | The connection information to use, or std::nullopt to stay unconnected. |
| sqliteSettings | The SQLite settings applied on this and every later Connect(); inert on other backends. |
|
static |
Wraps an ODBC connection handle that another component allocated, connected and keeps owning.
Statements run on the borrowed connection share the owner's session, including any transaction it has open. The server type, query formatter and driver name are detected as Connect() does, but no session setting is applied: neither the string-truncation mode, nor the SQLite settings, nor the post-connected hook. StringTruncationMode() reports the mode the session already has (read from ANSI_WARNINGS on Microsoft SQL Server). Close() and the destructor detach from the handle without disconnecting or freeing it, and Connect() on a borrowed connection fails.
| connectedHandle | A connected ODBC connection handle. It must stay valid until the returned connection is closed or destroyed, since both free the statement handles cached on it. |
connectedHandle. | std::invalid_argument | if connectedHandle is null. |
|
noexcept |
Tells whether this connection owns its ODBC handles or borrowed them (see Borrow).
|
static |
Retrieves the default connection information.
Thread-safe: the reference is to the calling thread's own snapshot of the default, refreshed when the application has replaced it since (see SetDefaultConnectionString), so another thread replacing the default never changes the string under a reader. The same thread's next call may, so copy it if it must stay fixed across such a switch.
|
staticnoexcept |
Identifies the current default connection string.
Incremented by every SetDefaultConnectionString and SetDefaultDataSource, so anything that caches a connection made from the default - a connection pool, the migration manager's mapper - can tell that it now points at a database the application has switched away from. Compare for equality only; the counter wraps.
Read it before reading DefaultConnectionString(), since the setters publish the new string first and the new generation second, so a connection stamped that way can only ever be considered older than it is, never newer.
|
static |
Sets the default connection information.
Thread-safe. Connections already made from the previous default are not touched; pooled ones are retired as they are next borrowed or returned (see DefaultConnectionStringGeneration).
| connectionString | The connection information to use. |
|
static |
Sets the default connection information as SqlConnectionDataSource.
| dataSource | The data source to flatten into the default connection string. |
|
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 263 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).
|
static |
The SQLite settings a newly constructed connection adopts.
Thread-safe. Defaults to a default-constructed SqliteConnectionSettings (60 second busy timeout, journal mode unchanged).
|
static |
Sets the SQLite settings newly constructed connections adopt.
Thread-safe. This is the way to configure connections that Lightweight constructs on the application's behalf, such as those of a Pool or a default-constructed DataMapper. Connections that already exist keep their settings; use SetSqliteSettings on those.
| settings | The new process-wide default. |
|
noexcept |
This connection's SQLite settings.
Captured from DefaultSqliteSettings when the connection object is constructed (or given to the constructor), and re-applied on every Connect().
| LIGHTWEIGHT_API std::expected< void, SqlErrorInfo > Lightweight::SqlConnection::SetSqliteSettings | ( | SqliteConnectionSettings const & | settings | ) |
Changes this connection's SQLite settings, applying them immediately when the connection is open to a SQLite database.
On other backends, or while unconnected, the settings are only stored, to be applied by the next Connect() to a SQLite database.
| settings | The settings to store and apply. |
PRAGMA statement that failed. The settings are stored either way.
|
static |
The connect-retry settings a newly constructed connection adopts.
Thread-safe. Defaults to no retries (maxRetries of zero), so a failed connect fails at once unless the application opts in.
|
static |
Sets the connect-retry settings newly constructed connections adopt.
Thread-safe. This is the way to make the connections that Lightweight opens on the application's behalf (a Pool, a default-constructed DataMapper, migrations, backups) ride out a database that is briefly unreachable. Connections that already exist keep their settings; use SetConnectRetrySettings on those.
| settings | The new process-wide default. |
|
noexcept |
This connection's connect-retry settings.
Captured from DefaultConnectRetrySettings when the connection object is constructed, and applied by every Connect().
|
noexcept |
Changes how this connection's Connect() retries a connect that failed transiently.
Connect() retries only failures that the dialect-agnostic classifier (GenericRetryOps) deems transient — a connection that could not be established or was dropped (SQLSTATE class 08), a timeout (HYT00 / HYT01) — and fails at once on anything else, such as rejected credentials. Each retry is reported through SqlLogger::OnWarning.
| settings | The backoff configuration; a maxRetries of zero disables retrying. |
| sleeper | How to wait between attempts; nullptr selects ThreadSleeper(). It must outlive the connection. Injected so tests need not wait out real delays. |
|
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 352 of file SqlConnection.hpp.
|
noexcept |
Closes the connection, freeing the underlying ODBC handles.
A borrowed connection (see Borrow) only detaches from its handle, leaving it connected.
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. A transient failure is retried as SetConnectRetrySettings configures. It always fails on a borrowed connection (see Borrow).
| 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. A transient failure is retried as SetConnectRetrySettings configures. It always fails on a borrowed connection (see Borrow).
| 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 719 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 724 of file SqlConnection.hpp.
|
inlinenoexcept |
Tells whether text reaches the driver intact through the ODBC wide (W) entry points.
Off Windows, a driver that implements only the ANSI entry points (such as the SQLite ODBC driver some Linux distributions ship) receives wide text from the driver manager narrowed one UTF-16 code unit to one byte, which corrupts every non-ASCII character. For such a driver the library hands over query text, catalog-function arguments and connection text as UTF-8 through the ANSI entry points, and reads its diagnostics through them. Always true on Windows, whose driver manager converts wide text to the code page an ANSI driver expects.
Definition at line 729 of file SqlConnection.hpp.
|
inlinenoexcept |
Retrieves a query formatter suitable for the SQL server being connected.
Definition at line 734 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 739 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 798 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 780 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 803 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 775 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 757 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::Delete(), Lightweight::DataMapper::FromTable(), Lightweight::DataMapper::QuerySingle(), and Lightweight::DataMapper::Update().
| 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. |
|
noexcept |
Rolls back a transaction left open on this connection and restores autocommit mode.
Recognizes a transaction the ODBC way, by autocommit being off - as SqlTransaction and any caller switching autocommit off leave it. A transaction opened by executing a raw BEGIN statement while autocommit is on is not visible to ODBC and is not ended here.
The connection pool calls this on every connection returned to it.
true when the connection is in autocommit mode afterwards (including when no transaction was open); false when the rollback or the mode switch failed.
|
inlinenoexcept |
Retrieves the native handle.
Definition at line 587 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().