Lightweight 0.20261105.1
Loading...
Searching...
No Matches
SqlStatement.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5// See SqlOdbcPrelude.hpp's header comment for why this replaces a direct <Windows.h> include.
6#include "Api.hpp"
7#include "DataBinder/Core.hpp"
8#include "DataBinder/SqlDate.hpp"
9#include "DataBinder/SqlDateTime.hpp"
10#include "DataBinder/SqlDynamicNumeric.hpp"
11#include "DataBinder/SqlFixedString.hpp"
12#include "DataBinder/SqlGuid.hpp"
13#include "DataBinder/SqlNumeric.hpp"
14#include "DataBinder/StringInterface.hpp"
15#include "DataBinder/UnicodeConverter.hpp"
16#include "DataMapper/Record.hpp"
17#include "Driver/Dispatch.hpp"
18#include "Driver/DriverSet.hpp"
19#if defined(LIGHTWEIGHT_DRIVER_ODBC)
20 #include "Driver/Odbc/Diagnostics.hpp"
21 #include "Driver/Odbc/RowArrayCursor.hpp"
22 #include "Driver/Odbc/SqlOdbcPrelude.hpp"
23#endif
24#include "SqlConnection.hpp"
25#include "SqlPreparedStatementCache.hpp"
26#include "SqlQuery.hpp"
27#include "SqlQueryFormatter.hpp"
28#include "SqlServerType.hpp"
29#include "SqlStatistics.hpp"
30#include "TracyProfiler.hpp"
31#include "Utils.hpp"
32
33#include <reflection-cpp/reflection.hpp>
34
35#include <algorithm>
36#include <array>
37#include <charconv>
38#include <chrono>
39#include <cmath>
40#include <concepts>
41#include <cstdint>
42#include <cstring>
43#include <expected>
44#include <format>
45#include <functional>
46#include <limits>
47#include <optional>
48#include <ranges>
49#include <source_location>
50#include <span>
51#include <stdexcept>
52#include <string>
53#include <string_view>
54#include <type_traits>
55#include <utility>
56#include <vector>
57
58namespace Lightweight
59{
60
61#if defined(LIGHTWEIGHT_DRIVER_ODBC)
62struct SqlRawColumn;
63#endif
64
65/// @brief Represents an SQL query object, that provides a ToSql() method.
66template <typename QueryObject>
67concept SqlQueryObject = requires(QueryObject const& queryObject) {
68 { queryObject.ToSql() } -> std::convertible_to<std::string>;
69};
70
71/// @brief Represents a query object that also knows the name of each column it projects.
72///
73/// Satisfied by the SELECT query builder's composed query, which records the caller-given name of every
74/// projected column as the projection is assembled. Statements executed from such a query object can
75/// resolve result columns by name — see the name-taking @c GetColumn overload of @c SqlResultCursor.
76template <typename QueryObject>
77concept SqlNamedProjectionQueryObject = SqlQueryObject<QueryObject> && requires(QueryObject const& queryObject) {
78 { queryObject.ProjectedFieldNames() } -> std::convertible_to<std::span<std::string const>>;
79 { queryObject.ProjectionHasWildcard() } -> std::convertible_to<bool>;
80};
81
82class SqlResultCursor;
83class SqlVariantRowCursor;
84#if defined(LIGHTWEIGHT_DRIVER_ODBC)
85class RowArrayCursor;
86#endif
87template <typename T>
88class SqlRowIterator;
89
90/// @brief High level API for (prepared) raw SQL statements
91///
92/// @ingroup CoreApi
93/// SQL prepared statement lifecycle:
94/// 1. Prepare the statement
95/// 2. Optionally bind output columns to local variables
96/// 3. Execute the statement (optionally with input parameters)
97/// 4. Fetch rows (if any)
98/// 5. Repeat steps 3 and 4 as needed
99class [[nodiscard]] SqlStatement final: public SqlDataBinderCallback
100{
101 public:
102 /// Construct a new SqlStatement object, using a new connection, and connect to the default database.
103 LIGHTWEIGHT_API SqlStatement();
104
105 /// Move constructor.
106 LIGHTWEIGHT_API SqlStatement(SqlStatement&& other) noexcept;
107 /// Move assignment operator.
108 LIGHTWEIGHT_API SqlStatement& operator=(SqlStatement&& other) noexcept;
109
110 SqlStatement(SqlStatement const&) noexcept = delete;
111 SqlStatement& operator=(SqlStatement const&) noexcept = delete;
112
113 /// Construct a new SqlStatement object, using the given connection.
114 LIGHTWEIGHT_API explicit SqlStatement(SqlConnection& relatedConnection);
115
116 /// Construct a new empty SqlStatement object. No SqlConnection is associated with this statement.
117 LIGHTWEIGHT_API explicit SqlStatement(std::nullopt_t /*nullopt*/);
118
119 LIGHTWEIGHT_API ~SqlStatement() noexcept final;
120
121 /// Checks whether the statement's connection is alive and the statement handle is valid.
122 [[nodiscard]] LIGHTWEIGHT_API bool IsAlive() const noexcept;
123
124 /// Checks whether the statement has been prepared.
125 [[nodiscard]] LIGHTWEIGHT_API bool IsPrepared() const noexcept;
126
127 /// Retrieves the connection associated with this statement.
128 [[nodiscard]] LIGHTWEIGHT_API SqlConnection& Connection() noexcept;
129
130 /// Retrieves the connection associated with this statement.
131 [[nodiscard]] LIGHTWEIGHT_API SqlConnection const& Connection() const noexcept;
132
133 /// Retrieves the last error information with respect to this SQL statement handle.
134 [[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo LastError() const;
135
136 /// Creates a new query builder for the given table, compatible with the SQL server being connected.
137 LIGHTWEIGHT_API SqlQueryBuilder Query(std::string_view const& table = {}) const;
138
139 /// Creates a new query builder for the given table with an alias, compatible with the SQL server being connected.
140 [[nodiscard]] LIGHTWEIGHT_API SqlQueryBuilder QueryAs(std::string_view const& table,
141 std::string_view const& tableAlias) const;
142
143 /// @return The tagged driver handle of the statement; empty when the statement holds none.
144 [[nodiscard]] Driver::StatementHandle const& DriverHandle() const noexcept;
145
146 /// Visits the statement's real driver struct, for driver-level code (schema/catalog, backup) that runs
147 /// driver operations which act on it.
148 ///
149 /// @param operation The name of the operation @p f performs, for the error message.
150 /// @param f Called with the driver's statement struct by reference; do not store the reference. It
151 /// typically takes one driver's struct only.
152 /// @return What @p f returns.
153 /// @throws SqlException with SQLSTATE @c IM001 (@c Driver::NotSupportedByDriver) when @p f cannot take
154 /// the struct of the driver the statement is bound to.
155 template <typename F>
156 decltype(auto) VisitDriver(std::string_view operation, F&& f);
157
158 /// Visits the statement's driver struct read-only, for driver-level code (schema/catalog, backup).
159 ///
160 /// @param operation The name of the operation @p f performs, for the error message.
161 /// @param f Called with the driver's statement struct by const reference; do not store the reference.
162 /// @return What @p f returns.
163 /// @throws SqlException with SQLSTATE @c IM001 when @p f cannot take the struct of the statement's driver.
164 template <typename F>
165 decltype(auto) VisitDriver(std::string_view operation, F&& f) const;
166
167 /// @return The id of the driver the statement was last bound to; valid on a moved-from statement too.
168 [[nodiscard]] SqlDriverId DriverId() const noexcept;
169
170 /// Prepares the statement for execution.
171 ///
172 /// @note When preparing a new SQL statement the previously executed statement, yielding a result set,
173 /// must have been closed.
174 LIGHTWEIGHT_API void Prepare(std::string_view query) &;
175
176 /// Prepares the statement for execution on an rvalue reference and returns the statement.
177 LIGHTWEIGHT_API SqlStatement Prepare(std::string_view query) &&;
178
179 /// Prepares the statement for execution.
180 ///
181 /// @note When preparing a new SQL statement the previously executed statement, yielding a result set,
182 /// must have been closed.
183 void Prepare(SqlQueryObject auto const& queryObject) &;
184
185 /// Prepares the statement from a query object on an rvalue reference and returns the statement.
186 SqlStatement Prepare(SqlQueryObject auto const& queryObject) &&;
187
188 /// Retrieves the last prepared query string.
189 [[nodiscard]] std::string const& PreparedQuery() const noexcept;
190
191 /// @brief Whether this statement takes part in its connection's prepared-statement cache.
192 /// @return The configured participation mode (@c SqlPreparedStatementCaching::Enabled by default).
193 [[nodiscard]] SqlPreparedStatementCaching PreparedStatementCaching() const noexcept;
194
195 /// @brief Opts this statement in or out of its connection's prepared-statement cache.
196 ///
197 /// Only has an effect while the connection has a non-zero cache capacity (see
198 /// @c SqlConnection::SetPreparedStatementCacheCapacity). Opt out for a statement whose query plan
199 /// must be re-derived — for instance because it runs across a schema change.
200 ///
201 /// The handle this statement currently holds is unaffected; from the next @c Prepare() on it is
202 /// simply neither taken from nor given back to the pool.
203 ///
204 /// @param caching Whether pooled handles may be reused by, and published from, this statement.
205 LIGHTWEIGHT_API void SetPreparedStatementCaching(SqlPreparedStatementCaching caching) noexcept;
206
207 /// @brief Bounds how long each later execution of this statement may run, where the driver supports it.
208 ///
209 /// The timeout belongs to this statement: it stays in effect across @c Prepare() and @c ExecuteDirect(),
210 /// also when the prepared-statement cache gives the statement another ODBC handle, and it never reaches
211 /// another statement of the connection, not even one that takes over this statement's pooled handle.
212 /// It bounds a single execution rather than a sequence of them, and neither a @c DataMapper nor a
213 /// lazily loaded relation uses it.
214 ///
215 /// What the driver does with it (see docs/usage.md):
216 /// - MS SQL Server fails the execution with SQLSTATE @c HYT00.
217 /// - PostgreSQL fails it with SQLSTATE @c 57014.
218 /// - SQLite ignores it: the query runs to completion, and @ref QueryTimeout() reads @c 0.
219 ///
220 /// @c IsQueryTimeoutError recognises both failures. @ref SqlRetryPolicy treats SQL Server's @c HYT00 as
221 /// transient, so running such a statement under a retry policy spends the timeout once per attempt.
222 ///
223 /// @param timeout The bound in whole seconds; @c 0 lifts it.
224 /// @throws std::invalid_argument If @p timeout is negative.
225 /// @throws SqlException If the driver rejects the value.
226 LIGHTWEIGHT_API void SetQueryTimeout(std::chrono::seconds timeout);
227
228 /// @brief Reads the query timeout from the driver.
229 ///
230 /// A driver that ignores the timeout reports @c 0 here whatever was set, so this tells whether
231 /// @ref SetQueryTimeout() can have any effect.
232 ///
233 /// @return The timeout currently in effect on the statement handle; @c 0 means none.
234 /// @throws SqlException If the driver cannot report it.
235 [[nodiscard]] LIGHTWEIGHT_API std::chrono::seconds QueryTimeout() const;
236
237 /// Binds an input parameter to the prepared statement at the given column index.
238 ///
239 /// The value is bound by address: the driver reads it at every @c Execute() until the parameter is
240 /// bound again or another query is prepared, so @p arg must stay alive as long as it is executed.
241 /// Temporaries are therefore rejected at compile time. A copy the binder made of @p arg (e.g. a
242 /// converted string) is kept by the statement for as long as the binding.
243 ///
244 /// Some binders bind a copy, made when binding, rather than @p arg itself: @c SqlGuid, @c SqlDynamicNumeric,
245 /// text that is converted (UTF-8 and UTF-32 strings everywhere, narrow strings on PostgreSQL or under the
246 /// SQLite driver's code-page option), @c SqlDateTime on the legacy SQL Server driver, and on SQLite
247 /// @c int8_t and @c uint32_t. For those, a change to @p arg after binding is not seen by the next
248 /// @c Execute(): bind the value again (or pass it to @c Execute()) after changing it.
249 ///
250 /// The indicator and staging storage a bind takes belongs to its parameter and is reused by that
251 /// parameter's binding after next, so binding by hand and executing in a loop, prepared or direct, holds at
252 /// most two bindings' storage per parameter; it is freed with the statement. A copy a binder made is released
253 /// when its parameter is bound again after an execution, so it does not accumulate either.
254 ///
255 /// The values an execute with arguments or a batch bound need not outlive that call, so the first bind by hand
256 /// after it resets those bindings: bind every parameter again before the next @c Execute(), or it fails with
257 /// the driver's "parameter not bound" error.
258 ///
259 /// @param columnIndex The 1-based parameter index.
260 /// @param arg The value to bind; it must outlive every @c Execute() of this binding.
261 template <SqlInputParameterBinder Arg>
262 void BindInputParameter(std::int16_t columnIndex, Arg const& arg);
263
264 /// Binds an input parameter to the prepared statement at the given column index with a column name hint.
265 ///
266 /// @param columnIndex The 1-based parameter index.
267 /// @param arg The value to bind; it must outlive every @c Execute() of this binding.
268 /// @param columnNameHint The column name, reported to the SQL logger.
269 template <SqlInputParameterBinder Arg, typename ColumnName>
270 void BindInputParameter(std::int16_t columnIndex, Arg const& arg, ColumnName&& columnNameHint);
271
272 /// Deleted: a temporary would be destroyed before the driver reads it at @c Execute() time.
273 template <SqlInputParameterBinder Arg>
274 void BindInputParameter(std::int16_t columnIndex, Arg const&& arg) = delete;
275
276 /// Deleted: a temporary would be destroyed before the driver reads it at @c Execute() time.
277 template <SqlInputParameterBinder Arg, typename ColumnName>
278 void BindInputParameter(std::int16_t columnIndex, Arg const&& arg, ColumnName&& columnNameHint) = delete;
279
280 /// Binds the given arguments to the prepared statement and executes it.
281 ///
282 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
283 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
284 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
285 template <SqlInputParameterBinder... Args>
286 [[nodiscard]] SqlResultCursor Execute(Args const&... args);
287
288 /// Binds the given arguments to the prepared statement and executes it.
289 ///
290 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
291 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
292 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
293 [[nodiscard]] LIGHTWEIGHT_API SqlResultCursor ExecuteWithVariants(std::vector<SqlVariant> const& args);
294
295 /// Executes the prepared statement on a batch of data.
296 ///
297 /// Each parameter represents a column, to be bound as input parameter.
298 /// The element types of each column container must be explicitly supported.
299 ///
300 /// In order to support column value types, their underlying storage must be contiguous.
301 /// Also the input range itself must be contiguous.
302 /// If any of these conditions are not met, the function will not compile - use ExecuteBatch() instead.
303 ///
304 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
305 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
306 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
307 ///
308 /// @throws SqlException with SQLSTATE IM001 on a driver without parameter arrays (every driver of a build
309 /// without ODBC).
310 template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::contiguous_range... MoreColumnBatches>
311 [[nodiscard]] SqlResultCursor ExecuteBatchNative(FirstColumnBatch const& firstColumnBatch,
312 MoreColumnBatches const&... moreColumnBatches);
313
314 /// Executes the prepared statement on a batch of data.
315 ///
316 /// Each parameter represents a column, to be bound as input parameter,
317 /// and the number of elements in these bound column containers will
318 /// mandate how many executions will happen.
319 ///
320 /// This function will bind and execute each row separately,
321 /// which is less efficient than ExecuteBatchNative(), but works non-contiguous input ranges.
322 ///
323 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
324 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
325 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
326 template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::range... MoreColumnBatches>
327 [[nodiscard]] SqlResultCursor ExecuteBatchSoft(FirstColumnBatch const& firstColumnBatch,
328 MoreColumnBatches const&... moreColumnBatches);
329
330 /// Executes the prepared statement on a batch of data.
331 ///
332 /// Each parameter represents a column, to be bound as input parameter,
333 /// and the number of elements in these bound column containers will
334 /// mandate how many executions will happen.
335 ///
336 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
337 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
338 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
339 template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::range... MoreColumnBatches>
340 [[nodiscard]] SqlResultCursor ExecuteBatch(FirstColumnBatch const& firstColumnBatch,
341 MoreColumnBatches const&... moreColumnBatches);
342
343#if defined(LIGHTWEIGHT_DRIVER_ODBC)
344 /// Executes the prepared statement on a batch of SqlRawColumn-prepared data.
345 ///
346 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
347 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
348 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
349 ///
350 /// @param columns The columns to bind as input parameters.
351 /// @param rowCount The number of rows to execute.
352 [[nodiscard]] LIGHTWEIGHT_API SqlResultCursor ExecuteBatch(std::span<SqlRawColumn const> columns, size_t rowCount);
353
354 /// Executes the prepared statement on a batch of SqlRawColumn-prepared data, reporting the
355 /// outcome of each row (parameter set).
356 ///
357 /// Unlike the overload without a status array, this one does not accept a partial success: a
358 /// driver that continues past a failing parameter set (SQL Server does) returns
359 /// `SQL_SUCCESS_WITH_INFO`, which only the status array tells apart from a full success.
360 /// The status and processed pointers are bound for this execution only, and reset on every exit.
361 ///
362 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
363 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
364 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
365 ///
366 /// @param columns The columns to bind as input parameters.
367 /// @param rowCount The number of rows to execute.
368 /// @param paramStatus Receives one status per row (`SQL_PARAM_SUCCESS`, `SQL_PARAM_ERROR`, ...);
369 /// at least @p rowCount entries. Entries the driver does not fill read `SQL_PARAM_UNUSED`;
370 /// a driver that stops at the first failing row leaves the rows after it that way.
371 /// @param paramsProcessed Receives the number of rows the driver processed; @p rowCount if the
372 /// driver does not report it.
373 /// @return The cursor of the execution.
374 /// @throws SqlException if the execution fails, if any row reports `SQL_PARAM_ERROR` (carrying
375 /// the first diagnostic record), or if the driver processed fewer than @p rowCount rows.
376 /// @p paramStatus and @p paramsProcessed hold what the driver reported either way.
377 /// @throws std::invalid_argument if the column count does not match the prepared statement or
378 /// @p paramStatus holds fewer than @p rowCount entries.
379 [[nodiscard]] LIGHTWEIGHT_API SqlResultCursor ExecuteBatch(std::span<SqlRawColumn const> columns,
380 std::size_t rowCount,
381 std::span<Driver::Odbc::RowStatus> paramStatus,
382 Driver::Odbc::ProcessedCount& paramsProcessed);
383#endif
384
385 /// Executes the prepared statement once per row of a *row-major* batch, preferring native ODBC
386 /// row-wise array binding (a single zero-copy @c SQLExecute) and transparently falling back to a
387 /// prepare-once + per-row execute when native binding is not possible.
388 ///
389 /// Unlike the column-major @c ExecuteBatch overloads, the data here is laid out as an array of row
390 /// structs (e.g. records). Each @p accessors invocable maps a row to one bound column's value,
391 /// returning a reference into the row (so the native path binds the value in place):
392 /// @code
393 /// stmt.ExecuteBatch(std::span { records }, [](Record const& r) -> auto const& { return r.id.Value(); }, ...);
394 /// @endcode
395 ///
396 /// The native row-wise path is taken when every column value type is row-bindable
397 /// (@c SqlNativeRowBindableValue, or @c std::optional of such a non-numeric type), every accessor
398 /// returns an lvalue reference, the row stride satisfies the indicator-alignment requirement, and the
399 /// driver advertises parameter-array support (@ref SqlConnection::SupportsNativeRowBatch). A
400 /// per-row runtime stride check guards against accessors that are not constant-offset subobjects.
401 /// Otherwise the soft path is used, which correctly binds every supported type (strings, binary,
402 /// variant, @c std::optional of any type, …) one row at a time. An accessor may also return its value
403 /// by value (a computed or converted value): the soft path keeps that value alive until its row has
404 /// executed. An accessor may be called more than once per row (a check of every row's values runs
405 /// before the first row is bound), and the accessors of one row are called in an unspecified order, so
406 /// they should be free of side effects.
407 ///
408 /// A parameter bound by hand afterwards first resets the bindings this call made, so every parameter must
409 /// then be bound again: an @c Execute() with one left unbound fails (07002 on SQL Server and the native SQLite3
410 /// driver, HY000 through the SQLite and PostgreSQL ODBC drivers, measured on Windows).
411 ///
412 /// @param rows Contiguous range of row structs (e.g. @c std::span<Record const>).
413 /// @param accessors One invocable per bound column; @c accessor(row) yields that column's value.
414 /// @return A result cursor for the executed batch (empty when @p rows is empty).
415 template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
416 requires(sizeof...(ColumnAccessors) >= 1
417 && (std::invocable<ColumnAccessors const&, std::ranges::range_value_t<Rows> const&> && ...))
418 [[nodiscard]] SqlResultCursor ExecuteBatch(Rows const& rows, ColumnAccessors const&... accessors);
419
420 /// Executes the given query directly.
421 [[nodiscard]] LIGHTWEIGHT_API SqlResultCursor
422 ExecuteDirect(std::string_view const& query, std::source_location location = std::source_location::current());
423
424 /// Executes the given query directly.
425 [[nodiscard]] SqlResultCursor ExecuteDirect(SqlQueryObject auto const& query,
426 std::source_location location = std::source_location::current());
427
428#if defined(LIGHTWEIGHT_DRIVER_ODBC)
429 /// Executes @p query and prepares bulk row-array fetching with up to @p arrayDepth rows per
430 /// SQLFetchScroll round-trip.
431 ///
432 /// This is a fast-path alternative to the per-cell SQLGetData loop used by the regular result
433 /// cursor: it binds one contiguous buffer per result column and materializes whole row blocks
434 /// per ODBC round-trip. Only fixed-stride column types are supported (integers, floating point,
435 /// and bounded character columns). LOB / unbounded columns (varchar(max)/text/varbinary(max))
436 /// are rejected by the returned cursor's construction.
437 ///
438 /// @param query The SQL query to execute.
439 /// @param arrayDepth Maximum number of rows materialized per SQLFetchScroll call (must be > 0).
440 /// @return A RowArrayCursor bound to this statement's result set.
441 [[nodiscard]] LIGHTWEIGHT_API RowArrayCursor ExecuteBatchFetch(std::string_view query, std::size_t arrayDepth);
442#endif
443
444 /// Executes an SQL migration query, as created b the callback.
445 template <typename Callable>
446 requires std::invocable<Callable, SqlMigrationQueryBuilder&>
447 void MigrateDirect(Callable const& callable, std::source_location location = std::source_location::current());
448
449 /// Executes the given query, assuming that only one result row and column is affected, that one will be
450 /// returned.
451 ///
452 /// @return The first column of the first row, or @c std::nullopt when that value is NULL or the query
453 /// returned no row.
454 template <typename T>
455 requires(!std::same_as<T, SqlVariant>)
456 [[nodiscard]] std::optional<T> ExecuteDirectScalar(std::string_view const& query,
457 std::source_location location = std::source_location::current());
458
459 /// Executes the given query and returns the single result as an SqlVariant.
460 ///
461 /// @return The first column of the first row; a NULL value as @c SqlNullValue.
462 /// @throws SqlException (SQLSTATE 02000) when the query returned no row.
463 template <typename T>
464 requires(std::same_as<T, SqlVariant>)
465 [[nodiscard]] T ExecuteDirectScalar(std::string_view const& query,
466 std::source_location location = std::source_location::current());
467
468 /// Executes the given query, assuming that only one result row and column is affected, that one will be
469 /// returned.
470 ///
471 /// @return The first column of the first row, or @c std::nullopt when that value is NULL or the query
472 /// returned no row.
473 template <typename T>
474 requires(!std::same_as<T, SqlVariant>)
475 [[nodiscard]] std::optional<T> ExecuteDirectScalar(SqlQueryObject auto const& query,
476 std::source_location location = std::source_location::current());
477
478 /// Executes the given query object and returns the single result as an SqlVariant.
479 ///
480 /// @return The first column of the first row; a NULL value as @c SqlNullValue.
481 /// @throws SqlException (SQLSTATE 02000) when the query returned no row.
482 template <typename T>
483 requires(std::same_as<T, SqlVariant>)
484 [[nodiscard]] T ExecuteDirectScalar(SqlQueryObject auto const& query,
485 std::source_location location = std::source_location::current());
486
487 /// Retrieves the last insert ID of the given table.
488 [[nodiscard]] LIGHTWEIGHT_API size_t LastInsertId(std::string_view tableName);
489
490 /// @brief Steps through every result the last execution still has pending and throws for the
491 /// first one that failed.
492 ///
493 /// A batch of several statements can report an error of a later statement only when its
494 /// result is reached (on SQL Server, every statement that produces a row count is a result of
495 /// its own). Closing the cursor discards those results without looking, because it must not
496 /// throw. Call this after executing a batch whose failure must not go unnoticed.
497 ///
498 /// @param location The caller's source location, reported with the error.
499 /// @throws SqlException A pending result reports an error; 08003 when the statement's connection session
500 /// ended (see SqlConnection::SessionId()).
501 LIGHTWEIGHT_API void ConsumePendingResults(std::source_location location = std::source_location::current());
502
503 private:
504 friend class SqlResultCursor;
505#if defined(LIGHTWEIGHT_DRIVER_ODBC)
506 friend class RowArrayCursor;
507#endif
508 friend class SqlVariantRowIterator;
509 template <typename T>
510 friend class SqlRowIterator;
511
512 /// @return The number of rows the last query affected.
513 /// @throws SqlException 08003 when the statement's connection session ended.
514 [[nodiscard]] LIGHTWEIGHT_API size_t NumRowsAffected() const;
515 /// @return The number of columns of the last query's result set.
516 /// @throws SqlException 08003 when the statement's connection session ended.
517 [[nodiscard]] LIGHTWEIGHT_API size_t NumColumnsAffected() const;
518 [[nodiscard]] LIGHTWEIGHT_API bool FetchRow();
519 [[nodiscard]] LIGHTWEIGHT_API std::expected<bool, SqlErrorInfo> TryFetchRow(
520 std::source_location location = std::source_location::current()) noexcept;
521 void CloseCursor() noexcept;
522
523 /// @brief Binds the given output column variables to the result columns of this statement.
524 ///
525 /// The binding outlives the result set and the cursor: executing the prepared statement again
526 /// fetches into the same variables. Preparing or directly executing another query drops it.
527 /// @tparam Args ODBC-bindable output column types.
528 /// @param args Pointers to caller-owned storage for each result column, in order.
529 template <SqlOutputColumnBinder... Args>
530 void BindOutputColumns(Args*... args);
531
532 /// @brief Binds the members of @p records to the result columns of this statement
533 /// in declaration order, via reflection.
534 /// @tparam Records Aggregate record types whose members map to result columns.
535 /// @param records Pointers to caller-owned record instances.
536 template <typename... Records>
537 requires(((std::is_class_v<Records> && std::is_aggregate_v<Records>) && ...))
538 void BindOutputColumnsToRecord(Records*... records);
539
540 /// @brief Binds a single output column variable to the result column at @p columnIndex.
541 /// @tparam T An ODBC-bindable output column type.
542 /// @param columnIndex 1-based result column index.
543 /// @param arg Pointer to caller-owned storage for the column value.
544 template <SqlOutputColumnBinder T>
545 void BindOutputColumn(SqlColumnIndex columnIndex, T* arg);
546
547 /// @brief Reads column @p column of the current row into @p result.
548 /// @param column 1-based result column index.
549 /// @param result Receives the value; on NULL its empty value (@c std::nullopt, a NULL @c SqlVariant,
550 /// @c T {}), on the per-row and the block-prefetched path alike, and on every driver.
551 /// @return @c false if the value is NULL.
552 template <SqlGetColumnNativeType T>
553 [[nodiscard]] bool GetColumn(SqlColumnIndex column, T* result) const;
554
555 /// @brief Reads column @p column of the current row.
556 /// @param column 1-based result column index.
557 /// @return The value. A NULL cell reads as @c std::nullopt or a NULL @c SqlVariant for those two
558 /// types; for any other @p T it throws @c std::runtime_error, on the per-row and the
559 /// block-prefetched path alike.
560 template <SqlGetColumnNativeType T>
561 [[nodiscard]] T GetColumn(SqlColumnIndex column) const;
562
563 /// @brief Native row-wise batch execution: binds each column in place over @p rows and submits the
564 /// whole batch in a single @c SQLExecute. Precondition: every column is row-bindable.
565 template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
566 [[nodiscard]] SqlResultCursor ExecuteBatchNativeRowWise(Rows const& rows, ColumnAccessors const&... accessors);
567
568 /// @brief Soft row-major batch execution: binds and executes each row individually. Works for every
569 /// supported column type and is the fallback when native row-wise binding does not apply.
570 template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
571 [[nodiscard]] SqlResultCursor ExecuteBatchSoftRowMajor(Rows const& rows, ColumnAccessors const&... accessors);
572
573 /// @brief Native row-wise array fetch: materializes the already-executed result set into @p out by
574 /// binding every result column row-wise over a contiguous block of @p out's records and pulling whole
575 /// blocks per @c SQLFetchScroll round-trip. The read-side mirror of @c ExecuteBatchNativeRowWise.
576 ///
577 /// Each @p accessors invocable maps a record to one bound column's mutable value reference (the same
578 /// declaration-order column set the per-row path binds), so the driver writes results in place — no
579 /// per-cell @c SQLGetData and no intermediate copy. @p out is grown a block at a time and trimmed to
580 /// the exact row count on the final partial block.
581 ///
582 /// A result set with an @c int8_t or @c uint32_t column is read per row where the driver does not convert
583 /// those C types over their full range (SQLite, see @c SqlQueryFormatter::ConvertsNarrowIntegerCTypes).
584 ///
585 /// @pre Every accessor's value type satisfies @c SqlRowWiseFetchableColumn and
586 /// @c sizeof(Record) % alignof(SqlIndicator) == 0 (so the row-strided indicator slots stay aligned).
587 /// The caller (DataMapper) guarantees both before selecting this path.
588 /// @param out Destination vector; results are appended to its current contents.
589 /// @param arrayDepth Requested maximum rows per @c SQLFetchScroll (clamped to a memory budget).
590 /// @param accessors One invocable per result column; @c accessor(record) yields its mutable value.
591 /// @throws SqlException when a fetch fails, a row of a block comes back with an error (the first diagnostic
592 /// that is not a warning), or a fetched @c bool stands for neither @c false nor @c true (22003).
593 /// @p out then holds what it held before plus the rows of the blocks fetched in full before the failing
594 /// one; the failing block's rows are removed.
595 /// @throws std::logic_error in a build without ODBC, should the connection ever claim row-array fetches
596 /// (no driver of such a build fetches blocks of rows).
597 template <typename Record, typename... ColumnAccessors>
598 void FetchAllRowWise(std::vector<Record>& out, std::size_t arrayDepth, ColumnAccessors const&... accessors);
599
600 /// @brief Row-wise array-binds one output column over a record block; returns the row-strided
601 /// indicator buffer to feed @c FinalizeRowWiseOutputColumn. For optional columns every row's
602 /// optional is pre-engaged so the contained storage is valid to bind into.
603 template <typename ValueType>
604 [[nodiscard]] SqlIndicator* BindRowWiseOutputColumn(SqlColumnIndex column,
605 void* base0,
606 std::size_t rowStride,
607 std::size_t depth);
608
609 /// @brief Issues the row-wise @c SQLBindCol for one non-optional value type @p Value at @p base0 (the
610 /// value slot in record 0; the driver strides it by the active @c SQL_ATTR_ROW_BIND_TYPE). Fixed-
611 /// capacity char strings bind their inline buffer as @c SQL_C_CHAR (length fixed up per row
612 /// afterwards); all other types bind in place via their @c SqlDataBinder::OutputColumn.
613 template <typename Value>
614 void BindRowWiseValue(SqlColumnIndex column, void* base0, SqlIndicator* indicators);
615
616 /// @brief Post-fetch fixup for one row-wise output column: resets each NULL row's @c std::optional to
617 /// @c std::nullopt (no-op for non-optional columns, whose value is materialized in place), and checks each
618 /// @c bool the driver wrote in place (see @ref CheckRowWiseBool).
619 /// @param booleanTrueMayBeMinusOne Whether the byte 0xFF is the dialect's form of a boolean true.
620 /// @throws SqlException 22003 for a @c bool byte that stands for neither @c false nor @c true.
621 template <typename ValueType>
622 static void FinalizeRowWiseOutputColumn(void* base0,
623 std::size_t rowStride,
624 std::size_t rowCount,
625 SqlIndicator const* indicators,
626 SqlColumnIndex column,
627 bool booleanTrueMayBeMinusOne);
628
629 /// @brief Checks the byte the driver wrote in place into a row-wise fetched @c bool: 0 and 1 stay, 0xFF (a
630 /// boolean true reported as -1) becomes 1 where @p booleanTrueMayBeMinusOne, and anything else (the PostgreSQL
631 /// driver writes a number's low byte) is set to 0, so the record holds a valid @c bool, and fails the fetch
632 /// with SQLSTATE 22003, as the per-row read of that @c bool does.
633 /// @param value The record's @c bool, read and written only as its byte.
634 /// @param column The 1-based column index, for the error.
635 /// @param booleanTrueMayBeMinusOne Whether the byte 0xFF is the dialect's form of a boolean true.
636 static void CheckRowWiseBool(bool* value, SqlColumnIndex column, bool booleanTrueMayBeMinusOne);
637
638 template <SqlGetColumnNativeType T>
639 [[nodiscard]] std::optional<T> GetNullableColumn(SqlColumnIndex column) const;
640
641 template <SqlGetColumnNativeType T>
642 [[nodiscard]] T GetColumnOr(SqlColumnIndex column, T&& defaultValue) const;
643
644 /// @brief Resolves a projected column name to its 1-based result column index.
645 ///
646 /// The mapping comes from the query builder that composed the statement's query, not from the
647 /// driver: result-set metadata cannot report table names portably (the SQL Server driver leaves
648 /// them empty under the default forward-only cursor), so a builder-recorded mapping is the only
649 /// one that behaves identically on every supported database.
650 ///
651 /// @param name The column name exactly as spelled in the query builder.
652 /// @return The 1-based result column index of @p name.
653 /// @throws std::invalid_argument If the statement carries no name mapping (raw SQL, or a
654 /// projection containing a wildcard), if @p name was never projected, or if @p name was
655 /// projected more than once and is therefore ambiguous.
656 [[nodiscard]] LIGHTWEIGHT_API SqlColumnIndex ResolveColumnName(std::string_view name) const;
657
658 /// @brief Renders the projected column names for a diagnostic message.
659 [[nodiscard]] LIGHTWEIGHT_API std::string DescribeProjectedFieldNames() const;
660
661 /// Throws unless @p result is a success code, reporting this statement's diagnostics.
662 /// @param result The return code to check.
663 /// @param sourceLocation Where the check originated.
664 LIGHTWEIGHT_API void RequireSuccess(SqlResult result,
665 std::source_location sourceLocation = std::source_location::current()) const;
666 LIGHTWEIGHT_API void PlanPostExecuteCallback(std::function<void()>&& cb) override;
667 LIGHTWEIGHT_API void KeepInputParameterAlive(SqlColumnIndex column, std::shared_ptr<void const> buffer) override;
668 LIGHTWEIGHT_API void PlanPostProcessOutputColumn(std::function<void()>&& cb) override;
669 LIGHTWEIGHT_API void PlanPreFetchOutputColumn(SqlOutputColumnPreFetch const& step) override;
670 [[nodiscard]] LIGHTWEIGHT_API std::size_t MinimumOutputColumnSize(SqlColumnIndex column,
671 SqlOutputColumnLength length) override;
672 /// @brief Starts binding output column @p column: drops the column's previously planned pre-fetch
673 /// and post-process callbacks and attributes the ones planned next to it, so re-binding a column
674 /// replaces its callbacks instead of accumulating them.
675 LIGHTWEIGHT_API void BeginOutputColumnBinding(SqlColumnIndex column) noexcept;
676 /// @brief Binds @p arg as output column @p column with @c SqlDataBinder<T>::OutputColumn right away.
677 /// @tparam T The bound variable's type.
678 /// @param column The 1-based column index.
679 /// @param arg The variable the column is fetched into.
680 template <SqlOutputColumnBinder T>
681 void BindOutputColumnNow(SqlColumnIndex column, T* arg);
682 /// @brief Resets a bound output variable to its default value; see @ref PlanNullReset.
683 using NullResetFunction = void (*)(void* target) noexcept;
684 /// @brief Plans that output column @p column's bound variable @p target is reset by @p reset after every
685 /// fetch whose row is NULL there, as @p indicator tells; replaces an earlier plan for the column.
686 /// @param column The 1-based column index.
687 /// @param indicator The column's length indicator.
688 /// @param target The value to reset.
689 /// @param reset Resets @p target.
690 LIGHTWEIGHT_API void PlanNullReset(SqlColumnIndex column,
691 SqlIndicator const* indicator,
692 void* target,
693 NullResetFunction reset);
694 /// @brief Drops the pre-fetch and post-process callbacks of every bound output column.
695 LIGHTWEIGHT_API void ResetOutputColumnCallbacks() noexcept;
696 /// @brief Drops the pre-fetch and post-process callbacks planned for output column @p column.
697 LIGHTWEIGHT_API void DropOutputColumnCallbacks(SqlColumnIndex column) noexcept;
698 /// @brief Forgets every output column binding: the recorded prefetch bindings and the binders'
699 /// callbacks. Called right where the columns are unbound, and only there: closing a cursor keeps the
700 /// bindings for the next execution of the prepared statement.
701 LIGHTWEIGHT_API void DropOutputColumnBindings() noexcept;
702 /// @brief Notes that an output column was bound with the driver right away rather than recorded, so a
703 /// later result set of this binding keeps the per-row path that fills it.
704 LIGHTWEIGHT_API void NoteOutputColumnBoundDirectly() noexcept;
705 [[nodiscard]] LIGHTWEIGHT_API SqlServerType ServerType() const noexcept override;
706 [[nodiscard]] LIGHTWEIGHT_API std::string const& DriverName() const noexcept override;
707 [[nodiscard]] LIGHTWEIGHT_API detail::NarrowTextBinding NarrowTextBindingMode() const noexcept override;
708 /// @copydoc SqlDataBinderCallback::ConvertsNarrowIntegerCTypes
709 [[nodiscard]] LIGHTWEIGHT_API bool ConvertsNarrowIntegerCTypes() const noexcept override;
710 /// @copydoc SqlDataBinderCallback::ProvideOutputColumnStaging
711 [[nodiscard]] LIGHTWEIGHT_API SqlOutputColumnStaging* ProvideOutputColumnStaging(SqlColumnIndex column) override;
712 /// @copydoc SqlDataBinderCallback::BooleanTrueMayBeMinusOne
713 [[nodiscard]] LIGHTWEIGHT_API bool BooleanTrueMayBeMinusOne() const noexcept override;
714 LIGHTWEIGHT_API void ProcessPostExecuteCallbacks();
715
716 LIGHTWEIGHT_API SqlIndicator* ProvideInputIndicator() override;
717 LIGHTWEIGHT_API SqlIndicator* ProvideInputIndicators(size_t rowCount) override;
718 LIGHTWEIGHT_API std::byte* ProvideBatchStagingBuffer(std::size_t byteCount) override;
719 /// Resolves the declared SQL type of a parameter of the prepared query. All parameters are
720 /// described on first use and remembered until a different query is prepared.
721 /// @param column The 1-based parameter index.
722 /// @return The declared SQL type, or @c std::nullopt when the driver cannot describe it.
723 [[nodiscard]] LIGHTWEIGHT_API std::optional<std::int16_t> DescribeInputParameterType(
724 SqlColumnIndex column) noexcept override;
725 /// @copydoc SqlDataBinderCallback::DescribeResultColumnType
726 [[nodiscard]] LIGHTWEIGHT_API std::optional<std::int16_t> DescribeResultColumnType(
727 SqlColumnIndex column) const noexcept override;
728 /// Records a binder's refusal, which the next failed RequireSuccess() raises instead of the handle's
729 /// (absent) diagnostic.
730 /// @param error The SQLSTATE and message to raise.
731 LIGHTWEIGHT_API void ReportInputParameterError(SqlErrorInfo const& error) noexcept override;
732 LIGHTWEIGHT_API void ClearBatchIndicators();
733 /// Provides the row-strided indicator storage of one column of a row-wise fetch, apart from the
734 /// parameter slots: parameters bound by hand stay bound across the fetch and must keep theirs.
735 /// @param byteCount The number of bytes to provide.
736 /// @return A pointer to the first byte, aligned to at least @c alignof(std::max_align_t).
737 LIGHTWEIGHT_API std::byte* ProvideRowWiseFetchIndicators(std::size_t byteCount);
738 /// Frees the storage of @ref ProvideRowWiseFetchIndicators, once the columns are unbound.
739 LIGHTWEIGHT_API void ReleaseRowWiseFetchIndicators() noexcept;
740 /// @brief Releases the buffers the binders handed over with @ref KeepInputParameterAlive().
741 /// Called wherever the parameter bindings they serve are dropped or their batch has executed.
742 LIGHTWEIGHT_API void DropInputParameterKeepAlives() noexcept;
743 /// How a bind uses the indicator and staging slots of its parameter (see @ref BindParameterValue()).
744 enum class ParameterSlotReuse : std::uint8_t
745 {
746 /// A bind by hand: it fills the parameter's other bank of slots, and the bank its binding reads becomes
747 /// free only once the bind has succeeded, so a failed bind leaves the binding intact.
748 NextBinding,
749 /// A round that binds every parameter anew: the bind reuses, and may resize, the slots its parameter's
750 /// binding reads. Safe only because such a round's bindings are never executed again unless every
751 /// parameter was bound anew: Execute() without arguments refuses a round's parameter count, and a bind
752 /// by hand first resets the round's bindings. A failed bind of the round leaves its parameter reading
753 /// slots it changed, so neither guard may be relaxed without binding such rounds by hand instead.
754 InPlace,
755 };
756 /// Binds @p value as input parameter @p column through the driver statement @p stmt, the binder taking its
757 /// indicator and staging slots from that parameter's own slots, so a parameter bound again and again holds at
758 /// most two bindings' slots, on every driver. A bind that takes no slot touches no slot storage.
759 /// @param stmt The driver's statement, as Driver::Visit() hands it over.
760 /// @param column The 1-based parameter index.
761 /// @param value The value to bind.
762 /// @param reuse How the bind uses the parameter's slots.
763 /// @return The binder's result.
764 template <typename DriverStatement, typename T>
765 SqlResult BindParameterValue(DriverStatement& stmt, SqlColumnIndex column, T const& value, ParameterSlotReuse reuse)
766 {
767 m_parameterBeingBound = column;
768 m_slotReuseBeingBound = reuse;
769 m_parameterTookSlots = false;
770 // Ended on every exit, a throwing binder's too: a slot asked for outside a bind is a batch's.
771 auto const endBind = detail::Finally([this] { m_parameterBeingBound = 0; });
772 auto const result = Driver::BindInputParameter(stmt, column, value, *this);
773 if (m_parameterTookSlots && reuse == ParameterSlotReuse::NextBinding && Succeeded(result))
774 AdoptParameterSlots();
775 return result;
776 }
777 /// Makes the slots the successful bind by hand in progress filled the ones its parameter's binding reads.
778 LIGHTWEIGHT_API void AdoptParameterSlots() noexcept;
779 /// Resets the parameter bindings an execute with arguments or a batch made, and releases the copies kept for
780 /// them, before a parameter is bound by hand: their values may have been temporaries of that call.
781 LIGHTWEIGHT_API void DropRoundBindings();
782#if defined(LIGHTWEIGHT_DRIVER_ODBC)
783 /// Starts a raw-column batch: refuses @p columns unless they match the prepared parameter count, and marks the
784 /// parameters as bound by a round. Called before any guard that releases parameters' copies is installed, so a
785 /// refused batch leaves the parameters bound by hand, and their copies, as they were.
786 /// @param columns The columns the batch binds.
787 /// @throws std::invalid_argument if the column count does not match the prepared statement.
788 LIGHTWEIGHT_API void StartRawBatchRound(std::span<SqlRawColumn const> columns);
789 /// Sets up column-wise array binding of @p rowCount rows and binds @p columns as input parameters, once
790 /// @ref StartRawBatchRound() accepted them.
791 /// @param columns The columns to bind.
792 /// @param rowCount The number of rows (parameter sets).
793 /// @param sourceLocation The caller, which every check reports as its location.
794 LIGHTWEIGHT_API void BindRawBatchColumns(std::span<SqlRawColumn const> columns,
795 std::size_t rowCount,
796 std::source_location sourceLocation);
797#endif
798 /// Restores single-row, column-bound parameter binding (the ODBC default) and unbinds the parameter
799 /// status and processed-count pointers. @c noexcept so it can run from a scope guard on the
800 /// native-batch exception path.
801 LIGHTWEIGHT_API void ResetParameterArrayBinding() noexcept;
802 /// Throws unless @p result is a success code or @c SQL_NO_DATA (a searched UPDATE/DELETE that matched
803 /// no rows). Mirrors @c Execute() so the batch execute paths tolerate zero-row updates.
804 LIGHTWEIGHT_API void RequireExecuteSucceededOrNoData(
805 SqlResult result, std::source_location sourceLocation = std::source_location::current()) const;
806 /// Native-batch execute check: tolerates @c SQL_NO_DATA and, on success, verifies the driver
807 /// processed all @p expectedCount parameter sets (guards against silent partial array execution).
808 LIGHTWEIGHT_API void RequireSuccessfulBatchExecute(
809 SqlResult result,
810 std::size_t processedCount,
811 std::size_t expectedCount,
812 std::source_location sourceLocation = std::source_location::current()) const;
813 /// @brief Re-issues @c SQLPrepare after a reused prepared statement went stale, for one retry.
814 ///
815 /// @c Prepare() skips @c SQLPrepare when the statement handle already holds exactly this query
816 /// text. A prepared statement can nevertheless stop being executable - most visibly on PostgreSQL,
817 /// where a DDL change between two executions makes the server reject the cached plan with
818 /// @c 0A000 - so an execute that fails with one of those SQLSTATEs re-prepares once and runs again.
819 /// Parameter bindings live on the handle and survive @c SQLPrepare, so the caller's already-bound
820 /// arguments stay valid for the retry.
821 ///
822 /// @note Retrying re-executes the whole statement. That is safe for the conditions listed above
823 /// because they are all raised while resolving or planning the statement, before it has had
824 /// any effect - a constraint violation or any other runtime rejection is deliberately not
825 /// retried.
826 ///
827 /// @param result The result of the execute that just failed.
828 /// @return @c true if the statement was re-prepared and the execute should be retried.
829 [[nodiscard]] LIGHTWEIGHT_API bool RetryStalePreparedStatement(SqlResult result);
830
831 LIGHTWEIGHT_API void RequireIndicators();
832 LIGHTWEIGHT_API SqlIndicator* GetIndicatorForColumn(SqlColumnIndex column) noexcept;
833
834 // --- Transparent block-prefetch: backs the classic per-row fetch loops (FetchRow + GetColumn,
835 // bound output columns, SqlRowIterator, SqlVariantRowCursor) with the existing RowArrayCursor so a
836 // whole block of rows is materialized per SQLFetchScroll round-trip instead of one SQLFetch per row.
837 // Out-of-line accessors because the prefetch state lives in the opaque Data struct.
838
839 /// @return The effective prefetch depth: the connection default gated by the driver's row-array
840 /// capability (1 — i.e. disabled — when unsupported or the connection default is <= 1).
841 [[nodiscard]] std::size_t EffectivePrefetchDepth() const noexcept;
842 /// @brief Arms (or disables) block-prefetch on the first fetch of a result set; idempotent.
843 void ArmPrefetchOnFirstFetch() noexcept;
844 /// @brief Issues the deferred output column binds of a bound-column loop, once per per-row result set.
845 [[nodiscard]] std::expected<void, SqlErrorInfo> IssueDeferredBinds(std::source_location location) noexcept;
846 /// @brief Runs the binders' pre-fetch steps, which restore the bound buffers before the next fetch.
847 [[nodiscard]] std::expected<void, SqlErrorInfo> RunPreFetchSteps(std::source_location location) noexcept;
848 /// @brief Runs the binders' post-process callbacks on the row just fetched.
849 [[nodiscard]] std::expected<void, SqlErrorInfo> RunPostProcessCallbacks(std::source_location location) noexcept;
850 /// @brief Fetches the next logical row from the block buffer, refilling the block and running the
851 /// recorded bound-column scatters as needed. @return true if a row is available.
852 [[nodiscard]] std::expected<bool, SqlErrorInfo> FetchRowPrefetched() noexcept;
853 /// @return Whether block-prefetch is currently materializing this result set.
854 [[nodiscard]] LIGHTWEIGHT_API bool IsPrefetchActive() const noexcept;
855#if defined(LIGHTWEIGHT_DRIVER_ODBC)
856 /// @return The active block-prefetch cursor (precondition: @ref IsPrefetchActive).
857 [[nodiscard]] LIGHTWEIGHT_API RowArrayCursor const& PrefetchCursorRef() const noexcept;
858#endif
859 /// @return The 0-based offset of the current logical row within the last fetched block.
860 [[nodiscard]] LIGHTWEIGHT_API std::size_t PrefetchRowInBlock() const noexcept;
861 /// @return Whether @ref BindOutputColumns should record scatter/deferred-bind closures (prefetch is
862 /// enabled and not yet disabled) instead of issuing @c SQLBindCol immediately.
863 [[nodiscard]] LIGHTWEIGHT_API bool ShouldRecordPrefetchBinding() const noexcept;
864 /// @brief Drops any previously recorded scatter/deferred-bind closures (for idempotent re-binding).
865 LIGHTWEIGHT_API void ResetPrefetchBindings() noexcept;
866 /// @brief Flags that a bound output column's target type cannot be served from the block buffer, so
867 /// arming must decline prefetch for this result set and keep the per-row path.
868 LIGHTWEIGHT_API void MarkPrefetchBindingUnsupported() noexcept;
869 /// @brief Keeps the result set about to be read into SqlVariant values on the per-row path where the
870 /// driver reports a cell its column type cannot convert as NULL (see
871 /// SqlQueryFormatter::ReportsUnconvertibleCellsAsNull()): only the per-row read can read it again as text.
872 LIGHTWEIGHT_API void KeepVariantReadsPerRow() noexcept;
873 /// @brief The class of C++ type a bound output column reads into. The block buffer serves a column
874 /// only when its SQL type is one this class reads the same way on the per-row path; for any other
875 /// pairing (e.g. an INTEGER column bound to a SqlDateTime) the per-row conversion is driver-specific,
876 /// so arming keeps the per-row path for the result set.
877 enum class PrefetchTarget : std::uint8_t
878 {
879 Any, //!< SqlVariant: takes whatever the column holds
880 Numeric, //!< arithmetic, enum and SqlNumeric targets: numeric columns
881 Temporal, //!< SqlDate and SqlDateTime: DATE and TIMESTAMP columns
882 Guid, //!< SqlGuid: GUID columns
883 Text, //!< string targets: numeric columns (temporal and GUID text is the driver's to format)
884 Exact, //!< SqlDynamicNumeric: integer columns (a floating-point value is the driver's to render)
885 };
886 /// @return The PrefetchTarget class of the bound destination type @p T (an optional's value type).
887 template <typename T>
888 [[nodiscard]] static constexpr PrefetchTarget PrefetchTargetOf() noexcept;
889 /// @brief Records, for one output column, the per-row scatter closure (copies the current block cell
890 /// into the bound destination) and the real bind thunk used if the result set turns out
891 /// prefetch-ineligible. Indexed by @p column so re-binding the same column overwrites rather than
892 /// appends — keeping the bound-column loop, the optional rebind idiom, and the DataMapper's per-row
893 /// re-binding all bounded.
894 /// @param column 1-based output column index.
895 /// @param target The class of the bound destination; arming declines prefetch when the column's SQL
896 /// type is one the per-row path would read differently into it (see PrefetchTarget).
897 /// @param scatter Copies the current block cell into the bound destination.
898 /// @param deferredBind Issues the real bind when the fast path is declined.
899 LIGHTWEIGHT_API void RecordPrefetchColumn(SqlColumnIndex column,
900 PrefetchTarget target,
901 std::function<void()> scatter,
902 std::function<void()> deferredBind);
903 /// @brief Records only the class of the destination an output column is read into, for a reader that
904 /// reads the columns with @c GetColumn instead of binding them (@ref SqlRowIterator): arming then keeps
905 /// the per-row path when the column's SQL type is one the per-row path reads differently into it.
906 /// @param column 1-based output column index.
907 /// @param target The class of the destination the column is read into.
908 LIGHTWEIGHT_API void RecordPrefetchColumnTarget(SqlColumnIndex column, PrefetchTarget target);
909 /// @brief Tears down all block-prefetch state, restoring the handle to single-row fetching.
910 LIGHTWEIGHT_API void ResetPrefetchState() noexcept;
911#if defined(LIGHTWEIGHT_DRIVER_ODBC)
912 /// @brief Builds an @c SqlVariant cell from the block buffer, mirroring @c SqlDataBinder<SqlVariant>.
913 [[nodiscard]] LIGHTWEIGHT_API SqlVariant MakePrefetchVariantCell(RowArrayCursor const& cursor,
914 std::size_t row,
915 SqlColumnIndex column) const;
916 /// @brief Converts a materialized block cell to the requested native type @p T.
917 template <typename T>
918 [[nodiscard]] T ConvertCell(RowArrayCursor const& cursor, std::size_t row, SqlColumnIndex column) const;
919#endif
920 /// @brief The precision and scale result column @p column declares, asked of the driver once per result set
921 /// and column, so a block-prefetched SqlDynamicNumeric read costs no driver call per cell.
922 /// @param column The 1-based column index.
923 /// @return The declared digits, as SqlDataBinder<SqlDynamicNumeric>::ColumnDigits() reports them.
924 [[nodiscard]] LIGHTWEIGHT_API SqlDataBinder<SqlDynamicNumeric>::DeclaredDigits DeclaredDynamicNumericDigits(
925 SqlColumnIndex column) const;
926
927#if defined(LIGHTWEIGHT_DRIVER_ODBC)
928 /// @brief Validates a 1-based column index against the active prefetch cursor, throwing
929 /// @c std::invalid_argument for an out-of-range index — matching the per-row path's behaviour for
930 /// an invalid descriptor index (ODBC SQLSTATE 07009).
931 LIGHTWEIGHT_API void RequirePrefetchColumnInRange(RowArrayCursor const& cursor, SqlColumnIndex column) const;
932
933 /// @brief Records the scatter + deferred-bind closures for one bound output column @p arg of type
934 /// @p T (used instead of an immediate @c SQLBindCol while prefetch is pending/active).
935 template <SqlOutputColumnBinder T>
936 void RecordPrefetchOutputColumn(SqlColumnIndex column, T* arg);
937#endif
938
939 /// @brief Adopts the column-name mapping of @p queryObject, replacing any previously held mapping.
940 ///
941 /// An implementation detail of the query-object @c Prepare / @c ExecuteDirect overloads: it is the
942 /// only way the mapping is ever populated, so it is not part of the public surface.
943 template <SqlQueryObject QueryObject>
944 void AdoptProjectedFieldNames(QueryObject const& queryObject);
945 // --- Prepared-statement cache: takes the statement handle from (and hands it back to) the pool
946 // owned by the connection, so re-preparing a query text that is already prepared skips SQLPrepare.
947
948 /// @return The connection's prepared-statement cache if this statement may use it, else nullptr.
949 [[nodiscard]] SqlPreparedStatementCache* UsablePreparedStatementCache() const noexcept;
950
951 /// @brief Parks the currently prepared handle in the pool and takes back one already prepared for
952 /// @p query, allocating a fresh handle when the pool has none.
953 ///
954 /// Parking first is what makes a repeated @c Prepare() of the same text free: the handle just
955 /// released is the one the immediately following lookup finds.
956 ///
957 /// @param cache The cache to park in and take from, already known to be usable.
958 /// @param query The SQL text about to be prepared.
959 /// @return true if the statement handle is already prepared for @p query, so @c SQLPrepare can be skipped.
960 [[nodiscard]] bool AcquirePreparedHandle(SqlPreparedStatementCache& cache, std::string_view query);
961
962 /// @brief Prepares @p queryText on the handle and, once that succeeded, records it and its
963 /// parameter count as what the handle holds.
964 ///
965 /// On failure it forgets @c m_preparedQuery before rethrowing, so that no later @c Prepare() of
966 /// the same text mistakes the handle for one that holds it.
967 /// @param queryText The SQL text to prepare.
968 /// @throws SqlException The driver rejected the prepare, or could not report the parameter count.
969 void PrepareOnHandle(std::string queryText);
970
971 /// @brief Executes @p query directly on the handle, through the entry point the driver takes query
972 /// text on (see SqlConnection::AcceptsWideQueryText()).
973 /// @param query The SQL text to execute, UTF-8.
974 /// @return The result of the direct execution.
975 [[nodiscard]] SqlResult ExecDirectOnHandle(std::string_view query);
976
977 /// @brief Records a freshly allocated handle: the connection session it belongs to, the handle with
978 /// the connection (which frees it on Close(), where the driver needs that) and, for a connection to an
979 /// ANSI-only driver, that its diagnostics are read through the ANSI entry points.
980 void RegisterHandleTextEntry();
981 /// @brief Fails with SQLSTATE 08003 when the statement's handle belongs to a connection session that has
982 /// ended (Close(), a re-connect): the handle is gone, and with it what was prepared on it. One session
983 /// compare per execution.
984 LIGHTWEIGHT_API void RequireCurrentSession();
985 /// @brief Fails with SQLSTATE 08003 like RequireCurrentSession(), without forgetting the handle of an
986 /// ended session: for the const queries of the current result, which must not hand that handle to the
987 /// driver either.
988 void RequireLiveHandle() const;
989 /// @brief Whether the statement's handle belongs to the connection's current session (always true for a
990 /// moved-from statement, which has nothing to check against).
991 [[nodiscard]] bool HasLiveHandle() const noexcept;
992
993 /// @brief Gives up the statement handle this statement holds: hands it back to the connection's
994 /// prepared-statement cache, or frees it. Used by the destructor and by move assignment.
995 void ReleaseHandle() noexcept;
996
997 /// @brief Forgets the statement handle when it died with an earlier session of the connection
998 /// (see SqlConnection::SessionId()), without freeing or pooling it (@c Driver::Abandon).
999 LIGHTWEIGHT_API void ForgetHandleOfEndedSession() noexcept;
1000
1001 /// @brief Describes every parameter of the prepared query.
1002 ///
1003 /// The MS SQL Server driver refuses @c SQLDescribeParam (07009) once any parameter of the
1004 /// handle is bound, so the parameters are described on this handle only while none is; otherwise
1005 /// on a second statement that prepares the same text and binds nothing.
1006 /// @return One declared SQL type per parameter, @ref SqlUnknownParameterType where the driver could not
1007 /// say.
1008 [[nodiscard]] std::vector<std::int16_t> DescribeInputParameterTypes() noexcept;
1009
1010 /// @brief Hands the statement handle to the pool if it carries a prepared query and caching is in effect.
1011 /// @return true if the handle was pooled (and must therefore not be freed by the caller).
1012 bool ReleasePreparedHandle() noexcept;
1013
1014 /// @copydoc ReleasePreparedHandle()
1015 /// @param cache The cache to park in, already known to be usable.
1016 bool ReleasePreparedHandle(SqlPreparedStatementCache& cache) noexcept;
1017
1018 /// @brief Parks the prepared handle before a direct execution, which would discard what the handle
1019 /// was prepared for, and gives this statement a fresh handle to execute on.
1020 void ReleasePreparedHandleForDirectExecution();
1021
1022 /// Allocates a statement handle if this statement currently has none.
1023 void EnsureStatementHandle();
1024
1025 /// Puts the timeout set through @ref SetQueryTimeout() on a handle this statement just took over.
1026 void ApplyQueryTimeoutToNewHandle();
1027
1028 /// @brief Allocates a statement handle on the connection and holds it.
1029 /// @return The result of the allocation; the handle is held whatever it is.
1030 [[nodiscard]] SqlResult AllocateHandle() noexcept;
1031
1032 // private data members
1033 struct Data;
1034 std::unique_ptr<Data, void (*)(Data*)> m_data; // The private data of the statement
1035 SqlConnection* m_connection {}; // Pointer to the connection object
1036 Driver::StatementHandle m_handle {}; // The driver's statement handle
1037 uint64_t m_sessionId {}; // The connection session m_handle was allocated in (see SqlConnection::SessionId())
1038 std::string m_preparedQuery; // The last prepared query
1039 std::optional<std::int16_t> m_numColumns; // The number of columns in the result set, if known
1040 // Column names of the last prepared/executed query object, in result-column order, for named
1041 // column access. Empty when the query carried no mapping (raw SQL, or a wildcard projection).
1042 std::vector<std::string> m_projectedFieldNames;
1043 bool m_projectionHasWildcard = false;
1044 /// The parameter a binder is binding through BindParameterValue(), or 0 outside a bind (a batch's slots).
1045 SqlColumnIndex m_parameterBeingBound = 0;
1046 /// How the bind in progress uses its parameter's slots.
1047 ParameterSlotReuse m_slotReuseBeingBound = ParameterSlotReuse::NextBinding;
1048 /// Whether the bind in progress asked for a slot, and so has a bank chosen.
1049 bool m_parameterTookSlots = false;
1050 /// The executes attempted so far, failed ones included: a parameter bound after one of them replaces the copies
1051 /// its previous bind handed over (see KeepInputParameterAlive()), whatever that execute's outcome.
1052 std::uint64_t m_executeAttempts = 0;
1053 /// Whether the parameters are bound by an execute with arguments or a batch, whose values need not outlive the
1054 /// call that bound them: the next BindInputParameter() resets those bindings first (see DropRoundBindings()).
1055 bool m_parameterRoundBound = false;
1056 std::int16_t m_expectedParameterCount {}; // The number of parameters expected by the query
1057 // The parameter count the driver reported for m_preparedQuery. m_expectedParameterCount is
1058 // deliberately overwritten by BindInputParameter() (with std::int16_t max, meaning "bound by hand"),
1059 // so a Prepare() that reuses the handle's statement - and therefore skips asking the driver - has to
1060 // restore the real count from here instead.
1061 std::int16_t m_preparedParameterCount {};
1062 bool m_reusedPreparedQuery { false }; // Whether the last Prepare() reused the handle's statement
1063 SqlPreparedStatementCaching m_preparedStatementCaching {
1064 SqlPreparedStatementCaching::Enabled
1065 }; // Whether this statement may use the connection's prepared-statement cache
1066};
1067
1069{
1070 return m_preparedStatementCaching;
1071}
1072
1073/// @ingroup CoreApi
1074/// API for reading an SQL query result set.
1075class [[nodiscard]] SqlResultCursor
1076{
1077 friend class SqlVariantRowIterator;
1078
1079 public:
1080 /// Constructs a result cursor for the given SQL statement.
1081 explicit LIGHTWEIGHT_FORCE_INLINE SqlResultCursor(SqlStatement& stmt) noexcept:
1082 m_stmt { &stmt }
1083 {
1084 }
1085
1086 SqlResultCursor() = delete;
1087 SqlResultCursor(SqlResultCursor const&) = delete;
1088 SqlResultCursor& operator=(SqlResultCursor const&) = delete;
1089
1090 /// Move constructor.
1091 constexpr SqlResultCursor(SqlResultCursor&& other) noexcept:
1092 m_stmt { other.m_stmt }
1093 {
1094 other.m_stmt = nullptr;
1095 }
1096
1097 /// Move assignment operator.
1098 constexpr SqlResultCursor& operator=(SqlResultCursor&& other) noexcept
1099 {
1100 if (this != &other)
1101 {
1102 m_stmt = other.m_stmt;
1103 other.m_stmt = nullptr;
1104 }
1105 return *this;
1106 }
1107
1108 LIGHTWEIGHT_FORCE_INLINE ~SqlResultCursor()
1109 {
1110 if (m_stmt)
1111 {
1112 m_stmt->CloseCursor();
1113 m_stmt = nullptr;
1114 }
1115 }
1116
1117 /// Retrieves the number of rows affected by the last query.
1118 /// @throws SqlException 08003 when the cursor's connection session ended.
1119 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE size_t NumRowsAffected() const
1120 {
1121 return m_stmt->NumRowsAffected();
1122 }
1123
1124 /// Retrieves the number of columns affected by the last query.
1125 /// @throws SqlException 08003 when the cursor's connection session ended.
1126 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE size_t NumColumnsAffected() const
1127 {
1128 return m_stmt->NumColumnsAffected();
1129 }
1130
1131 /// @return How the narrow (@c char) string binders exchange text with this cursor's driver.
1132 [[nodiscard]] detail::NarrowTextBinding NarrowTextBindingMode() const noexcept
1133 {
1134 return m_stmt->NarrowTextBindingMode();
1135 }
1136
1137 /// @brief The SQL data type the driver reports for a result column.
1138 /// @param column 1-based result column index.
1139 /// @return The reported type (@c SqlResultColumnType::Unknown for a type without an enumerator), or the
1140 /// error (`07009` for a column the result set does not have) if the column cannot be described.
1141 [[nodiscard]] LIGHTWEIGHT_API std::expected<SqlResultColumnType, SqlErrorInfo> ColumnSqlType(
1142 SqlColumnIndex column) const;
1143
1144 /// @copydoc SqlStatement::ConsumePendingResults
1145 LIGHTWEIGHT_FORCE_INLINE void ConsumePendingResults(std::source_location location = std::source_location::current())
1146 {
1147 m_stmt->ConsumePendingResults(location);
1148 }
1149
1150 /// Binds the given arguments to the prepared statement to store the fetched data to.
1151 ///
1152 /// The statement must be prepared before calling this function.
1153 template <SqlOutputColumnBinder... Args>
1154 LIGHTWEIGHT_FORCE_INLINE void BindOutputColumns(Args*... args)
1155 {
1156 m_stmt->BindOutputColumns(args...);
1157 }
1158
1159 /// Binds a single output column at the given index to store fetched data.
1160 template <SqlOutputColumnBinder T>
1161 LIGHTWEIGHT_FORCE_INLINE void BindOutputColumn(SqlColumnIndex columnIndex, T* arg)
1162 {
1163 m_stmt->BindOutputColumn(columnIndex, arg);
1164 }
1165
1166 /// Fetches the next row of the result set.
1167 ///
1168 /// A cursor does not outlive its connection's session: once the connection is closed (or connected
1169 /// again), FetchRow() fails with SQLSTATE 08003, so the usual @c while (cursor.FetchRow()) loop stops
1170 /// there. Reading a column of the current row after the connection was closed is not allowed.
1171 /// @return @c true for a row, @c false at the end of the result set.
1172 /// @throws SqlException 08003 when the connection's session ended; the driver's error otherwise.
1173 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE bool FetchRow()
1174 {
1175 return m_stmt->FetchRow();
1176 }
1177
1178 /// Attempts to fetch the next row, returning an error info on failure instead of throwing.
1179 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE std::expected<bool, SqlErrorInfo> TryFetchRow(
1180 std::source_location location = std::source_location::current()) noexcept
1181 {
1182 return m_stmt->TryFetchRow(location);
1183 }
1184
1185 /// Binds the given records to the prepared statement to store the fetched data to.
1186 template <typename... Records>
1187 requires(((std::is_class_v<Records> && std::is_aggregate_v<Records>) && ...))
1188 LIGHTWEIGHT_FORCE_INLINE void BindOutputColumnsToRecord(Records*... records)
1189 {
1190 m_stmt->BindOutputColumnsToRecord(records...);
1191 }
1192
1193 /// @brief Fast bulk retrieval: materializes this result set into @p out via native ODBC row-wise
1194 /// array fetch. Forwards to @c SqlStatement::FetchAllRowWise; see its contract (eligibility and
1195 /// alignment preconditions are the caller's responsibility).
1196 /// @param out Destination vector; results are appended.
1197 /// @param arrayDepth Requested maximum rows per @c SQLFetchScroll round-trip.
1198 /// @param accessors One invocable per result column; @c accessor(record) yields its mutable value.
1199 template <typename Record, typename... ColumnAccessors>
1200 LIGHTWEIGHT_FORCE_INLINE void FetchAllRowWise(std::vector<Record>& out,
1201 std::size_t arrayDepth,
1202 ColumnAccessors const&... accessors)
1203 {
1204 m_stmt->FetchAllRowWise(out, arrayDepth, accessors...);
1205 }
1206
1207 /// Retrieves the value of the column at the given index for the currently selected row.
1208 ///
1209 /// @param column 1-based result column index.
1210 /// @param result Receives the value. On NULL it receives its empty value instead (@c std::nullopt, a
1211 /// NULL @c SqlVariant, @c T {}), whatever it held before, on the per-row and the
1212 /// block-prefetched path alike.
1213 /// @return @c true if the value is not NULL, @c false otherwise.
1214 template <SqlGetColumnNativeType T>
1215 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE bool GetColumn(SqlColumnIndex column, T* result) const
1216 {
1217 return m_stmt->GetColumn<T>(column, result);
1218 }
1219
1220 /// Retrieves the value of the column at the given index for the currently selected row.
1221 ///
1222 /// @param column 1-based result column index.
1223 /// @return The value. A NULL cell reads as @c std::nullopt or a NULL @c SqlVariant for those two
1224 /// types; for any other @p T it throws @c std::runtime_error, on the per-row and the
1225 /// block-prefetched path alike (use @c GetNullableColumn or @c GetColumnOr for a column that
1226 /// may be NULL).
1227 template <SqlGetColumnNativeType T>
1228 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE T GetColumn(SqlColumnIndex column) const
1229 {
1230 return m_stmt->GetColumn<T>(column);
1231 }
1232
1233 /// Retrieves the value of the column at the given index for the currently selected row.
1234 ///
1235 /// If the value is NULL, std::nullopt is returned.
1236 template <SqlGetColumnNativeType T>
1237 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE std::optional<T> GetNullableColumn(SqlColumnIndex column) const
1238 {
1239 return m_stmt->GetNullableColumn<T>(column);
1240 }
1241
1242 /// Retrieves the value of the column at the given index for the currently selected row.
1243 ///
1244 /// If the value is NULL, the given @p defaultValue is returned.
1245 template <SqlGetColumnNativeType T>
1246 [[nodiscard]] T GetColumnOr(SqlColumnIndex column, T&& defaultValue) const
1247 {
1248 return m_stmt->GetColumnOr(column, std::forward<T>(defaultValue));
1249 }
1250
1251 /// @brief Retrieves the value of the named column for the currently selected row.
1252 ///
1253 /// The name is the one spelled in the query builder that composed this query — a bare column name
1254 /// for @c Field("x"), the qualified @c "table.column" for @c Field({"table", "x"}), or the alias for
1255 /// an aliased projection. Only builder-composed queries carry a mapping.
1256 ///
1257 /// @note Reads must still ascend in column order: the SQL Server driver rejects out-of-order
1258 /// @c SQLGetData with SQLSTATE 07009, and addressing columns by name makes it easy to
1259 /// reorder them inadvertently.
1260 ///
1261 /// @param name The column name as spelled in the query builder.
1262 /// @return The column value converted to @p T.
1263 /// @throws std::invalid_argument If no mapping is available, or @p name is unknown or ambiguous.
1264 template <SqlGetColumnNativeType T>
1265 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE T GetColumn(std::string_view name) const
1266 {
1267 return m_stmt->GetColumn<T>(m_stmt->ResolveColumnName(name));
1268 }
1269
1270 /// @brief Retrieves the value of the named column, or @c std::nullopt if it is NULL.
1271 ///
1272 /// The name is the one spelled in the query builder that composed this query; only builder-composed
1273 /// queries carry a mapping. Reads must ascend in column order — see the name-taking @c GetColumn.
1274 ///
1275 /// @param name The column name as spelled in the query builder.
1276 /// @return The column value converted to @p T, or @c std::nullopt if the column is NULL.
1277 /// @throws std::invalid_argument If no mapping is available, or @p name is unknown or ambiguous.
1278 template <SqlGetColumnNativeType T>
1279 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE std::optional<T> GetNullableColumn(std::string_view name) const
1280 {
1281 return m_stmt->GetNullableColumn<T>(m_stmt->ResolveColumnName(name));
1282 }
1283
1284 /// @brief Retrieves the value of the named column, or @p defaultValue if it is NULL.
1285 ///
1286 /// The name is the one spelled in the query builder that composed this query; only builder-composed
1287 /// queries carry a mapping. Reads must ascend in column order — see the name-taking @c GetColumn.
1288 ///
1289 /// @param name The column name as spelled in the query builder.
1290 /// @param defaultValue The value to return when the column is NULL.
1291 /// @return The column value converted to @p T, or @p defaultValue if the column is NULL.
1292 /// @throws std::invalid_argument If no mapping is available, or @p name is unknown or ambiguous.
1293 template <SqlGetColumnNativeType T>
1294 [[nodiscard]] T GetColumnOr(std::string_view name, T&& defaultValue) const
1295 {
1296 return m_stmt->GetColumnOr(m_stmt->ResolveColumnName(name), std::forward<T>(defaultValue));
1297 }
1298
1299 private:
1300 SqlStatement* m_stmt;
1301};
1302
1303struct [[nodiscard]] SqlSentinelIterator
1304{
1305};
1306
1307class [[nodiscard]] SqlVariantRowIterator
1308{
1309 public:
1310 explicit SqlVariantRowIterator(SqlSentinelIterator /*sentinel*/) noexcept:
1311 _cursor { nullptr }
1312 {
1313 }
1314
1315 /// @throws SqlException Fetching the first row failed.
1316 explicit SqlVariantRowIterator(SqlResultCursor& cursor):
1317 _numResultColumns { static_cast<SqlColumnIndex>(cursor.NumColumnsAffected()) },
1318 _cursor { &cursor }
1319 {
1320 _row.reserve(_numResultColumns);
1321 cursor.m_stmt->KeepVariantReadsPerRow(); // before the first fetch decides on block prefetch
1322 ++(*this);
1323 }
1324
1325 SqlVariantRow& operator*() noexcept
1326 {
1327 return _row;
1328 }
1329
1330 SqlVariantRow const& operator*() const noexcept
1331 {
1332 return _row;
1333 }
1334
1335 /// @throws SqlException Fetching or reading the next row failed.
1336 SqlVariantRowIterator& operator++()
1337 {
1338 _end = !_cursor->FetchRow();
1339 if (!_end)
1340 {
1341 _row.clear();
1342 for (auto const i: std::views::iota(SqlColumnIndex(1), SqlColumnIndex(_numResultColumns + 1)))
1343 _row.emplace_back(_cursor->GetColumn<SqlVariant>(i));
1344 }
1345 return *this;
1346 }
1347
1348 bool operator!=(SqlSentinelIterator /*sentinel*/) const noexcept
1349 {
1350 return !_end;
1351 }
1352
1353 bool operator!=(SqlVariantRowIterator const& /*rhs*/) const noexcept
1354 {
1355 return !_end;
1356 }
1357
1358 private:
1359 bool _end = false;
1360 SqlColumnIndex _numResultColumns = 0;
1361 SqlResultCursor* _cursor;
1362 SqlVariantRow _row;
1363};
1364
1365class [[nodiscard]] SqlVariantRowCursor
1366{
1367 public:
1368 explicit SqlVariantRowCursor(SqlResultCursor&& cursor):
1369 _resultCursor { std::move(cursor) }
1370 {
1371 }
1372
1373 /// @throws SqlException Fetching the first row failed.
1374 SqlVariantRowIterator begin()
1375 {
1376 return SqlVariantRowIterator { _resultCursor };
1377 }
1378
1379 static SqlSentinelIterator end() noexcept
1380 {
1381 return SqlSentinelIterator {};
1382 }
1383
1384 private:
1385 SqlResultCursor _resultCursor;
1386};
1387
1388/// @brief SQL query result row iterator
1389///
1390/// Can be used to iterate over rows of the database and fetch them into a record type.
1391/// @tparam T The record type to fetch the rows into.
1392/// @code
1393///
1394/// struct MyRecord
1395/// {
1396/// Field<SqlGuid, PrimaryKey::AutoAssign> field1;
1397/// Field<int> field2;
1398/// Field<double> field3;
1399/// };
1400///
1401/// for (auto const& row : SqlRowIterator<MyRecord>(conn))
1402/// {
1403/// // row is of type MyRecord
1404/// // row.field1, row.field2, row.field3 are accessible
1405/// }
1406/// @endcode
1407///
1408/// Pass a second argument to iterate over a subset of the table only. The callable receives the
1409/// underlying @ref SqlSelectQueryBuilder with the projection for @c T already applied, so the full
1410/// WHERE / ORDER BY / LIMIT surface of the query builder is available:
1411/// @code
1412///
1413/// for (auto const& row : SqlRowIterator<MyRecord>(conn, [](auto& query) {
1414/// return query.Where("field2", 10).OrWhere([](auto& query) {
1415/// return query.Where("field2", 20).Where("field3", 3.14);
1416/// });
1417/// }))
1418/// {
1419/// // only the rows matching the condition above are fetched
1420/// }
1421/// @endcode
1422template <typename T>
1424{
1425 public:
1426 /// Callable refining the SELECT query before it is executed.
1427 ///
1428 /// It is invoked with the query builder that already carries the projection for @c T. Any value
1429 /// the callable returns is ignored, so the builder's chaining methods can be returned directly.
1430 using QueryCustomizer = std::function<void(SqlSelectQueryBuilder&)>;
1431
1432 /// Constructs a row iterator over all rows of the record's table, using the given SQL connection.
1434 _connection { &conn }
1435 {
1436 }
1437
1438 /// Constructs a row iterator over the subset of rows selected by @p queryCustomizer.
1439 ///
1440 /// @param conn The SQL connection to run the query on.
1441 /// @param queryCustomizer Callable refining the SELECT query, e.g. by adding WHERE conditions.
1443 _connection { &conn },
1444 _queryCustomizer { std::move(queryCustomizer) }
1445 {
1446 }
1447
1448 class iterator
1449 {
1450 public:
1451 using difference_type = bool;
1452 using value_type = T;
1453
1454 iterator& operator++()
1455 {
1456 if (_cursor)
1457 {
1458 _is_end = !_cursor->FetchRow();
1459 return *this;
1460 }
1461 _is_end = true;
1462 return *this;
1463 }
1464
1465 /// @throws SqlException Reading a column of the current row failed.
1466 LIGHTWEIGHT_FORCE_INLINE value_type operator*()
1467 {
1468 auto res = detail::MakeUninitialized<T>();
1469
1470 // begin() projects the record via Select().Fields<T>(), which emits one column per
1471 // RecordColumnMember. Enumerate by column position rather than by member position, so that
1472 // relation members (HasMany, HasManyThrough, HasOneThrough, ...) neither need a column nor
1473 // shift the ones that follow them.
1474 SqlColumnIndex columnIndex = 0;
1475 EnumerateRecordMembers(res, [this, &columnIndex]<size_t I, typename FieldType>(FieldType& value) {
1476 if constexpr (RecordColumnMember<FieldType>)
1477 {
1478 ++columnIndex;
1479 if constexpr (FieldWithStorage<FieldType>)
1480 value = _cursor->GetColumn<typename FieldType::ValueType>(columnIndex);
1481 else
1482 value = _cursor->GetColumn<FieldType>(columnIndex);
1483 }
1484 });
1485
1486 return res;
1487 }
1488
1489 LIGHTWEIGHT_FORCE_INLINE constexpr bool operator!=(iterator const& other) const noexcept
1490 {
1491 return _is_end != other._is_end;
1492 }
1493
1494 constexpr iterator(std::default_sentinel_t /*sentinel*/) noexcept:
1495 _is_end { true },
1496 _cursor { std::nullopt }
1497 {
1498 }
1499
1500 explicit iterator(SqlConnection& conn):
1501 _stmt { std::make_unique<SqlStatement>(conn) },
1502 _cursor { std::nullopt }
1503 {
1504 }
1505
1506 LIGHTWEIGHT_FORCE_INLINE SqlStatement& Statement() noexcept
1507 {
1508 return *_stmt;
1509 }
1510
1511 void SetCursor(SqlResultCursor cursor) noexcept
1512 {
1513 _cursor.emplace(std::move(cursor));
1514 }
1515
1516 private:
1517 bool _is_end = false;
1518 std::unique_ptr<SqlStatement> _stmt;
1519 std::optional<SqlResultCursor> _cursor;
1520 };
1521
1522 /// Returns an iterator to the first row of the result set.
1523 iterator begin()
1524 {
1525 auto it = iterator { *_connection };
1526 auto& stmt = it.Statement();
1527 stmt.Prepare(it.Statement().Query(RecordTableName<T>).Select().template Fields<T>().Build(_queryCustomizer).All());
1528 it.SetCursor(stmt.Execute());
1529 // The rows are read with GetColumn, so the column types are known before the first fetch: a member
1530 // type the block buffer cannot rebuild keeps the result set on the per-row path, as in
1531 // ExecuteDirectScalar, instead of failing the read; so does a member whose column has an SQL type
1532 // the per-row path reads differently into it (e.g. a SqlDateTime member over an INTEGER column),
1533 // which arming checks against the recorded member classes.
1534 if constexpr (ColumnsArePrefetchConvertible())
1535 RecordColumnPrefetchTargets(stmt);
1536 else
1537 stmt.MarkPrefetchBindingUnsupported();
1538 ++it;
1539 return it;
1540 }
1541
1542 /// Returns a sentinel iterator representing the end of the result set.
1543 iterator end() noexcept
1544 {
1545 return iterator { std::default_sentinel };
1546 }
1547
1548 private:
1549 /// @return Whether the block buffer can serve every column member of @c T to @c GetColumn.
1550 static constexpr bool ColumnsArePrefetchConvertible() noexcept;
1551
1552 /// Records the class of each column member of @c T on @p stmt, so arming the block prefetch can check
1553 /// each column's SQL type against the member it is read into.
1554 /// @param stmt The statement the rows are read from, executed and not yet fetched.
1555 static void RecordColumnPrefetchTargets(SqlStatement& stmt);
1556
1557 SqlConnection* _connection;
1558 QueryCustomizer _queryCustomizer = [](SqlSelectQueryBuilder& /*query*/) {
1559 };
1560};
1561
1562// {{{ inline implementation
1563inline LIGHTWEIGHT_FORCE_INLINE bool SqlStatement::IsAlive() const noexcept
1564{
1565 return m_connection && m_connection->IsAlive() && !m_handle.IsEmpty();
1566}
1567
1568inline LIGHTWEIGHT_FORCE_INLINE bool SqlStatement::IsPrepared() const noexcept
1569{
1570 return !m_preparedQuery.empty();
1571}
1572
1573inline LIGHTWEIGHT_FORCE_INLINE SqlConnection& SqlStatement::Connection() noexcept
1574{
1575 return *m_connection;
1576}
1577
1578inline LIGHTWEIGHT_FORCE_INLINE SqlConnection const& SqlStatement::Connection() const noexcept
1579{
1580 return *m_connection;
1581}
1582
1583inline LIGHTWEIGHT_FORCE_INLINE Driver::StatementHandle const& SqlStatement::DriverHandle() const noexcept
1584{
1585 return m_handle;
1586}
1587
1588/// Visits the statement's real driver struct (see the declaration).
1589/// @param operation The name of the operation @p f performs, for the error message.
1590/// @param f Called with the driver's statement struct by reference.
1591/// @return What @p f returns.
1592template <typename F>
1593inline LIGHTWEIGHT_FORCE_INLINE decltype(auto) SqlStatement::VisitDriver(std::string_view operation, F&& f)
1594{
1595 return Driver::VisitRequired(m_handle, operation, std::forward<F>(f));
1596}
1597
1598/// Visits the statement's driver struct read-only (see the declaration).
1599/// @param operation The name of the operation @p f performs, for the error message.
1600/// @param f Called with the driver's statement struct by const reference.
1601/// @return What @p f returns.
1602template <typename F>
1603inline LIGHTWEIGHT_FORCE_INLINE decltype(auto) SqlStatement::VisitDriver(std::string_view operation, F&& f) const
1604{
1605 return Driver::VisitRequired(m_handle, operation, std::forward<F>(f));
1606}
1607
1608inline LIGHTWEIGHT_FORCE_INLINE SqlDriverId SqlStatement::DriverId() const noexcept
1609{
1610 return m_handle.DriverId();
1611}
1612
1613#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1614inline LIGHTWEIGHT_FORCE_INLINE Driver::Odbc::NativeStatementHandle Driver::Odbc::NativeHandle(
1615 SqlStatement const& stmt) noexcept
1616{
1617 // The body is in Driver::Odbc scope, where `Driver` names the Odbc::Driver struct, hence the unqualified names.
1618 return Visit(stmt.DriverHandle(), [](auto const& held) -> NativeStatementHandle {
1619 if constexpr (std::same_as<std::remove_cvref_t<decltype(held)>, Statement>)
1620 return held.handle;
1621 else
1622 return NativeStatementHandle {};
1623 });
1624}
1625#endif
1626
1627template <SqlQueryObject QueryObject>
1628inline void SqlStatement::AdoptProjectedFieldNames(QueryObject const& queryObject)
1629{
1630 if constexpr (SqlNamedProjectionQueryObject<QueryObject>)
1631 {
1632 auto const names = queryObject.ProjectedFieldNames();
1633 m_projectedFieldNames.assign(names.begin(), names.end());
1634 m_projectionHasWildcard = queryObject.ProjectionHasWildcard();
1635 }
1636 else
1637 {
1638 // A statement is reusable, so a query object without a mapping must drop the previous one
1639 // rather than let stale names resolve against unrelated result columns.
1640 m_projectedFieldNames.clear();
1641 m_projectionHasWildcard = false;
1642 }
1643}
1644
1645inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::Prepare(SqlQueryObject auto const& queryObject) &
1646{
1647 Prepare(queryObject.ToSql());
1648 // After the raw overload, which drops any previously held mapping.
1649 AdoptProjectedFieldNames(queryObject);
1650}
1651
1652inline LIGHTWEIGHT_FORCE_INLINE SqlStatement SqlStatement::Prepare(SqlQueryObject auto const& queryObject) &&
1653{
1654 auto preparedStatement = std::move(*this).Prepare(queryObject.ToSql());
1655 preparedStatement.AdoptProjectedFieldNames(queryObject);
1656 return preparedStatement;
1657}
1658
1659inline LIGHTWEIGHT_FORCE_INLINE std::string const& SqlStatement::PreparedQuery() const noexcept
1660{
1661 return m_preparedQuery;
1662}
1663
1664/// @brief Out-of-line definition of `SqlStatement::BindOutputColumns`.
1665template <SqlOutputColumnBinder... Args>
1666inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::BindOutputColumns(Args*... args)
1667{
1668#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1669 if (ShouldRecordPrefetchBinding())
1670 {
1671 // Prefetch is pending/active: defer the SQLBindCol and instead record per-column scatters that
1672 // copy each block cell into the caller's storage. ResetPrefetchBindings makes the optional
1673 // rebind idiom (re-calling BindOutputColumns each row) idempotent rather than accumulating.
1674 ResetPrefetchBindings();
1675 SqlColumnIndex i = 0;
1676 ((++i, RecordPrefetchOutputColumn<Args>(i, args)), ...);
1677 return;
1678 }
1679#endif
1680
1681 // One compare per call, however many columns it binds; 08003 once the session ended. A binding recorded for
1682 // the block prefetch above reaches the driver at the fetch, which checks the session itself.
1683 RequireCurrentSession();
1684 RequireIndicators();
1685 NoteOutputColumnBoundDirectly();
1686
1687 SqlColumnIndex i = 0;
1688 ((++i, BindOutputColumnNow<Args>(i, args)), ...);
1689}
1690
1691namespace detail
1692{
1693 /// @brief Whether a bound output variable of type @p T is a fixed-size value the driver may write in
1694 /// place, so that the statement resets it to @c T{} on a NULL row: SQL Server's and PostgreSQL's drivers
1695 /// leave such a buffer untouched on NULL, which would keep the previous row's value. A @c std::optional
1696 /// resets itself, and a fixed-capacity string's binder empties it.
1697 template <typename T>
1698 concept ResetsBoundValueOnNull = std::is_trivially_copyable_v<T> && std::is_default_constructible_v<T>
1699 && std::is_assignable_v<T&, T> && !SqlIsStdOptional<T> && !IsSqlFixedString<T>;
1700
1701 /// @brief The value a NULL row resets in the bound variable @p value: the variable itself, or the value a
1702 /// wrapper that binds through its @c MutableValue() (a @c Field, a @c BelongsTo) holds, so the wrapper's own
1703 /// state (whether it is modified) is the same after a NULL row as after any other.
1704 /// @param value The bound variable.
1705 /// @return The value to reset.
1706 template <typename T>
1707 [[nodiscard]] constexpr auto& BoundNullResetTarget(T& value) noexcept
1708 {
1709 if constexpr (requires { requires std::is_lvalue_reference_v<decltype(value.MutableValue())>; })
1710 return BoundNullResetTarget(value.MutableValue());
1711 else
1712 return value;
1713 }
1714} // namespace detail
1715
1716/// @brief Out-of-line definition of `SqlStatement::BindOutputColumnNow`: binds @p arg as output column
1717/// @p column with @c SqlDataBinder<T>::OutputColumn right away, replacing the column's planned callbacks.
1718/// @tparam T The bound variable's type.
1719/// @param column The 1-based column index.
1720/// @param arg The variable the column is fetched into.
1721template <SqlOutputColumnBinder T>
1722inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::BindOutputColumnNow(SqlColumnIndex column, T* arg)
1723{
1724 BeginOutputColumnBinding(column);
1725 auto* const indicator = GetIndicatorForColumn(column);
1726 auto const result =
1727 Driver::Visit(m_handle, [&](auto& stmt) { return Driver::BindOutputColumn(stmt, column, arg, indicator, *this); });
1728 // A binder can have planned callbacks before it failed; the column is not bound, so they must not
1729 // run on the following fetches (the diagnostics stay on the handle for RequireSuccess).
1730 if (!Succeeded(result))
1731 DropOutputColumnCallbacks(column);
1732 RequireSuccess(result);
1733
1734 // A NULL row reads as T{}, on every driver and as under block prefetch; run after the binders' own steps.
1735 // A plain entry per column rather than a planned callback: no std::function, and the column is not added
1736 // to the ones the pre-fetch steps visit.
1737 auto& target = detail::BoundNullResetTarget(*arg);
1738 using Target = std::remove_cvref_t<decltype(target)>;
1739 if constexpr (detail::ResetsBoundValueOnNull<Target>)
1740 PlanNullReset(column, indicator, std::addressof(target), [](void* value) noexcept {
1741 *static_cast<Target*>(value) = Target {};
1742 });
1743}
1744
1745template <typename... Records>
1746 requires(((std::is_class_v<Records> && std::is_aggregate_v<Records>) && ...))
1747void SqlStatement::BindOutputColumnsToRecord(Records*... records)
1748{
1749#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1750 if (ShouldRecordPrefetchBinding())
1751 {
1752 ResetPrefetchBindings();
1753 SqlColumnIndex i = 0;
1754 ((EnumerateRecordMembers(*records,
1755 [this, &i]<size_t I, typename FieldType>(FieldType& value) {
1756 // Only members mapping onto a column occupy a result set index.
1757 if constexpr (RecordColumnMember<FieldType>)
1758 {
1759 ++i;
1760 this->RecordPrefetchOutputColumn<FieldType>(i, &value);
1761 }
1762 })),
1763 ...);
1764 return;
1765 }
1766#endif
1767
1768 // One compare per call, however many records and columns it binds; 08003 once the session ended. A binding
1769 // recorded for the block prefetch above reaches the driver at the fetch, which checks the session itself.
1770 RequireCurrentSession();
1771 RequireIndicators();
1772 NoteOutputColumnBoundDirectly();
1773
1774 SqlColumnIndex i = 0;
1775 ((EnumerateRecordMembers(*records,
1776 [this, &i]<size_t I, typename FieldType>(FieldType& value) {
1777 // Only members mapping onto a column occupy a result set index.
1778 if constexpr (RecordColumnMember<FieldType>)
1779 {
1780 ++i;
1781 this->BindOutputColumnNow<FieldType>(i, &value);
1782 }
1783 })),
1784 ...);
1785}
1786
1787/// @brief Out-of-line definition of `SqlStatement::BindOutputColumn`.
1788template <SqlOutputColumnBinder T>
1789inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::BindOutputColumn(SqlColumnIndex columnIndex, T* arg)
1790{
1791 // Singular bind: no ResetPrefetchBindings (callers — e.g. the DataMapper — set columns one at a
1792 // time); RecordPrefetchColumn overwrites the column's slot so per-row re-binding stays bounded.
1793#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1794 if (ShouldRecordPrefetchBinding())
1795 {
1796 RecordPrefetchOutputColumn<T>(columnIndex, arg);
1797 return;
1798 }
1799#endif
1800
1801 RequireIndicators();
1802 NoteOutputColumnBoundDirectly();
1803
1804 BindOutputColumnNow<T>(columnIndex, arg);
1805}
1806
1807/// @copydoc SqlStatement::BindInputParameter(std::int16_t, Arg const&)
1808template <SqlInputParameterBinder Arg>
1809inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::BindInputParameter(std::int16_t columnIndex, Arg const& arg)
1810{
1811 RequireCurrentSession(); // one compare per bind call; 08003 once the session ended
1812 if (m_parameterRoundBound)
1813 DropRoundBindings();
1814 // tell Execute() that we don't know the expected count
1815 m_expectedParameterCount = (std::numeric_limits<decltype(m_expectedParameterCount)>::max)();
1816 Driver::Visit(m_handle, [&](auto& stmt) {
1817 RequireSuccess(
1818 BindParameterValue(stmt, static_cast<SqlColumnIndex>(columnIndex), arg, ParameterSlotReuse::NextBinding));
1819 });
1820}
1821
1822/// @copydoc SqlStatement::BindInputParameter(std::int16_t, Arg const&, ColumnName&&)
1823template <SqlInputParameterBinder Arg, typename ColumnName>
1824inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::BindInputParameter(std::int16_t columnIndex,
1825 Arg const& arg,
1826 ColumnName&& columnNameHint)
1827{
1828 SqlLogger::GetLogger().OnBindInputParameter(std::forward<ColumnName>(columnNameHint), arg);
1829 BindInputParameter(columnIndex, arg);
1830}
1831
1832template <SqlInputParameterBinder... Args>
1833SqlResultCursor SqlStatement::Execute(Args const&... args)
1834{
1835 // Each input parameter must have an address,
1836 // such that the driver can bind it without needing to copy it.
1837 // The memory region behind the input parameter must exist until the statement is executed.
1838
1839 ZoneScopedN("SqlStatement::Execute");
1840 ZoneTextObject(m_preparedQuery);
1841 RequireCurrentSession();
1842 SqlLogger::GetLogger().OnExecute(m_preparedQuery);
1843
1844 if (!(m_expectedParameterCount == (std::numeric_limits<decltype(m_expectedParameterCount)>::max)()
1845 && sizeof...(args) == 0)
1846 && !(m_expectedParameterCount == sizeof...(args)))
1847 throw std::invalid_argument { "Invalid argument count" };
1848
1849 // Every parameter is bound below, each reusing its slots in place; without arguments, those bound by hand stay
1850 // bound.
1851 if constexpr (sizeof...(Args) > 0)
1852 m_parameterRoundBound = true;
1853
1854 // stmt is used only in the fold over args, which Execute() without arguments leaves empty.
1855 Driver::Visit(m_handle, [&]([[maybe_unused]] auto& stmt) {
1856 SqlColumnIndex i = 0;
1857 ((++i,
1858 SqlLogger::GetLogger().OnBindInputParameter({}, args),
1859 RequireSuccess(BindParameterValue(stmt, i, args, ParameterSlotReuse::InPlace))),
1860 ...);
1861 });
1862
1863 LIGHTWEIGHT_STATS_SCOPE(::Lightweight::SqlStatisticsOperation::Execute);
1864 ++m_executeAttempts;
1865 auto result = Driver::Execute(m_handle);
1866
1867 // A prepared statement Prepare() reused rather than re-issued can have gone stale server-side.
1868 if (RetryStalePreparedStatement(result))
1869 result = Driver::Execute(m_handle);
1870
1871 if (result != SqlResult::NoData && result != SqlResult::Success && result != SqlResult::SuccessWithInfo)
1872 throw SqlException(LastError(), std::source_location::current());
1873
1874 ProcessPostExecuteCallbacks();
1875 return SqlResultCursor { *this };
1876}
1877
1878// A column-wise parameter array strides a fixed-length C type by the C type's size, not by the element's,
1879// so only types whose bound C type is exactly sizeof(T) qualify. SqlTime does not: it stores the 12-byte
1880// TIME2 layout but binds SQL_C_TYPE_TIME (6 bytes), so its column-major batches take the soft path. (The
1881// row-wise path strides by the row size and still binds SqlTime natively.) A type also needs a column-wise
1882// SqlDataBinder<T>::BatchInputParameter of the ODBC driver, the only one with parameter arrays; one without
1883// (wchar_t, the UTF-16 fixed strings) takes the soft path.
1884#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1885// clang-format off
1886template <typename T>
1887concept SqlNativeContiguousValueConcept =
1888 ( std::same_as<T, bool>
1889 || std::same_as<T, char>
1890 || std::same_as<T, unsigned char>
1891 || std::same_as<T, std::int16_t>
1892 || std::same_as<T, std::uint16_t>
1893 || std::same_as<T, std::int32_t>
1894 || std::same_as<T, std::uint32_t>
1895 || std::same_as<T, std::int64_t>
1896 || std::same_as<T, std::uint64_t>
1897 || std::same_as<T, float>
1898 || std::same_as<T, double>
1899 || std::same_as<T, SqlDate>
1900 || std::same_as<T, SqlDateTime>
1901 || std::same_as<T, SqlFixedString<T::Capacity, typename T::value_type, T::PostRetrieveOperation>>)
1902 && requires(Driver::Odbc::Statement& stmt, SqlColumnIndex column, T const* values, std::size_t rowCount, SqlDataBinderCallback& cb) {
1903 { SqlDataBinder<T>::BatchInputParameter(stmt, column, values, rowCount, cb) } -> std::same_as<SqlResult>;
1904 };
1905
1906template <typename FirstColumnBatch, typename... MoreColumnBatches>
1907concept SqlNativeBatchable =
1908 std::ranges::contiguous_range<FirstColumnBatch>
1909 && (std::ranges::contiguous_range<MoreColumnBatches> && ...)
1910 && SqlNativeContiguousValueConcept<std::ranges::range_value_t<FirstColumnBatch>>
1911 && (SqlNativeContiguousValueConcept<std::ranges::range_value_t<MoreColumnBatches>> && ...);
1912
1913// clang-format on
1914#else
1915/// @brief Whether the column batches can execute as one native parameter array: never without ODBC, the only driver
1916/// with parameter arrays.
1917template <typename FirstColumnBatch, typename... MoreColumnBatches>
1918concept SqlNativeBatchable = false;
1919#endif
1920
1921/// @brief A value type that can be bound in a native ODBC row-wise parameter array (fixed-width,
1922/// inline, indicator-free, bound identically across backends). Backed by the data-driven
1923/// @c SqlIsNativeRowBindableValue trait that each eligible binder header opts into.
1924template <typename V>
1925concept SqlNativeRowBindableValue = SqlIsNativeRowBindableValue<V>;
1926
1927/// @brief A @c std::optional column that can be bound zero-copy in a native row-wise batch: the
1928/// contained type is row-bindable and non-numeric (numeric optionals are not bound at a uniform
1929/// offset/representation across backends and therefore use the soft path).
1930template <typename V>
1932 SqlIsStdOptional<V> && SqlNativeRowBindableValue<typename V::value_type> && !SqlIsNumericValue<typename V::value_type>;
1933
1934/// @brief A column value type usable on the native row-wise batch path — either a row-bindable fixed
1935/// value or a row-bindable optional of one.
1936template <typename V>
1938
1939/// @brief A column usable on the native row-wise array-FETCH fast path. Intentionally identical to the
1940/// write-side @c SqlRowBindableColumn — the set of types we can bind row-wise into a record block on
1941/// fetch matches the set we can bind row-wise as a parameter array on execute: fixed-width primitives,
1942/// date/time/datetime, numeric, char-based fixed-capacity strings, and non-numeric optionals of those.
1943///
1944/// Char fixed strings are materialized by a dedicated SQL_C_CHAR bind plus a per-row length/trim fixup
1945/// (see @c BindRowWiseOutputColumn / @c FinalizeRowWiseOutputColumn); on PostgreSQL, whose driver
1946/// transcodes SQL_C_CHAR through the client codepage, records carrying one fall back to the per-row
1947/// (wide) path instead — see @c SqlConnection::RoundTripsNarrowTextByteExact. Growable strings/binary,
1948/// GUID and variant are not row-bindable and make the whole record fall back to the per-row fetch path.
1949template <typename V>
1951
1952/// @brief Whether @p V (or the value type of a @c std::optional @p V) binds through a staging copy on a
1953/// driver that does not convert its C type over the type's full range (see @c SqlStagedIntegerDataBinder).
1954///
1955/// A row-wise array bind strides the bound address through the caller's rows, so it cannot stage: on such
1956/// a driver a row-wise batch carrying one takes the per-row path, and the row-wise fetch binds it in place.
1957/// @return @c true for @c int8_t and @c uint32_t (and optionals of them).
1958template <typename V>
1959constexpr bool SqlColumnMayStage() noexcept
1960{
1961 if constexpr (SqlIsStdOptional<V>)
1962 return SqlColumnMayStage<typename V::value_type>();
1963 else
1964 return requires { &SqlDataBinder<V>::OutputColumnInPlace; };
1965}
1966
1967/// @brief Whether @p V's binder provides a row-wise batch entry point (@c BatchRowWiseInputParameter).
1968///
1969/// Such types (e.g. @c std::optional of a fixed type, or inline fixed-capacity strings) need a
1970/// temporary row-strided NULL/length indicator buffer, which in turn requires the row stride to keep
1971/// @c SQLLEN indicator slots aligned. Plain indicator-free fixed values bind via @c InputParameter and
1972/// do not satisfy this concept.
1973#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1974template <typename V>
1975concept SqlHasRowWiseBatchBinder = requires(
1976 Driver::Odbc::Statement& stmt, SqlColumnIndex column, V const* elem0, std::size_t n, SqlDataBinderCallback& cb) {
1977 { SqlDataBinder<V>::BatchRowWiseInputParameter(stmt, column, elem0, n, n, cb) } -> std::same_as<SqlResult>;
1978};
1979#else
1980/// Without ODBC no binder provides a row-wise batch entry point: there are no parameter arrays.
1981template <typename V>
1982concept SqlHasRowWiseBatchBinder = false;
1983#endif
1984
1985namespace detail
1986{
1987 template <typename V>
1988 struct IsNarrowFixedStringColumn: std::false_type
1989 {
1990 };
1991
1992 template <std::size_t N, SqlFixedStringMode Mode>
1993 struct IsNarrowFixedStringColumn<SqlFixedString<N, char, Mode>>: std::true_type
1994 {
1995 };
1996
1997 template <std::size_t N, SqlFixedStringMode Mode>
1998 struct IsNarrowFixedStringColumn<std::optional<SqlFixedString<N, char, Mode>>>: std::true_type
1999 {
2000 };
2001
2002 /// @brief Refuses a batch of which a value cannot be written, before any of it is bound or executed.
2003 ///
2004 /// Checks the value @p project yields of every element of @p values through
2005 /// @c SqlDataBinder<Value>::UnwritableYear (see SqlBinderChecksYear); a value type without that check
2006 /// costs nothing.
2007 /// @param values The rows (or the values of one column) of the batch.
2008 /// @param project Yields the value to check from an element of @p values.
2009 /// @throws SqlException SQLSTATE 22008 for the first value whose year cannot be written.
2010 template <std::ranges::range Values, typename Project>
2011 void RequireWritableYears(Values const& values, Project const& project)
2012 {
2013 using Value =
2014 std::remove_cvref_t<std::invoke_result_t<Project const&, std::ranges::range_reference_t<Values const>>>;
2015 if constexpr (SqlBinderChecksYear<Value>)
2016 for (auto const& element: values)
2017 if (auto const year = SqlDataBinder<Value>::UnwritableYear(std::invoke(project, element)))
2018 throw SqlException(UnwritableYearError(*year));
2019 }
2020} // namespace detail
2021
2022/// @brief Whether @p V is a char fixed-capacity string, or a @c std::optional of one. The row-wise batch binds
2023/// such a column as @c SQL_C_CHAR in place, without the narrow-text conversion the single-row binder applies.
2024template <typename V>
2025constexpr bool SqlIsNarrowFixedStringColumn = detail::IsNarrowFixedStringColumn<V>::value;
2026
2027#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2028template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::contiguous_range... MoreColumnBatches>
2029SqlResultCursor SqlStatement::ExecuteBatchNative(FirstColumnBatch const& firstColumnBatch,
2030 MoreColumnBatches const&... moreColumnBatches)
2031{
2032 static_assert(SqlNativeBatchable<FirstColumnBatch, MoreColumnBatches...>,
2033 "Must be a supported native contiguous element type.");
2034
2035 ZoneScopedN("SqlStatement::ExecuteBatchNative");
2036 ZoneTextObject(m_preparedQuery);
2037 RequireCurrentSession();
2038
2039 if (m_expectedParameterCount != 1 + sizeof...(moreColumnBatches))
2040 throw std::invalid_argument { "Invalid number of columns" };
2041
2042 auto const rowCount = std::ranges::size(firstColumnBatch);
2043 ZoneValue(rowCount);
2044 if (!((std::size(moreColumnBatches) == rowCount) && ...))
2045 throw std::invalid_argument { "Uneven number of rows" };
2046 m_parameterRoundBound = true;
2047
2048 size_t rowStart = 0;
2049
2050 // Restore single-row parameter binding on every exit, as ExecuteBatchNativeRowWise does: the
2051 // parameter-set size and the bind-offset pointer (to the local above) must not outlive this call,
2052 // or a later Execute() without re-Prepare() re-runs N parameter sets through a dangling offset.
2053 auto const restoreParameterBinding = detail::Finally([this] {
2054 ResetParameterArrayBinding();
2055 ClearBatchIndicators();
2056 DropInputParameterKeepAlives();
2057 });
2058
2059 auto const location = std::source_location::current();
2060 Driver::VisitRequired(m_handle, "ExecuteBatchNative", [&](Driver::Odbc::Statement& stmt) {
2061 Driver::Odbc::SetColumnWiseParameterArray(
2062 stmt, rowCount, &rowStart, [&](SqlResult result) { RequireSuccess(result, location); });
2063 });
2064 ClearBatchIndicators();
2065 // Column-wise parameter arrays and their batch binders are ODBC's.
2066 Driver::VisitRequired(m_handle, "ExecuteBatchNative", [&](Driver::Odbc::Statement& stmt) {
2067 RequireSuccess(
2068 SqlDataBinder<std::remove_cvref_t<decltype(*std::ranges::data(firstColumnBatch))>>::BatchInputParameter(
2069 stmt, 1, std::ranges::data(firstColumnBatch), rowCount, *this));
2070 SqlColumnIndex column = 1;
2071 (RequireSuccess(
2072 SqlDataBinder<std::remove_cvref_t<decltype(*std::ranges::data(moreColumnBatches))>>::BatchInputParameter(
2073 stmt, ++column, std::ranges::data(moreColumnBatches), rowCount, *this)),
2074 ...);
2075 });
2076 SqlLogger::GetLogger().OnExecuteNativeBatch(m_preparedQuery);
2077 {
2079 ++m_executeAttempts;
2080 RequireSuccess(Driver::Execute(m_handle));
2081 }
2082 ProcessPostExecuteCallbacks();
2083 return SqlResultCursor { *this };
2084}
2085#else
2086// Without ODBC no driver has column-wise parameter arrays. The call makes the checks and leaves the statement as a
2087// statement of such a driver does in a build with ODBC, and fails with the same unsupported-operation error (IM001).
2088template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::contiguous_range... MoreColumnBatches>
2089SqlResultCursor SqlStatement::ExecuteBatchNative(FirstColumnBatch const& firstColumnBatch,
2090 MoreColumnBatches const&... moreColumnBatches)
2091{
2092 ZoneScopedN("SqlStatement::ExecuteBatchNative");
2093 ZoneTextObject(m_preparedQuery);
2094 RequireCurrentSession();
2095
2096 if (m_expectedParameterCount != 1 + sizeof...(moreColumnBatches))
2097 throw std::invalid_argument { "Invalid number of columns" };
2098
2099 auto const rowCount = std::ranges::size(firstColumnBatch);
2100 ZoneValue(rowCount);
2101 if (!((std::size(moreColumnBatches) == rowCount) && ...))
2102 throw std::invalid_argument { "Uneven number of rows" };
2103 m_parameterRoundBound = true;
2104
2105 auto const restoreParameterBinding = detail::Finally([this] {
2106 ResetParameterArrayBinding();
2107 ClearBatchIndicators();
2108 DropInputParameterKeepAlives();
2109 });
2110 throw SqlException(Driver::NotSupportedByDriver(m_handle.DriverId(), "ExecuteBatchNative"));
2111}
2112#endif
2113
2114/// @copydoc SqlStatement::ExecuteBatch
2115template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::range... MoreColumnBatches>
2116inline LIGHTWEIGHT_FORCE_INLINE SqlResultCursor SqlStatement::ExecuteBatch(FirstColumnBatch const& firstColumnBatch,
2117 MoreColumnBatches const&... moreColumnBatches)
2118{
2119 // If the input ranges are contiguous and their element types are contiguous and supported as well,
2120 // we can use the native batch execution.
2121 // The driver's capability only: the server-type table never gated this overload. With one driver the
2122 // condition is a constant.
2123 if constexpr (SqlNativeBatchable<FirstColumnBatch, MoreColumnBatches...>)
2124 {
2125 if (Driver::SupportsParameterArrays(m_handle.DriverId()))
2126 return ExecuteBatchNative(firstColumnBatch, moreColumnBatches...);
2127 }
2128 return ExecuteBatchSoft(firstColumnBatch, moreColumnBatches...);
2129}
2130
2131template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::range... MoreColumnBatches>
2132SqlResultCursor SqlStatement::ExecuteBatchSoft(FirstColumnBatch const& firstColumnBatch,
2133 MoreColumnBatches const&... moreColumnBatches)
2134{
2135 ZoneScopedN("SqlStatement::ExecuteBatchSoft");
2136 ZoneTextObject(m_preparedQuery);
2137 RequireCurrentSession();
2138
2139 if (m_expectedParameterCount != 1 + sizeof...(moreColumnBatches))
2140 throw std::invalid_argument { "Invalid number of columns" };
2141
2142 auto const rowCount = std::ranges::size(firstColumnBatch);
2143 ZoneValue(rowCount);
2144 if (!((std::size(moreColumnBatches) == rowCount) && ...))
2145 throw std::invalid_argument { "Uneven number of rows" };
2146 m_parameterRoundBound = true;
2147
2148 // Rows execute one by one: a value that cannot be written is refused before the first one is stored.
2149 detail::RequireWritableYears(firstColumnBatch, std::identity {});
2150 (detail::RequireWritableYears(moreColumnBatches, std::identity {}), ...);
2151
2152 for (auto const rowIndex: std::views::iota(size_t { 0 }, rowCount))
2153 {
2154 std::apply(
2155 [&]<SqlInputParameterBinder... ColumnValues>(ColumnValues const&... columnsInRow) {
2156 Driver::Visit(m_handle, [&](auto& stmt) {
2157 SqlColumnIndex column = 0;
2158 ((++column, RequireSuccess(BindParameterValue(stmt, column, columnsInRow, ParameterSlotReuse::InPlace))),
2159 ...);
2160 });
2161 {
2163 ++m_executeAttempts;
2164 RequireSuccess(Driver::Execute(m_handle));
2165 }
2166 ProcessPostExecuteCallbacks();
2167 },
2168 std::make_tuple(
2169 std::ref(*std::ranges::next(std::ranges::begin(firstColumnBatch), static_cast<std::ptrdiff_t>(rowIndex))),
2170 std::ref(
2171 *std::ranges::next(std::ranges::begin(moreColumnBatches), static_cast<std::ptrdiff_t>(rowIndex)))...));
2172 }
2173 return SqlResultCursor { *this };
2174}
2175
2176template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
2177 requires(sizeof...(ColumnAccessors) >= 1
2178 && (std::invocable<ColumnAccessors const&, std::ranges::range_value_t<Rows> const&> && ...))
2179SqlResultCursor SqlStatement::ExecuteBatch(Rows const& rows, ColumnAccessors const&... accessors)
2180{
2181 ZoneScopedN("SqlStatement::ExecuteBatch(row-major)");
2182 ZoneTextObject(m_preparedQuery);
2183 RequireCurrentSession();
2184
2185 using RowElem = std::ranges::range_value_t<Rows>;
2186
2187 auto const rowCount = std::ranges::size(rows);
2188 if (rowCount == 0)
2189 return SqlResultCursor { *this };
2190
2191 if (m_expectedParameterCount != static_cast<std::int16_t>(sizeof...(accessors)))
2192 throw std::invalid_argument { "Invalid number of columns" };
2193
2194 // Compile-time eligibility for the native row-wise path: every column must be row-bindable, every
2195 // accessor must return an lvalue reference (so the bound address is a stable subobject), and — when
2196 // any column needs a row-strided indicator (optionals, inline fixed-capacity strings) — the row
2197 // stride must keep SqlIndicator slots aligned and non-overlapping.
2198 constexpr bool allColumnsRowBindable =
2200 constexpr bool allAccessorsReturnReference =
2201 (std::is_reference_v<std::invoke_result_t<ColumnAccessors const&, RowElem const&>> && ...);
2202 constexpr bool anyStridedIndicatorColumn =
2204 constexpr bool indicatorAlignmentSatisfied = (sizeof(RowElem) % alignof(SqlIndicator)) == 0;
2205 constexpr bool anyNarrowFixedStringColumn =
2206 (SqlIsNarrowFixedStringColumn<std::remove_cvref_t<std::invoke_result_t<ColumnAccessors const&, RowElem const&>>>
2207 || ...);
2208
2209 if constexpr (allColumnsRowBindable && allAccessorsReturnReference
2210 && (!anyStridedIndicatorColumn || indicatorAlignmentSatisfied))
2211 {
2212 auto const* rowData = std::ranges::data(rows);
2213
2214 // Runtime guard: confirm each accessor yields a constant-offset subobject (stride == sizeof row),
2215 // so binding row 0's address and striding by sizeof(RowElem) addresses every row correctly.
2216 auto const accessorStrideMatchesRow = [&](auto const& accessor) noexcept -> bool {
2217 auto const* first = reinterpret_cast<std::byte const*>(std::addressof(accessor(rowData[0])));
2218 auto const* second = reinterpret_cast<std::byte const*>(std::addressof(accessor(rowData[1])));
2219 return static_cast<std::size_t>(second - first) == sizeof(RowElem);
2220 };
2221 bool const rowStrideOk = rowCount < 2 || (accessorStrideMatchesRow(accessors) && ...);
2222
2223 // A narrow fixed string cannot be converted in place, so a connection that converts narrow text with
2224 // the process code page takes the per-row path. PostgreSQL keeps the narrow bind.
2225 bool const narrowColumnsBindInPlace =
2226 !anyNarrowFixedStringColumn || NarrowTextBindingMode() != detail::NarrowTextBinding::WideFromProcessCodePage;
2227
2228 // A column whose binder stages its value on this driver cannot be array-bound in the caller's rows.
2229 constexpr bool anyColumnMayStage =
2230 (SqlColumnMayStage<std::remove_cvref_t<std::invoke_result_t<ColumnAccessors const&, RowElem const&>>>() || ...);
2231 bool const bindsInPlace = !anyColumnMayStage || detail::ConvertsNarrowIntegerCTypes(m_connection->ServerType());
2232
2233 if (m_connection->SupportsNativeRowBatch() && rowStrideOk && narrowColumnsBindInPlace && bindsInPlace)
2234 return ExecuteBatchNativeRowWise(rows, accessors...);
2235 }
2236
2237 return ExecuteBatchSoftRowMajor(rows, accessors...);
2238}
2239
2240#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2241template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
2242SqlResultCursor SqlStatement::ExecuteBatchNativeRowWise(Rows const& rows, ColumnAccessors const&... accessors)
2243{
2244 ZoneScopedN("SqlStatement::ExecuteBatchNativeRowWise");
2245 ZoneTextObject(m_preparedQuery);
2246 m_parameterRoundBound = true;
2247
2248 using RowElem = std::ranges::range_value_t<Rows>;
2249 auto const rowCount = std::ranges::size(rows);
2250 ZoneValue(rowCount);
2251 auto const* rowData = std::ranges::data(rows);
2252
2253 // Optimistic init: a driver that ignores SQL_ATTR_PARAMS_PROCESSED_PTR leaves this == rowCount, so the
2254 // post-execute completeness check never false-trips on such a driver.
2255 Driver::Odbc::ProcessedCount processedCount = rowCount;
2256
2257 // Restore single-row binding and release scratch buffers on EVERY exit — success or exception — so a
2258 // throwing bind/execute can never leave the handle in a stale multi-paramset/row-wise state for a
2259 // later reuse (e.g. a single Execute() without re-Prepare). Installed before the attributes are set,
2260 // so a failure mid-setup is unwound too.
2261 auto const restoreParameterBinding = detail::Finally([this] {
2262 ResetParameterArrayBinding();
2263 ClearBatchIndicators();
2264 DropInputParameterKeepAlives();
2265 });
2266
2267 // Row-wise array binding: the driver strides every bound value and indicator pointer by sizeof(RowElem).
2268 auto const location = std::source_location::current();
2269 Driver::VisitRequired(m_handle, "row-wise native batch", [&](Driver::Odbc::Statement& stmt) {
2270 Driver::Odbc::SetRowWiseParameterArray(
2271 stmt, rowCount, sizeof(RowElem), &processedCount, [&](SqlResult result) { RequireSuccess(result, location); });
2272 });
2273
2274 // Row-wise parameter arrays and their batch binders are ODBC's.
2275 Driver::VisitRequired(m_handle, "row-wise native batch", [&](Driver::Odbc::Statement& stmt) {
2276 SqlColumnIndex column = 0;
2277 auto const bindColumn = [&](auto const& accessor) {
2278 ++column;
2279 using ValueType = std::remove_cvref_t<decltype(accessor(rowData[0]))>;
2280 // Types needing a per-row indicator (optionals, inline fixed-capacity strings) provide a
2281 // row-wise batch binder; indicator-free fixed values bind directly via InputParameter.
2282 // A date's binder sees only row 0 here: every row's year must be one that can be written.
2283 detail::RequireWritableYears(std::span { rowData, rowCount }, accessor);
2284 if constexpr (SqlHasRowWiseBatchBinder<ValueType>)
2285 RequireSuccess(SqlDataBinder<ValueType>::BatchRowWiseInputParameter(
2286 stmt, column, std::addressof(accessor(rowData[0])), sizeof(RowElem), rowCount, *this));
2287 else
2288 RequireSuccess(BindParameterValue(stmt, column, accessor(rowData[0]), ParameterSlotReuse::InPlace));
2289 };
2290 (bindColumn(accessors), ...);
2291 });
2292
2293 SqlLogger::GetLogger().OnExecuteNativeBatch(m_preparedQuery);
2294 // Capture the result before reading processedCount: SQLExecute updates it via the bound pointer, and
2295 // function-argument evaluation order is unspecified.
2297 ++m_executeAttempts;
2298 auto const executeResult = Driver::Execute(m_handle);
2299 RequireSuccessfulBatchExecute(executeResult, processedCount, rowCount);
2300 ProcessPostExecuteCallbacks();
2301
2302 return SqlResultCursor { *this };
2303}
2304#else
2305template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
2306SqlResultCursor SqlStatement::ExecuteBatchNativeRowWise(Rows const& rows, ColumnAccessors const&... accessors)
2307{
2308 // Without ODBC no driver executes parameter arrays (SupportsNativeRowBatch() is false), so the row-major
2309 // ExecuteBatch never takes this path; were it reached, the batch runs row by row.
2310 return ExecuteBatchSoftRowMajor(rows, accessors...);
2311}
2312#endif
2313
2314template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
2315SqlResultCursor SqlStatement::ExecuteBatchSoftRowMajor(Rows const& rows, ColumnAccessors const&... accessors)
2316{
2317 ZoneScopedN("SqlStatement::ExecuteBatchSoftRowMajor");
2318 ZoneTextObject(m_preparedQuery);
2319 m_parameterRoundBound = true;
2320
2321 auto const* rowData = std::ranges::data(rows);
2322 auto const rowCount = std::ranges::size(rows);
2323 ZoneValue(rowCount);
2324
2325 // Rows execute one by one: a value that cannot be written is refused before the first one is stored.
2326 (detail::RequireWritableYears(std::span { rowData, rowCount }, accessors), ...);
2327
2328 // The binders keep pointers into the values they bind, so each value must live until its row has executed.
2329 // The values are the arguments of one call: a value an accessor returns by value is a temporary that lives
2330 // until that call returns, and one it returns by reference is bound where it is, without a copy.
2331 auto const bindAndExecuteRow = [this](auto const&... values) {
2332 Driver::Visit(m_handle, [&](auto& stmt) {
2333 SqlColumnIndex column = 0;
2334 ((++column, RequireSuccess(BindParameterValue(stmt, column, values, ParameterSlotReuse::InPlace))), ...);
2335 });
2336 SqlLogger::GetLogger().OnExecute(m_preparedQuery);
2337 {
2338 LIGHTWEIGHT_STATS_SCOPE(::Lightweight::SqlStatisticsOperation::Execute);
2339 ++m_executeAttempts;
2340 RequireExecuteSucceededOrNoData(Driver::Execute(m_handle));
2341 }
2342 ProcessPostExecuteCallbacks();
2343 };
2344 for (auto const rowIndex: std::views::iota(std::size_t { 0 }, rowCount))
2345 bindAndExecuteRow(accessors(rowData[rowIndex])...);
2346
2347 return SqlResultCursor { *this };
2348}
2349
2350#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2351template <typename Value>
2352void SqlStatement::BindRowWiseValue(SqlColumnIndex column, void* base0, SqlIndicator* indicators)
2353{
2354 if constexpr (IsSqlFixedString<Value>)
2355 {
2356 // Char fixed-capacity strings are stored inline, so each row's character buffer is reached at
2357 // Data(row0) + i*rowStride. Bind it as SQL_C_CHAR with the Capacity(+NUL) buffer length (matching
2358 // the non-PostgreSQL single-row OutputColumn); FinalizeRowWiseOutputColumn sets each row's length
2359 // from its indicator and applies the trailing-whitespace/NUL trim. PostgreSQL never reaches here:
2360 // such records take the per-row (wide) path (see SqlConnection::RoundTripsNarrowTextByteExact).
2361 Driver::VisitRequired(m_handle, "block fetch", [&](Driver::Odbc::Statement& stmt) {
2362 RequireSuccess(Driver::Odbc::BindTextColumn(stmt,
2363 column,
2364 SqlBasicStringOperations<Value>::Data(static_cast<Value*>(base0)),
2365 static_cast<SqlIndicator>(Value::Capacity) + 1,
2366 indicators));
2367 });
2368 }
2369 else if constexpr (std::same_as<Value, bool>)
2370 {
2371 // The row array strides through the records, so no staging byte: bound in place, and each row's byte is
2372 // checked before the record is read (FinalizeRowWiseOutputColumn).
2373 BeginOutputColumnBinding(column);
2374 Driver::VisitRequired(m_handle, "block fetch", [&](Driver::Odbc::Statement& stmt) {
2375 RequireSuccess(SqlDataBinder<bool>::OutputBitColumnInPlace(stmt, column, static_cast<bool*>(base0), indicators));
2376 });
2377 }
2378 else if constexpr (SqlColumnMayStage<Value>())
2379 {
2380 // The row array strides through the records, so no staging copy: bound in place as its own C type.
2381 // Only reached where the driver converts that C type over the full range: elsewhere (SQLite)
2382 // FetchAllRowWise reads such a result set per row.
2383 BeginOutputColumnBinding(column);
2384 Driver::VisitRequired(m_handle, "block fetch", [&](Driver::Odbc::Statement& stmt) {
2385 RequireSuccess(SqlDataBinder<Value>::OutputColumnInPlace(stmt, column, static_cast<Value*>(base0), indicators));
2386 });
2387 }
2388 else
2389 {
2390 // Fixed-width value (primitive, date/time/datetime, numeric): a plain, callback-free SQLBindCol
2391 // straight into the record field; the driver strides by rowStride.
2392 BeginOutputColumnBinding(column);
2393 Driver::Visit(m_handle, [&](auto& stmt) {
2394 RequireSuccess(Driver::BindOutputColumn(stmt, column, static_cast<Value*>(base0), indicators, *this));
2395 });
2396 }
2397}
2398
2399template <typename ValueType>
2400SqlIndicator* SqlStatement::BindRowWiseOutputColumn(SqlColumnIndex column,
2401 void* base0,
2402 std::size_t rowStride,
2403 std::size_t depth)
2404{
2405 // Row-wise binding strides the indicator pointer by SQL_ATTR_ROW_BIND_TYPE (== rowStride), the same
2406 // as the value pointer; there is no separate indicator stride. So the indicator array over-allocates
2407 // to rowStride per row (only sizeof(SqlIndicator) of each slot is used) — intrinsic to ODBC row-wise
2408 // binding, identical to the write side (see SqlDataBinderCallback::ProvideBatchStagingBuffer).
2409 auto* const indicatorBytes = ProvideRowWiseFetchIndicators(((depth - 1) * rowStride) + sizeof(SqlIndicator));
2410 auto* const indicators = reinterpret_cast<SqlIndicator*>(indicatorBytes);
2411
2412 if constexpr (SqlIsStdOptional<ValueType>)
2413 {
2414 using Inner = ValueType::value_type;
2415 auto* const optBytes = static_cast<std::byte*>(base0);
2416 // Pre-engage every row's optional so its contained storage is valid to bind into; rows that come
2417 // back NULL are reset to std::nullopt in FinalizeRowWiseOutputColumn.
2418 for (auto const i: std::views::iota(std::size_t { 0 }, depth))
2419 reinterpret_cast<ValueType*>(optBytes + (i * rowStride))->emplace();
2420 // The contained value of row 0 (constant offset within every optional); the driver strides it by
2421 // rowStride to reach each row's contained storage in place.
2422 auto* const contained0 = reinterpret_cast<Inner*>(optBytes + detail::OptionalValueOffset<Inner>());
2423 BindRowWiseValue<Inner>(column, contained0, indicators);
2424 }
2425 else
2426 {
2427 BindRowWiseValue<ValueType>(column, base0, indicators);
2428 }
2429 return indicators;
2430}
2431
2432template <typename ValueType>
2433void SqlStatement::FinalizeRowWiseOutputColumn(void* base0,
2434 std::size_t rowStride,
2435 std::size_t rowCount,
2436 SqlIndicator const* indicators,
2437 SqlColumnIndex column,
2438 bool booleanTrueMayBeMinusOne)
2439{
2440 auto const indicatorAt = [&](std::size_t i) noexcept {
2441 return *reinterpret_cast<SqlIndicator const*>(reinterpret_cast<std::byte const*>(indicators) + (i * rowStride));
2442 };
2443
2444 if constexpr (SqlIsStdOptional<ValueType>)
2445 {
2446 using Inner = ValueType::value_type;
2447 auto* const optBytes = static_cast<std::byte*>(base0);
2448 for (auto const i: std::views::iota(std::size_t { 0 }, rowCount))
2449 {
2450 auto* const optional = reinterpret_cast<ValueType*>(optBytes + (i * rowStride));
2451 if (indicatorAt(i) == SqlNullData)
2452 optional->reset();
2453 else if constexpr (IsSqlFixedString<Inner>)
2454 {
2455 // Engaged char fixed string: set its length and trim, matching the single-row binder.
2456 // BindRowWiseOutputColumn pre-engages every row and only the NULL branch above ever
2457 // disengages one, so this holds unconditionally — tested anyway to keep the access
2458 // provably safe rather than invariant-dependent.
2459 if (optional->has_value())
2460 SqlBasicStringOperations<Inner>::PostProcessOutputColumn(std::addressof(**optional), indicatorAt(i));
2461 }
2462 else if constexpr (std::same_as<Inner, bool>)
2463 {
2464 if (optional->has_value())
2465 CheckRowWiseBool(std::addressof(**optional), column, booleanTrueMayBeMinusOne);
2466 }
2467 // Engaged fixed-width inner: already materialized in place, nothing more to do.
2468 }
2469 }
2470 else if constexpr (std::same_as<ValueType, bool>)
2471 {
2472 auto* const base = static_cast<std::byte*>(base0);
2473 for (auto const i: std::views::iota(std::size_t { 0 }, rowCount))
2474 if (indicatorAt(i) != SqlNullData)
2475 CheckRowWiseBool(reinterpret_cast<bool*>(base + (i * rowStride)), column, booleanTrueMayBeMinusOne);
2476 }
2477 else if constexpr (IsSqlFixedString<ValueType>)
2478 {
2479 auto* const base = static_cast<std::byte*>(base0);
2480 for (auto const i: std::views::iota(std::size_t { 0 }, rowCount))
2481 SqlBasicStringOperations<ValueType>::PostProcessOutputColumn(
2482 reinterpret_cast<ValueType*>(base + (i * rowStride)), indicatorAt(i));
2483 }
2484 // Plain fixed-width non-optional columns: the value is materialized in place; a NULL leaves the
2485 // default-constructed value untouched, matching the single-row bound-output path.
2486}
2487#endif
2488
2489inline void SqlStatement::CheckRowWiseBool(bool* value, SqlColumnIndex column, bool booleanTrueMayBeMinusOne)
2490{
2491 auto written = static_cast<unsigned char>(0);
2492 std::memcpy(&written, value, 1);
2493 if (written <= 1)
2494 return;
2495 auto const minusOne = written == std::numeric_limits<unsigned char>::max() && booleanTrueMayBeMinusOne;
2496 auto const valid = static_cast<unsigned char>(minusOne ? 1 : 0);
2497 std::memcpy(value, &valid, 1);
2498 if (!minusOne)
2499 detail::ThrowNumericValueOutOfRange(column, static_cast<unsigned>(written), 0U, 1U);
2500}
2501
2502template <typename Record, typename... ColumnAccessors>
2503void SqlStatement::FetchAllRowWise(std::vector<Record>& out,
2504 [[maybe_unused]] std::size_t arrayDepth,
2505 ColumnAccessors const&... accessors)
2506{
2507 ZoneScopedN("SqlStatement::FetchAllRowWise");
2508 ZoneTextObject(m_preparedQuery);
2509 RequireCurrentSession(); // before the guard below touches the handle: 08003 once the session ended
2510
2511 static_assert(sizeof...(ColumnAccessors) >= 1, "FetchAllRowWise requires at least one column accessor");
2512
2513 // A column whose binder stages its value where the driver does not convert its C type over the full range
2514 // (int8_t, uint32_t on SQLite) cannot be array-bound in the records, and a driver without row arrays (the native
2515 // SQLite3 driver) binds none: such a result set is read per row.
2516 constexpr bool anyColumnMayStage =
2517 (SqlColumnMayStage<std::remove_cvref_t<std::invoke_result_t<ColumnAccessors const&, Record&>>>() || ...);
2518 auto const readsPerRow = !m_connection->SupportsNativeRowArrayFetch()
2519 || (anyColumnMayStage && !detail::ConvertsNarrowIntegerCTypes(m_connection->ServerType()));
2520 if (readsPerRow)
2521 {
2522 while (FetchRow())
2523 {
2524 auto& record = detail::EmplaceBackUninitialized(out);
2525 try
2526 {
2527 SqlColumnIndex column = 0;
2528 ((++column, (void) GetColumn(column, std::addressof(accessors(record)))), ...);
2529 }
2530 catch (...)
2531 {
2532 out.pop_back(); // keep only the rows read in full
2533 throw;
2534 }
2535 }
2536 return;
2537 }
2538
2539#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2540 constexpr std::size_t columnCount = sizeof...(ColumnAccessors);
2541
2542 // Adapt the depth to the per-cursor memory budget. The row-strided indicator staging over-allocates
2543 // to sizeof(Record) per row per column, so the per-row footprint is sizeof(Record) * (1 + columns)
2544 // (data block + one indicator buffer per column). Clamp like RowArrayCursor so wide rows bind fewer
2545 // rows per round-trip instead of exhausting memory.
2546 {
2547 auto const perRow = sizeof(Record) * (1 + columnCount);
2548 auto const budgetDepth = RowArrayCursor::MemoryBudgetBytes / std::max<std::size_t>(perRow, 1);
2549 auto const minDepth = std::min(RowArrayCursor::MinArrayDepth, arrayDepth); // never raise above the request
2550 arrayDepth = std::clamp(budgetDepth, minDepth, arrayDepth);
2551 }
2552
2553 std::vector<Driver::Odbc::RowStatus> rowStatus(arrayDepth);
2554 Driver::Odbc::ProcessedCount rowsFetched = 0;
2555
2556 // Restore single-row, column-bound fetch state and release staging buffers on EVERY exit — success or
2557 // exception — so a throwing bind/fetch can never leave the handle in a stale row-array state for a
2558 // later reuse. Mirrors ExecuteBatchNativeRowWise's restoreParameterBinding guard.
2559 auto const restoreFetchState = detail::Finally([this] {
2560 Driver::VisitIfSupported(m_handle, [](Driver::Odbc::Statement& stmt) {
2561 (void) Driver::Odbc::UnbindColumns(stmt);
2562 Driver::Odbc::ResetRowArrayAttributes(stmt);
2563 });
2564 DropOutputColumnBindings();
2565 ReleaseRowWiseFetchIndicators();
2566 });
2567
2568 auto const location = std::source_location::current();
2569 Driver::VisitRequired(m_handle, "block fetch", [&](Driver::Odbc::Statement& stmt) {
2570 Driver::Odbc::SetRowArray(stmt, sizeof(Record), arrayDepth, rowStatus.data(), &rowsFetched, [&](SqlResult result) {
2571 RequireSuccess(result, location);
2572 });
2573 });
2574
2575 auto const booleanTrueMayBeMinusOne = BooleanTrueMayBeMinusOne();
2576 for (;;)
2577 {
2578 std::size_t const base = out.size();
2579 detail::ResizeUninitialized(out, base + arrayDepth);
2580 // A failing block leaves @p out with the rows of the earlier blocks only.
2581 try
2582 {
2583 Record* const row0 = out.data() + base;
2584
2585 // Rebind each column into this block's records (the value pointer follows out's storage across a
2586 // reallocation) and refresh the per-column row-strided indicator buffers.
2587 ReleaseRowWiseFetchIndicators();
2588 std::array<SqlIndicator*, columnCount> indicators {};
2589 SqlColumnIndex column = 0;
2590 std::size_t bindIndex = 0;
2591 ((indicators[bindIndex++] = BindRowWiseOutputColumn<std::remove_cvref_t<decltype(accessors(*row0))>>(
2592 ++column, std::addressof(accessors(*row0)), sizeof(Record), arrayDepth)),
2593 ...);
2594
2595 rowsFetched = 0;
2596 auto const fetchResult = Driver::VisitRequired(
2597 m_handle, "block fetch", [](Driver::Odbc::Statement& stmt) { return Driver::Odbc::FetchNextBlock(stmt); });
2598 if (fetchResult == SqlResult::NoData)
2599 {
2600 detail::ResizeUninitialized(out, base);
2601 break;
2602 }
2603 // SQL_SUCCESS_WITH_INFO is acceptable: rowsFetched stays valid. The fixed-width eligibility gate
2604 // keeps the bound columns from truncating, so it should not occur for these columns in practice.
2605 if (!Succeeded(fetchResult))
2606 RequireSuccess(fetchResult);
2607
2608 auto const fetched = static_cast<std::size_t>(rowsFetched);
2609 // A row the driver could not convert (SQL Server: a number other than 0 or 1 into a bool, 22003) comes
2610 // back as SQL_ROW_ERROR within a successful block: raise its diagnostic rather than keep the row. The
2611 // diagnostics are ordered by row, so a warning of an earlier row (01S07) may come before it.
2612 if (fetchResult == SqlResult::SuccessWithInfo
2613 && std::ranges::contains(rowStatus | std::views::take(fetched), Driver::Odbc::RowStatusError))
2614 Driver::VisitRequired(m_handle, "block fetch", [](Driver::Odbc::Statement const& stmt) {
2615 throw SqlException(Driver::Odbc::DiagnoseFirstError(stmt));
2616 });
2617 SqlLogger::GetLogger().OnFetchRow(); // one block-fetch round-trip (vs. one per row on the slow path)
2618 LIGHTWEIGHT_STATS_ROWS(fetched, true);
2619
2620 SqlColumnIndex finalizeColumn = 0;
2621 ((++finalizeColumn,
2622 FinalizeRowWiseOutputColumn<std::remove_cvref_t<decltype(accessors(*row0))>>(std::addressof(accessors(*row0)),
2623 sizeof(Record),
2624 fetched,
2625 indicators[finalizeColumn - 1],
2626 finalizeColumn,
2627 booleanTrueMayBeMinusOne)),
2628 ...);
2629
2630 detail::ResizeUninitialized(out, base + fetched);
2631 if (fetched < arrayDepth)
2632 break;
2633 }
2634 catch (...)
2635 {
2636 detail::ResizeUninitialized(out, base);
2637 throw;
2638 }
2639 }
2640
2641 SqlLogger::GetLogger().OnFetchEnd();
2642#else
2643 // No driver of this build fetches row arrays, so readsPerRow above is always true; were it not, refuse rather
2644 // than return with @p out untouched.
2645 throw std::logic_error("SqlStatement: no driver of this build fetches blocks of rows");
2646#endif
2647}
2648
2649template <SqlGetColumnNativeType T>
2650inline bool SqlStatement::GetColumn(SqlColumnIndex column, T* result) const
2651{
2652#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2653 if (IsPrefetchActive())
2654 {
2655 auto const& cursor = PrefetchCursorRef();
2656 auto const row = PrefetchRowInBlock();
2657 RequirePrefetchColumnInRange(cursor, column);
2658 if (cursor.IsCellNull(row, column))
2659 {
2660 // As on the per-row path below: a NULL leaves the target holding its empty value (nullopt,
2661 // a NULL SqlVariant), whatever it held before.
2662 if constexpr (std::default_initializable<T>)
2663 *result = T {};
2664 return false;
2665 }
2666 *result = ConvertCell<T>(cursor, row, column);
2667 return true;
2668 }
2669#endif
2670 SqlIndicator indicator {};
2671 // A const member sees the handle struct as const; binders take it mutably, so they get a copy (a plain handle).
2672 Driver::Visit(m_handle, [&](auto const& held) {
2673 auto stmt = held;
2674 RequireSuccess(Driver::ReadColumn(stmt, column, result, &indicator, *this));
2675 });
2676 if (indicator != SqlNullData)
2677 return true;
2678 // The binders reset a nullable target on NULL; what a driver leaves in another one differs (SQLite's
2679 // ODBC driver zeroes an int, a string keeps the binder's initial buffer, the native driver leaves the
2680 // target untouched), so it is made the empty value here.
2681 if constexpr (std::default_initializable<T>)
2682 *result = T {};
2683 return false;
2684}
2685
2686namespace detail
2687{
2688
2689 template <typename T>
2690 concept SqlNullableType = (std::same_as<T, SqlVariant> || IsSpecializationOf<std::optional, T>);
2691
2692 /// Detects @c SqlFixedString<N, Char, Mode> specializations (the inline fixed-capacity strings).
2693 template <typename T>
2694 struct IsSqlFixedStringSpec: std::false_type
2695 {
2696 };
2697 template <std::size_t N, typename Char, SqlFixedStringMode Mode>
2698 struct IsSqlFixedStringSpec<SqlFixedString<N, Char, Mode>>: std::true_type
2699 {
2700 };
2701 template <typename T>
2702 concept SqlFixedStringCell = IsSqlFixedStringSpec<std::remove_cvref_t<T>>::value;
2703
2704 /// The plain standard string flavours the block-prefetch reader converts to from UTF-8 bytes.
2705 template <typename T>
2706 concept PlainStringCell =
2707 std::same_as<T, std::string> || std::same_as<T, std::u8string> || std::same_as<T, std::u16string>
2708 || std::same_as<T, std::u32string> || std::same_as<T, std::wstring>;
2709
2710 /// Detects @c SqlNumeric<Precision, Scale> specializations.
2711 template <typename T>
2712 struct IsSqlNumericSpec: std::false_type
2713 {
2714 };
2715 template <std::size_t Precision, std::size_t Scale>
2716 struct IsSqlNumericSpec<SqlNumeric<Precision, Scale>>: std::true_type
2717 {
2718 };
2719 template <typename T>
2720 concept SqlNumericCell = IsSqlNumericSpec<std::remove_cvref_t<T>>::value;
2721
2722 /// Views a UTF-8 @c std::string (opaque byte container) as a @c std::u8string_view for conversion.
2723 [[nodiscard]] inline std::u8string_view AsU8View(std::string const& utf8) noexcept
2724 {
2725 return std::u8string_view { reinterpret_cast<char8_t const*>(utf8.data()), utf8.size() };
2726 }
2727
2728 /// @brief Trims the trailing bytes of a fetched fixed-string value to match
2729 /// @c SqlFixedString::PostProcessOutputColumn (which the single-row @c GetColumn path applies), so a
2730 /// prefetched value is byte-identical to a per-row read. Every mode strips trailing NULs;
2731 /// @c FIXED_SIZE_RIGHT_TRIMMED additionally strips trailing ASCII whitespace (e.g. @c CHAR(N) space
2732 /// padding). Operates on the raw UTF-8 bytes before any wide conversion — ASCII whitespace/NUL are
2733 /// single bytes that map one-to-one to their wide code units, so the result matches a trim applied
2734 /// after conversion.
2735 /// @tparam Mode The fixed string's @c SqlFixedStringMode (its @c PostRetrieveOperation).
2736 /// @param bytes The fetched UTF-8 bytes, trimmed in place.
2737 template <SqlFixedStringMode Mode>
2738 inline void TrimFixedStringBytes(std::string& bytes) noexcept
2739 {
2740 auto const isTrailingTrimmable = [](char c) noexcept {
2741 if (c == '\0')
2742 return true;
2743 if constexpr (Mode == SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
2744 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f';
2745 else
2746 return false;
2747 };
2748 while (!bytes.empty() && isTrailingTrimmable(bytes.back()))
2749 bytes.pop_back();
2750 }
2751
2752 /// @brief Decodes the fetched UTF-8 bytes into a @c std::basic_string of the target character type
2753 /// @p Char, reusing the project's UnicodeConverter. The block-prefetch reader stores text as UTF-8
2754 /// (RowArrayCursor::GetString); this re-encodes it to the string target's element type.
2755 /// @tparam Char The target character type (@c char / @c char8_t / @c char16_t / @c char32_t / @c wchar_t).
2756 /// @param utf8 The fetched UTF-8 bytes.
2757 /// @return The decoded string in the target encoding.
2758 template <typename Char>
2759 [[nodiscard]] inline std::basic_string<Char> DecodeUtf8To(std::string const& utf8)
2760 {
2761 if constexpr (std::same_as<Char, char>)
2762 return utf8;
2763 else if constexpr (std::same_as<Char, char8_t>)
2764 return std::u8string { AsU8View(utf8) };
2765 else if constexpr (std::same_as<Char, char16_t>)
2766 return ToUtf16(AsU8View(utf8));
2767 else if constexpr (std::same_as<Char, char32_t>)
2768 return ToUtf32<std::u32string>(AsU8View(utf8));
2769 else
2770 return ToStdWideString(AsU8View(utf8));
2771 }
2772
2773 /// @brief Any string-like target the block-prefetch reader reconstructs from UTF-8 bytes: the plain
2774 /// standard strings plus the Lightweight string wrappers (fixed- and dynamic-capacity). Each exposes a
2775 /// @c value_type and is constructible from a @c std::basic_string of that type.
2776 template <typename T>
2777 concept StringLikeCell = PlainStringCell<T> || SqlStringInterface<T>;
2778
2779 /// A scalar target type the block-prefetch reader can reconstruct faithfully (mirrors the non-throwing
2780 /// branches of @c SqlStatement::ConvertCell). Excludes types whose faithful reconstruction needs the
2781 /// dedicated single-row binder (e.g. @c SqlNumeric, @c SqlTime, binary, user types), and @c char, whose
2782 /// binder reads the column as text although the type is integral.
2783 template <typename T>
2784 concept PrefetchConvertibleScalar =
2785 std::same_as<T, SqlVariant> || std::same_as<T, SqlDate> || std::same_as<T, SqlDateTime> || std::same_as<T, SqlGuid>
2786 || std::same_as<T, SqlDateTime::native_type> || std::same_as<T, SqlDynamicNumeric> || StringLikeCell<T>
2787 || std::is_floating_point_v<T> || (std::is_integral_v<T> && !std::same_as<T, char>) || std::is_enum_v<T>;
2788
2789 template <typename T>
2790 struct PrefetchConvertibleOptional: std::false_type
2791 {
2792 };
2793 template <typename U>
2794 struct PrefetchConvertibleOptional<std::optional<U>>: std::bool_constant<PrefetchConvertibleScalar<U>>
2795 {
2796 };
2797
2798 /// A bound output target the prefetch scatter can serve: a convertible scalar or an optional of one.
2799 template <typename T>
2800 concept PrefetchConvertible = PrefetchConvertibleScalar<T> || PrefetchConvertibleOptional<T>::value;
2801
2802#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2803 /// @brief Names a block-buffer representation for a diagnostic.
2804 [[nodiscard]] constexpr std::string_view BoundTypeName(RowArrayCursor::BoundType boundType) noexcept
2805 {
2806 constexpr auto Names = std::array<std::string_view, 7> {
2807 "BIGINT", "DOUBLE", "CHAR", "WCHAR", "DATE", "TIMESTAMP", "GUID",
2808 };
2809 return Names.at(static_cast<std::size_t>(boundType));
2810 }
2811
2812 /// @brief Reports a cross-type read the ODBC conversion rules do not define (e.g. a DATE column read
2813 /// as @c double), with SQLSTATE 07006 ("Restricted data type attribute violation"), the error the
2814 /// per-row @c SQLGetData path raises for it on a driver that follows those rules.
2815 template <typename T>
2816 [[noreturn]] inline void ThrowRestrictedPrefetchConversion(RowArrayCursor const& cursor, SqlColumnIndex column)
2817 {
2818 throw SqlException(SqlErrorInfo {
2819 .nativeErrorCode = 0,
2820 .sqlState = "07006",
2821 .message = std::format("Restricted data type attribute violation: column {} ({}) cannot be read as {}",
2822 column,
2823 BoundTypeName(cursor.ColumnBoundType(column)),
2824 Reflection::TypeNameOf<T>),
2825 });
2826 }
2827
2828 /// @brief Reconstructs a temporal or GUID cell from the block buffer, applying the conversions the
2829 /// ODBC rules define between the bound representation and @p T: a TIMESTAMP read as a date keeps its
2830 /// date part, a DATE read as a timestamp is midnight of that day, and a GUID stored as text (SQLite)
2831 /// is parsed back. Any other cross-type read throws (see @ref ThrowRestrictedPrefetchConversion).
2832 template <typename T>
2833 [[nodiscard]] inline T ReadTemporalGuidCell(RowArrayCursor const& cursor, std::size_t row, SqlColumnIndex column)
2834 {
2835 using BoundType = RowArrayCursor::BoundType;
2836 auto const boundType = cursor.ColumnBoundType(column);
2837 if constexpr (std::same_as<T, SqlDate>)
2838 {
2839 if (boundType == BoundType::Date)
2840 return cursor.GetDate(row, column).value_or(SqlDate {});
2841 if (boundType == BoundType::Timestamp)
2842 {
2843 auto const timestamp = cursor.GetTimestamp(row, column).value_or(SqlDateTime {}).sqlValue;
2844 auto date = SqlDate {};
2845 date.sqlValue.year = timestamp.year;
2846 date.sqlValue.month = timestamp.month;
2847 date.sqlValue.day = timestamp.day;
2848 return date;
2849 }
2850 }
2851 else if constexpr (std::same_as<T, SqlDateTime>)
2852 {
2853 if (boundType == BoundType::Timestamp)
2854 return cursor.GetTimestamp(row, column).value_or(SqlDateTime {});
2855 if (boundType == BoundType::Date)
2856 {
2857 auto const date = cursor.GetDate(row, column).value_or(SqlDate {}).sqlValue;
2858 auto timestamp = SqlDateTime {};
2859 timestamp.sqlValue.year = date.year;
2860 timestamp.sqlValue.month = date.month;
2861 timestamp.sqlValue.day = date.day;
2862 return timestamp;
2863 }
2864 }
2865 else // SqlGuid
2866 {
2867 if (boundType == BoundType::Guid)
2868 return cursor.GetGuid(row, column).value_or(SqlGuid {});
2869 if (boundType == BoundType::Char || boundType == BoundType::WChar)
2870 return SqlGuid::TryParse(cursor.GetString(row, column).value_or(std::string {})).value_or(SqlGuid {});
2871 }
2872 ThrowRestrictedPrefetchConversion<T>(cursor, column);
2873 }
2874
2875 /// @brief Reconstructs a @c SqlNumeric cell from the block buffer (driver-reported as a fixed-width
2876 /// numeric, bound @c Int64 or @c Double). Any other bound type throws (see
2877 /// @ref ThrowRestrictedPrefetchConversion).
2878 template <typename T>
2879 [[nodiscard]] inline T ReadNumericCell(RowArrayCursor const& cursor, std::size_t row, SqlColumnIndex column)
2880 {
2881 using BoundType = RowArrayCursor::BoundType;
2882 switch (cursor.ColumnBoundType(column))
2883 {
2884 case BoundType::Double:
2885 return T { cursor.GetF64(row, column).value_or(0.0) };
2886 case BoundType::Int64:
2887 return T { static_cast<double>(cursor.GetI64(row, column).value_or(0)) };
2888 default:
2889 ThrowRestrictedPrefetchConversion<T>(cursor, column);
2890 }
2891 }
2892
2893 /// @brief Reconstructs a @c SqlDynamicNumeric cell from the block buffer as the per-row read gives it, for the
2894 /// cells the block can give it for: an integer, through the binder's own reading of the column's declared
2895 /// precision and scale (see @c SqlDataBinder<SqlDynamicNumeric>::FromLiteral), so value, precision and
2896 /// scale equal the per-row read. A NULL cell is the zero value, as the binder leaves it.
2897 ///
2898 /// A floating-point cell is not reconstructed: the per-row read takes the driver's own text for it, which
2899 /// differs by driver (digits, exponent form, a trailing ".0"). ExecuteDirectScalar() knows the type before
2900 /// the first fetch and keeps such a result set on the per-row path (SqlDynamicNumeric binds no output column,
2901 /// so it is neither a bound column nor a record member); this, the raw read of an already-fetched block,
2902 /// throws 07006 and names the two ways out.
2903 /// @param cursor The block.
2904 /// @param row The cell's row in the block.
2905 /// @param column The 1-based column index.
2906 /// @param declaredDigitsOf Called with @p column for the column's declared precision and scale, only for an
2907 /// integer cell; the statement answers it once per result set and column.
2908 /// @return The cell's value.
2909 /// @throws SqlException 07006 for a floating-point or other non-integer cell; 22003 for an integer wider than
2910 /// the declared precision admits, as the binder throws.
2911 template <typename DeclaredDigitsOf>
2912 [[nodiscard]] SqlDynamicNumeric ReadDynamicNumericCell(RowArrayCursor const& cursor,
2913 std::size_t row,
2914 SqlColumnIndex column,
2915 DeclaredDigitsOf const& declaredDigitsOf)
2916 {
2917 using BoundType = RowArrayCursor::BoundType;
2918 if (cursor.IsCellNull(row, column))
2919 return SqlDynamicNumeric {};
2920 switch (cursor.ColumnBoundType(column))
2921 {
2922 case BoundType::Int64:
2923 break;
2924 case BoundType::Double:
2925 throw SqlException(SqlErrorInfo {
2926 .nativeErrorCode = 0,
2927 .sqlState = "07006",
2928 .message = std::format(
2929 "Restricted data type attribute violation: column {} (DOUBLE) cannot be read as SqlDynamicNumeric "
2930 "from a block-prefetched result set, since the value is the text the driver renders for it. "
2931 "Read it as double or std::string, or disable block prefetch with "
2932 "SqlConnection::SetDefaultPrefetchDepth(1) to read it as SqlDynamicNumeric.",
2933 column),
2934 });
2935 default:
2936 ThrowRestrictedPrefetchConversion<SqlDynamicNumeric>(cursor, column);
2937 }
2938 auto text = std::array<char, 24> {};
2939 auto const* const end =
2940 std::to_chars(text.data(), text.data() + text.size(), cursor.GetI64(row, column).value_or(0)).ptr;
2941 auto const literal = std::string_view { text.data(), end };
2942 if (auto value = SqlDataBinder<SqlDynamicNumeric>::FromLiteral(literal, declaredDigitsOf(column)); value)
2943 return *value;
2944 throw SqlException(SqlErrorInfo {
2945 .nativeErrorCode = 0,
2946 .sqlState = "22003",
2947 .message = std::format("Column {} holds {}, which SqlDynamicNumeric cannot represent exactly: it carries more "
2948 "than {} significant digits. Read the column as an integer or std::string instead.",
2949 column,
2950 literal,
2951 SqlMaxDynamicNumericPrecision),
2952 });
2953 }
2954
2955 /// @brief Renders a block-buffer cell to UTF-8 text. Character columns are returned verbatim;
2956 /// numeric, temporal and GUID columns are formatted to their text form. This mirrors the driver's
2957 /// @c SQL_C_CHAR conversion on the single-row @c GetColumn path so that reading a non-character column
2958 /// as a string (e.g. a generic "print every column as text" loop) yields the value rather than an
2959 /// empty string. Integer text is identical to the driver's; floating/temporal text uses the value
2960 /// type's @c std::formatter, which is backend-independent.
2961 [[nodiscard]] inline std::string RenderCellAsUtf8(RowArrayCursor const& cursor, std::size_t row, SqlColumnIndex column)
2962 {
2963 switch (cursor.ColumnBoundType(column))
2964 {
2965 case RowArrayCursor::BoundType::Char:
2966 case RowArrayCursor::BoundType::WChar:
2967 return cursor.GetString(row, column).value_or(std::string {});
2968 case RowArrayCursor::BoundType::Int64:
2969 return std::format("{}", cursor.GetI64(row, column).value_or(0));
2970 case RowArrayCursor::BoundType::Double:
2971 return std::format("{}", cursor.GetF64(row, column).value_or(0.0));
2972 case RowArrayCursor::BoundType::Date:
2973 return std::format("{}", cursor.GetDate(row, column).value_or(SqlDate {}));
2974 case RowArrayCursor::BoundType::Timestamp:
2975 return std::format("{}", cursor.GetTimestamp(row, column).value_or(SqlDateTime {}));
2976 case RowArrayCursor::BoundType::Guid:
2977 return std::format("{}", cursor.GetGuid(row, column).value_or(SqlGuid {}));
2978 }
2979 return std::string {};
2980 }
2981
2982 /// @brief Reconstructs a string-like cell (plain @c std::string flavours and the Lightweight string
2983 /// wrappers) from the block buffer, rendering any bound type to text via @ref RenderCellAsUtf8.
2984 /// Fixed-capacity strings get the same trailing trim the single-row @c GetColumn path applies via
2985 /// @c SqlFixedString::PostProcessOutputColumn; the UTF-8 bytes are then re-encoded to the target's
2986 /// element type.
2987 template <typename T>
2988 [[nodiscard]] inline T ReadStringLikeCell(RowArrayCursor const& cursor, std::size_t row, SqlColumnIndex column)
2989 {
2990 auto utf8 = RenderCellAsUtf8(cursor, row, column);
2991 if constexpr (SqlFixedStringCell<T>)
2992 TrimFixedStringBytes<T::PostRetrieveOperation>(utf8);
2993 return T { DecodeUtf8To<typename T::value_type>(utf8) };
2994 }
2995
2996 /// @brief An integer block cell as @p T. A value outside an integer @p T's range fails with SQLSTATE 22003, as
2997 /// the SQL Server driver fails the per-row read (the SQLite and PostgreSQL drivers wrap or clamp it per row
2998 /// instead). One compare, and only where @p T is narrower than the 64-bit cell: a 64-bit @p T takes the cell's
2999 /// bits, which is how a driver stores an unsigned 64-bit value (2^63 and above as negative). A @c bool takes 0 and
3000 /// 1 (and -1 where the driver reports a boolean true so, see @c BoolFromInteger) and fails with 22003 otherwise, as
3001 /// its per-row read does; enumerations take the value as before. Where the dialect stages @c int8_t and
3002 /// @c uint32_t (SQLite), those two take the decision of their per-row read, which accepts the form earlier
3003 /// versions stored as well (see @c SqlStagedIntegerDataBinder::NarrowStaged).
3004 /// @param value The cell's value.
3005 /// @param column The 1-based column index, for the error.
3006 /// @param cb The statement, which answers the two dialect questions.
3007 /// @return The value as @p T.
3008 template <typename T>
3009 [[nodiscard]] inline T IntegerCellAs(std::int64_t value, SqlColumnIndex column, SqlDataBinderCallback const& cb)
3010 {
3011 if constexpr (SqlColumnMayStage<T>())
3012 {
3013 if (!cb.ConvertsNarrowIntegerCTypes())
3014 return SqlDataBinder<T>::NarrowStaged(value, column);
3015 }
3016 if constexpr (std::same_as<T, bool>)
3017 return BoolFromInteger(value, column, cb.BooleanTrueMayBeMinusOne());
3018 else
3019 {
3020 if constexpr (std::is_integral_v<T> && sizeof(T) < sizeof(std::int64_t))
3021 {
3022 if (!std::in_range<T>(value))
3023 ThrowNumericValueOutOfRange(column, value, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
3024 }
3025 return static_cast<T>(value);
3026 }
3027 }
3028
3029 /// @brief A floating-point block cell as @p T. Read into an integer @p T, a value whose integral part is outside
3030 /// @p T's range (or NaN), which has no defined conversion, fails with SQLSTATE 22003, as the drivers fail it. A
3031 /// @c bool takes the integral part of a value in [0, 2), as ODBC converts a number to @c SQL_C_BIT.
3032 /// @param value The cell's value.
3033 /// @param column The 1-based column index, for the error.
3034 /// @return The value as @p T, the fraction truncated for an integer @p T.
3035 template <typename T>
3036 [[nodiscard]] inline T FloatingPointCellAs(double value, SqlColumnIndex column)
3037 {
3038 if constexpr (std::same_as<T, bool>)
3039 return BoolFromFloatingPoint(value, column);
3040 else
3041 {
3042 if constexpr (std::is_integral_v<T>)
3043 {
3044 // The conversion truncates toward zero. The lowest value (0 or -2^digits) and highest + 1
3045 // (2^digits, at most 2^64) are powers of two, so both bounds are exact doubles; the highest + 1 is
3046 // built from 2^(digits - 1), which a 64-bit unsigned integer holds for every target.
3047 constexpr auto lowest = static_cast<double>(std::numeric_limits<T>::min());
3048 constexpr auto beyond =
3049 static_cast<double>(std::uint64_t { 1 } << (std::numeric_limits<T>::digits - 1)) * 2.0;
3050 auto const truncated = std::trunc(value);
3051 if (!(truncated >= lowest && truncated < beyond))
3052 ThrowNumericValueOutOfRange(column, value, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
3053 }
3054 return static_cast<T>(value);
3055 }
3056 }
3057
3058 /// @brief Reconstructs an arithmetic or enum cell from the block buffer, coercing whichever fixed-width
3059 /// representation the column was bound as (@c Int64 or @c Double) to @p T. Any other bound type throws
3060 /// (see @ref ThrowRestrictedPrefetchConversion).
3061 /// @param cb The statement, which answers the dialect questions of @ref IntegerCellAs.
3062 template <typename T>
3063 [[nodiscard]] inline T ReadArithmeticCell(RowArrayCursor const& cursor,
3064 std::size_t row,
3065 SqlColumnIndex column,
3066 SqlDataBinderCallback const& cb)
3067 {
3068 using BoundType = RowArrayCursor::BoundType;
3069 switch (cursor.ColumnBoundType(column))
3070 {
3071 case BoundType::Int64:
3072 return IntegerCellAs<T>(cursor.GetI64(row, column).value_or(0), column, cb);
3073 case BoundType::Double:
3074 return FloatingPointCellAs<T>(cursor.GetF64(row, column).value_or(0.0), column);
3075 default:
3076 ThrowRestrictedPrefetchConversion<T>(cursor, column);
3077 }
3078 }
3079#endif
3080} // end namespace detail
3081
3082template <typename T>
3083constexpr bool SqlRowIterator<T>::ColumnsArePrefetchConvertible() noexcept
3084{
3085 auto convertible = true;
3086 EnumerateRecordMembers<T>([&convertible]<size_t I, typename FieldType>() {
3087 if constexpr (RecordColumnMember<FieldType>)
3088 {
3089 if constexpr (FieldWithStorage<FieldType>)
3090 convertible = convertible && detail::PrefetchConvertible<typename FieldType::ValueType>;
3091 else
3092 convertible = convertible && detail::PrefetchConvertible<FieldType>;
3093 }
3094 });
3095 return convertible;
3096}
3097
3098template <typename T>
3099void SqlRowIterator<T>::RecordColumnPrefetchTargets(SqlStatement& stmt)
3100{
3101 SqlColumnIndex column = 0;
3102 EnumerateRecordMembers<T>([&stmt, &column]<size_t I, typename FieldType>() {
3103 if constexpr (RecordColumnMember<FieldType>)
3104 {
3105 ++column;
3106 if constexpr (FieldWithStorage<FieldType>)
3107 stmt.RecordPrefetchColumnTarget(column, SqlStatement::PrefetchTargetOf<typename FieldType::ValueType>());
3108 else
3109 stmt.RecordPrefetchColumnTarget(column, SqlStatement::PrefetchTargetOf<FieldType>());
3110 }
3111 });
3112}
3113
3114#if defined(LIGHTWEIGHT_DRIVER_ODBC)
3115template <typename T>
3116inline T SqlStatement::ConvertCell(RowArrayCursor const& cursor, std::size_t row, SqlColumnIndex column) const
3117{
3118 // Dispatch the target type to the matching reconstruction helper. The arming allowlist keeps the
3119 // column's bound representation in step with the natural target type; for a cross-type raw GetColumn
3120 // read each helper applies the conversion the ODBC rules define, or throws where they define none.
3121 if constexpr (std::same_as<T, SqlVariant>)
3122 return MakePrefetchVariantCell(cursor, row, column);
3123 else if constexpr (IsSpecializationOf<std::optional, T>)
3124 {
3125 if (cursor.IsCellNull(row, column))
3126 return std::nullopt;
3127 return T { ConvertCell<typename T::value_type>(cursor, row, column) };
3128 }
3129 else if constexpr (std::same_as<T, SqlDate> || std::same_as<T, SqlDateTime> || std::same_as<T, SqlGuid>)
3130 return detail::ReadTemporalGuidCell<T>(cursor, row, column);
3131 else if constexpr (std::same_as<T, SqlDateTime::native_type>)
3132 // Its binder reads the timestamp struct and converts it; the block buffer holds that struct.
3133 return detail::ReadTemporalGuidCell<SqlDateTime>(cursor, row, column).value();
3134 else if constexpr (detail::SqlNumericCell<T>)
3135 return detail::ReadNumericCell<T>(cursor, row, column);
3136 else if constexpr (std::same_as<T, SqlDynamicNumeric>)
3137 return detail::ReadDynamicNumericCell(
3138 cursor, row, column, [this](SqlColumnIndex index) { return DeclaredDynamicNumericDigits(index); });
3139 else if constexpr (detail::StringLikeCell<T>)
3140 return detail::ReadStringLikeCell<T>(cursor, row, column);
3141 else if constexpr (std::is_floating_point_v<T> || (std::is_integral_v<T> && !std::same_as<T, char>) || std::is_enum_v<T>)
3142 return detail::ReadArithmeticCell<T>(cursor, row, column, *this);
3143 else
3144 // A target type the block buffer cannot reconstruct (e.g. a user type with a custom binder). The
3145 // bound path and ExecuteDirectScalar decline prefetch for such targets (see PrefetchConvertible);
3146 // a raw GetColumn only learns the type once the block is fetched, too late to fall back.
3147 throw SqlException(SqlErrorInfo {
3148 .nativeErrorCode = 0,
3149 .sqlState = "HY000",
3150 .message =
3151 std::format("Column {} cannot be read as {} from a block-prefetched result set: the type's binder needs the "
3152 "per-row fetch. Bind it with BindOutputColumns() before the first FetchRow(), or disable "
3153 "block prefetch with SqlConnection::SetDefaultPrefetchDepth(1).",
3154 column,
3155 Reflection::TypeNameOf<T>),
3156 });
3157}
3158
3159template <SqlOutputColumnBinder T>
3160inline void SqlStatement::RecordPrefetchOutputColumn(SqlColumnIndex column, T* arg)
3161{
3162 auto deferredBind = [this, column, arg] {
3163 RequireIndicators();
3164 BindOutputColumnNow<T>(column, arg);
3165 };
3166 if constexpr (detail::PrefetchConvertible<T>)
3167 {
3168 RecordPrefetchColumn(
3169 column,
3170 PrefetchTargetOf<T>(),
3171 [this, column, arg] { *arg = ConvertCell<T>(PrefetchCursorRef(), PrefetchRowInBlock(), column); },
3172 std::move(deferredBind));
3173 }
3174 else
3175 {
3176 // The target type cannot be reconstructed from the block buffer; record only the real bind and
3177 // flag the set so arming declines prefetch and the deferred binds drive the per-row path.
3178 RecordPrefetchColumn(column, PrefetchTarget::Any, {}, std::move(deferredBind));
3179 MarkPrefetchBindingUnsupported();
3180 }
3181}
3182#endif
3183
3184template <typename T>
3185constexpr SqlStatement::PrefetchTarget SqlStatement::PrefetchTargetOf() noexcept
3186{
3187 if constexpr (IsSpecializationOf<std::optional, T>)
3188 return PrefetchTargetOf<typename T::value_type>();
3189 else if constexpr (std::same_as<T, SqlVariant>)
3190 return PrefetchTarget::Any;
3191 else if constexpr (std::same_as<T, SqlDate> || std::same_as<T, SqlDateTime> || std::same_as<T, SqlDateTime::native_type>)
3192 return PrefetchTarget::Temporal;
3193 else if constexpr (std::same_as<T, SqlGuid>)
3194 return PrefetchTarget::Guid;
3195 else if constexpr (std::same_as<T, SqlDynamicNumeric>)
3196 return PrefetchTarget::Exact;
3197 else if constexpr (detail::StringLikeCell<T>)
3198 return PrefetchTarget::Text;
3199 else
3200 return PrefetchTarget::Numeric;
3201}
3202
3203template <SqlGetColumnNativeType T>
3204inline T SqlStatement::GetColumn(SqlColumnIndex column) const
3205{
3206#if defined(LIGHTWEIGHT_DRIVER_ODBC)
3207 if (IsPrefetchActive())
3208 {
3209 auto const& cursor = PrefetchCursorRef();
3210 auto const row = PrefetchRowInBlock();
3211 RequirePrefetchColumnInRange(cursor, column);
3212 if constexpr (!detail::SqlNullableType<T>)
3213 if (cursor.IsCellNull(row, column))
3214 throw std::runtime_error { "Column value is NULL" };
3215 return ConvertCell<T>(cursor, row, column);
3216 }
3217#endif
3218 auto result = detail::MakeUninitialized<T>();
3219 SqlIndicator indicator {};
3220 {
3221 // SQLGetData is where the ODBC driver materializes the column value (driver/network I/O).
3222 // Isolating it lets a profiler separate I/O-bound retrieval from CPU-bound value conversion
3223 // done by the caller — the key question for deciding what to parallelize.
3224 ZoneScopedN("SqlStatement::ColumnGetData");
3225 Driver::Visit(m_handle, [&](auto const& held) {
3226 auto stmt = held;
3227 RequireSuccess(Driver::ReadColumn(stmt, column, &result, &indicator, *this));
3228 });
3229 }
3230 if constexpr (!detail::SqlNullableType<T>)
3231 if (indicator == SqlNullData)
3232 throw std::runtime_error { "Column value is NULL" };
3233 return result;
3234}
3235
3236template <SqlGetColumnNativeType T>
3237inline std::optional<T> SqlStatement::GetNullableColumn(SqlColumnIndex column) const
3238{
3239#if defined(LIGHTWEIGHT_DRIVER_ODBC)
3240 if (IsPrefetchActive())
3241 {
3242 auto const& cursor = PrefetchCursorRef();
3243 auto const row = PrefetchRowInBlock();
3244 RequirePrefetchColumnInRange(cursor, column);
3245 if (cursor.IsCellNull(row, column))
3246 return std::nullopt;
3247 return ConvertCell<T>(cursor, row, column);
3248 }
3249#endif
3250 auto result = detail::MakeUninitialized<T>();
3251 SqlIndicator indicator {}; // TODO: Handle NULL values if we find out that we need them for our use-cases.
3252 {
3253 ZoneScopedN("SqlStatement::ColumnGetData");
3254 Driver::Visit(m_handle, [&](auto const& held) {
3255 auto stmt = held;
3256 RequireSuccess(Driver::ReadColumn(stmt, column, &result, &indicator, *this));
3257 });
3258 }
3259 if (indicator == SqlNullData)
3260 return std::nullopt;
3261 return { std::move(result) };
3262}
3263
3264template <SqlGetColumnNativeType T>
3265T SqlStatement::GetColumnOr(SqlColumnIndex column, T&& defaultValue) const
3266{
3267 return GetNullableColumn<T>(column).value_or(std::forward<T>(defaultValue));
3268}
3269
3270inline LIGHTWEIGHT_FORCE_INLINE SqlResultCursor SqlStatement::ExecuteDirect(SqlQueryObject auto const& query,
3271 std::source_location location)
3272{
3273 auto cursor = ExecuteDirect(query.ToSql(), location);
3274 // After the raw overload, which drops any previously held mapping.
3275 AdoptProjectedFieldNames(query);
3276 return cursor;
3277}
3278
3279template <typename Callable>
3280 requires std::invocable<Callable, SqlMigrationQueryBuilder&>
3281void SqlStatement::MigrateDirect(Callable const& callable, std::source_location location)
3282{
3283 ZoneScopedN("SqlStatement::MigrateDirect");
3284 auto migration = SqlMigrationQueryBuilder { Connection().QueryFormatter() };
3285 callable(migration);
3286 auto const queries = migration.GetPlan().ToSql();
3287 ZoneValue(queries.size());
3288
3289 // A comment-only `-- LIGHTWEIGHT_SQLITE_GUARD:` script (e.g. ALTER COLUMN or a foreign-key change on
3290 // SQLite) carries no executable DDL: the schema change is performed by the migration executor's
3291 // table-rebuild path, which only runs via MigrationManager. Executing such a script directly here
3292 // would silently do nothing, so fail loudly and point at the supported entry point instead.
3293 auto const isCommentOnlyGuardScript = [](std::string_view script) {
3294 constexpr std::string_view marker = "-- LIGHTWEIGHT_SQLITE_GUARD:";
3295 if (!script.starts_with(marker))
3296 return false;
3297 auto const newline = script.find('\n');
3298 if (newline == std::string_view::npos)
3299 return true; // sentinel line only, nothing executable follows
3300 auto const body = script.substr(newline + 1);
3301 auto const bodyStart = body.find_first_not_of(" \t\r\n");
3302 return bodyStart == std::string_view::npos || body.substr(bodyStart).starts_with("--");
3303 };
3304
3305 for (auto const& query: queries)
3306 {
3307 if (isCommentOnlyGuardScript(query))
3308 throw std::runtime_error(
3309 std::format("SqlStatement::MigrateDirect cannot apply this SQLite schema change directly because it "
3310 "requires a table rebuild (e.g. ALTER COLUMN or a foreign-key change). Apply it through "
3311 "MigrationManager::ApplyPendingMigrations, which runs the rebuild executor.\n Script: {}",
3312 query));
3313 ExecuteDirect(query, location).ConsumePendingResults(location);
3314 }
3315
3316 // The plans of any pooled handle were derived from the schema we just changed.
3317 Connection().ClearPreparedStatementCache();
3318}
3319
3320template <typename T>
3321 requires(!std::same_as<T, SqlVariant>)
3322inline std::optional<T> SqlStatement::ExecuteDirectScalar(std::string_view const& query, std::source_location location)
3323{
3324 auto cursor = ExecuteDirect(query, location);
3325 // The type is known before the first fetch: keep a type the block buffer cannot rebuild on the per-row path,
3326 // and a column whose SQL type the per-row path reads differently into it (see PrefetchTarget).
3327 if constexpr (!detail::PrefetchConvertible<T>)
3328 MarkPrefetchBindingUnsupported();
3329 else
3330 RecordPrefetchColumnTarget(1, PrefetchTargetOf<T>());
3331 // FetchRow() throws on a failure; false means an empty result set, which has no scalar.
3332 if (!FetchRow())
3333 return std::nullopt;
3334 return GetNullableColumn<T>(1);
3335}
3336
3337template <typename T>
3338 requires(std::same_as<T, SqlVariant>)
3339inline T SqlStatement::ExecuteDirectScalar(std::string_view const& query, std::source_location location)
3340{
3341 auto cursor = ExecuteDirect(query, location);
3342 KeepVariantReadsPerRow();
3343 // FetchRow() throws on a failure; false means an empty result set, which has no value to report.
3344 if (!FetchRow())
3345 throw SqlException(SqlErrorInfo { .nativeErrorCode = 0,
3346 .sqlState = "02000",
3347 .message = std::format("The scalar query returned no row: {}", query) },
3348 location);
3349 if (auto result = GetNullableColumn<T>(1); result.has_value())
3350 return *result;
3351 return SqlVariant { SqlNullValue };
3352}
3353
3354template <typename T>
3355 requires(!std::same_as<T, SqlVariant>)
3356inline std::optional<T> SqlStatement::ExecuteDirectScalar(SqlQueryObject auto const& query, std::source_location location)
3357{
3358 return ExecuteDirectScalar<T>(query.ToSql(), location);
3359}
3360
3361template <typename T>
3362 requires(std::same_as<T, SqlVariant>)
3363inline T SqlStatement::ExecuteDirectScalar(SqlQueryObject auto const& query, std::source_location location)
3364{
3365 return ExecuteDirectScalar<T>(query.ToSql(), location);
3366}
3367
3368inline LIGHTWEIGHT_FORCE_INLINE void SqlStatement::CloseCursor() noexcept
3369{
3370 // Tear down any block-prefetch first: the RowArrayCursor destructor unbinds the columns and
3371 // restores SQL_ATTR_ROW_ARRAY_SIZE so the cursor release below — and the next query on this
3372 // statement — start from a clean single-row state. Resets the prefetch lifecycle to Unarmed.
3373 // The column bindings and their callbacks stay: releasing the cursor does not unbind, and the next
3374 // execution of the prepared statement fetches into them again.
3375 // A cursor kept across its connection's Close() or re-connect holds a handle the session ended with:
3376 // forget it (one session compare per cursor) and touch nothing.
3377 ForgetHandleOfEndedSession();
3378 ResetPrefetchState();
3379 if (m_handle.IsEmpty())
3380 {
3381 SqlLogger::GetLogger().OnFetchEnd();
3382 return;
3383 }
3384
3385 // SQL Server batches and DML/DDL row-count tokens produce multiple result
3386 // sets per SQLExecDirect. Releasing the cursor (SQL_CLOSE) only discards the current
3387 // cursor — remaining result sets stay pending on the *connection*, and
3388 // without MARS every subsequent statement on that connection fails with
3389 // HY000 "Connection is busy with results for another command". Drain via
3390 // SQLMoreResults until SQL_NO_DATA (or an error), then close. An error found here is dropped;
3391 // callers that must see it use ConsumePendingResults() first.
3392 //
3393 // SQLMoreResults is standard ODBC; SQLite and PostgreSQL drivers return
3394 // SQL_NO_DATA on the first call when nothing is pending, so the cost on
3395 // single-statement queries is one no-op driver call.
3396 Driver::DiscardResults(m_handle);
3397 SqlLogger::GetLogger().OnFetchEnd();
3398}
3399
3400// }}}
3401
3402} // namespace Lightweight
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
SQLULEN ProcessedCount
The count a driver writes back through a parameter-array or row-array attribute pointer (SQL_ATTR_PAR...
Definition Statement.hpp:44
A cursor that fetches result rows in bulk (ODBC row-array binding) for fast column reads.
Represents a connection to a SQL database.
LIGHTWEIGHT_API bool IsAlive() const noexcept
Tests if the connection is still active.
Query builder for building SQL migration queries.
Definition Migrate.hpp:521
API Entry point for building SQL queries.
Definition SqlQuery.hpp:32
LIGHTWEIGHT_FORCE_INLINE T GetColumn(std::string_view name) const
Retrieves the value of the named column for the currently selected row.
T GetColumnOr(SqlColumnIndex column, T &&defaultValue) const
LIGHTWEIGHT_FORCE_INLINE void BindOutputColumnsToRecord(Records *... records)
Binds the given records to the prepared statement to store the fetched data to.
constexpr SqlResultCursor(SqlResultCursor &&other) noexcept
Move constructor.
LIGHTWEIGHT_FORCE_INLINE SqlResultCursor(SqlStatement &stmt) noexcept
Constructs a result cursor for the given SQL statement.
LIGHTWEIGHT_FORCE_INLINE T GetColumn(SqlColumnIndex column) const
LIGHTWEIGHT_FORCE_INLINE void FetchAllRowWise(std::vector< Record > &out, std::size_t arrayDepth, ColumnAccessors const &... accessors)
Fast bulk retrieval: materializes this result set into out via native ODBC row-wise array fetch....
constexpr SqlResultCursor & operator=(SqlResultCursor &&other) noexcept
Move assignment operator.
LIGHTWEIGHT_FORCE_INLINE void BindOutputColumn(SqlColumnIndex columnIndex, T *arg)
Binds a single output column at the given index to store fetched data.
LIGHTWEIGHT_FORCE_INLINE void BindOutputColumns(Args *... args)
T GetColumnOr(std::string_view name, T &&defaultValue) const
Retrieves the value of the named column, or defaultValue if it is NULL.
LIGHTWEIGHT_FORCE_INLINE std::optional< T > GetNullableColumn(std::string_view name) const
Retrieves the value of the named column, or std::nullopt if it is NULL.
LIGHTWEIGHT_FORCE_INLINE std::optional< T > GetNullableColumn(SqlColumnIndex column) const
LIGHTWEIGHT_FORCE_INLINE size_t NumColumnsAffected() const
LIGHTWEIGHT_FORCE_INLINE size_t NumRowsAffected() const
LIGHTWEIGHT_FORCE_INLINE bool GetColumn(SqlColumnIndex column, T *result) const
LIGHTWEIGHT_FORCE_INLINE void ConsumePendingResults(std::source_location location=std::source_location::current())
Steps through every result the last execution still has pending and throws for the first one that fai...
LIGHTWEIGHT_FORCE_INLINE bool FetchRow()
LIGHTWEIGHT_FORCE_INLINE std::expected< bool, SqlErrorInfo > TryFetchRow(std::source_location location=std::source_location::current()) noexcept
Attempts to fetch the next row, returning an error info on failure instead of throwing.
LIGHTWEIGHT_API std::expected< SqlResultColumnType, SqlErrorInfo > ColumnSqlType(SqlColumnIndex column) const
The SQL data type the driver reports for a result column.
detail::NarrowTextBinding NarrowTextBindingMode() const noexcept
SQL query result row iterator.
SqlRowIterator(SqlConnection &conn)
Constructs a row iterator over all rows of the record's table, using the given SQL connection.
SqlRowIterator(SqlConnection &conn, QueryCustomizer queryCustomizer)
std::function< void(SqlSelectQueryBuilder &)> QueryCustomizer
iterator end() noexcept
Returns a sentinel iterator representing the end of the result set.
iterator begin()
Returns an iterator to the first row of the result set.
Query builder for building SELECT ... queries.
Definition Select.hpp:100
High level API for (prepared) raw SQL statements.
LIGHTWEIGHT_API void Prepare(std::string_view query) &
Driver::StatementHandle const & DriverHandle() const noexcept
SqlPreparedStatementCaching PreparedStatementCaching() const noexcept
Whether this statement takes part in its connection's prepared-statement cache.
LIGHTWEIGHT_API SqlQueryBuilder QueryAs(std::string_view const &table, std::string_view const &tableAlias) const
Creates a new query builder for the given table with an alias, compatible with the SQL server being c...
LIGHTWEIGHT_API size_t LastInsertId(std::string_view tableName)
Retrieves the last insert ID of the given table.
LIGHTWEIGHT_API SqlConnection & Connection() noexcept
Retrieves the connection associated with this statement.
LIGHTWEIGHT_API SqlResultCursor ExecuteBatch(std::span< SqlRawColumn const > columns, std::size_t rowCount, std::span< Driver::Odbc::RowStatus > paramStatus, Driver::Odbc::ProcessedCount &paramsProcessed)
SqlDriverId DriverId() const noexcept
LIGHTWEIGHT_API void ConsumePendingResults(std::source_location location=std::source_location::current())
Steps through every result the last execution still has pending and throws for the first one that fai...
LIGHTWEIGHT_API RowArrayCursor ExecuteBatchFetch(std::string_view query, std::size_t arrayDepth)
LIGHTWEIGHT_API SqlStatement(SqlStatement &&other) noexcept
Move constructor.
LIGHTWEIGHT_API SqlStatement()
Construct a new SqlStatement object, using a new connection, and connect to the default database.
LIGHTWEIGHT_API bool IsPrepared() const noexcept
Checks whether the statement has been prepared.
LIGHTWEIGHT_API SqlStatement & operator=(SqlStatement &&other) noexcept
Move assignment operator.
LIGHTWEIGHT_API SqlStatement(std::nullopt_t)
Construct a new empty SqlStatement object. No SqlConnection is associated with this statement.
LIGHTWEIGHT_API SqlResultCursor ExecuteDirect(std::string_view const &query, std::source_location location=std::source_location::current())
Executes the given query directly.
LIGHTWEIGHT_API bool IsAlive() const noexcept
Checks whether the statement's connection is alive and the statement handle is valid.
LIGHTWEIGHT_API SqlResultCursor ExecuteBatch(std::span< SqlRawColumn const > columns, size_t rowCount)
decltype(auto) VisitDriver(std::string_view operation, F &&f)
LIGHTWEIGHT_API SqlStatement(SqlConnection &relatedConnection)
Construct a new SqlStatement object, using the given connection.
Requires that T maps onto a column of its record's table.
Definition Record.hpp:419
Whether SqlDataBinder<T> can read T from a result column on at least one enabled driver.
Definition Core.hpp:830
Whether V's binder provides a row-wise batch entry point (BatchRowWiseInputParameter).
Whether the elements of range T can be bound as input parameters on at least one enabled driver.
Definition Core.hpp:794
Whether SqlDataBinder<T> can bind T as an input parameter on at least one enabled driver.
Definition Core.hpp:786
Represents a query object that also knows the name of each column it projects.
A value type that can be bound in a native ODBC row-wise parameter array (fixed-width,...
A std::optional column that can be bound zero-copy in a native row-wise batch: the contained type is ...
Whether SqlDataBinder<T> can bind T as an output column on at least one enabled driver.
Definition Core.hpp:790
Represents an SQL query object, that provides a ToSql() method.
A column value type usable on the native row-wise batch path — either a row-bindable fixed value or a...
A column usable on the native row-wise array-FETCH fast path. Intentionally identical to the write-si...
SqlPreparedStatementCaching
Whether a single SqlStatement takes part in its connection's prepared-statement cache.
@ Execute
The execution of a prepared statement (SqlStatement::Execute).
constexpr void EnumerateRecordMembers(Record &record, Callable &&callable)
Invokes callable as callable<I>(member) for each member of record.
constexpr auto SqlNullValue
std::u16string ToUtf16(std::basic_string_view< T > const u32InputString)
LIGHTWEIGHT_API std::wstring ToStdWideString(std::u8string_view u8InputString)
One column pair of a composite foreign key: "this record's column references that one".
The ODBC driver's statement handle struct.
Definition Handles.hpp:43
Represents a SQL error as reported by the database driver.
Definition SqlError.hpp:29
std::int32_t nativeErrorCode
The driver's native error code.
Definition SqlError.hpp:31
A step a binder plans to run before every fetch into the output column it binds.
Definition Core.hpp:49
Represents a value that can be any of the supported SQL data types.