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#include "../../Api.hpp"
6#include "../../SqlBindingTypes.hpp"
7#include "../../SqlConnectInfo.hpp"
8#include "../../SqlError.hpp"
9#include "../Concept.hpp"
10#include "Handles.hpp"
11
12#include <expected>
13#include <source_location>
14#include <string>
15
16/// @file
17/// The connection and transaction operations of the SQLite3 driver: the connection half of the
18/// @ref Lightweight::Driver::SqlDriver concept, plus connecting from a @ref Lightweight::SqliteConnectInfo.
19///
20/// A @ref Lightweight::Driver::Sqlite3::Connection is one pointer to a driver-owned @c ConnectionState
21/// (private @c State.hpp). Every failure of a connection-level call is kept in that state, as the diagnostics
22/// @ref Lightweight::Driver::Sqlite3::LastError reports.
23
24namespace Lightweight::Driver::Sqlite3
25{
26
27// {{{ The connection half of the SqlDriver concept
28
29/// @brief Creates the connection's state, holding no database yet, unless @p connection already has one.
30///
31/// Running out of memory is not reported: the state stays null, and the connect that follows reports it.
32///
33/// @param connection The connection to allocate the state of.
34LIGHTWEIGHT_API void Allocate(Connection& connection) noexcept;
35
36/// @brief Closes the connection and leaves @p connection empty; safe on an empty one.
37///
38/// Finalizes the native statement of every statement still allocated on the connection and orphans their
39/// states (they stay valid until their statement frees them), closes the database and destroys the state.
40///
41/// @param connection The connection.
42/// @param diagnostic Unused: there is no refusal to read a diagnostic of.
43/// @return Nothing: closing a SQLite database is never refused (@c sqlite3_close_v2 defers what it cannot do yet).
44[[nodiscard]] LIGHTWEIGHT_API std::expected<void, SqlErrorInfo> Close(Connection& connection,
45 CloseDiagnostic diagnostic) noexcept;
46
47/// @brief Ends the session of the connection, keeping its state for the next connect: finalizes the native
48/// statement of every statement still allocated on it, orphaning their states (they then fail with @c 08003), and
49/// closes the database.
50/// @param connection The connection; one that is not open has nothing to end.
51/// @return @c SqlResult::Success.
52[[nodiscard]] LIGHTWEIGHT_API SqlResult Disconnect(Connection& connection) noexcept;
53
54/// @brief Tells whether @p connection has its state (connected or not).
55/// @param connection The connection.
56/// @return @c true unless the state is null.
57[[nodiscard]] inline bool IsAllocated(Connection const& connection) noexcept
58{
59 return connection.state != nullptr;
60}
61
62/// @brief Tells whether a database is open; a native connection never dies on its own.
63/// @param connection The connection.
64/// @return @c true between a successful @c Connect and @c Close.
65[[nodiscard]] LIGHTWEIGHT_API bool IsAlive(Connection const& connection) noexcept;
66
67/// @brief The last failure of a connection-level call.
68///
69/// Kept in the connection's state, so a failed open reports its error after the native connection it
70/// came from is closed.
71///
72/// @param connection The connection.
73/// @return The diagnostics; value-initialized fields when nothing failed since the last successful connect.
74[[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo LastError(Connection const& connection);
75
76/// @brief The name of the DBMS.
77/// @param connection The connection.
78/// @return @c "SQLite", the name @c ServerTypeFromServerName recognizes as SQLite.
79[[nodiscard]] LIGHTWEIGHT_API std::string ServerName(Connection const& connection);
80
81/// @brief The version of the DBMS: the SQLite library the driver is linked against.
82/// @param connection The connection.
83/// @return @c LibraryVersion.
84[[nodiscard]] LIGHTWEIGHT_API std::string ServerVersion(Connection const& connection);
85
86/// @brief The name of the driver the connection runs on, as @c SqlConnection::DriverName() reports it (for ODBC,
87/// the driver library the driver manager loaded). Not @c Driver::Name ("SQLite3"), the kind of driver that error
88/// messages name.
89/// @param connection The connection.
90/// @return @c "sqlite3-native".
91[[nodiscard]] LIGHTWEIGHT_API std::string DriverName(Connection const& connection);
92
93/// @brief The database the connection was opened on.
94/// @param connection The connection.
95/// @return @c SqliteConnectInfo::database of the last successful @c Connect; empty before one.
96[[nodiscard]] LIGHTWEIGHT_API std::string DatabaseName(Connection const& connection);
97
98/// @brief The user the connection is logged in as; SQLite has no users.
99/// @param connection The connection.
100/// @return An empty string.
101[[nodiscard]] LIGHTWEIGHT_API std::string UserName(Connection const& connection);
102
103/// @brief Tells whether a transaction is open (@c sqlite3_get_autocommit is 0).
104///
105/// On ODBC the same question reads "is autocommit off"; @c SqlTransaction hides the difference.
106///
107/// @param connection The connection.
108/// @return @c true when a database is open and a transaction is open on it.
109[[nodiscard]] LIGHTWEIGHT_API bool TransactionActive(Connection const& connection) noexcept;
110
111/// @brief Tells whether the data source supports transactions; SQLite always does.
112/// @param connection The connection.
113/// @return @c true.
114[[nodiscard]] LIGHTWEIGHT_API bool TransactionsAllowed(Connection const& connection) noexcept;
115
116/// @brief Switches autocommit mode on or off: off begins a transaction (@c BEGIN, or adopts one that is open
117/// already), on commits it as @c Commit does.
118/// @param connection The connected connection.
119/// @param enabled Whether every statement commits on its own.
120/// @return @c Success, or @c Error with the failure kept for @c LastError (@c 25000 as for @c Commit).
121[[nodiscard]] LIGHTWEIGHT_API SqlResult SetAutoCommit(Connection& connection, bool enabled) noexcept;
122
123/// @brief Commits the transaction @c SetAutoCommit began (@c COMMIT); nothing to do when none was begun.
124///
125/// SQLite rolls a transaction back by itself when a statement in it fails with a conflict resolution of
126/// @c ROLLBACK (@c ON @c CONFLICT @c ROLLBACK, @c RAISE(ROLLBACK, ...) in a trigger) or with a full disk or an I/O
127/// error; the statements run after that run in autocommit mode, each committed on its own. A transaction that was
128/// begun but is not open any more is therefore not committed silently: @c Error with SQLSTATE @c 25000
129/// ("invalid transaction state", which the retry classifiers take as permanent, as they take the SQLite ODBC driver's
130/// failure of that commit). Only a successful @c COMMIT ends the
131/// begun transaction: after any failed commit (this one, a busy database, a deferred foreign key) it stays begun, so a
132/// retried commit fails again instead of reporting success; @c Rollback ends it.
133///
134/// @param connection The connection.
135/// @return @c Success, or @c Error with the failure kept for @c LastError; @c 08003 when the connection is not
136/// open.
137[[nodiscard]] LIGHTWEIGHT_API SqlResult Commit(Connection& connection) noexcept;
138
139/// @brief Rolls back the open transaction (@c ROLLBACK); nothing to do when none is open, also when SQLite already
140/// rolled back the transaction @c SetAutoCommit began (see @c Commit). Ends the begun transaction either way.
141/// @param connection The connection.
142/// @return @c Success, or @c Error with the failure kept for @c LastError; @c 08003 when the connection is not
143/// open.
144[[nodiscard]] LIGHTWEIGHT_API SqlResult Rollback(Connection& connection) noexcept;
145
146/// @brief Sets the transaction isolation level: SQLite transactions are serializable, which satisfies every
147/// standard level, so a valid one is accepted and nothing is issued.
148/// @param connection The connection.
149/// @param mode The isolation level.
150/// @return @c Success for a @c SqlIsolationMode enumerator; @c Error with SQLSTATE @c HY024 (kept for
151/// @c LastError) for any other value.
152[[nodiscard]] LIGHTWEIGHT_API SqlResult SetIsolation(Connection& connection, SqlIsolationMode mode) noexcept;
153
154/// @brief Rolls back the open transaction (@c ROLLBACK), if one is open.
155/// @param connection The connection.
156/// @return Whether the connection is in autocommit mode afterwards; @c false when no database is open.
157[[nodiscard]] LIGHTWEIGHT_API bool RollbackOpenTransaction(Connection& connection) noexcept;
158
159/// @brief The non-throwing verdict on @p result of a call on @p connection; this driver has no fault seam, so
160/// nothing is ever injected.
161/// @param connection The connection @p result came from (unused).
162/// @param result The result to check.
163/// @param location Where the check originated (unused).
164/// @return @c { Succeeded(result), std::nullopt }.
165[[nodiscard]] inline ::Lightweight::Driver::CallOutcome CheckResult([[maybe_unused]] Connection const& connection,
166 SqlResult result,
167 [[maybe_unused]] std::source_location location) noexcept
168{
169 return ::Lightweight::Driver::CallOutcome { .succeeded = Succeeded(result), .injectedError = std::nullopt };
170}
171
172/// @brief Fails: this driver has no catalog functions, so no search pattern of theirs to escape (the dialect's
173/// @c SqlCatalogQueries::searchPatternEscape states the escape of the SQL catalog, see
174/// @c SqlQueryFormatter::CatalogQueries()).
175/// @param connection The connection (unused).
176/// @return @c NotSupportedByDriver(SqlDriverId::Sqlite3, "catalog access") (SQLSTATE @c IM001).
177[[nodiscard]] LIGHTWEIGHT_API std::expected<std::string, SqlErrorInfo> SearchPatternEscape(Connection const& connection);
178
179// }}}
180
181// {{{ Connecting
182
183/// @brief Opens the database @p info names (@c sqlite3_open_v2), with extended result codes on.
184///
185/// Closes a database the connection still has open first (as @c Close does, keeping the state: its
186/// statements are orphaned), and allocates the state if @p connection has none. Statements allocated while the
187/// connection was not open stay registered and become usable. The open flags map one to one onto SQLite's;
188/// a combination SQLite does not define (no access flag, both @c ReadOnly and @c ReadWrite, @c Create with
189/// @c ReadOnly, an unknown flag) is rejected with SQLSTATE @c HY024 before anything is opened, and so is any connect
190/// with @c HY000 when the SQLite library is built single-threaded (@c SQLITE_THREADSAFE=0). The SQLite
191/// settings of @p info (busy timeout, journal mode) are not applied here — @c SqlConnection applies them
192/// through the query formatter once connected, as it does on the ODBC path.
193///
194/// @param connection The connection.
195/// @param info The database and how to open it.
196/// @param location Where the connect originated (unused by this driver; the ODBC driver's fault seam needs it).
197/// @return Nothing on success; else the diagnostics of the failed open, which are also kept in the state so
198/// @c LastError reports them after the failed native connection is closed.
199[[nodiscard]] LIGHTWEIGHT_API std::expected<void, SqlErrorInfo> Connect(Connection& connection,
200 SqliteConnectInfo const& info,
201 std::source_location location);
202
203// }}}
204
205static_assert(::Lightweight::Driver::SqlDriverConnectionOperations<Driver>);
206
207} // namespace Lightweight::Driver::Sqlite3
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
std::string ServerName(ConnectionHandle const &connection)
The name of the DBMS the connection is connected to.
Definition Dispatch.hpp:633
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
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 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
bool succeeded
Whether the checked call should be treated as having succeeded.
Definition Concept.hpp:78
The SQLite3 driver's connection handle struct: one pointer to the driver-owned connection state.
Definition Handles.hpp:38
Represents a SQL error as reported by the database driver.
Definition SqlError.hpp:29
What a connection to a SQLite database is opened from through the native SQLite3 driver.