Lightweight 0.20261105.1
Loading...
Searching...
No Matches
Connection.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5// <sql.h> below needs a few symbols resolved first — see SqlOdbcPrelude.hpp's header comment.
6#include "../../Api.hpp"
7#include "../../SqlBindingTypes.hpp"
8#include "../../SqlConnectInfo.hpp"
9#include "../../SqlError.hpp"
10#include "../../SqlServerType.hpp"
11#include "Catalog.hpp"
12#include "Handles.hpp"
13#include "SqlOdbcPrelude.hpp"
14#include "Statement.hpp"
15
16#include <expected>
17#include <source_location>
18#include <string>
19#include <utility>
20
21#include <sql.h>
22#include <sqlext.h>
23
24/// @file
25/// The connection and transaction operations of the ODBC driver: everything SqlConnection and
26/// SqlTransaction ask an ODBC connection handle to do. The first group is the connection half of the
27/// @ref Lightweight::Driver::SqlDriver concept; the second group is ODBC-only (connecting through a
28/// connection string or a data source, and the per-driver choice between the W and the ANSI entry points).
29///
30/// Every function is a thin wrapper: the same ODBC calls with the same arguments in the same order as
31/// the code it was moved from. Calls whose result the caller checks hand it back as
32/// @c Lightweight::SqlResult, so the caller keeps its check at the same point.
33
34namespace Lightweight::Driver::Odbc
35{
36
37// {{{ The connection half of the SqlDriver concept
38
39/// @brief Allocates an environment handle set to ODBC 3 and a connection handle on it, unless
40/// @p connection already holds an environment handle.
41///
42/// The results are not reported: a handle that failed to allocate stays null, and the connect that
43/// follows reports the failure. A connection whose environment handle exists but whose connection
44/// handle failed to allocate is left as it is.
45///
46/// @param connection The connection to allocate the handles of.
47LIGHTWEIGHT_API void Allocate(Connection& connection) noexcept;
48
49/// @brief Closes the connection: disconnects it, frees its connection and environment handles and leaves
50/// @p connection empty.
51///
52/// The handles are freed whatever the disconnect reports; a refused disconnect (e.g. the SQLite ODBC driver's
53/// 25000 "unfinished statements" while statements are allocated) is reported, with the diagnostic read before
54/// the connection handle is freed.
55///
56/// @param connection The connection; it must own its handles (not be borrowed).
57/// @param diagnostic Whether the diagnostic of a refused disconnect is read: a handle never connected refuses
58/// with 08003 ("connection not open"), which is not read (@c CloseDiagnostic::Skip).
59/// @return Nothing, or the diagnostic of a disconnect the driver refused, when read.
60[[nodiscard]] LIGHTWEIGHT_API std::expected<void, SqlErrorInfo> Close(Connection& connection,
61 CloseDiagnostic diagnostic) noexcept;
62
63/// @brief Names the driver @p connectionString reaches without connecting: its @c DRIVER, else the driver the
64/// driver manager lists for its @c DSN (@c SQLDataSources), else nothing.
65/// @param connection The connection; its environment handle is asked for the data sources.
66/// @param connectionString The connection string to connect from.
67/// @return The driver's name or library path, or empty.
68[[nodiscard]] LIGHTWEIGHT_API std::string DriverNameOf(Connection const& connection,
69 SqlConnectionString const& connectionString);
70
71/// @brief Ends the session of the connection (@c SQLDisconnect), keeping its handles for the next connect.
72///
73/// A successful disconnect also forgets that the connection handle takes text through the ANSI entry points
74/// (see RegisterTextEntry()). A refused one leaves the session, and that record, as they were.
75///
76/// @param connection The connection; may hold no connection handle, which is nothing to end.
77/// @return The result of @c SQLDisconnect; @c SqlResult::Success without a connection handle.
78[[nodiscard]] LIGHTWEIGHT_API SqlResult Disconnect(Connection& connection) noexcept;
79
80/// @brief Tells whether @p connection holds a connection handle (connected or not).
81/// @param connection The connection.
82/// @return @c true unless the connection handle is null.
83[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE bool IsAllocated(Connection const& connection) noexcept
84{
85 return connection.dbc != SQL_NULL_HDBC;
86}
87
88/// @brief Tells whether the driver still considers the connection alive (@c SQL_ATTR_CONNECTION_DEAD).
89/// @param connection The connection.
90/// @return @c true when the attribute could be read and reports a live connection.
91[[nodiscard]] LIGHTWEIGHT_API bool IsAlive(Connection const& connection) noexcept;
92
93/// @brief Reads the first diagnostic record of the connection handle.
94///
95/// Unlike Diagnose(Connection const&), never falls back to the environment handle.
96///
97/// @param connection The connection.
98/// @return The diagnostics; value-initialized fields when the driver has none to report.
99[[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo LastError(Connection const& connection);
100
101/// @brief The name of the DBMS the connection is connected to (@c SQL_DBMS_NAME).
102/// @param connection The connected connection.
103/// @return The name in UTF-8, or an empty string if the driver cannot tell.
104[[nodiscard]] LIGHTWEIGHT_API std::string ServerName(Connection const& connection);
105
106/// @brief The version of the DBMS the connection is connected to (@c SQL_DBMS_VER).
107/// @param connection The connected connection.
108/// @return The version in UTF-8, or an empty string if the driver cannot tell.
109[[nodiscard]] LIGHTWEIGHT_API std::string ServerVersion(Connection const& connection);
110
111/// @brief The file name of the ODBC driver the connection runs on (@c SQL_DRIVER_NAME).
112/// @param connection The connected connection.
113/// @return The name in UTF-8, or an empty string if the driver cannot tell.
114[[nodiscard]] LIGHTWEIGHT_API std::string DriverName(Connection const& connection);
115
116/// @brief The name of the database in use (@c SQL_DATABASE_NAME).
117/// @param connection The connected connection.
118/// @return The name in UTF-8, or an empty string if the driver cannot tell.
119[[nodiscard]] LIGHTWEIGHT_API std::string DatabaseName(Connection const& connection);
120
121/// @brief The name of the user the connection is logged in as (@c SQL_USER_NAME).
122/// @param connection The connected connection.
123/// @return The name in UTF-8, or an empty string if the driver cannot tell.
124[[nodiscard]] LIGHTWEIGHT_API std::string UserName(Connection const& connection);
125
126/// @brief Tells whether a transaction is open, i.e. autocommit is off.
127/// @param connection The connection.
128/// @return @c true when the autocommit attribute was read without diagnostics and is off.
129[[nodiscard]] LIGHTWEIGHT_API bool TransactionActive(Connection const& connection) noexcept;
130
131/// @brief Tells whether the data source supports transactions (@c SQL_TXN_CAPABLE).
132/// @param connection The connected connection.
133/// @return @c true when the capability was read without diagnostics and is not @c SQL_TC_NONE.
134[[nodiscard]] LIGHTWEIGHT_API bool TransactionsAllowed(Connection const& connection) noexcept;
135
136/// @brief Switches autocommit mode on or off.
137/// @param connection The connection.
138/// @param enabled Whether every statement commits on its own.
139/// @return The result of @c SQLSetConnectAttr.
140[[nodiscard]] LIGHTWEIGHT_API SqlResult SetAutoCommit(Connection& connection, bool enabled) noexcept;
141
142/// @brief Commits the open transaction.
143/// @param connection The connection.
144/// @return The result of @c SQLEndTran.
145[[nodiscard]] LIGHTWEIGHT_API SqlResult Commit(Connection& connection) noexcept;
146
147/// @brief Rolls back the open transaction.
148/// @param connection The connection.
149/// @return The result of @c SQLEndTran.
150[[nodiscard]] LIGHTWEIGHT_API SqlResult Rollback(Connection& connection) noexcept;
151
152/// @brief Sets the transaction isolation level of the connection.
153/// @param connection The connection.
154/// @param mode The isolation level; not @c SqlIsolationMode::DriverDefault, which has no ODBC value.
155/// @return The result of @c SQLSetConnectAttr.
156[[nodiscard]] LIGHTWEIGHT_API SqlResult SetIsolation(Connection& connection, SqlIsolationMode mode) noexcept;
157
158/// @brief Rolls back the open transaction and switches autocommit back on
159/// (@c RestoreAutoCommitAfterRollback), stopping at the first step that fails.
160/// @param connection The connection, with a transaction open.
161/// @return Whether both steps succeeded.
162[[nodiscard]] LIGHTWEIGHT_API bool RollbackOpenTransaction(Connection& connection) noexcept;
163
164/// @brief The non-throwing, fault-seam-aware verdict on @p result of a call on @p connection (see
165/// detail::CheckOdbcConnectionCall()).
166/// @param connection The connection @p result came from.
167/// @param result The result to check.
168/// @param sourceLocation Where the check originated; forwarded to the fault source.
169/// @return The verdict, plus the injected diagnostic when one was injected.
170[[nodiscard]] inline detail::OdbcCallOutcome CheckResult(Connection const& connection,
171 SqlResult result,
172 std::source_location sourceLocation)
173{
174 return detail::CheckOdbcConnectionCall(std::to_underlying(result), connection.dbc, sourceLocation);
175}
176
177// }}}
178
179// {{{ Optional connection operations (see Driver/Dispatch.hpp)
180
181/// @brief Tells whether the driver can read a column bound with @c SQLBindCol again with @c SQLGetData
182/// (@c SQL_GD_BOUND in @c SQL_GETDATA_EXTENSIONS).
183/// @param connection The connected connection.
184/// @return @c true when the driver reports @c SQL_GD_BOUND; @c false when it does not, or cannot be asked.
185[[nodiscard]] LIGHTWEIGHT_API bool ReadsBoundColumnsAgain(Connection const& connection) noexcept;
186
187/// @brief Tells how narrow strings are bound on a connection to @p serverType.
188///
189/// The SQLite ODBC driver's @c OEMCP option (Windows only) makes it convert @c SQL_C_CHAR with the thread's ANSI
190/// code page. The driver takes the option from the connection string, then from the data source's profile; when
191/// neither sets it, it is on for a data-source connect (@c SQLConnect) and off for a connection string. Every
192/// other case is @c detail::NarrowTextBindingOf(serverType).
193///
194/// @param connection The connected connection.
195/// @param serverType The connected backend.
196/// @param connectInfo What the connection was connected from: a connection string, or a data source.
197/// @return The binding the narrow string binders use on this connection.
198[[nodiscard]] LIGHTWEIGHT_API ::Lightweight::detail::NarrowTextBinding NarrowTextBinding(Connection const& connection,
199 SqlServerType serverType,
200 SqlConnectInfo const& connectInfo);
201
202// }}}
203
204// {{{ ODBC-only connection operations
205
206/// @brief Connects through a connection string (@c SQLDriverConnect) and switches autocommit on.
207///
208/// The session the connection handle had must have been ended first (Disconnect()). A connection string holding non-ASCII
209/// text goes to the W or the ANSI entry point as RememberTextEntry() recorded for its driver; failures
210/// are not reported to the logger.
211///
212/// @param connection The connection; its handles must be allocated.
213/// @param connectionString The connection string.
214/// @param location Where the connect originated; the fault seam sees it as the location of the
215/// connection checks. Deliberately without a default: the fault-seam tests match
216/// these checks by the caller's function name.
217/// @return Nothing on success, else the diagnostics of the failed step (an injected one through the
218/// fault seam where a test installed one).
219[[nodiscard]] LIGHTWEIGHT_API std::expected<void, SqlErrorInfo> Connect(Connection& connection,
220 SqlConnectionString const& connectionString,
221 std::source_location location);
222
223/// @brief Connects to an ODBC data source (@c SQLConnect) and switches autocommit on.
224///
225/// The session the connection handle had must have been ended first (Disconnect()). Sets the login timeout and, on
226/// an explicit request, the SQL Server encryption attribute. Every failure but running out of memory is
227/// reported to the logger.
228///
229/// @param connection The connection; its handles must be allocated.
230/// @param dataSource The data source, credentials, timeout and encryption request.
231/// @param location Where the connect originated; the fault seam sees it as the location of the
232/// connection checks. Deliberately without a default: the fault-seam tests match
233/// these checks by the caller's function name.
234/// @return Nothing on success, else the diagnostics of the failed step (an injected one through the
235/// fault seam where a test installed one).
236[[nodiscard]] LIGHTWEIGHT_API std::expected<void, SqlErrorInfo> Connect(Connection& connection,
237 SqlConnectionDataSource const& dataSource,
238 std::source_location location);
239
240/// @brief Tells whether the driver behind @p connection receives wide text unchanged.
241///
242/// Off Windows, the driver echoes, through @c SQLNativeSqlW and without a server round trip, a statement
243/// holding a CJK character: a driver manager narrowing wide text for an ANSI-only driver cannot carry it.
244/// The Windows driver manager converts wide text for such a driver to the ANSI code page it expects, so
245/// there the wide entry points are always the right ones.
246///
247/// @param connection The connected connection.
248/// @return @c true when the W entry points carry text intact, including when the driver cannot echo it.
249[[nodiscard]] LIGHTWEIGHT_API bool AcceptsWideQueryText(Connection const& connection) noexcept;
250
251/// @brief Switches autocommit back on after SqlConnection::RollbackOpenTransaction() rolled back.
252///
253/// Deliberately keeps the wide entry point (@c SQLSetConnectAttrW) this call site has always used,
254/// whereas SetAutoCommit() keeps the ANSI one SqlTransaction has always used.
255///
256/// @param connection The connection.
257/// @return The result of @c SQLSetConnectAttrW.
258[[nodiscard]] LIGHTWEIGHT_API SqlResult RestoreAutoCommitAfterRollback(Connection& connection) noexcept;
259
260/// @brief Records whether the connection's driver takes text through the W entry points, so that the
261/// diagnostics of the connection, and of every statement allocated on it later, are read accordingly.
262/// @param connection The connected connection.
263/// @param acceptsWideQueryText What AcceptsWideQueryText() found.
264LIGHTWEIGHT_API void RegisterTextEntry(Connection const& connection, bool acceptsWideQueryText) noexcept;
265
266/// @brief Records, process-wide, whether the driver a connection string names accepts wide text, so a
267/// later Connect() through it chooses its entry point before connecting. Best effort.
268/// @param connectionString The connection string a connection was established with.
269/// @param acceptsWideQueryText What AcceptsWideQueryText() found for that connection.
270LIGHTWEIGHT_API void RememberTextEntry(SqlConnectionString const& connectionString, bool acceptsWideQueryText) noexcept;
271
272/// @brief Records, process-wide, whether the driver behind a data source accepts wide text, so a later
273/// Connect() to it chooses its entry point before connecting. Best effort.
274/// @param dataSource The data source a connection was established to.
275/// @param acceptsWideQueryText What AcceptsWideQueryText() found for that connection.
276LIGHTWEIGHT_API void RememberTextEntry(SqlConnectionDataSource const& dataSource, bool acceptsWideQueryText) noexcept;
277
278// }}}
279
280static_assert(SqlDriver<Driver>);
281
282} // namespace Lightweight::Driver::Odbc
bool IsAllocated(ConnectionHandle const &connection) noexcept
Tells whether connection holds a driver connection (connected or not).
Definition Dispatch.hpp:597
std::string ServerVersion(ConnectionHandle const &connection)
The version of the DBMS the connection is connected to.
Definition Dispatch.hpp:641
std::expected< void, SqlErrorInfo > Connect(ConnectionHandle &handle, Info const &info, std::source_location location)
Connects handle from info through the enabled driver that connects from it.
Definition Dispatch.hpp:782
bool TransactionActive(ConnectionHandle const &connection) noexcept
Tells whether a transaction is open, i.e. autocommit is off.
Definition Dispatch.hpp:673
void Allocate(ConnectionHandle &connection) noexcept
Allocates the driver's connection resources, unless the connection already holds them.
Definition Dispatch.hpp:569
SqlResult SetAutoCommit(ConnectionHandle &connection, bool enabled) noexcept
Switches autocommit mode on or off.
Definition Dispatch.hpp:690
bool ReadsBoundColumnsAgain(ConnectionHandle const &connection) noexcept
Tells whether the connection's driver can read a bound output column again, so that a bound value lon...
Definition Dispatch.hpp:820
std::string ServerName(ConnectionHandle const &connection)
The name of the DBMS the connection is connected to.
Definition Dispatch.hpp:633
std::string DriverNameOf(ConnectionHandle const &connection, SqlConnectionString const &connectionString)
Names the driver a connect from connectionString reaches, without connecting (see ServerTypeFromDrive...
Definition Dispatch.hpp:855
SqlResult SetIsolation(ConnectionHandle &connection, SqlIsolationMode mode) noexcept
Sets the transaction isolation level of the connection.
Definition Dispatch.hpp:715
bool RollbackOpenTransaction(ConnectionHandle &connection) noexcept
Rolls back the open transaction and switches autocommit back on.
Definition Dispatch.hpp:723
SqlErrorInfo LastError(ConnectionHandle const &connection)
Reads the connection's diagnostics: the first record its last failed call left.
Definition Dispatch.hpp:613
SqlResult Disconnect(ConnectionHandle &connection) noexcept
Ends the connection's session, keeping its driver resources for the next connect.
Definition Dispatch.hpp:589
SqlResult Commit(ConnectionHandle &connection) noexcept
Commits the open transaction.
Definition Dispatch.hpp:698
std::string DriverName(ConnectionHandle const &connection)
The name of the driver (library) the connection runs on.
Definition Dispatch.hpp:649
void RegisterTextEntry(ConnectionHandle const &connection, bool acceptsWideQueryText) noexcept
Records whether the connection's driver takes text through its wide entry points, where the driver ha...
Definition Dispatch.hpp:871
std::string UserName(ConnectionHandle const &connection)
The name of the user the connection is logged in as.
Definition Dispatch.hpp:665
std::expected< void, SqlErrorInfo > Close(ConnectionHandle &connection, CloseDiagnostic diagnostic) noexcept
Closes the connection: disconnects it, frees its driver resources and leaves connection empty,...
Definition Dispatch.hpp:580
SqlResult Rollback(ConnectionHandle &connection) noexcept
Rolls back the open transaction.
Definition Dispatch.hpp:706
bool AcceptsWideQueryText(ConnectionHandle const &connection) noexcept
Tells whether the connection's driver receives wide (UTF-16) query text unchanged.
Definition Dispatch.hpp:805
bool TransactionsAllowed(ConnectionHandle const &connection) noexcept
Tells whether the data source supports transactions.
Definition Dispatch.hpp:681
std::string DatabaseName(ConnectionHandle const &connection)
The name of the database in use.
Definition Dispatch.hpp:657
CallOutcome CheckResult(StatementHandle const &statement, SqlResult result, std::source_location location)
The non-throwing, fault-seam-aware verdict on result.
Definition Dispatch.hpp:489
bool IsAlive(ConnectionHandle const &connection) noexcept
Tells whether the driver still considers the connection alive.
Definition Dispatch.hpp:605
LIGHTWEIGHT_API void RememberTextEntry(SqlConnectionString const &connectionString, bool acceptsWideQueryText) noexcept
Records, process-wide, whether the driver a connection string names accepts wide text,...
LIGHTWEIGHT_API SqlResult RestoreAutoCommitAfterRollback(Connection &connection) noexcept
Switches autocommit back on after SqlConnection::RollbackOpenTransaction() rolled back.
A database driver the library can be built with.
Definition Concept.hpp:316
std::variant< SqlConnectionDataSource, SqlConnectionString, SqliteConnectInfo > SqlConnectInfo
What a connection is opened from: an ODBC data source, an ODBC connection string, or a SQLite databas...
Verdict of a non-throwing checked driver call, carrying the diagnostic that justifies a failure verdi...
Definition Concept.hpp:76
The ODBC driver's connection handle struct.
Definition Handles.hpp:53
SQLHDBC dbc
The native ODBC connection handle.
Definition Handles.hpp:58
Represents a SQL error as reported by the database driver.
Definition SqlError.hpp:29