Lightweight 0.20261105.1
Loading...
Searching...
No Matches
BoundOutputColumn.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 "../../DataBinder/Core.hpp"
7#include "../../SqlBindingTypes.hpp"
8#include "../../SqlError.hpp"
9#include "../Dispatch.hpp"
10#include "Diagnostics.hpp"
11#include "Handles.hpp"
12#include "SqlOdbcPrelude.hpp"
13
14#include <algorithm>
15#include <cstddef>
16#include <format>
17#include <string>
18#include <utility>
19
20#include <sql.h>
21#include <sqlext.h>
22
23/// @file
24/// The ODBC driver's part of binding an output column straight into a growable container: the pre-fetch step
25/// that restores the bound buffer before every fetch, the declared-length lookup that sizes it where the driver
26/// cannot read a bound column again, and the re-read of a bound value of unknown length. The leaf binders'
27/// ODBC overloads (strings, binary) use them; the native SQLite3 driver reads every bound column afresh for each
28/// row and needs none of them.
29
30namespace Lightweight::Driver::Odbc
31{
32
33/// @brief The pre-fetch step of @c PlanBoundBufferRestore: grows the container back to the bound size
34/// and re-binds the column if its storage moved.
35/// @tparam Ops @c SqlBasicStringOperations-shaped buffer operations of @p Container.
36/// @tparam UnitBytes Bytes per element of the bound buffer.
37/// @tparam TerminatorUnits Elements the bound buffer has beyond its size for the driver's terminator.
38/// @param step The planned step.
39/// @param statement The statement the column is bound on (an ODBC statement: only the ODBC binders plan the step).
40/// @return @c SqlResult::Success, or the result of re-binding the column.
41/// @throws std::bad_alloc When growing the container back allocates (its storage was moved out); the
42/// fetch reports that as HY001.
43template <typename Ops, typename Container, std::size_t UnitBytes, std::size_t TerminatorUnits>
44SqlResult RestoreBoundBuffer(SqlOutputColumnPreFetch& step, ::Lightweight::Driver::StatementHandle& statement)
45{
46 return VisitRequired(statement, "restoring a bound output column", [&step](Statement& stmt) -> SqlResult {
47 auto* const result = static_cast<Container*>(step.target);
48 auto const size = static_cast<std::size_t>(Ops::Size(result));
49 if (static_cast<void const*>(Ops::Data(result)) != step.boundData)
50 step.boundSize = (std::max) (step.boundSize, size);
51 if (size != step.boundSize)
52 {
53 // The driver overwrites the regrown part, so where the container can skip initializing it
54 // (std::basic_string), it does: a long value grows the bound size, and every later row would
55 // otherwise zero-fill up to it. A vector (binary) zero-fills up to the bound size.
56 if constexpr (requires { Ops::ResizeForOverwrite(result, step.boundSize); })
57 Ops::ResizeForOverwrite(result, step.boundSize);
58 else
59 Ops::Resize(result, static_cast<SQLLEN>(step.boundSize));
60 }
61 auto* const data = Ops::Data(result);
62 if (static_cast<void const*>(data) == step.boundData)
63 return SqlResult::Success;
64 auto const rc = SQLBindCol(stmt.handle,
65 step.column,
66 step.cType,
67 static_cast<SQLPOINTER>(data),
68 static_cast<SQLLEN>((step.boundSize + TerminatorUnits) * UnitBytes),
69 step.indicator);
70 // Recorded only once bound: after a failed bind the next fetch must try again, not fetch through the
71 // binding of the storage that moved away.
72 if (SQL_SUCCEEDED(rc))
73 step.boundData = data;
74 return ToResult(rc);
75 });
76}
77
78// DeclaredBoundColumnSize(), part of the SqlDriver concept, is in Statement.hpp.
79
80/// @brief Fails the fetch of a bound value longer than its buffer that the driver cannot read again.
81///
82/// The binders' post-processing reads such a value with @c SQLGetData; a driver without
83/// @c SQL_GD_BOUND (MS SQL Server) refuses that for a bound column. Rather than return the value
84/// truncated to the buffer, the fetch fails with this error (SQLSTATE 22001).
85///
86/// @param stmt The statement the column is bound on (its diagnostic names the driver's reason).
87/// @param column The 1-based column index.
88/// @param totalLength The value's length as the driver reported it, in bytes, or @c SQL_NO_TOTAL.
89[[noreturn]] inline void ThrowBoundValueNotReadable(SQLHSTMT stmt, SqlColumnIndex column, SQLLEN totalLength)
90{
91 auto info = Diagnose(Statement { .handle = stmt });
92 // 22001 (string data, right truncation) names what happened to the value; the driver's own
93 // state for the refused re-read (e.g. 07009 on SQL Server) only says why it could not be avoided.
94 info.sqlState = "22001";
95 info.nativeErrorCode = 0;
96 auto const length =
97 totalLength == SQL_NO_TOTAL ? std::string { "length unknown" } : std::format("{} bytes", totalLength);
98 info.message = std::format("Column {}: the value ({}) is longer than its bound buffer, and the driver cannot "
99 "read a bound column again (no SQL_GD_BOUND). Read the column with GetColumn(), or "
100 "size the bound variable to the longest value before binding it. ({})",
101 column,
102 length,
103 info.message);
104 throw SqlException(std::move(info));
105}
106
107/// @brief Reads a bound value again in full that the driver reported longer than its buffer without
108/// saying how long (@c SQL_NO_TOTAL), in chunks through @p getData, doubling @p result as it goes.
109///
110/// Only a row whose value overflowed its bound buffer gets here. The container keeps its grown size, so
111/// the caller decides what the value's length means for it, and re-binds the column if the container's
112/// storage moved (see @c PlanBoundBufferRestore), also when this throws.
113///
114/// @tparam Ops @c SqlBasicStringOperations-shaped buffer operations of @p Container.
115/// @tparam UnitBytes Bytes per element of the buffer.
116/// @tparam TerminatorUnits Elements the bound buffer has beyond its size for the driver's terminator.
117/// @param stmt The statement the column is bound on (for the driver's diagnostic).
118/// @param column The 1-based column index.
119/// @param cType The C data type the column is bound as; a character type takes one element of each
120/// chunk for its terminator.
121/// @param result The bound container.
122/// @param indicator The column's length/indicator buffer; set to the value's length in bytes.
123/// @param getData Reads the next chunk: @c SQLGetData of the column as @p cType, given the target, its
124/// length in bytes and the indicator.
125/// @param maxBytes The most bytes the container grows to.
126/// @return The value's length in elements; 0 for a NULL, which leaves @p indicator at @c SQL_NULL_DATA (a
127/// column unbound after a failed re-bind is read through here, NULL rows included).
128/// @throws SqlException 22001 when the driver cannot read the bound column again (see
129/// @c ThrowBoundValueNotReadable) or the value exceeds @p maxBytes; HY000 when the driver reports
130/// a length that contradicts the call.
131template <typename Ops, std::size_t UnitBytes, std::size_t TerminatorUnits, typename Container, typename GetData>
132std::size_t ReadBoundValueOfUnknownLength(SQLHSTMT stmt,
133 SqlColumnIndex column,
134 SQLSMALLINT cType,
135 Container* result,
136 SQLLEN* indicator,
137 GetData const& getData,
138 std::size_t maxBytes = ::Lightweight::detail::MaxUnknownLengthValueBytes)
139{
140 using ::Lightweight::detail::DefaultBoundColumnSize;
141 using ::Lightweight::detail::ThrowBoundValueMisread;
142 auto const terminatorUnits = std::size_t { cType == SQL_C_BINARY ? 0U : 1U };
143 if (Ops::Size(result) < DefaultBoundColumnSize)
144 Ops::Resize(result, static_cast<SQLLEN>(DefaultBoundColumnSize));
145 auto read = std::size_t { 0 };
146 auto first = true;
147 while (true)
148 {
149 auto const units = Ops::Size(result) - read + TerminatorUnits;
150 auto const rv =
151 getData(static_cast<SQLPOINTER>(Ops::Data(result) + read), static_cast<SQLLEN>(units * UnitBytes), indicator);
152 if (rv == SQL_NO_DATA)
153 {
154 // All of it was delivered by the previous chunk. On the first call nothing was: the driver
155 // does not read the bound column again.
156 if (first)
157 ThrowBoundValueNotReadable(stmt, column, SQL_NO_TOTAL);
158 break;
159 }
160 if (!SQL_SUCCEEDED(rv))
161 ThrowBoundValueNotReadable(stmt, column, SQL_NO_TOTAL);
162 if (first && *indicator == SQL_NULL_DATA)
163 return 0; // a NULL: nothing to read, the indicator says so
164 first = false;
165 if (rv == SQL_SUCCESS)
166 {
167 // The last chunk: its indicator is its length, which fits what was offered.
168 if (*indicator < 0 || std::cmp_greater(*indicator, (units - terminatorUnits) * UnitBytes))
169 ThrowBoundValueMisread(column, "HY000", std::format("the driver reported {} bytes", *indicator));
170 read += static_cast<std::size_t>(*indicator) / UnitBytes;
171 break;
172 }
173 read += units - terminatorUnits; // a full chunk: there is more
174 if (Ops::Size(result) * 2 * UnitBytes > maxBytes)
175 ThrowBoundValueMisread(column, "22001", std::format("it is longer than {} bytes", maxBytes));
176 Ops::Resize(result, static_cast<SQLLEN>(Ops::Size(result) * 2));
177 }
178 *indicator = static_cast<SQLLEN>(read * UnitBytes);
179 return read;
180}
181
182/// @brief @c ReadBoundValueOfUnknownLength reading through @c SQLGetData.
183/// @return The value's length in elements.
184template <typename Ops, std::size_t UnitBytes, std::size_t TerminatorUnits, typename Container>
186 SQLHSTMT stmt, SqlColumnIndex column, SQLSMALLINT cType, Container* result, SQLLEN* indicator)
187{
188 return ReadBoundValueOfUnknownLength<Ops, UnitBytes, TerminatorUnits>(
189 stmt, column, cType, result, indicator, [&](SQLPOINTER target, SQLLEN length, SQLLEN* lengthIndicator) {
190 return SQLGetData(stmt, column, cType, target, length, lengthIndicator);
191 });
192}
193
194/// @brief Keeps an output column that is bound straight into a growable container bound for every
195/// fetch of the result set.
196///
197/// The binder's post-processing shrinks the container to each row's length, so before the next
198/// fetch it is grown back to the bound size. When its storage moved — a truncation re-fetch grew it,
199/// or the caller moved the value out — the column is re-bound to the new storage, at the larger of
200/// the old bound size and the container's current size. Per row this is a size compare and a pointer
201/// compare when nothing changed; growing back within the retained capacity allocates nothing, and
202/// planning the step allocates nothing either (see @c SqlOutputColumnPreFetch).
203///
204/// @tparam Ops @c SqlBasicStringOperations-shaped buffer operations of @p Container.
205/// @tparam UnitBytes Bytes per element of the bound buffer.
206/// @tparam TerminatorUnits Elements the bound buffer has beyond its size for the driver's terminator.
207/// @param column The 1-based column index.
208/// @param cType The C data type the column is bound as.
209/// @param result The bound container.
210/// @param indicator The column's length/indicator buffer.
211/// @param cb The binder callback the step is planned on.
212template <typename Ops, std::size_t UnitBytes, std::size_t TerminatorUnits, typename Container>
214 SqlColumnIndex column, SQLSMALLINT cType, Container* result, SQLLEN* indicator, SqlDataBinderCallback& cb)
215{
216 auto step = SqlOutputColumnPreFetch {
217 .run = &RestoreBoundBuffer<Ops, Container, UnitBytes, TerminatorUnits>,
218 .target = result,
219 .boundData = static_cast<void const*>(Ops::Data(result)),
220 .boundSize = static_cast<std::size_t>(Ops::Size(result)),
221 .column = column,
222 .cType = cType,
223 };
224 step.indicator = indicator; // the driver writes through it: the step re-binds the column with it
226}
227
228} // namespace Lightweight::Driver::Odbc
void ThrowBoundValueNotReadable(SQLHSTMT stmt, SqlColumnIndex column, SQLLEN totalLength)
Fails the fetch of a bound value longer than its buffer that the driver cannot read again.
void PlanBoundBufferRestore(SqlColumnIndex column, SQLSMALLINT cType, Container *result, SQLLEN *indicator, SqlDataBinderCallback &cb)
Keeps an output column that is bound straight into a growable container bound for every fetch of the ...
SqlResult RestoreBoundBuffer(SqlOutputColumnPreFetch &step, ::Lightweight::Driver::StatementHandle &statement)
The pre-fetch step of PlanBoundBufferRestore: grows the container back to the bound size and re-binds...
std::size_t ReadBoundValueOfUnknownLength(SQLHSTMT stmt, SqlColumnIndex column, SQLSMALLINT cType, Container *result, SQLLEN *indicator, GetData const &getData, std::size_t maxBytes=::Lightweight::detail::MaxUnknownLengthValueBytes)
Reads a bound value again in full that the driver reported longer than its buffer without saying how ...
decltype(auto) VisitRequired(Handle &&handle, std::string_view operation, F &&f)
Calls f with the held struct when invocable; otherwise throws SqlException(NotSupportedByDriver(id,...
Definition Dispatch.hpp:945
SqlErrorInfo Diagnose(StatementHandle const &statement)
Reads the statement's diagnostics: the first record its last failed call left.
Definition Dispatch.hpp:466
virtual void PlanPreFetchOutputColumn(SqlOutputColumnPreFetch const &step)=0
The ODBC driver's statement handle struct.
Definition Handles.hpp:43
SQLHSTMT handle
The native ODBC statement handle.
Definition Handles.hpp:45
std::string sqlState
The SQLSTATE diagnostic code (5 characters).
Definition SqlError.hpp:33
A step a binder plans to run before every fetch into the output column it binds.
Definition Core.hpp:49
std::size_t boundSize
The element count the column is currently bound with.
Definition Core.hpp:59
SqlIndicator * indicator
The column's length/indicator buffer.
Definition Core.hpp:55
void * target
The bound object the step works on.
Definition Core.hpp:53
void const * boundData
The storage the column is currently bound to.
Definition Core.hpp:57
std::int16_t cType
The driver's C type code the column is bound as.
Definition Core.hpp:63
SqlResult(* run)(SqlOutputColumnPreFetch &step, Driver::StatementHandle &statement)
Runs the step. Returns SqlResult::Success, or the failing result (the fetch then fails with it).
Definition Core.hpp:51
SqlColumnIndex column
The 1-based column index.
Definition Core.hpp:61