Lightweight 0.20261105.1
Loading...
Searching...
No Matches
Statement.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5// <sql.h> below needs a few symbols resolved first — see SqlOdbcPrelude.hpp's header comment.
6#include "../../Api.hpp"
7#include "../../SqlBindingTypes.hpp"
8#include "../../SqlError.hpp"
9#include "Diagnostics.hpp"
10#include "Handles.hpp"
11#include "SqlOdbcPrelude.hpp"
12
13#include <array>
14#include <chrono>
15#include <cstddef>
16#include <cstdint>
17#include <cstring>
18#include <expected>
19#include <optional>
20#include <source_location>
21#include <string>
22#include <string_view>
23#include <utility>
24#include <vector>
25
26#include <sql.h>
27#include <sqlext.h>
28
29/// @file
30/// The statement operations of the ODBC driver: everything SqlStatement and its cursors ask an ODBC
31/// statement handle to do. The first group is the statement half of the @ref Lightweight::Driver::SqlDriver
32/// concept; the second group is ODBC-only (parameter and row arrays, column binding, describing), used
33/// by code paths that exist only for the ODBC driver.
34///
35/// Every function is a thin wrapper: the same ODBC calls with the same arguments in the same order as
36/// the code it was moved from, and the return code handed back as @c Lightweight::SqlResult so that the
37/// caller decides how to check it (and keeps the fault seam of @c RequireSuccess at its call site).
38
39namespace Lightweight::Driver::Odbc
40{
41
42/// @brief The count a driver writes back through a parameter-array or row-array attribute pointer
43/// (@c SQL_ATTR_PARAMS_PROCESSED_PTR, @c SQL_ATTR_ROWS_FETCHED_PTR).
44using ProcessedCount = SQLULEN;
45
46/// @brief One element of a parameter-status or row-status array (@c SQL_ATTR_PARAM_STATUS_PTR,
47/// @c SQL_ATTR_ROW_STATUS_PTR).
48using RowStatus = SQLUSMALLINT;
49
50/// @brief The parameter status of a parameter set the driver did not process (@c SQL_PARAM_UNUSED).
51inline constexpr RowStatus ParamStatusUnused = SQL_PARAM_UNUSED;
52
53/// @brief The parameter status of a parameter set that failed (@c SQL_PARAM_ERROR).
54inline constexpr RowStatus ParamStatusError = SQL_PARAM_ERROR;
55
56/// @brief The row status of a fetched row the driver could not convert (@c SQL_ROW_ERROR).
57inline constexpr RowStatus RowStatusError = SQL_ROW_ERROR;
58
59/// @brief The declared SQL type @c DescribeParameterTypes reports for a parameter it could not describe.
60inline constexpr std::int16_t UnknownParameterType = SQL_UNKNOWN_TYPE;
61
62/// @brief What @ref DescribeColumn reports about a result column.
64{
65 /// The @c SQL_* type code of the column.
66 std::int16_t sqlType {};
67
68 /// The column size (maximum character count for character columns); 0 when the driver cannot bound it.
69 std::size_t columnSize {};
70};
71
72namespace detail
73{
74 /// @brief Packs an integral ODBC statement-attribute value into the @c SQLPOINTER ABI slot.
75 ///
76 /// @c SQLSetStmtAttr takes its value argument as @c SQLPOINTER. For attributes whose value is an
77 /// integer (e.g. @c SQL_ATTR_ROW_ARRAY_SIZE, @c SQL_ATTR_ROW_BIND_TYPE), ODBC's documented
78 /// convention is to pass the integer in the pointer slot. The bit-pattern is copied with
79 /// @c std::memcpy instead of a cast so there is no integer-to-pointer conversion to reason about.
80 ///
81 /// @param value The integral attribute value to convey to ODBC.
82 /// @return A @c SQLPOINTER carrying the same bit-pattern as @p value.
83 [[nodiscard]] inline SQLPOINTER OdbcIntAttr(SQLULEN value) noexcept
84 {
85 static_assert(sizeof(SQLPOINTER) >= sizeof(SQLULEN),
86 "SQLPOINTER must be wide enough to carry an integral ODBC attribute value");
87 SQLPOINTER ptr = nullptr;
88 std::memcpy(static_cast<void*>(&ptr), &value, sizeof(value));
89 return ptr;
90 }
91} // namespace detail
92
93// {{{ The statement half of the SqlDriver concept
94
95/// @brief Allocates a statement handle on @p connection.
96/// @param connection The connection to allocate on.
97/// @param stmt Receives the handle; it is written whatever the result (null on failure).
98/// @return The result of @c SQLAllocHandle.
99[[nodiscard]] LIGHTWEIGHT_API SqlResult Allocate(Connection const& connection, Statement& stmt) noexcept;
100
101/// @brief Frees the statement handle and leaves @p stmt empty.
102/// @param stmt The statement to free; may be empty.
103LIGHTWEIGHT_API void Free(Statement& stmt) noexcept;
104
105/// @brief Gives up a statement handle whose connection session ended, and leaves @p stmt empty.
106///
107/// The driver freed the handle with the session (Close(), a re-connect), so it is not freed again: only the
108/// record that its diagnostics are read through the ANSI entry points is dropped.
109/// @param stmt The statement; may be empty.
110LIGHTWEIGHT_API void Abandon(Statement& stmt) noexcept;
111
112/// @brief Prepares @p query on the statement.
113/// @param stmt The statement.
114/// @param query The SQL text, UTF-8.
115/// @param wideQueryText Whether to hand the text to the W entry point (as UTF-16); otherwise the ANSI
116/// entry point gets the UTF-8 bytes unchanged (see SqlConnection::AcceptsWideQueryText()).
117/// @return The result of @c SQLPrepare.
118[[nodiscard]] LIGHTWEIGHT_API SqlResult Prepare(Statement& stmt, std::string_view query, bool wideQueryText);
119
120/// @brief Executes the prepared statement with the currently bound parameters.
121/// @param stmt The statement.
122/// @return The result of @c SQLExecute; @c SqlResult::NoData for a searched UPDATE/DELETE that matched no rows.
123[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult Execute(Statement& stmt) noexcept
124{
125 return ToResult(SQLExecute(stmt.handle));
126}
127
128/// @brief Executes @p query directly, without preparing it.
129/// @param stmt The statement.
130/// @param query The SQL text, UTF-8.
131/// @param wideQueryText As for @c Prepare.
132/// @return The result of @c SQLExecDirect.
133[[nodiscard]] LIGHTWEIGHT_API SqlResult ExecuteDirect(Statement& stmt, std::string_view query, bool wideQueryText);
134
135/// @brief Fetches the next row of the result set into the bound columns.
136/// @param stmt The statement.
137/// @return The result of @c SQLFetch; @c SqlResult::NoData past the last row.
138[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult Fetch(Statement& stmt) noexcept
139{
140 return ToResult(SQLFetch(stmt.handle));
141}
142
143/// @brief Advances to the next pending result set.
144/// @param stmt The statement.
145/// @return The result of @c SQLMoreResults; @c SqlResult::NoData when none is pending.
146[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult MoreResults(Statement& stmt) noexcept
147{
148 return ToResult(SQLMoreResults(stmt.handle));
149}
150
151/// @brief Closes the cursor of a result set that was read to its end (@c SQLCloseCursor). Pending result
152/// sets are left alone; the result is not reported.
153/// @param stmt The statement.
154LIGHTWEIGHT_API void CloseCursor(Statement& stmt) noexcept;
155
156/// @brief Closes any open cursor and discards its pending rows (@c SQLFreeStmt with @c SQL_CLOSE), so the
157/// handle can run another query. Pending result sets are left alone; the result is not reported.
158/// @param stmt The statement.
159/// @note Not part of the @ref Lightweight::Driver::SqlDriver concept: @c DiscardResults covers it there.
160LIGHTWEIGHT_API void ReleaseCursor(Statement& stmt) noexcept;
161
162/// @brief Drains every pending result set (@c SQLMoreResults until @c SQL_NO_DATA or an error), then closes
163/// the cursor (@c ReleaseCursor), so the handle can run another query. An error met while draining ends
164/// the drain and is not reported.
165/// @param stmt The statement.
166inline void DiscardResults(Statement& stmt) noexcept
167{
168 while (true)
169 {
170 auto const rc = MoreResults(stmt);
171 if (rc == SqlResult::NoData || !Succeeded(rc))
172 break;
173 }
174 ReleaseCursor(stmt);
175}
176
177/// @brief Unbinds every bound result column (@c SQLFreeStmt with @c SQL_UNBIND).
178/// @param stmt The statement.
179/// @return The result of @c SQLFreeStmt.
180[[nodiscard]] LIGHTWEIGHT_API SqlResult UnbindColumns(Statement& stmt) noexcept;
181
182/// @brief Drops every parameter binding (@c SQLFreeStmt with @c SQL_RESET_PARAMS).
183/// @param stmt The statement.
184/// @return The result of @c SQLFreeStmt.
185[[nodiscard]] LIGHTWEIGHT_API SqlResult ResetParameters(Statement& stmt) noexcept;
186
187/// @brief Restores single-row, column-bound parameter binding (the ODBC default) and unbinds the
188/// parameter status and processed-count pointers. The results are not reported: resetting to defaults on
189/// a live handle does not meaningfully fail.
190/// @param stmt The statement.
191LIGHTWEIGHT_API void ResetParameterArrays(Statement& stmt) noexcept;
192
193/// @brief Reports the number of columns of the current result set.
194/// @param stmt The statement.
195/// @param count Receives the column count (0 for a statement that produced no result set).
196/// @return The result of @c SQLNumResultCols.
197[[nodiscard]] LIGHTWEIGHT_API SqlResult NumResultColumns(Statement const& stmt, std::int16_t& count) noexcept;
198
199/// @brief Reports the number of parameters of the prepared statement.
200/// @param stmt The statement.
201/// @param count Receives the parameter count.
202/// @return The result of @c SQLNumParams.
203[[nodiscard]] LIGHTWEIGHT_API SqlResult NumParameters(Statement const& stmt, std::int16_t& count) noexcept;
204
205/// @brief Reports the number of rows the last executed statement affected.
206/// @param stmt The statement.
207/// @param count Receives the row count; -1 when the driver cannot tell.
208/// @return The result of @c SQLRowCount.
209[[nodiscard]] LIGHTWEIGHT_API SqlResult NumRowsAffected(Statement const& stmt, std::ptrdiff_t& count) noexcept;
210
211/// @brief The name of a result column, as the driver describes it.
212/// @param stmt The statement, with a result set.
213/// @param column The 1-based result column.
214/// @return The column name in UTF-8, or the statement's diagnostics if the column cannot be described.
215/// @note Not part of the @ref Lightweight::Driver::SqlDriver concept: no driver-neutral caller needs it.
216[[nodiscard]] LIGHTWEIGHT_API std::expected<std::string, SqlErrorInfo> ColumnName(Statement const& stmt,
217 SqlColumnIndex column);
218
219/// @brief The SQL data type of a result column, as the driver describes it.
220/// @param stmt The statement, with a result set.
221/// @param column The 1-based result column.
222/// @return The type, @c SqlResultColumnType::Unknown for a type without an enumerator, or the statement's
223/// diagnostics if the column cannot be described.
224[[nodiscard]] LIGHTWEIGHT_API std::expected<SqlResultColumnType, SqlErrorInfo> ColumnType(Statement const& stmt,
225 SqlColumnIndex column);
226
227/// @brief Maps an ODBC @c SQL_* type code onto the driver-neutral @c SqlResultColumnType.
228/// @param sqlType The @c SQL_* type code, as @c DescribeColumn reports it.
229/// @return The mapped type, @c SqlResultColumnType::Unknown for a code without an enumerator.
230[[nodiscard]] LIGHTWEIGHT_API SqlResultColumnType ToResultColumnType(std::int16_t sqlType) noexcept;
231
232/// @brief Sets the query timeout of the statement.
233/// @param stmt The statement.
234/// @param timeout The timeout; zero means none.
235/// @return The result of @c SQLSetStmtAttr.
236[[nodiscard]] LIGHTWEIGHT_API SqlResult SetQueryTimeout(Statement& stmt, std::chrono::seconds timeout) noexcept;
237
238/// @brief Reports the query timeout of the statement.
239/// @param stmt The statement.
240/// @param timeout Receives the timeout; zero means none.
241/// @return The result of @c SQLGetStmtAttr.
242[[nodiscard]] LIGHTWEIGHT_API SqlResult QueryTimeout(Statement const& stmt, std::chrono::seconds& timeout) noexcept;
243
244/// Asks the driver for the concise SQL type of result column @p column with @c SQLDescribeColW.
245///
246/// SQLDescribeCol reports the concise SQL type code (e.g. SQL_TYPE_DATE, SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP). It
247/// is asked rather than SQLColAttribute(SQL_DESC_CONCISE_TYPE), which the SQLite driver answers with SQL_WCHAR
248/// for a BLOB column. The W variant keeps the ODBC call surface on the Unicode-app path the rest of the library
249/// uses. The column name is not needed, but a real buffer with its true length is passed: psqlODBC under
250/// unixODBC fails a null or zero-length name buffer with HY001 ("Could not allocate memory for column name").
251/// On the stack, and a name longer than it is only truncated (01004, a success).
252/// @param stmt The statement handle.
253/// @param column The 1-based column index.
254/// @param columnType Receives the SQL type.
255/// @return The driver's return code.
256inline SQLRETURN DescribeResultColumnSqlType(SQLHSTMT stmt, SqlColumnIndex column, SQLSMALLINT* columnType) noexcept
257{
258 SQLULEN columnSize {};
259 SQLSMALLINT decimalDigits {};
260 SQLSMALLINT nullable {};
261 auto columnName = std::array<SQLWCHAR, 64> {};
262 SQLSMALLINT columnNameLength {};
263 return SQLDescribeColW(stmt,
264 column,
265 columnName.data(),
266 static_cast<SQLSMALLINT>(columnName.size()),
267 &columnNameLength,
268 columnType,
269 &columnSize,
270 &decimalDigits,
271 &nullable);
272}
273
274/// Asks the driver for the concise SQL type of result column @p column (see the overload above).
275/// @param stmt The statement handle.
276/// @param column The 1-based column index.
277/// @return The SQL type, or @c std::nullopt when the driver cannot describe the column.
278inline std::optional<SQLSMALLINT> DescribeResultColumnSqlType(SQLHSTMT stmt, SqlColumnIndex column) noexcept
279{
280 SQLSMALLINT columnType {};
281 if (!SQL_SUCCEEDED(DescribeResultColumnSqlType(stmt, column, &columnType)))
282 return std::nullopt;
283 return columnType;
284}
285
286/// Asks the driver for the concise SQL type of result column @p column (see the overloads above): the
287/// @ref Lightweight::Driver::SqlDriver concept's form, which SqlStatement caches for the leaf binders.
288/// @param stmt The statement.
289/// @param column The 1-based column index.
290/// @return The SQL type, or @c std::nullopt when the driver cannot describe the column.
291[[nodiscard]] inline std::optional<std::int16_t> DescribeResultColumnSqlType(Statement const& stmt,
292 SqlColumnIndex column) noexcept
293{
294 return DescribeResultColumnSqlType(stmt.handle, column);
295}
296
297/// The layout of the parameter array that is being bound.
299{
300 /// The byte distance from one row's value to the next.
301 std::size_t rowStride {};
302 /// The number of rows.
303 std::size_t rowCount {};
304};
305
306/// Reads the layout of the parameter array the statement is bound with.
307///
308/// @param stmt The statement whose parameters are being bound.
309/// @param valueSize The size of one value, which is the stride of a column-wise array.
310/// @param columnWiseRowCount The row count of a column-wise (or single-row) binding.
311/// @return The row size and parameter set size of a row-wise binding, otherwise the column-wise layout.
313 std::size_t valueSize,
314 std::size_t columnWiseRowCount) noexcept
315{
316 auto bindType = SQLULEN { SQL_PARAM_BIND_BY_COLUMN };
317 if (!SQL_SUCCEEDED(SQLGetStmtAttr(stmt.handle, SQL_ATTR_PARAM_BIND_TYPE, &bindType, 0, nullptr))
318 || bindType == SQL_PARAM_BIND_BY_COLUMN)
319 return { .rowStride = valueSize, .rowCount = columnWiseRowCount };
320
321 auto parameterSetSize = SQLULEN { 1 };
322 if (!SQL_SUCCEEDED(SQLGetStmtAttr(stmt.handle, SQL_ATTR_PARAMSET_SIZE, &parameterSetSize, 0, nullptr)))
323 parameterSetSize = 1;
324 return { .rowStride = static_cast<std::size_t>(bindType), .rowCount = static_cast<std::size_t>(parameterSetSize) };
325}
326
327// Diagnose(Statement const&) and RequireSuccess(Statement const&, ...), also part of the concept, are in
328// Diagnostics.hpp.
329
330/// @brief The non-throwing, fault-seam-aware verdict on @p result (see detail::CheckOdbcCall()).
331/// @param stmt The statement @p result came from.
332/// @param result The result to check.
333/// @param sourceLocation Where the check originated; forwarded to the fault source.
334/// @return The verdict, plus the injected diagnostic when one was injected.
335[[nodiscard]] inline detail::OdbcCallOutcome CheckResult(Statement const& stmt,
336 SqlResult result,
337 std::source_location sourceLocation)
338{
339 return detail::CheckOdbcCall(std::to_underlying(result), stmt.handle, sourceLocation);
340}
341
342/// @brief The type a @c DATA_TYPE code of a catalog result set (@c SQLColumns, ...) stands for: the code mapped as
343/// @c ToResultColumnType maps a code @c SQLDescribeCol reports.
344/// @param stmt The statement holding the catalog result set (unused: the codes are ODBC's).
345/// @param dataType The @c SQL_* code, as read from the result set.
346/// @return The mapped type; @c SqlResultColumnType::Unknown for a code without an enumerator, or outside the
347/// range of an @c SQLSMALLINT.
348[[nodiscard]] inline SqlResultColumnType CatalogColumnType([[maybe_unused]] Statement const& stmt, int dataType) noexcept
349{
350 if (!std::in_range<std::int16_t>(dataType))
351 return SqlResultColumnType::Unknown;
352 return ToResultColumnType(static_cast<std::int16_t>(dataType));
353}
354
355/// @brief The declared length of output column @p column as a bound buffer size: between
356/// @c detail::DefaultBoundColumnSize and @c detail::MaxDeclaredBoundColumnSize, and
357/// @c detail::DefaultBoundColumnSize for a length the driver does not report or one above the maximum (a MAX or
358/// LONG column). One @c SQLColAttribute call.
359///
360/// @param stmt The statement holding the result set.
361/// @param column The 1-based column index.
362/// @param length Which declared length to ask for.
363/// @return The number of elements to bind, without a terminator.
364[[nodiscard]] LIGHTWEIGHT_API std::size_t DeclaredBoundColumnSize(Statement const& stmt,
365 SqlColumnIndex column,
366 SqlOutputColumnLength length) noexcept;
367
368/// @brief Describes a result column (@c SQLDescribeCol): the @ref Lightweight::Driver::SqlDriver concept's form,
369/// with the type mapped by @c ToResultColumnType.
370/// @param stmt The statement, with a result set.
371/// @param column The 1-based result column.
372/// @param description Receives the description.
373/// @return The result of @c SQLDescribeCol.
374[[nodiscard]] inline SqlResult DescribeColumn(Statement const& stmt,
375 SqlColumnIndex column,
376 SqlColumnDescription& description) noexcept;
377
378// }}}
379
380// {{{ ODBC-only statement operations
381
382/// @brief Records @p stmt as belonging to a connection whose driver takes text only through the ANSI
383/// entry points, so that its diagnostics are read through those as well.
384/// @param stmt The freshly allocated statement.
385/// @param connection The connection it was allocated on.
386LIGHTWEIGHT_API void RegisterAnsiOnly(Statement const& stmt, Connection const& connection) noexcept;
387
388/// @brief Restores single-row, column-bound fetching and unbinds the row status and rows-fetched
389/// pointers. The results are not reported. Part of the @ref Lightweight::Driver::SqlDriver concept.
390/// @param stmt The statement.
391LIGHTWEIGHT_API void ResetRowArrayAttributes(Statement& stmt) noexcept;
392
393/// @brief Sets up column-wise parameter-array binding of @p rowCount parameter sets.
394/// @param stmt The statement.
395/// @param rowCount The number of parameter sets.
396/// @param bindOffset The @c SQL_ATTR_PARAM_BIND_OFFSET_PTR value.
397/// @param check Called with each attribute's result, right after setting it; throwing stops the setup.
398template <typename Check>
399void SetColumnWiseParameterArray(Statement& stmt, std::size_t rowCount, void* bindOffset, Check const& check)
400{
401 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAMSET_SIZE, detail::OdbcIntAttr(rowCount), 0)));
402 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_BIND_OFFSET_PTR, bindOffset, 0)));
403 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_BIND_TYPE, SQL_PARAM_BIND_BY_COLUMN, 0)));
404 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_OPERATION_PTR, SQL_PARAM_PROCEED, 0)));
405}
406
407/// @brief Sets up row-wise parameter-array binding of @p rowCount parameter sets, @p rowStride bytes apart.
408/// @param stmt The statement.
409/// @param rowCount The number of parameter sets.
410/// @param rowStride The byte distance between two consecutive parameter sets.
411/// @param processedCount Receives the number of parameter sets the driver processed.
412/// @param check Called with each attribute's result, right after setting it; throwing stops the setup.
413template <typename Check>
415 Statement& stmt, std::size_t rowCount, std::size_t rowStride, ProcessedCount* processedCount, Check const& check)
416{
417 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAMSET_SIZE, detail::OdbcIntAttr(rowCount), 0)));
418 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_BIND_TYPE, detail::OdbcIntAttr(rowStride), 0)));
419 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_BIND_OFFSET_PTR, nullptr, 0)));
420 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_OPERATION_PTR, SQL_PARAM_PROCEED, 0)));
421 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAMS_PROCESSED_PTR, processedCount, 0)));
422}
423
424/// @brief Binds the arrays the driver reports per-parameter-set status and the processed count into.
425/// @param stmt The statement.
426/// @param paramStatus Receives one status per parameter set.
427/// @param processedCount Receives the number of parameter sets the driver processed.
428/// @param check Called with each attribute's result, right after setting it; throwing stops the setup.
429template <typename Check>
430void SetParameterStatusArrays(Statement& stmt, RowStatus* paramStatus, ProcessedCount* processedCount, Check const& check)
431{
432 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAM_STATUS_PTR, paramStatus, 0)));
433 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_PARAMS_PROCESSED_PTR, processedCount, 0)));
434}
435
436/// @brief Sets up row-array fetching of up to @p arrayDepth rows per @c FetchNextBlock.
437/// @param stmt The statement.
438/// @param rowBindType The @c SQL_ATTR_ROW_BIND_TYPE: 0 (@c SQL_BIND_BY_COLUMN) for column-wise binding,
439/// otherwise the byte distance between two consecutive bound rows.
440/// @param arrayDepth The number of rows per block.
441/// @param rowStatus Receives one status per fetched row.
442/// @param rowsFetched Receives the number of rows of the last fetched block.
443/// @param check Called with each attribute's result, right after setting it; throwing stops the setup.
444template <typename Check>
446 std::size_t rowBindType,
447 std::size_t arrayDepth,
448 RowStatus* rowStatus,
449 ProcessedCount* rowsFetched,
450 Check const& check)
451{
452 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_ROW_BIND_TYPE, detail::OdbcIntAttr(rowBindType), 0)));
453 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_ROW_ARRAY_SIZE, detail::OdbcIntAttr(arrayDepth), 0)));
454 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_ROW_STATUS_PTR, rowStatus, 0)));
455 check(ToResult(SQLSetStmtAttr(stmt.handle, SQL_ATTR_ROWS_FETCHED_PTR, rowsFetched, 0)));
456}
457
458/// @brief Binds a result column to a buffer (@c SQLBindCol).
459/// @param stmt The statement.
460/// @param column The 1-based result column.
461/// @param cType The @c SQL_C_* type to bind as.
462/// @param buffer The (first row's) value buffer.
463/// @param bufferLength The byte length of one row's value buffer; ignored for fixed-size C types.
464/// @param indicators The (first row's) length indicator.
465/// @return The result of @c SQLBindCol.
466[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult BindColumn(Statement& stmt,
467 SqlColumnIndex column,
468 std::int16_t cType,
469 void* buffer,
470 SqlIndicator bufferLength,
471 SqlIndicator* indicators) noexcept
472{
473 return ToResult(SQLBindCol(stmt.handle, column, cType, buffer, bufferLength, indicators));
474}
475
476/// @brief Binds a result column to a narrow character buffer (@c SQL_C_CHAR).
477/// @param stmt The statement.
478/// @param column The 1-based result column.
479/// @param buffer The (first row's) character buffer.
480/// @param bufferLength The byte length of one row's buffer, including the NUL terminator.
481/// @param indicators The (first row's) length indicator.
482/// @return The result of @c SQLBindCol.
483[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult BindTextColumn(
484 Statement& stmt, SqlColumnIndex column, char* buffer, SqlIndicator bufferLength, SqlIndicator* indicators) noexcept
485{
486 return BindColumn(stmt, column, SQL_C_CHAR, buffer, bufferLength, indicators);
487}
488
489/// @brief Binds UTF-16 text as an input parameter of SQL type @c SQL_WVARCHAR (@c SQLBindParameter with
490/// @c SQL_C_WCHAR). @p lengthIndicator serves as both the buffer length and the length indicator.
491/// @param stmt The statement.
492/// @param parameter The 1-based parameter.
493/// @param text The text; must stay alive until the statement is executed.
494/// @param columnSize The declared column size of the parameter.
495/// @param lengthIndicator The byte length of @p text; must stay alive until the statement is executed. Shared code
496/// passes a length >= 0 only: the other drivers do not give ODBC's special lengths a meaning
497/// (the native SQLite3 driver fails a negative one with HY090).
498/// @return The result of @c SQLBindParameter.
499/// @note Part of the @ref Lightweight::Driver::SqlDriver concept: SqlSchema binds the names of its SQL Server
500/// catalog queries (@c sys.*) through it, without naming the driver.
501[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult BindUtf16TextParameter(
502 Statement& stmt, std::uint16_t parameter, char16_t* text, std::size_t columnSize, SqlIndicator& lengthIndicator) noexcept
503{
504 return ToResult(SQLBindParameter(stmt.handle,
505 parameter,
506 SQL_PARAM_INPUT,
507 SQL_C_WCHAR,
508 SQL_WVARCHAR,
509 static_cast<SQLULEN>(columnSize),
510 0,
511 text,
512 lengthIndicator,
513 &lengthIndicator));
514}
515
516/// @brief Fetches the next block of rows into the row-array bound columns (@c SQLFetchScroll, @c SQL_FETCH_NEXT).
517/// @param stmt The statement.
518/// @return The result of @c SQLFetchScroll; @c SqlResult::NoData past the last row.
519[[nodiscard]] inline LIGHTWEIGHT_FORCE_INLINE SqlResult FetchNextBlock(Statement& stmt) noexcept
520{
521 return ToResult(SQLFetchScroll(stmt.handle, SQL_FETCH_NEXT, 0));
522}
523
524/// @brief Describes a result column (@c SQLDescribeCol).
525/// @param stmt The statement, with a result set.
526/// @param column The 1-based result column.
527/// @param description Receives the description.
528/// @return The result of @c SQLDescribeCol.
529[[nodiscard]] LIGHTWEIGHT_API SqlResult DescribeColumn(Statement const& stmt,
530 SqlColumnIndex column,
531 ColumnDescription& description) noexcept;
532
533inline SqlResult DescribeColumn(Statement const& stmt, SqlColumnIndex column, SqlColumnDescription& description) noexcept
534{
535 auto odbcDescription = ColumnDescription {};
536 auto const result = DescribeColumn(stmt, column, odbcDescription);
537 description = SqlColumnDescription { .type = ToResultColumnType(odbcDescription.sqlType),
538 .columnSize = odbcDescription.columnSize };
539 return result;
540}
541
542/// @brief Describes the declared SQL type of each of the first @p count parameters (@c SQLDescribeParam).
543/// @param stmt The prepared statement.
544/// @param count The number of parameters to describe.
545/// @return One @c SQL_* type per parameter, @c UnknownParameterType where the driver could not say.
546[[nodiscard]] LIGHTWEIGHT_API std::vector<std::int16_t> DescribeParameterTypes(Statement const& stmt, std::size_t count);
547
548/// @brief The number of parameters currently bound on the statement, read from its application
549/// parameter descriptor.
550/// @param stmt The statement.
551/// @return The bound parameter count, or -1 if the descriptor cannot be read.
552[[nodiscard]] LIGHTWEIGHT_API std::int16_t BoundParameterCount(Statement const& stmt) noexcept;
553
554// }}}
555
556// static_assert(SqlDriver<Driver>) is in Connection.hpp, after the connection operations the concept requires.
557
558} // namespace Lightweight::Driver::Odbc
void ResetParameterArrays(StatementHandle &statement) noexcept
Restores single-row parameter binding after a parameter-array execution. Not reported.
Definition Dispatch.hpp:402
void CloseCursor(StatementHandle &statement) noexcept
Closes the cursor of a result set that was read to its end. Pending result sets are left alone.
Definition Dispatch.hpp:371
SqlResult UnbindColumns(StatementHandle &statement) noexcept
Unbinds every bound result column.
Definition Dispatch.hpp:387
std::optional< std::int16_t > DescribeResultColumnSqlType(StatementHandle const &statement, SqlColumnIndex column) noexcept
The driver's own SQL type code of a result column, as the driver's leaf binders read it (see SqlDataB...
Definition Dispatch.hpp:535
void Allocate(ConnectionHandle &connection) noexcept
Allocates the driver's connection resources, unless the connection already holds them.
Definition Dispatch.hpp:569
SqlResult NumResultColumns(StatementHandle const &statement, std::int16_t &count) noexcept
Reports the number of columns of the current result set.
Definition Dispatch.hpp:411
SqlResult SetQueryTimeout(StatementHandle &statement, std::chrono::seconds timeout) noexcept
Sets the query timeout of the statement.
Definition Dispatch.hpp:449
void DiscardResults(StatementHandle &statement) noexcept
Drains every pending result set and closes the cursor, so the handle can run another query....
Definition Dispatch.hpp:379
void Free(StatementHandle &statement) noexcept
Frees the statement's driver handle and leaves statement empty, bound to the same driver.
Definition Dispatch.hpp:285
void RegisterAnsiOnly(StatementHandle const &statement, ConnectionHandle const &connection) noexcept
Records statement as belonging to a connection whose driver takes text only through its ANSI entry po...
Definition Dispatch.hpp:883
SqlResult NumParameters(StatementHandle const &statement, std::int16_t &count) noexcept
Reports the number of parameters of the prepared statement.
Definition Dispatch.hpp:420
SqlResultColumnType CatalogColumnType(StatementHandle const &statement, int dataType) noexcept
The type a DATA_TYPE code of the driver's catalog result sets (see OpenCatalog) stands for.
Definition Dispatch.hpp:512
SqlResult QueryTimeout(StatementHandle const &statement, std::chrono::seconds &timeout) noexcept
Reports the query timeout of the statement.
Definition Dispatch.hpp:458
void ResetRowArrayAttributes(StatementHandle &statement) noexcept
Restores single-row fetching after a row-array fetch. Not reported; nothing for a driver without row ...
Definition Dispatch.hpp:558
SqlResult NumRowsAffected(StatementHandle const &statement, std::ptrdiff_t &count) noexcept
Reports the number of rows the last executed statement affected.
Definition Dispatch.hpp:429
void Abandon(StatementHandle &statement) noexcept
Gives up the statement's driver handle after its connection session ended, and leaves statement empty...
Definition Dispatch.hpp:294
std::size_t DeclaredBoundColumnSize(StatementHandle const &statement, SqlColumnIndex column, SqlOutputColumnLength length) noexcept
The declared length of a result column as a bound buffer size (see SqlDataBinderCallback::MinimumOutp...
Definition Dispatch.hpp:548
std::int16_t BoundParameterCount(StatementHandle const &statement) noexcept
The number of parameters currently bound on the statement.
Definition Dispatch.hpp:910
SqlResult DescribeColumn(StatementHandle const &statement, SqlColumnIndex column, SqlColumnDescription &description)
Describes a result column: its type and its size.
Definition Dispatch.hpp:522
SqlResult ResetParameters(StatementHandle &statement) noexcept
Drops every parameter binding.
Definition Dispatch.hpp:395
std::expected< SqlResultColumnType, SqlErrorInfo > ColumnType(StatementHandle const &statement, SqlColumnIndex column)
The SQL data type of a result column, as the driver describes it.
Definition Dispatch.hpp:439
std::vector< std::int16_t > DescribeParameterTypes(StatementHandle const &statement, std::size_t count)
Describes the declared SQL type of each of the first count parameters.
Definition Dispatch.hpp:897
SqlResult MoreResults(StatementHandle &statement) noexcept
Advances to the next pending result set.
Definition Dispatch.hpp:364
CallOutcome CheckResult(StatementHandle const &statement, SqlResult result, std::source_location location)
The non-throwing, fault-seam-aware verdict on result.
Definition Dispatch.hpp:489
void SetRowWiseParameterArray(Statement &stmt, std::size_t rowCount, std::size_t rowStride, ProcessedCount *processedCount, Check const &check)
Sets up row-wise parameter-array binding of rowCount parameter sets, rowStride bytes apart.
LIGHTWEIGHT_API void ReleaseCursor(Statement &stmt) noexcept
Closes any open cursor and discards its pending rows (SQLFreeStmt with SQL_CLOSE),...
LIGHTWEIGHT_FORCE_INLINE SqlResult BindUtf16TextParameter(Statement &stmt, std::uint16_t parameter, char16_t *text, std::size_t columnSize, SqlIndicator &lengthIndicator) noexcept
Binds UTF-16 text as an input parameter of SQL type SQL_WVARCHAR (SQLBindParameter with SQL_C_WCHAR)....
SQLULEN ProcessedCount
The count a driver writes back through a parameter-array or row-array attribute pointer (SQL_ATTR_PAR...
Definition Statement.hpp:44
SQLUSMALLINT RowStatus
One element of a parameter-status or row-status array (SQL_ATTR_PARAM_STATUS_PTR, SQL_ATTR_ROW_STATUS...
Definition Statement.hpp:48
constexpr RowStatus ParamStatusUnused
The parameter status of a parameter set the driver did not process (SQL_PARAM_UNUSED).
Definition Statement.hpp:51
LIGHTWEIGHT_API std::expected< std::string, SqlErrorInfo > ColumnName(Statement const &stmt, SqlColumnIndex column)
The name of a result column, as the driver describes it.
constexpr RowStatus RowStatusError
The row status of a fetched row the driver could not convert (SQL_ROW_ERROR).
Definition Statement.hpp:57
void SetColumnWiseParameterArray(Statement &stmt, std::size_t rowCount, void *bindOffset, Check const &check)
Sets up column-wise parameter-array binding of rowCount parameter sets.
LIGHTWEIGHT_API SqlResultColumnType ToResultColumnType(std::int16_t sqlType) noexcept
Maps an ODBC SQL_* type code onto the driver-neutral SqlResultColumnType.
constexpr RowStatus ParamStatusError
The parameter status of a parameter set that failed (SQL_PARAM_ERROR).
Definition Statement.hpp:54
LIGHTWEIGHT_FORCE_INLINE SqlResult FetchNextBlock(Statement &stmt) noexcept
Fetches the next block of rows into the row-array bound columns (SQLFetchScroll, SQL_FETCH_NEXT).
ParameterArrayLayout CurrentParameterArrayLayout(Statement const &stmt, std::size_t valueSize, std::size_t columnWiseRowCount) noexcept
constexpr std::int16_t UnknownParameterType
The declared SQL type DescribeParameterTypes reports for a parameter it could not describe.
Definition Statement.hpp:60
void SetRowArray(Statement &stmt, std::size_t rowBindType, std::size_t arrayDepth, RowStatus *rowStatus, ProcessedCount *rowsFetched, Check const &check)
Sets up row-array fetching of up to arrayDepth rows per FetchNextBlock.
LIGHTWEIGHT_FORCE_INLINE SqlResult BindColumn(Statement &stmt, SqlColumnIndex column, std::int16_t cType, void *buffer, SqlIndicator bufferLength, SqlIndicator *indicators) noexcept
Binds a result column to a buffer (SQLBindCol).
LIGHTWEIGHT_FORCE_INLINE SqlResult BindTextColumn(Statement &stmt, SqlColumnIndex column, char *buffer, SqlIndicator bufferLength, SqlIndicator *indicators) noexcept
Binds a result column to a narrow character buffer (SQL_C_CHAR).
void SetParameterStatusArrays(Statement &stmt, RowStatus *paramStatus, ProcessedCount *processedCount, Check const &check)
Binds the arrays the driver reports per-parameter-set status and the processed count into.
@ Execute
The execution of a prepared statement (SqlStatement::Execute).
@ ExecuteDirect
The execution of a one-shot statement (SqlStatement::ExecuteDirect).
@ Prepare
The preparation of a statement (SqlStatement::Prepare).
Verdict of a non-throwing checked driver call, carrying the diagnostic that justifies a failure verdi...
Definition Concept.hpp:76
What DescribeColumn reports about a result column.
Definition Statement.hpp:64
std::int16_t sqlType
The SQL_* type code of the column.
Definition Statement.hpp:66
std::size_t columnSize
The column size (maximum character count for character columns); 0 when the driver cannot bound it.
Definition Statement.hpp:69
The ODBC driver's connection handle struct.
Definition Handles.hpp:53
The layout of the parameter array that is being bound.
std::size_t rowStride
The byte distance from one row's value to the next.
std::size_t rowCount
The number of rows.
The ODBC driver's statement handle struct.
Definition Handles.hpp:43
SQLHSTMT handle
The native ODBC statement handle.
Definition Handles.hpp:45
What a driver reports about a result column (see DescribeColumn).
Definition Concept.hpp:172
SqlResultColumnType type
The column's type, SqlResultColumnType::Unknown for one without an enumerator.
Definition Concept.hpp:174