Lightweight 0.20261105.1
Loading...
Searching...
No Matches
Statement.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 "../../SqlError.hpp"
8#include "../Concept.hpp"
9#include "Connection.hpp"
10#include "Handles.hpp"
11
12#include <chrono>
13#include <concepts>
14#include <cstddef>
15#include <cstdint>
16#include <expected>
17#include <optional>
18#include <source_location>
19#include <span>
20#include <string>
21#include <string_view>
22#include <type_traits>
23
24/// @file
25/// The statement operations of the SQLite3 driver: the statement half of the @ref Lightweight::Driver::SqlDriver
26/// concept, and the typed bind and read functions the leaf data binders call instead of SQLite's own.
27///
28/// A @ref Lightweight::Driver::Sqlite3::Statement is one pointer to a driver-owned @c StatementState (private
29/// @c State.hpp), registered with its connection's state. SQLite yields the first row on the first step; the
30/// driver hides that: @ref Lightweight::Driver::Sqlite3::Execute keeps that row pending and the first
31/// @ref Lightweight::Driver::Sqlite3::Fetch hands it out.
32///
33/// Every failure is captured in the statement's state when it happens, so
34/// @ref Lightweight::Driver::Sqlite3::Diagnose reports the statement's own failure even after another statement
35/// of the same connection succeeded. A statement whose connection is closed (or not open yet) answers @c Error
36/// with SQLSTATE @c 08003 to every operation that returns a @c Lightweight::SqlResult.
37///
38/// Parameters and columns are 1-based throughout.
39
40namespace Lightweight
41{
42template <typename>
43struct SqlDataBinder;
44
45class SqlDataBinderCallback;
46} // namespace Lightweight
47
48namespace Lightweight::Driver::Sqlite3
49{
50
51// {{{ The statement half of the SqlDriver concept
52
53/// @brief Creates a statement state registered with @p connection's state.
54///
55/// Works on a connection that is allocated but not connected yet: the statement then answers @c Error
56/// @c 08003 to everything until the connection is open. A @p stmt that already has a state keeps its memory,
57/// but is reset to a new statement's state — prepared statement finalized, readers, bindings, error and row
58/// forgotten — and registered with @p connection instead.
59///
60/// @param connection The connection; it must be allocated.
61/// @param stmt Receives the state.
62/// @return @c Success; @c Error when @p connection has no state or memory ran out (@p stmt is then unchanged).
63[[nodiscard]] LIGHTWEIGHT_API SqlResult Allocate(Connection const& connection, Statement& stmt) noexcept;
64
65/// @brief Finalizes the prepared statement, unregisters the state from its connection and destroys it; leaves
66/// @p stmt empty. An orphaned state (its connection closed) is just destroyed; an empty @p stmt is left alone.
67///
68/// Statements of an @c ExecuteDirect text still pending are run first, as @c DiscardResults does, so freeing a
69/// statement whose text is not exhausted runs the rest of it rather than dropping it. A statement of it that fails
70/// stops the text; its diagnostics are reported to the @c SqlLogger (@c OnError), since this function returns nothing.
71/// @param stmt The statement.
72LIGHTWEIGHT_API void Free(Statement& stmt) noexcept;
73
74/// @brief Gives up a statement whose connection session ended (the connection was closed or connected again),
75/// and leaves @p stmt empty.
76///
77/// Usually ending the session finalized the native statement and orphaned the state, which the statement still owns.
78/// The state may also still be attached to an open database (that of a moved-from @c SqlConnection, now owned by
79/// another): this is @c Free without running a pending @c ExecuteDirect text — the rest is dropped unrun, so
80/// nothing of the connection is touched.
81/// @param stmt The statement; may be empty.
82LIGHTWEIGHT_API void Abandon(Statement& stmt) noexcept;
83
84/// @brief Prepares @p query (@c sqlite3_prepare_v3), finalizing what the statement held before.
85///
86/// Statements of an earlier @c ExecuteDirect text still pending are run first, as @c DiscardResults does.
87/// Prepares exactly one statement, since a prepared statement has one parameter set: text holding a further
88/// statement after the first is @c Error @c 42000 ("Prepare() takes one statement"); blanks, comments and
89/// semicolons after it are not one. Text holding no statement at all prepares nothing and succeeds. SQLite stops
90/// parsing at a NUL character: text left after one is @c Error @c 42000 ("the SQL text holds a NUL character").
91/// A statement with more than 32767 parameters or result columns (what the @c std::int16_t counts can report)
92/// is @c Error @c HY000. Registered output-column readers survive it, as @c SQLBindCol bindings do: the owner
93/// unbinds them (@c UnbindColumns).
94///
95/// @param stmt The statement.
96/// @param query The SQL text, UTF-8.
97/// @param wideQueryText Ignored: SQLite takes UTF-8.
98/// @return @c Success, or @c Error with the failure captured for @c Diagnose.
99[[nodiscard]] LIGHTWEIGHT_API SqlResult Prepare(Statement& stmt, std::string_view query, bool wideQueryText);
100
101/// @brief Executes the prepared statement with the bound parameters.
102///
103/// Resets a statement that was stepped, then steps once. A statement with result columns keeps the first row
104/// pending, for @c Fetch to hand out first. A statement without result columns runs to completion, records
105/// its change count (@c NumRowsAffected) and is reset.
106///
107/// Every parameter must have been bound since the bindings were last cleared, else @c Error @c 07002 naming the
108/// first unbound one (an unbound parameter is never a silent NULL; @c BindNull binds NULL on purpose). The
109/// bindings stay across executions, as on ODBC, until @c ResetParameters or the next prepare: a statement bound
110/// once executes again with the same values, and binding one parameter again changes only that one. The text and
111/// blob bytes bound to a statement without result columns are referenced, so they must stay alive and unchanged as
112/// long as the binding is executed; a statement with result columns copied them. A bind that fails leaves its
113/// parameter unbound. With
114/// numbered parameters SQLite counts up to the largest index (@c ?5 alone is 5 parameters): every index up to it
115/// must be bound, gaps included (to NULL, say).
116///
117/// @param stmt The statement.
118/// @return @c Success (never @c NoData), or @c Error with the failure captured for @c Diagnose.
119[[nodiscard]] LIGHTWEIGHT_API SqlResult Execute(Statement& stmt) noexcept;
120
121/// @brief Runs the statements of @p query in order, each prepared and executed as @c Prepare and
122/// @c Execute do.
123///
124/// Statements of an earlier text still pending are run first, as @c DiscardResults does. A statement without
125/// result columns runs to completion at once; the first with result columns becomes the current result set and
126/// the rest of the text is kept (a copy the statement owns) for @c MoreResults. A failing statement stops the
127/// text: its error is returned and the statements after it do not run. The text takes no parameters: a statement
128/// of it that has some fails with @c 07002. Text holding no statement succeeds without executing anything. Text
129/// holding a NUL character fails with @c 42000 before any of it runs.
130///
131/// @param stmt The statement.
132/// @param query The SQL text, UTF-8: any number of statements.
133/// @param wideQueryText Ignored: SQLite takes UTF-8.
134/// @return @c Success, or @c Error with the failure captured for @c Diagnose.
135[[nodiscard]] LIGHTWEIGHT_API SqlResult ExecuteDirect(Statement& stmt, std::string_view query, bool wideQueryText);
136
137/// @brief Makes the next row the current one and runs the registered readers on it in column order.
138///
139/// The row @c Execute left pending comes first. A reader that fails stops the row: the result is @c Error,
140/// @c Diagnose reports the reader's diagnostic, and the row stays current, so its columns can still be read. A
141/// reader that throws (a binder running out of memory, a user's binder refusing a value) fails the same way: the
142/// exception is caught and kept as the diagnostic — a @c SqlException's own, @c HY001 for @c std::bad_alloc,
143/// @c HY000 with the message of any other exception — and the statement stays usable.
144///
145/// @param stmt The statement.
146/// @return @c Success on a row; @c NoData past the last row (and again on every further call); @c Error with
147/// @c 24000 when the statement has no result set, else with the failure captured for @c Diagnose.
148[[nodiscard]] LIGHTWEIGHT_API SqlResult Fetch(Statement& stmt) noexcept;
149
150/// @brief Moves to the next result set of an @c ExecuteDirect text: closes the current one and runs the
151/// pending rest of the text as @c ExecuteDirect runs a text.
152/// @param stmt The statement.
153/// @return @c Success when a further statement with result columns became current; @c NoData when the text is
154/// exhausted; @c Error when a statement of it failed (the statements after it do not run), and @c Error
155/// @c 08003 on a statement whose connection is closed.
156[[nodiscard]] LIGHTWEIGHT_API SqlResult MoreResults(Statement& stmt) noexcept;
157
158/// @brief Closes the cursor: resets the statement (bindings stay). The pending rest of an @c ExecuteDirect
159/// text stays pending, for @c MoreResults. Nothing on an orphaned statement.
160/// @param stmt The statement.
161LIGHTWEIGHT_API void CloseCursor(Statement& stmt) noexcept;
162
163/// @brief Discards the pending results: resets the statement (bindings stay) and runs the pending rest of an
164/// @c ExecuteDirect text to its end or its first failing statement, dropping that failure (@c Diagnose keeps
165/// reporting what it reported before). Nothing on an orphaned statement, whose pending text was dropped unrun.
166/// @param stmt The statement.
167LIGHTWEIGHT_API void DiscardResults(Statement& stmt) noexcept;
168
169/// @brief Forgets every registered output reader (@c RegisterOutputReader).
170/// @param stmt The statement.
171/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
172[[nodiscard]] LIGHTWEIGHT_API SqlResult UnbindColumns(Statement& stmt) noexcept;
173
174/// @brief Clears the parameter bindings (@c sqlite3_clear_bindings): every parameter is NULL until bound again.
175/// @param stmt The statement.
176/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
177[[nodiscard]] LIGHTWEIGHT_API SqlResult ResetParameters(Statement& stmt) noexcept;
178
179/// @brief Nothing: this driver has no parameter arrays.
180/// @param stmt The statement.
181LIGHTWEIGHT_API void ResetParameterArrays(Statement& stmt) noexcept;
182
183/// @brief The number of result columns of the prepared statement (@c sqlite3_column_count).
184/// @param stmt The statement.
185/// @param count Receives the count; 0 when nothing is prepared. SQLite caps it at 32767.
186/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
187[[nodiscard]] LIGHTWEIGHT_API SqlResult NumResultColumns(Statement const& stmt, std::int16_t& count) noexcept;
188
189/// @brief The number of parameters of the prepared statement (@c sqlite3_bind_parameter_count).
190/// @param stmt The statement.
191/// @param count Receives the count (the largest parameter index); 0 when nothing is prepared. @c Prepare refuses
192/// a statement with more than 32767 parameters, so it always fits.
193/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
194[[nodiscard]] LIGHTWEIGHT_API SqlResult NumParameters(Statement const& stmt, std::int16_t& count) noexcept;
195
196/// @brief The number of rows the statement's last execution changed, known once that execution completed.
197///
198/// A statement without result columns completes inside @c Execute. A statement with result columns completes
199/// when @c Execute or @c Fetch steps past its last row: an @c INSERT / @c UPDATE / @c DELETE with
200/// @c RETURNING has written all its rows on the first step, but SQLite reports the count only at completion, so
201/// it reads 0 until @c Fetch returned @c NoData. The count is @c sqlite3_changes64 when the connection's total
202/// change count moved during the execution, else 0: a DDL statement, transaction control, a @c PRAGMA or a
203/// @c SELECT reads 0, not the count of an earlier statement. After an @c ExecuteDirect text of several
204/// statements (and after @c MoreResults) it is the count of the last statement of the text that completed,
205/// also when a later statement of it failed.
206///
207/// @param stmt The statement.
208/// @param count Receives the count; 0 before the execution completed.
209/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
210[[nodiscard]] LIGHTWEIGHT_API SqlResult NumRowsAffected(Statement const& stmt, std::ptrdiff_t& count) noexcept;
211
212/// @brief The type of result column @p column.
213///
214/// A column declared with a type name the SQLite formatter emits has the type the SQLite ODBC driver reports for
215/// that name (the name is matched in any case, without its "(size)"; @c DECIMAL, @c GUID and the character types
216/// report @c WVarChar, @c TEXT @c WLongVarChar, @c REAL @c Double, @c BLOB @c Binary). Any other column (an
217/// expression, or a type name the table lacks) has the type of the storage class of its value in the row at hand
218/// (the pending or the current one): @c Integer is @c BigInt, @c Float @c Double, @c Text @c VarChar, @c Blob
219/// @c VarBinary, and @c Null (or no row at hand) @c Unknown.
220/// @param stmt The statement.
221/// @param column The column.
222/// @return The type; the diagnostics for an out-of-range column (@c 07009) or a closed connection (@c 08003).
223[[nodiscard]] LIGHTWEIGHT_API std::expected<SqlResultColumnType, SqlErrorInfo> ColumnType(Statement const& stmt,
224 SqlColumnIndex column);
225
226/// @brief Accepts a query timeout and stores nothing: as on the ODBC SQLite path it is not enforced.
227/// @param stmt The statement.
228/// @param timeout The timeout.
229/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
230[[nodiscard]] LIGHTWEIGHT_API SqlResult SetQueryTimeout(Statement& stmt, std::chrono::seconds timeout) noexcept;
231
232/// @brief The query timeout: always none.
233/// @param stmt The statement.
234/// @param timeout Receives 0.
235/// @return @c Success; @c Error @c 08003 on a statement whose connection is closed.
236[[nodiscard]] LIGHTWEIGHT_API SqlResult QueryTimeout(Statement const& stmt, std::chrono::seconds& timeout) noexcept;
237
238/// @brief The diagnostics of the statement's last failure, captured in its state when the failing call
239/// returned (never read later from the connection, where another statement may have replaced it).
240/// @param stmt The statement.
241/// @return The diagnostics; value-initialized fields when nothing failed since the last @c Prepare;
242/// @c 08003 for a statement without state.
243[[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo Diagnose(Statement const& stmt);
244
245/// @brief Throws unless @p result is a success, as @c Driver::ClassifyResult decides from @c Diagnose:
246/// @c std::invalid_argument for @c 07009, @c SqlException for any other failure.
247/// @param stmt The statement @p result came from.
248/// @param result The result to check.
249/// @param location Where the check originated, for the message of @c std::invalid_argument.
250LIGHTWEIGHT_API void RequireSuccess(Statement const& stmt,
251 SqlResult result,
252 std::source_location location = std::source_location::current());
253
254/// @brief The non-throwing verdict on @p result; this driver has no fault seam, so nothing is ever injected.
255/// @param stmt The statement @p result came from.
256/// @param result The result to check.
257/// @param location Where the check originated (unused).
258/// @return @c { Succeeded(result), std::nullopt }.
259[[nodiscard]] inline ::Lightweight::Driver::CallOutcome CheckResult([[maybe_unused]] Statement const& stmt,
260 SqlResult result,
261 [[maybe_unused]] std::source_location location) noexcept
262{
263 return ::Lightweight::Driver::CallOutcome { .succeeded = Succeeded(result), .injectedError = std::nullopt };
264}
265
266/// @brief Fails: this driver has no catalog functions (SqlSchema reads its catalog with the SQL of
267/// @c SqlQueryFormatter::CatalogQueries()).
268/// @param stmt The statement.
269/// @param request The catalog function asked for (unused).
270/// @return @c Error, with the statement's diagnostics @c NotSupportedByDriver(SqlDriverId::Sqlite3, "catalog access")
271/// (SQLSTATE @c IM001); @c Error @c 08003 on a statement whose connection is closed.
272[[nodiscard]] LIGHTWEIGHT_API SqlResult OpenCatalog(Statement const& stmt, SqlCatalogRequest const& request) noexcept;
273
274/// @brief The type a catalog @c DATA_TYPE code stands for: none, since this driver opens no catalog result set.
275/// @param stmt The statement (unused).
276/// @param dataType The code (unused).
277/// @return @c SqlResultColumnType::Unknown.
278[[nodiscard]] constexpr SqlResultColumnType CatalogColumnType([[maybe_unused]] Statement const& stmt,
279 [[maybe_unused]] int dataType) noexcept
280{
281 return SqlResultColumnType::Unknown;
282}
283
284/// @brief Describes result column @p column: its type as @c ColumnType reports it, and no column size (SQLite does
285/// not bound a column's values).
286/// @param stmt The statement.
287/// @param column The column.
288/// @param description Receives the description; left unchanged on failure.
289/// @return @c Success; @c Error with the diagnostics of @c ColumnType (@c 07009, @c 08003).
290[[nodiscard]] LIGHTWEIGHT_API SqlResult DescribeColumn(Statement const& stmt,
291 SqlColumnIndex column,
292 SqlColumnDescription& description);
293
294/// @brief The driver's SQL type code of result column @p column: none, since this driver's leaf binders read the
295/// storage class of the value instead and never ask.
296/// @param stmt The statement (unused).
297/// @param column The column (unused).
298/// @return @c std::nullopt.
299[[nodiscard]] constexpr std::optional<std::int16_t> DescribeResultColumnSqlType(
300 [[maybe_unused]] Statement const& stmt, [[maybe_unused]] SqlColumnIndex column) noexcept
301{
302 return std::nullopt;
303}
304
305/// @brief The bound buffer size the declared length of result column @p column asks for: the default, since this
306/// driver fills a bound column afresh for every row and so never cuts a value off.
307/// @param stmt The statement (unused).
308/// @param column The column (unused).
309/// @param length Which declared length (unused).
310/// @return @c detail::DefaultBoundColumnSize.
311[[nodiscard]] LIGHTWEIGHT_API std::size_t DeclaredBoundColumnSize(Statement const& stmt,
312 SqlColumnIndex column,
313 SqlOutputColumnLength length) noexcept;
314
315/// @brief Nothing: this driver has no row arrays.
316/// @param stmt The statement.
317LIGHTWEIGHT_API void ResetRowArrayAttributes(Statement& stmt) noexcept;
318
319/// @brief Binds UTF-16 text to @p parameter (as @c BindText16), read from @p text for @p lengthIndicator bytes.
320/// @param stmt The statement.
321/// @param parameter The parameter.
322/// @param text The text; must stay alive and unchanged as long as the binding is executed (see @c BindText).
323/// @param columnSize The declared column size (unused: SQLite does not bound a parameter's value).
324/// @param lengthIndicator The byte length of @p text, >= 0 only: ODBC's special lengths (@c SqlNullData, a
325/// NUL-terminated length) mean nothing here.
326/// @return As for @c BindText16; @c Error with SQLSTATE @c HY090 for a negative @p lengthIndicator, nothing bound.
327[[nodiscard]] LIGHTWEIGHT_API SqlResult BindUtf16TextParameter(Statement& stmt,
328 std::uint16_t parameter,
329 char16_t* text,
330 std::size_t columnSize,
331 SqlIndicator& lengthIndicator) noexcept;
332
333// }}}
334
335// {{{ Typed bind and read functions (what the leaf data binders call)
336
337/// @brief Records a failure the driver did not produce itself (a leaf binder's conversion error) as the
338/// statement's diagnostic, native error code 0.
339/// @param stmt The statement.
340/// @param sqlState The SQLSTATE.
341/// @param message The message.
342/// @return @c Error, so a binder can `return Fail(stmt, "22003", "numeric value out of range");`.
343[[nodiscard]] LIGHTWEIGHT_API SqlResult Fail(Statement& stmt, std::string_view sqlState, std::string_view message) noexcept;
344
345/// @brief Binds SQL NULL to @p parameter; it counts as bound for @c Execute (bind unused numbered parameters
346/// this way).
347/// @param stmt The statement.
348/// @param parameter The parameter.
349/// @return @c Success, or @c Error (@c 07009 for an out-of-range parameter) with the failure captured.
350[[nodiscard]] LIGHTWEIGHT_API SqlResult BindNull(Statement& stmt, SqlColumnIndex parameter) noexcept;
351
352/// @brief Binds an integer to @p parameter, by value.
353/// @param stmt The statement.
354/// @param parameter The parameter.
355/// @param value The value.
356/// @return @c Success, or @c Error (@c 07009 for an out-of-range parameter) with the failure captured.
357[[nodiscard]] LIGHTWEIGHT_API SqlResult BindInt64(Statement& stmt, SqlColumnIndex parameter, std::int64_t value) noexcept;
358
359/// @brief Binds a floating-point number to @p parameter, by value.
360/// @param stmt The statement.
361/// @param parameter The parameter.
362/// @param value The value.
363/// @return @c Success, or @c Error (@c 07009 for an out-of-range parameter) with the failure captured.
364[[nodiscard]] LIGHTWEIGHT_API SqlResult BindDouble(Statement& stmt, SqlColumnIndex parameter, double value) noexcept;
365
366/// @brief Binds UTF-8 text to @p parameter; an empty view binds empty text, never NULL.
367///
368/// On a statement without result columns the bytes are referenced, not copied: they must stay alive and unchanged
369/// as long as the binding is executed (until the parameter is bound again, @c ResetParameters or the next prepare).
370/// On a statement with result columns they are copied.
371///
372/// @param stmt The statement.
373/// @param parameter The parameter.
374/// @param utf8 The text; embedded NULs are kept.
375/// @return @c Success, or @c Error (@c 07009 for an out-of-range parameter) with the failure captured.
376[[nodiscard]] LIGHTWEIGHT_API SqlResult BindText(Statement& stmt, SqlColumnIndex parameter, std::string_view utf8) noexcept;
377
378/// @brief Binds UTF-16 text (native byte order) to @p parameter; referenced or copied as by @c BindText.
379/// @param stmt The statement.
380/// @param parameter The parameter.
381/// @param utf16 The text; embedded NULs are kept.
382/// @return @c Success, or @c Error (@c 07009 for an out-of-range parameter) with the failure captured.
383[[nodiscard]] LIGHTWEIGHT_API SqlResult BindText16(Statement& stmt,
384 SqlColumnIndex parameter,
385 std::u16string_view utf16) noexcept;
386
387/// @brief Binds bytes to @p parameter; referenced or copied as by @c BindText. Empty bytes bind an empty
388/// blob, never NULL.
389/// @param stmt The statement.
390/// @param parameter The parameter.
391/// @param bytes The bytes.
392/// @return @c Success, or @c Error (@c 07009 for an out-of-range parameter) with the failure captured.
393[[nodiscard]] LIGHTWEIGHT_API SqlResult BindBlob(Statement& stmt,
394 SqlColumnIndex parameter,
395 std::span<std::byte const> bytes) noexcept;
396
397/// @brief Reads result column @p column of the current row as an integer (SQLite converts other storage classes).
398/// @param stmt The statement.
399/// @param column The column.
400/// @param value Receives the value; untouched for NULL.
401/// @param indicator Receives the byte length of the value, or @c SqlNullData for NULL; may be null unless the
402/// value is NULL.
403/// @return @c Success; @c Error with @c 07009 (column out of range), @c 24000 (no current row) or @c 22002
404/// (NULL, but @p indicator is null).
405[[nodiscard]] LIGHTWEIGHT_API SqlResult ReadInt64(Statement& stmt,
406 SqlColumnIndex column,
407 std::int64_t& value,
408 SqlIndicator* indicator) noexcept;
409
410/// @brief Reads result column @p column of the current row as a floating-point number; as @c ReadInt64.
411/// @param stmt The statement.
412/// @param column The column.
413/// @param value Receives the value; untouched for NULL.
414/// @param indicator As for @c ReadInt64.
415/// @return As for @c ReadInt64.
416[[nodiscard]] LIGHTWEIGHT_API SqlResult ReadDouble(Statement& stmt,
417 SqlColumnIndex column,
418 double& value,
419 SqlIndicator* indicator) noexcept;
420
421/// @brief Reads result column @p column of the current row as UTF-8 text, without copying it.
422///
423/// The view points into SQLite's buffer: it stays valid until the statement is stepped (@c Fetch), reset
424/// (@c Execute, @c CloseCursor, ...) or finalized, or the same column is read as UTF-16 or as a blob.
425///
426/// @param stmt The statement.
427/// @param column The column.
428/// @param utf8 Receives the text, with its full length (embedded NULs kept); untouched for NULL.
429/// @param indicator As for @c ReadInt64; the byte length.
430/// @return As for @c ReadInt64; also @c Error @c HY001 when SQLite runs out of memory converting the value.
431[[nodiscard]] LIGHTWEIGHT_API SqlResult ReadText(Statement& stmt,
432 SqlColumnIndex column,
433 std::string_view& utf8,
434 SqlIndicator* indicator) noexcept;
435
436/// @brief Reads result column @p column of the current row as UTF-16 text (native byte order), without copying it.
437///
438/// The view points into SQLite's buffer, valid as long as that of @c ReadText (reading the column as UTF-8
439/// ends it).
440///
441/// @param stmt The statement.
442/// @param column The column.
443/// @param utf16 Receives the text; untouched for NULL.
444/// @param indicator As for @c ReadInt64; the byte length (twice the code units).
445/// @return As for @c ReadText.
446[[nodiscard]] LIGHTWEIGHT_API SqlResult ReadText16(Statement& stmt,
447 SqlColumnIndex column,
448 std::u16string_view& utf16,
449 SqlIndicator* indicator) noexcept;
450
451/// @brief Reads result column @p column of the current row as bytes, without copying them.
452///
453/// The span points into SQLite's buffer, valid as long as that of @c ReadText (reading the column as text
454/// ends it).
455///
456/// @param stmt The statement.
457/// @param column The column.
458/// @param bytes Receives the bytes; untouched for NULL.
459/// @param indicator As for @c ReadInt64; the byte length.
460/// @return As for @c ReadText.
461[[nodiscard]] LIGHTWEIGHT_API SqlResult ReadBlob(Statement& stmt,
462 SqlColumnIndex column,
463 std::span<std::byte const>& bytes,
464 SqlIndicator* indicator) noexcept;
465
466/// @brief The storage class of a SQLite value.
467enum class StorageClass : std::uint8_t
468{
469 /// SQL NULL.
470 Null,
471 /// A signed integer of up to 8 bytes.
472 Integer,
473 /// An 8-byte IEEE floating-point number.
474 Float,
475 /// Text.
476 Text,
477 /// Bytes, stored as given.
478 Blob,
479};
480
481/// @brief The driver-neutral type of a value of @p storageClass, as @c ColumnType reports a column whose declared
482/// type does not name one: @c Integer is @c BigInt, @c Float @c Double, @c Text @c VarChar, @c Blob @c VarBinary,
483/// @c Null @c Unknown.
484/// @param storageClass The storage class.
485/// @return The type.
486[[nodiscard]] constexpr SqlResultColumnType TypeOfStorageClass(StorageClass storageClass) noexcept
487{
488 switch (storageClass)
489 {
490 case StorageClass::Integer:
491 return SqlResultColumnType::BigInt;
492 case StorageClass::Float:
493 return SqlResultColumnType::Double;
494 case StorageClass::Text:
495 return SqlResultColumnType::VarChar;
496 case StorageClass::Blob:
497 return SqlResultColumnType::VarBinary;
498 case StorageClass::Null:
499 break;
500 }
501 return SqlResultColumnType::Unknown;
502}
503
504/// @brief The storage class of result column @p column's value in the row at hand (the pending or the current one).
505/// @param stmt The statement.
506/// @param column The column.
507/// @return The storage class; @c Null when there is no row at hand, the column is out of range or the connection
508/// is closed.
509[[nodiscard]] LIGHTWEIGHT_API StorageClass ColumnStorageClass(Statement const& stmt, SqlColumnIndex column) noexcept;
510
511/// @brief The prepared SQL text with the values currently bound in place of the parameters
512/// (@c sqlite3_expanded_sql); unbound parameters read NULL.
513///
514/// It reads every value currently bound. A parameter stays bound across executions until it is bound again,
515/// @c ResetParameters runs or another query is prepared, and on a statement without result columns text and blobs
516/// are bound by reference: every currently bound value must still be alive when this is called. That includes
517/// values bound by an @c SqlStatement::Execute(args...) or a batch, which may be gone once that call returned (the
518/// statement resets them only at the next bind by hand). A statement with result columns copied its values when
519/// they were bound. For tests of the driver; library code must not use it for logging (it would read the caller's
520/// values at a moment the caller does not control).
521///
522/// @param stmt The statement.
523/// @return The text; empty when nothing is prepared, memory ran out, or SQLite was built without it.
524[[nodiscard]] LIGHTWEIGHT_API std::string ExpandedSql(Statement const& stmt);
525
526/// @brief The type result column @p column is declared with (@c sqlite3_column_decltype).
527///
528/// The view stays valid until the statement is stepped again (SQLite re-prepares a statement whose schema
529/// changed on its next step), prepared again or freed.
530///
531/// @param stmt The statement.
532/// @param column The column.
533/// @return The declared type as written in the schema; empty for an expression column, an out-of-range column,
534/// or when nothing is prepared.
535[[nodiscard]] LIGHTWEIGHT_API std::string_view ColumnDeclaredType(Statement const& stmt, SqlColumnIndex column) noexcept;
536
537/// @brief A registered reader: reads one column of the current row into the bound target.
538///
539/// Called by @c Fetch with the statement, the column, and the target and indicator it was registered with.
540/// It must store no pointer to anything but its target: the statement owning the handle may move.
541using OutputReader = SqlResult (*)(Statement& stmt, SqlColumnIndex column, void* target, SqlIndicator* indicator);
542
543/// @brief Registers @p reader as the reader of @p column, run on every row @c Fetch makes current.
544///
545/// Registering a column again replaces its reader. The reader table grows here, never during a fetch.
546///
547/// @param stmt The statement.
548/// @param column The column; it is not checked against the prepared statement (a reader of a column the
549/// result set lacks fails when it reads, with @c 07009).
550/// @param reader The reader; null unregisters the column.
551/// @param target Handed to @p reader on every row.
552/// @param indicator Handed to @p reader on every row.
553/// @return @c Success; @c Error with @c 07009 for column 0, @c HY001 when memory ran out, @c 08003 on a statement
554/// whose connection is closed.
555[[nodiscard]] LIGHTWEIGHT_API SqlResult RegisterOutputReader(
556 Statement& stmt, SqlColumnIndex column, OutputReader reader, void* target, SqlIndicator* indicator) noexcept;
557
558/// @brief The binder callback the readers of @c RegisterOutputColumn hand to @c SqlDataBinder<T>::GetColumn.
559///
560/// Answers @c ServerType() with @c SqlServerType::SQLITE and @c DriverName() with @c "sqlite3-native"; it
561/// refers to no statement.
562///
563/// @return The one, stateless, callback.
564[[nodiscard]] LIGHTWEIGHT_API SqlDataBinderCallback const& OutputReaderCallback() noexcept;
565
566namespace detail
567{
568 /// @brief The reader @ref RegisterOutputColumn registers for a target of type @p T: @c SqlDataBinder<T>::GetColumn,
569 /// and on a NULL the target's empty value @c T{}.
570 /// @param stmt The statement.
571 /// @param column The column.
572 /// @param target The bound @p T.
573 /// @param indicator The bound indicator.
574 /// @return What @c GetColumn returns.
575 template <typename T>
576 SqlResult ReadOutputColumn(Statement& stmt, SqlColumnIndex column, void* target, SqlIndicator* indicator)
577 {
578 auto* const result = static_cast<T*>(target);
579 auto const read = SqlDataBinder<T>::GetColumn(stmt, column, result, indicator, OutputReaderCallback());
580 // GetColumn leaves the target untouched on NULL; a bound column is made its empty value instead, so a NULL
581 // row never shows the row before it (what the ODBC path gives, and SqlStatement::GetColumn on both drivers).
582 if constexpr (std::default_initializable<T> && std::is_move_assignable_v<T>)
583 if (Succeeded(read) && indicator && *indicator == SqlNullData)
584 *result = T {};
585 return read;
586 }
587} // namespace detail
588
589/// @brief Registers @c SqlDataBinder<T>::GetColumn as the reader of @p column, filling @p result on every row
590/// (what every leaf binder's @c OutputColumn calls). A NULL row leaves @p result holding @c T{} (for a type that has
591/// one: a disengaged optional, a NULL @c SqlVariant, 0, an empty string), never the previous row's value.
592/// @param stmt The statement.
593/// @param column The column.
594/// @param result The bound target.
595/// @param indicator The bound indicator.
596/// @return As for @c RegisterOutputReader.
597template <typename T>
598[[nodiscard]] SqlResult RegisterOutputColumn(Statement& stmt,
599 SqlColumnIndex column,
600 T* result,
601 SqlIndicator* indicator) noexcept
602{
603 return RegisterOutputReader(stmt, column, &detail::ReadOutputColumn<T>, result, indicator);
604}
605
606// }}}
607
608static_assert(::Lightweight::Driver::SqlDriverStatementOperations<Driver>);
609static_assert(::Lightweight::Driver::SqlDriver<Driver>);
610
611} // namespace Lightweight::Driver::Sqlite3
void ResetParameterArrays(StatementHandle &statement) noexcept
Restores single-row parameter binding after a parameter-array execution. Not reported.
Definition Dispatch.hpp:402
void CloseCursor(StatementHandle &statement) noexcept
Closes the cursor of a result set that was read to its end. Pending result sets are left alone.
Definition Dispatch.hpp:371
SqlResult UnbindColumns(StatementHandle &statement) noexcept
Unbinds every bound result column.
Definition Dispatch.hpp:387
std::optional< std::int16_t > DescribeResultColumnSqlType(StatementHandle const &statement, SqlColumnIndex column) noexcept
The driver's own SQL type code of a result column, as the driver's leaf binders read it (see SqlDataB...
Definition Dispatch.hpp:535
void Allocate(ConnectionHandle &connection) noexcept
Allocates the driver's connection resources, unless the connection already holds them.
Definition Dispatch.hpp:569
void RequireSuccess(StatementHandle const &statement, SqlResult result, std::source_location location=std::source_location::current())
Throws unless result indicates success: std::invalid_argument for a soft failure the caller is expect...
Definition Dispatch.hpp:477
SqlResult NumResultColumns(StatementHandle const &statement, std::int16_t &count) noexcept
Reports the number of columns of the current result set.
Definition Dispatch.hpp:411
SqlResult SetQueryTimeout(StatementHandle &statement, std::chrono::seconds timeout) noexcept
Sets the query timeout of the statement.
Definition Dispatch.hpp:449
void DiscardResults(StatementHandle &statement) noexcept
Drains every pending result set and closes the cursor, so the handle can run another query....
Definition Dispatch.hpp:379
void Free(StatementHandle &statement) noexcept
Frees the statement's driver handle and leaves statement empty, bound to the same driver.
Definition Dispatch.hpp:285
SqlResult OpenCatalog(StatementHandle const &statement, SqlCatalogRequest const &request)
Opens the catalog result set request names on statement, in the layout the ODBC specification gives t...
Definition Dispatch.hpp:502
SqlResult NumParameters(StatementHandle const &statement, std::int16_t &count) noexcept
Reports the number of parameters of the prepared statement.
Definition Dispatch.hpp:420
SqlResultColumnType CatalogColumnType(StatementHandle const &statement, int dataType) noexcept
The type a DATA_TYPE code of the driver's catalog result sets (see OpenCatalog) stands for.
Definition Dispatch.hpp:512
SqlResult QueryTimeout(StatementHandle const &statement, std::chrono::seconds &timeout) noexcept
Reports the query timeout of the statement.
Definition Dispatch.hpp:458
void ResetRowArrayAttributes(StatementHandle &statement) noexcept
Restores single-row fetching after a row-array fetch. Not reported; nothing for a driver without row ...
Definition Dispatch.hpp:558
SqlResult NumRowsAffected(StatementHandle const &statement, std::ptrdiff_t &count) noexcept
Reports the number of rows the last executed statement affected.
Definition Dispatch.hpp:429
void Abandon(StatementHandle &statement) noexcept
Gives up the statement's driver handle after its connection session ended, and leaves statement empty...
Definition Dispatch.hpp:294
std::size_t DeclaredBoundColumnSize(StatementHandle const &statement, SqlColumnIndex column, SqlOutputColumnLength length) noexcept
The declared length of a result column as a bound buffer size (see SqlDataBinderCallback::MinimumOutp...
Definition Dispatch.hpp:548
SqlErrorInfo Diagnose(StatementHandle const &statement)
Reads the statement's diagnostics: the first record its last failed call left.
Definition Dispatch.hpp:466
SqlResult DescribeColumn(StatementHandle const &statement, SqlColumnIndex column, SqlColumnDescription &description)
Describes a result column: its type and its size.
Definition Dispatch.hpp:522
SqlResult ResetParameters(StatementHandle &statement) noexcept
Drops every parameter binding.
Definition Dispatch.hpp:395
std::expected< SqlResultColumnType, SqlErrorInfo > ColumnType(StatementHandle const &statement, SqlColumnIndex column)
The SQL data type of a result column, as the driver describes it.
Definition Dispatch.hpp:439
SqlResult MoreResults(StatementHandle &statement) noexcept
Advances to the next pending result set.
Definition Dispatch.hpp:364
CallOutcome CheckResult(StatementHandle const &statement, SqlResult result, std::source_location location)
The non-throwing, fault-seam-aware verdict on result.
Definition Dispatch.hpp:489
LIGHTWEIGHT_API SqlResult ReadText16(Statement &stmt, SqlColumnIndex column, std::u16string_view &utf16, SqlIndicator *indicator) noexcept
Reads result column column of the current row as UTF-16 text (native byte order), without copying it.
SqlResult RegisterOutputColumn(Statement &stmt, SqlColumnIndex column, T *result, SqlIndicator *indicator) noexcept
Registers SqlDataBinder<T>::GetColumn as the reader of column, filling result on every row (what ever...
StorageClass
The storage class of a SQLite value.
@ Float
An 8-byte IEEE floating-point number.
@ Integer
A signed integer of up to 8 bytes.
LIGHTWEIGHT_API StorageClass ColumnStorageClass(Statement const &stmt, SqlColumnIndex column) noexcept
The storage class of result column column's value in the row at hand (the pending or the current one)...
LIGHTWEIGHT_API SqlResult Fail(Statement &stmt, std::string_view sqlState, std::string_view message) noexcept
Records a failure the driver did not produce itself (a leaf binder's conversion error) as the stateme...
LIGHTWEIGHT_API SqlResult ReadBlob(Statement &stmt, SqlColumnIndex column, std::span< std::byte const > &bytes, SqlIndicator *indicator) noexcept
Reads result column column of the current row as bytes, without copying them.
LIGHTWEIGHT_API SqlResult ReadInt64(Statement &stmt, SqlColumnIndex column, std::int64_t &value, SqlIndicator *indicator) noexcept
Reads result column column of the current row as an integer (SQLite converts other storage classes).
LIGHTWEIGHT_API std::string_view ColumnDeclaredType(Statement const &stmt, SqlColumnIndex column) noexcept
The type result column column is declared with (sqlite3_column_decltype).
SqlResult(*)(Statement &stmt, SqlColumnIndex column, void *target, SqlIndicator *indicator) OutputReader
A registered reader: reads one column of the current row into the bound target.
LIGHTWEIGHT_API SqlResult BindInt64(Statement &stmt, SqlColumnIndex parameter, std::int64_t value) noexcept
Binds an integer to parameter, by value.
LIGHTWEIGHT_API SqlResult BindNull(Statement &stmt, SqlColumnIndex parameter) noexcept
Binds SQL NULL to parameter; it counts as bound for Execute (bind unused numbered parameters this way...
LIGHTWEIGHT_API SqlResult ReadText(Statement &stmt, SqlColumnIndex column, std::string_view &utf8, SqlIndicator *indicator) noexcept
Reads result column column of the current row as UTF-8 text, without copying it.
LIGHTWEIGHT_API SqlResult RegisterOutputReader(Statement &stmt, SqlColumnIndex column, OutputReader reader, void *target, SqlIndicator *indicator) noexcept
Registers reader as the reader of column, run on every row Fetch makes current.
LIGHTWEIGHT_API SqlResult BindBlob(Statement &stmt, SqlColumnIndex parameter, std::span< std::byte const > bytes) noexcept
Binds bytes to parameter; referenced or copied as by BindText. Empty bytes bind an empty blob,...
LIGHTWEIGHT_API SqlResult BindText(Statement &stmt, SqlColumnIndex parameter, std::string_view utf8) noexcept
Binds UTF-8 text to parameter; an empty view binds empty text, never NULL.
LIGHTWEIGHT_API SqlDataBinderCallback const & OutputReaderCallback() noexcept
The binder callback the readers of RegisterOutputColumn hand to SqlDataBinder<T>::GetColumn.
LIGHTWEIGHT_API std::string ExpandedSql(Statement const &stmt)
The prepared SQL text with the values currently bound in place of the parameters (sqlite3_expanded_sq...
LIGHTWEIGHT_API SqlResult BindText16(Statement &stmt, SqlColumnIndex parameter, std::u16string_view utf16) noexcept
Binds UTF-16 text (native byte order) to parameter; referenced or copied as by BindText.
LIGHTWEIGHT_API SqlResult BindDouble(Statement &stmt, SqlColumnIndex parameter, double value) noexcept
Binds a floating-point number to parameter, by value.
constexpr SqlResultColumnType TypeOfStorageClass(StorageClass storageClass) noexcept
The driver-neutral type of a value of storageClass, as ColumnType reports a column whose declared typ...
LIGHTWEIGHT_API SqlResult ReadDouble(Statement &stmt, SqlColumnIndex column, double &value, SqlIndicator *indicator) noexcept
Reads result column column of the current row as a floating-point number; as ReadInt64.
@ Execute
The execution of a prepared statement (SqlStatement::Execute).
@ ExecuteDirect
The execution of a one-shot statement (SqlStatement::ExecuteDirect).
@ Prepare
The preparation of a statement (SqlStatement::Prepare).
bool succeeded
Whether the checked call should be treated as having succeeded.
Definition Concept.hpp:78
What a catalog call asks for: the ODBC catalog function and its arguments, in driver-neutral terms.
Definition Concept.hpp:136
What a driver reports about a result column (see DescribeColumn).
Definition Concept.hpp:172
The SQLite3 driver's connection handle struct: one pointer to the driver-owned connection state.
Definition Handles.hpp:38
The SQLite3 driver's statement handle struct: one pointer to the driver-owned statement state.
Definition Handles.hpp:48
Represents a SQL error as reported by the database driver.
Definition SqlError.hpp:29