Lightweight 0.20261105.1
Loading...
Searching...
No Matches
RowArrayCursor.hpp
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 "../../DataBinder/SqlDate.hpp"
8#include "../../DataBinder/SqlDateTime.hpp"
9#include "../../DataBinder/SqlGuid.hpp"
10#include "../../SqlBindingTypes.hpp"
11#include "SqlOdbcPrelude.hpp"
12
13#include <cstddef>
14#include <cstdint>
15#include <optional>
16#include <stdexcept>
17#include <string>
18#include <vector>
19
20#include <sql.h>
21#include <sqlext.h>
22
23namespace Lightweight
24{
25
26class SqlStatement;
27
28/// @brief Thrown by RowArrayCursor's constructor when the executed result set cannot be fixed-stride
29/// array-bound.
30///
31/// Raised for an unbounded/LOB or over-wide character column (e.g. a column the driver reports
32/// as SQL_LONGVARCHAR with no size, common for SQLite's dynamically-typed columns), or a query that
33/// produced no result columns. It is a precondition signal, not a database error, so callers that
34/// use bulk array-fetch purely as an optimization should catch it and fall back to the single-row
35/// path. Distinct from SqlException so transient-error retry logic does not mistake it for one.
36class RowArrayCursorUnsupported: public std::runtime_error
37{
38 public:
39 using std::runtime_error::runtime_error;
40};
41
42/// @brief A cursor that fetches result rows in bulk (ODBC row-array binding) for fast column reads.
43///
44/// Created via @c SqlStatement::ExecuteBatchFetch. Instead of issuing one SQLGetData per cell,
45/// this cursor binds a contiguous buffer per result column and lets the driver materialize whole
46/// blocks of rows per SQLFetchScroll round-trip — eliminating per-cell driver round-trips.
47///
48/// Supported (fixed-stride) column types, decided per column from SQLDescribeCol:
49/// - integer SQL types (SQL_BIT, SQL_TINYINT, SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT)
50/// are bound as SQL_C_SBIGINT (an int64 buffer);
51/// - floating SQL types (SQL_REAL, SQL_FLOAT, SQL_DOUBLE) are bound as SQL_C_DOUBLE;
52/// - all other types (char/varchar/decimal/date/time/timestamp/numeric/...) are bound as
53/// SQL_C_CHAR with a per-column buffer sized from the reported column size (plus a margin,
54/// capped at @ref RowArrayCursor::MaxCharColumnBytes).
55///
56/// LOB / unbounded columns (the driver reports column size 0 or an absurdly large size) are
57/// rejected: constructing the cursor throws std::runtime_error. Such columns must use the
58/// single-row SQLGetData fallback instead.
59///
60/// The cursor is non-copyable and non-movable: it owns the ODBC statement's array-binding state for
61/// its entire lifetime. The constructor binds raw pointers into its own members
62/// (SQL_ATTR_ROWS_FETCHED_PTR, SQL_ATTR_ROW_STATUS_PTR) and SQLBindCol into its per-column buffers,
63/// so the object must not be relocated after construction — a move would leave the statement handle
64/// pointing at the moved-from storage (use-after-free). It is constructed in place via
65/// @c SqlStatement::ExecuteBatchFetch (guaranteed copy elision) and used as a local. The bound
66/// buffers must outlive the SQLBindCol binding until fetching completes. Cell indices are 1-based to
67/// match SqlResultCursor::GetColumn.
68class [[nodiscard]] RowArrayCursor
69{
70 public:
71 /// Maximum byte width allocated for a single bound character column (per row). Columns whose
72 /// reported size exceeds this are treated as unbounded/LOB and rejected.
73 static constexpr std::size_t MaxCharColumnBytes = 8192;
74
75 /// Per-cursor byte budget for the bound column buffers. The effective array depth is
76 /// clamp(budget / row-byte-width, MinArrayDepth, requested depth), so wide tables (many or
77 /// large character columns) bind fewer rows per round-trip instead of exhausting memory —
78 /// the footprint otherwise multiplies across workers x columns x depth on real schemas.
79 static constexpr std::size_t MemoryBudgetBytes = 4 * 1024 * 1024;
80
81 /// Lower bound for the budget-adapted array depth, so bulk fetch always makes progress even
82 /// on extremely wide rows (never reduced below this unless the caller requested less).
83 static constexpr std::size_t MinArrayDepth = 16;
84
85 RowArrayCursor() = delete;
86 RowArrayCursor(RowArrayCursor const&) = delete;
87 RowArrayCursor& operator=(RowArrayCursor const&) = delete;
89 RowArrayCursor& operator=(RowArrayCursor&&) = delete;
90
91 /// @brief Constructs the cursor on a statement whose query has already been executed.
92 /// Inspects the result columns via SQLDescribeCol, allocates per-column buffers, and binds
93 /// them with the row-array statement attributes.
94 /// @param stmt The executed statement (must outlive the cursor).
95 /// @param arrayDepth Maximum number of rows materialized per FetchArray() (must be > 0). The
96 /// effective depth may be reduced to fit MemoryBudgetBytes (see ArrayDepth()).
97 LIGHTWEIGHT_API RowArrayCursor(SqlStatement& stmt, std::size_t arrayDepth);
98
99 /// @brief Resets the statement's row-array attributes and unbinds the columns so the handle
100 /// can be safely reused.
101 LIGHTWEIGHT_API ~RowArrayCursor() noexcept;
102
103 /// @brief Fetches the next block of rows into the bound buffers.
104 /// @return The number of rows materialized (0 at end of result set).
105 [[nodiscard]] LIGHTWEIGHT_API std::size_t FetchArray();
106
107 /// @brief The number of result columns.
108 [[nodiscard]] LIGHTWEIGHT_API std::size_t ColumnCount() const noexcept;
109
110 /// @brief The effective maximum number of rows per FetchArray() — the requested depth, possibly
111 /// reduced so the bound buffers fit MemoryBudgetBytes (never below MinArrayDepth unless the
112 /// caller requested less).
113 [[nodiscard]] LIGHTWEIGHT_API std::size_t ArrayDepth() const noexcept;
114
115 /// @brief Reads an integer cell from the last fetched block.
116 /// @param rowInBatch 0-based row offset within the block returned by the last FetchArray().
117 /// @param column 1-based result column index.
118 /// @return The value, or std::nullopt if the cell is NULL.
119 [[nodiscard]] LIGHTWEIGHT_API std::optional<std::int64_t> GetI64(std::size_t rowInBatch, SqlColumnIndex column) const;
120
121 /// @brief Reads a floating-point cell from the last fetched block.
122 /// @param rowInBatch 0-based row offset within the block returned by the last FetchArray().
123 /// @param column 1-based result column index.
124 /// @return The value, or std::nullopt if the cell is NULL.
125 [[nodiscard]] LIGHTWEIGHT_API std::optional<double> GetF64(std::size_t rowInBatch, SqlColumnIndex column) const;
126
127 /// @brief Reads a text cell from the last fetched block, however the driver bound it.
128 ///
129 /// Narrow-bound cells (SQL_C_CHAR) are returned verbatim — identical bytes to a single-row
130 /// SQL_C_CHAR read. Wide-bound cells (the driver reported SQL_WCHAR/SQL_WVARCHAR, e.g. MSSQL
131 /// NVARCHAR, or SQLite which reports all text as wide) are converted UTF-16 -> UTF-8; for
132 /// valid UTF-8 source data that round-trip is byte-lossless, so the result again matches the
133 /// single-row read of the same cell.
134 ///
135 /// @param rowInBatch 0-based row offset within the block returned by the last FetchArray().
136 /// @param column 1-based result column index.
137 /// @return The UTF-8 value, or std::nullopt if the cell is NULL.
138 [[nodiscard]] LIGHTWEIGHT_API std::optional<std::string> GetString(std::size_t rowInBatch, SqlColumnIndex column) const;
139
140 /// @brief Reads a DATE cell from the last fetched block. Valid only for Date-bound columns.
141 /// @param rowInBatch 0-based row offset within the block returned by the last FetchArray().
142 /// @param column 1-based result column index.
143 /// @return The value, or std::nullopt if the cell is NULL.
144 [[nodiscard]] LIGHTWEIGHT_API std::optional<SqlDate> GetDate(std::size_t rowInBatch, SqlColumnIndex column) const;
145
146 /// @brief Reads a TIMESTAMP/DATETIME cell from the last fetched block. Valid only for
147 /// Timestamp-bound columns.
148 /// @param rowInBatch 0-based row offset within the block returned by the last FetchArray().
149 /// @param column 1-based result column index.
150 /// @return The value, or std::nullopt if the cell is NULL.
151 [[nodiscard]] LIGHTWEIGHT_API std::optional<SqlDateTime> GetTimestamp(std::size_t rowInBatch,
152 SqlColumnIndex column) const;
153
154 /// @brief Reads a GUID cell from the last fetched block. Valid only for Guid-bound columns
155 /// (drivers that report SQL_GUID, i.e. MSSQL uniqueidentifier / PostgreSQL uuid).
156 /// @param rowInBatch 0-based row offset within the block returned by the last FetchArray().
157 /// @param column 1-based result column index.
158 /// @return The value, or std::nullopt if the cell is NULL.
159 [[nodiscard]] LIGHTWEIGHT_API std::optional<SqlGuid> GetGuid(std::size_t rowInBatch, SqlColumnIndex column) const;
160
161 /// @brief How a result column is bound for bulk fetch (the canonical fixed-stride C representation
162 /// chosen from the column's SQL type). Public so a transparent prefetch layer can dispatch a generic
163 /// cell read to the matching @c Get* accessor.
164 enum class BoundType : std::uint8_t
165 {
166 Int64, //!< bound as SQL_C_SBIGINT into an int64 buffer
167 Double, //!< bound as SQL_C_DOUBLE into a double buffer
168 Char, //!< bound as SQL_C_CHAR into a per-column byte buffer
169 WChar, //!< bound as SQL_C_WCHAR (UTF-16) into a per-column byte buffer
170 Date, //!< bound as SQL_C_TYPE_DATE into a SQL_DATE_STRUCT buffer
171 Timestamp, //!< bound as SQL_C_TYPE_TIMESTAMP into a SQL_TIMESTAMP_STRUCT buffer
172 Guid, //!< bound as SQL_C_GUID into a 16-byte GUID buffer
173 };
174
175 /// @brief The bound representation chosen for a result column.
176 /// @param column 1-based result column index.
177 /// @return The @ref BoundType the column was bound as.
178 [[nodiscard]] LIGHTWEIGHT_API BoundType ColumnBoundType(SqlColumnIndex column) const;
179
180 /// @brief The raw SQL data type the driver reported for a result column (the @c SQL_* value from
181 /// @c SQLDescribeCol), letting callers gate on the exact source type rather than the coarser
182 /// @ref BoundType (which collapses e.g. textual TIME/NUMERIC into @c Char).
183 /// @param column 1-based result column index.
184 /// @return The reported @c SQL_* type code.
185 [[nodiscard]] LIGHTWEIGHT_API SQLSMALLINT ColumnSqlType(SqlColumnIndex column) const;
186
187 /// @brief The driver-neutral type of a result column: @ref ColumnSqlType mapped onto
188 /// @c SqlResultColumnType.
189 /// @param column 1-based result column index.
190 /// @return The column's type, @c SqlResultColumnType::Unknown for a type without an enumerator.
191 [[nodiscard]] LIGHTWEIGHT_API SqlResultColumnType ColumnResultType(SqlColumnIndex column) const;
192
193 /// @brief Whether a cell in the last fetched block is SQL NULL.
194 /// @param rowInBatch 0-based row offset within the block returned by the last @ref FetchArray.
195 /// @param column 1-based result column index.
196 /// @return @c true if the cell's length indicator is @c SQL_NULL_DATA.
197 [[nodiscard]] LIGHTWEIGHT_API bool IsCellNull(std::size_t rowInBatch, SqlColumnIndex column) const;
198
199 private:
200 /// Per-column binding metadata + owning buffers.
201 struct BoundColumn
202 {
203 BoundType type {}; //!< how this column is bound
204 SQLSMALLINT sqlType {}; //!< raw SQL_* type reported by SQLDescribeCol
205 SqlResultColumnType resultType {}; //!< sqlType mapped onto the driver-neutral type
206 std::size_t elementWidth {}; //!< byte stride of one row's value in the buffer
207 std::vector<char> buffer; //!< arrayDepth * elementWidth contiguous bytes
208 std::vector<SQLLEN> indicators; //!< arrayDepth length indicators (SQL_NULL_DATA etc.)
209 };
210
211 void ResetStatementState() noexcept;
212
213 /// Shared accessor prelude: bounds-checks @p rowInBatch against the last fetched block,
214 /// verifies the column is bound as @p expected, and returns the cell's buffer address —
215 /// or nullptr when the cell is SQL NULL.
216 [[nodiscard]] char const* CheckedCell(std::size_t rowInBatch,
217 SqlColumnIndex column,
218 BoundType expected,
219 char const* accessorName) const;
220
221 SqlStatement* m_stmt;
222 std::size_t m_arrayDepth;
223 std::size_t m_lastFetched = 0;
224 std::vector<BoundColumn> m_columns;
225 SQLULEN m_rowsFetched = 0;
226 std::vector<SQLUSMALLINT> m_rowStatus;
227};
228
229} // namespace Lightweight
Thrown by RowArrayCursor's constructor when the executed result set cannot be fixed-stride array-boun...
A cursor that fetches result rows in bulk (ODBC row-array binding) for fast column reads.
LIGHTWEIGHT_API bool IsCellNull(std::size_t rowInBatch, SqlColumnIndex column) const
Whether a cell in the last fetched block is SQL NULL.
LIGHTWEIGHT_API RowArrayCursor(SqlStatement &stmt, std::size_t arrayDepth)
Constructs the cursor on a statement whose query has already been executed. Inspects the result colum...
LIGHTWEIGHT_API BoundType ColumnBoundType(SqlColumnIndex column) const
The bound representation chosen for a result column.
LIGHTWEIGHT_API ~RowArrayCursor() noexcept
Resets the statement's row-array attributes and unbinds the columns so the handle can be safely reuse...
BoundType
How a result column is bound for bulk fetch (the canonical fixed-stride C representation chosen from ...
LIGHTWEIGHT_API SQLSMALLINT ColumnSqlType(SqlColumnIndex column) const
The raw SQL data type the driver reported for a result column (the SQL_* value from SQLDescribeCol),...
LIGHTWEIGHT_API SqlResultColumnType ColumnResultType(SqlColumnIndex column) const
The driver-neutral type of a result column: ColumnSqlType mapped onto SqlResultColumnType.
High level API for (prepared) raw SQL statements.