Lightweight 0.20261105.1
Loading...
Searching...
No Matches
State.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5// PRIVATE header of the SQLite3 driver: included only by the driver's .cpp files, never installed and never
6// included by a public header. It is the one header that includes sqlite3.h.
7
8#include "../../SqlBindingTypes.hpp"
9#include "../../SqlError.hpp"
10#include "Handles.hpp"
11#include "Statement.hpp"
12
13#include <cstdint>
14#include <exception>
15#include <optional>
16#include <string>
17#include <string_view>
18#include <vector>
19
20#include <sqlite3.h>
21
22namespace Lightweight::Driver::Sqlite3
23{
24
25/// The SQLSTATE of an operation on a connection, or a statement of one, that is closed or not open yet.
26inline constexpr std::string_view ConnectionNotOpenState = "08003";
27
28/// What @c DriverName reports for a native connection, and the binder callback of the output readers too.
29inline constexpr std::string_view NativeDriverName = "sqlite3-native";
30
31/// @brief Keeps the error @p makeError builds as a last failure. Running out of memory while building it (or any
32/// other exception) leaves no error rather than a stale one.
33/// @param lastError The connection's or statement's last failure.
34/// @param makeError Builds the @c SqlErrorInfo; may throw.
35template <typename MakeError>
36void KeepError(std::optional<SqlErrorInfo>& lastError, MakeError const& makeError) noexcept
37{
38 try
39 {
40 lastError = makeError();
41 }
42 catch (std::exception const&)
43 {
44 lastError.reset();
45 }
46}
47
48/// @brief Where a statement stands between @c Execute and the end of its result set.
49enum class StatementPhase : std::uint8_t
50{
51 /// Not stepped since it was prepared or reset: nothing to reset before the next step, no row at hand.
52 Idle,
53 /// Stepped once by @c Execute onto the first row, which the next @c Fetch hands out without stepping.
54 PendingRow,
55 /// A row is current (handed out by @c Fetch); the next @c Fetch steps.
56 Fetching,
57 /// Stepped past the last row (or failed while fetching): @c Fetch answers @c NoData until the next @c Execute.
58 Done,
59};
60
61/// @brief One registered output reader: what @c Fetch runs for one result column on every row.
63{
64 /// The reader; null for a column without one.
66 /// The target handed to @ref reader.
67 void* target {};
68 /// The indicator handed to @ref reader.
69 SqlIndicator* indicator {};
70};
71
72/// @brief The driver-owned state of one SQLite statement: everything mutable behind a @ref Statement.
73///
74/// Created by the statement's @c Allocate with @c std::make_unique, released into its handle struct and
75/// registered with its connection's state (@c AttachStatement); destroyed only by the statement's @c Free,
76/// which finalizes @ref native, unregisters it and re-adopts it. Its connection never destroys it: closing the
77/// connection (or connecting it again) finalizes @ref native and orphans the state (@ref connection becomes
78/// null), so a statement or cursor destroyed after its connection still touches valid memory.
79///
80/// Invariant: @ref native is non-null only while @ref connection is non-null and has an open database, so a
81/// non-null @ref native is all a per-row operation needs to check.
83{
84 /// The connection the statement belongs to; null once orphaned by that connection's @c Close.
86
87 /// The prepared statement; null when nothing is prepared, and after the connection closed.
88 ::sqlite3_stmt* native {};
89
90 /// The previous statement in the connection's statement list; null for the first one.
92
93 /// The next statement in the connection's statement list; null for the last one.
95
96 /// The number of result columns of @ref native, cached at prepare and refreshed by each @c Execute (SQLite
97 /// may re-prepare a statement whose schema changed). It decides whether bound text is referenced or copied.
99
100 /// The number of parameters of @ref native, cached at prepare. Kept as wide as SQLite reports it (a build may
101 /// allow 250000); @c Prepare refuses a statement whose counts do not fit the @c std::int16_t the concept uses.
103
104 /// Where the statement stands in its result set.
105 StatementPhase phase {};
106
107 /// Whether @ref native writes nothing (@c sqlite3_stmt_readonly), cached at prepare: such a statement reports
108 /// no changed rows, whatever another statement of the connection wrote meanwhile.
109 bool readOnly = true;
110
111 /// Which parameters (index - 1) were bound since the bindings were last cleared; sized at prepare, so binding
112 /// never allocates. @c Execute refuses (@c 07002) while any is unbound, rather than writing NULL for it.
113 std::vector<bool> boundParameters {};
114
115 /// The number of @c true entries of @ref boundParameters, so the check before every execution is one compare.
117
118 /// The change count of the statement's last completed execution (see @c NumRowsAffected); 0 until it completed.
119 std::int64_t rowsAffected {};
120
121 /// The connection's total change count (@c sqlite3_total_changes64) when @c Execute started; a completed
122 /// statement that did not move it changed no rows, whatever @c sqlite3_changes64 still reports.
123 std::int64_t totalChangesAtExecute {};
124
125 /// The registered output readers, indexed by column - 1; grown by @c RegisterOutputReader only.
126 std::vector<BoundColumn> boundColumns {};
127
128 /// The statement's last failure, captured when the failing call returned. Disengaged until something
129 /// failed since the last prepare.
130 std::optional<SqlErrorInfo> lastError {};
131
132 /// The statements of an @c ExecuteDirect text not run yet: the text after the statement whose result set is
133 /// current. A copy owned here (the caller's text dies when @c ExecuteDirect returns), run by @c MoreResults,
134 /// @c DiscardResults, @c Prepare and @c ExecuteDirect; empty when nothing is pending. Orphaning the statement
135 /// (@c DetachStatement) drops it unrun. Only one @c sqlite3_stmt of the text exists at any time, in
136 /// @ref native.
137 std::string pendingTail {};
138};
139
140/// @brief The driver-owned state of one SQLite connection: everything mutable behind a @ref Connection.
141///
142/// Created by @c Allocate(Connection&) with @c std::make_unique and released into the handle struct, so the
143/// handle is its only owner; @c Close(Connection&) re-adopts it into a @c std::unique_ptr and destroys it. A
144/// connection and its statements are used by one thread at a time, their destruction included (the public
145/// contract, stated on @c Driver::Sqlite3::Connection), so the state carries no lock.
147{
148 /// The open database; null before a successful @c Connect and after a failed one.
149 ::sqlite3* database {};
150
151 /// Whether @c SetAutoCommit(false) began (or adopted) a transaction that no @c Commit, @c Rollback or
152 /// @c SetAutoCommit(true) has ended yet. SQLite rolls a transaction back by itself on some failures
153 /// (@c ON @c CONFLICT @c ROLLBACK, @c RAISE(ROLLBACK, ...), a full disk); this flag is how @c Commit tells
154 /// that case (fails with @c 25000) from a commit with no transaction begun (succeeds).
155 bool transactionBegun = false;
156
157 /// The database the connection was opened on (@c SqliteConnectInfo::database), as @c DatabaseName reports it.
158 std::string databaseName {};
159
160 /// The last failure of a connection-level call, kept so that @c LastError reports it even when the native
161 /// connection it came from is gone (a failed open closes it). Disengaged until something failed.
162 std::optional<SqlErrorInfo> lastError {};
163
164 /// The first of the statements allocated on this connection and not yet freed; an intrusive list through
165 /// @ref StatementState::nextOfConnection, so attaching and detaching are O(1) and never allocate.
167};
168
169/// @brief Removes @p statement from its connection's statement list and orphans it, dropping its pending tail
170/// (@ref StatementState::pendingTail) unrun; nothing if it has no connection. Does not touch
171/// @ref StatementState::native.
172/// @param statement The statement.
173inline void DetachStatement(StatementState& statement) noexcept
174{
175 if (!statement.connection)
176 return;
177 statement.pendingTail.clear();
178 if (statement.previousOfConnection)
179 statement.previousOfConnection->nextOfConnection = statement.nextOfConnection;
180 else
181 statement.connection->firstStatement = statement.nextOfConnection;
182 if (statement.nextOfConnection)
183 statement.nextOfConnection->previousOfConnection = statement.previousOfConnection;
184 statement.connection = nullptr;
185 statement.previousOfConnection = nullptr;
186 statement.nextOfConnection = nullptr;
187}
188
189/// @brief Registers @p statement with @p connection, so that closing the connection finalizes and orphans it.
190/// A statement still attached to a connection (this one or another) is detached from it first.
191/// @param connection The connection the statement is allocated on.
192/// @param statement The statement.
193inline void AttachStatement(ConnectionState& connection, StatementState& statement) noexcept
194{
195 DetachStatement(statement);
196 statement.connection = &connection;
197 statement.previousOfConnection = nullptr;
198 statement.nextOfConnection = connection.firstStatement;
199 if (connection.firstStatement)
200 connection.firstStatement->previousOfConnection = &statement;
201 connection.firstStatement = &statement;
202}
203
204/// @brief The diagnostics of the last failed call on @p database: its extended result code and SQLite's message.
205/// @param database The native connection; null reports @c SQLITE_NOMEM, as SQLite does for a missing handle.
206/// @return The diagnostics, the SQLSTATE taken from @c SqlStateFromResultCode.
207[[nodiscard]] SqlErrorInfo ErrorInfoOf(::sqlite3* database);
208
209} // namespace Lightweight::Driver::Sqlite3
SqlResult(*)(Statement &stmt, SqlColumnIndex column, void *target, SqlIndicator *indicator) OutputReader
A registered reader: reads one column of the current row into the bound target.
One registered output reader: what Fetch runs for one result column on every row.
Definition State.hpp:63
void * target
The target handed to reader.
Definition State.hpp:67
SqlIndicator * indicator
The indicator handed to reader.
Definition State.hpp:69
OutputReader reader
The reader; null for a column without one.
Definition State.hpp:65
The driver-owned state of one SQLite connection: everything mutable behind a Connection.
Definition State.hpp:147
std::optional< SqlErrorInfo > lastError
Definition State.hpp:162
std::string databaseName
The database the connection was opened on (SqliteConnectInfo::database), as DatabaseName reports it.
Definition State.hpp:158
::sqlite3 * database
The open database; null before a successful Connect and after a failed one.
Definition State.hpp:149
The driver-owned state of one SQLite statement: everything mutable behind a Statement.
Definition State.hpp:83
std::vector< BoundColumn > boundColumns
The registered output readers, indexed by column - 1; grown by RegisterOutputReader only.
Definition State.hpp:126
ConnectionState * connection
The connection the statement belongs to; null once orphaned by that connection's Close.
Definition State.hpp:85
std::optional< SqlErrorInfo > lastError
Definition State.hpp:130
std::int64_t rowsAffected
The change count of the statement's last completed execution (see NumRowsAffected); 0 until it comple...
Definition State.hpp:119
int boundParameterCount
The number of true entries of boundParameters, so the check before every execution is one compare.
Definition State.hpp:116
StatementPhase phase
Where the statement stands in its result set.
Definition State.hpp:105
StatementState * previousOfConnection
The previous statement in the connection's statement list; null for the first one.
Definition State.hpp:91
StatementState * nextOfConnection
The next statement in the connection's statement list; null for the last one.
Definition State.hpp:94
::sqlite3_stmt * native
The prepared statement; null when nothing is prepared, and after the connection closed.
Definition State.hpp:88