|
Lightweight 0.20260617.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,. | |
| uint64_t | ConnectionId () const noexcept |
| Retrieves the connection ID. | |
| LIGHTWEIGHT_API void | Close () noexcept |
| Closes the connection (attempting to put it back into the connect[[ion pool). | |
| 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. | |
| 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. | |
| 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 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. | |
Represents a connection to a SQL database.
Definition at line 40 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. |
|
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 91 of file SqlConnection.hpp.
|
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 320 of file SqlConnection.hpp.
Referenced by Lightweight::DataMapper::CreateTable(), Lightweight::DataMapper::Query(), Lightweight::DataMapper::Query(), Lightweight::DataMapper::Query(), Lightweight::DataMapper::QuerySingle(), SupportsNativeRowArrayFetch(), and SupportsNativeRowBatch().
|
inlinenoexcept |
Retrieves the name of the driver used for this connection.
Definition at line 325 of file SqlConnection.hpp.
|
inlinenoexcept |
Retrieves a query formatter suitable for the SQL server being connected.
Definition at line 330 of file SqlConnection.hpp.
Referenced by Lightweight::DataMapper::Query().
|
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 335 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 371 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 353 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 376 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). |
| 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 232 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().