Lightweight 0.20261105.1
Loading...
Searching...
No Matches
Data Binder API

Lightweight SQL client is non-intrusively extensible with respect to custom column data types.

A lot of standard types are already supported, but if you need to add a custom type, you can do it by implementing a simple interface.

Custom Column Data Type Binder Example

Suppose you have a custom type CustomType that you want to bind to the SQL statement.

struct CustomType
{
int value;
constexpr auto operator<=>(CustomType const&) const noexcept = default;
};

To bind the custom type to the SQL statement, you need to implement the SqlDataBinder<> specialization for the custom type.

template <>
struct SqlDataBinder<CustomType>
{
/// Define the column type for the custom type, e.g. SqlColumnTypeDefinitions::Guid {}.
static constexpr auto ColumnType = SqlDataBinder<decltype(CustomType::value)>::ColumnType;
/// Binds the custom type to the SQL statement as an input parameter.
static SQLRETURN InputParameter(SQLHSTMT hStmt,
SQLUSMALLINT column,
CustomType const& value,
SqlDataBinderCallback& cb) noexcept
{
return SqlDataBinder<int>::InputParameter(hStmt, column, value.value, cb);
}
/// Binds the custom type to the SQL statement as an output parameter.
///
/// This function is used to bind the custom type to the SQL statement as an output parameter,
/// which means that the SQL statement will return the custom type's value into the `result` parameter.
///
/// @param hStmt The SQL statement handle.
/// @param column The column number.
/// @param result The custom type to bind to the SQL statement.
/// @param indicator The indicator, which is used to determine whether the value is NULL.
/// @param callback The callback that is called after the binding process is completed.
///
/// @see SqlDataBinderCallback
static SQLRETURN OutputColumn(SQLHSTMT hStmt,
SQLUSMALLINT column,
CustomType* result,
SQLLEN* indicator,
SqlDataBinderCallback& callback) noexcept
{
return SqlDataBinder<int>::OutputColumn(hStmt, column, &result->value, indicator, callback);
}
/// Retrieves the custom type's value from the SQL statement's currnt result row at the given column.
///
/// This function is used to retrieve the custom type's value from the SQL statement's current result row at the given column.
///
/// @param hStmt The SQL statement handle.
/// @param column The column number.
/// @param result The custom type to bind to the SQL statement.
/// @param indicator The indicator, which is used to determine whether the value is NULL.
/// @param callback The callback that can be used to access some runtime information.
///
/// @see SqlDataBinderCallback
static SQLRETURN GetColumn(SQLHSTMT hStmt,
SQLUSMALLINT column,
CustomType* result,
SQLLEN* indicator,
SqlDataBinderCallback const& cb) noexcept
{
return SqlDataBinder<int>::GetColumn(hStmt, column, &result->value, indicator, cb);
}
/// Provides a human-readable representation of the custom type.
///
/// This is used purely for debugging purposes.
static std::string Inspect(CustomType const& value) noexcept
{
return std::format("CustomType({})", value.value);
}
};

InputParameter()

The InputParameter() function binds the custom type to the SQL statement as an input parameter.

It is usually sufficient to call one of the already existing SqlDataBinder<T>::InputParameter(...) functions for the underlying type.

Sometimes you may need to perform additional operations, such as converting the custom type to the underlying type, before calling the SqlDataBinder<T>::InputParameter(...) function. Then you can make use of the passed callback to also make sure any additional operations are performed at the end of the binding process.

A binder that binds a copy it made (a converted string, a value in another layout) instead of the caller's value must keep that copy alive for as long as the parameter is bound to it: the driver reads it at every Execute() until the parameter is bound again. Hand the copy to callback.KeepInputParameterAlive(column, buffer) once SQLBindParameter() has succeeded, or wrap the bind in detail::KeepAliveIfBound(), which does exactly that:

static SQLRETURN InputParameter(SQLHSTMT hStmt,
SQLUSMALLINT column,
CustomType const& value,
SqlDataBinderCallback& cb) noexcept
{
auto const copy = std::make_shared<int>(value.value * 10);
return detail::KeepAliveIfBound(
cb, column, copy, SQLBindParameter(hStmt, column, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, copy.get(), 0, nullptr));
}

The statement releases the copy when the parameter is bound again after an execution (a failed one too), when a batch it was bound for has executed, and when the parameter bindings are dropped (a new query is prepared, or a direct query replaces a prepared one). A failed bind hands nothing over, so the previous binding keeps its buffers.

OutputColumn()

The OutputColumn() function binds the custom type to the SQL statement as an output parameter.

It is usually sufficient to call one of the already existing SqlDataBinder<T>::OutputColumn(...)

GetColumn()

The GetColumn() function retrieves the custom type from the SQL statement.

Calling GetColumn() is usually less efficient than calling OutputColumn() because it requires an additional copy operation.

Custom types and block prefetch

By default a connection fetches eligible result sets (all columns numeric, temporal or GUID) in blocks of rows and serves GetColumn<T>() from that block buffer (see "Transparent block-prefetch" in usage.md). The block buffer holds the column's value as a built-in type; it cannot run a custom binder. Where the column type is known before the first fetch, Lightweight keeps such a result set on the per-row path, so the custom binder runs: a column bound with BindOutputColumns(), ExecuteDirectScalar<CustomType>(), and the members of a record read with SqlRowIterator<T>.

A raw GetColumn<CustomType>() on a result set that is already block-prefetched learns the type too late and throws a SqlException (SQLSTATE HY000) instead of returning a wrong value. Two ways out:

  • bind the column with BindOutputColumns() (or BindOutputColumn()) before the first FetchRow(), or
  • disable block prefetch for the connection with SqlConnection::SetDefaultPrefetchDepth(1).

char is handled the same way: its binder reads the column as text, which the block buffer does not do for a numeric column, so GetColumn<char>() on a block-prefetched result set throws HY000 too, while a bound char keeps the per-row path. Reading a built-in type from a column of another kind (for example a REAL column as std::string) follows the rules in "Reading a column as another type under prefetch" in usage.md.

Inspect()

The Inspect() function is used to provide a human-readable representation of the custom type.

This function should be used purely for debugging purposes.

UnwritableYear() (optional)

static std::optional<SQLSMALLINT> UnwritableYear(T const& value) noexcept tells, before anything is bound, that a value holds a date or timestamp whose year cannot be written (a negative year, see below), and returns that year. The binders of SqlDate, SqlDateTime, std::optional, Field, BelongsTo and SqlVariant define it, and a batch that executes row by row checks every row through it before the first one is stored. A custom binder that wraps a date should define it too, forwarding to the date's binder. Without it, its bad rows are still refused with 22008, by the wrapped date's InputParameter(), but in such a batch the rows before the bad one are already stored.

The hook must have exactly this signature. A binder that declares a member named UnwritableYear with another one (returning std::optional<int>, say, or not noexcept) does not compile: SqlBinderChecksYear<T> fails with a static_assert that names the expected signature, rather than skipping the hook and storing the rows before a bad one.

A NULL row in a bound variable

A bound output column that is not a std::optional reads a NULL row as T{}, on every database, per row and under block prefetch alike, so it never keeps the previous row's value. SQL Server's and PostgreSQL's drivers leave a buffer bound in place untouched on NULL, so the statement resets a variable whose type is trivially copyable (the integers, floating point, char, SqlGuid, SqlDate, SqlTime, SqlDateTime, SqlNumeric, and a custom type of that kind) after its binder's own post-processing. A Field or a BelongsTo has the value it wraps reset, so whether it is modified is the same after a NULL row as after any other. A custom binder of a type that is not trivially copyable (one that owns memory) must set the value itself on NULL, in the step it plans with PlanPostProcessOutputColumn(), as the string and binary binders do.

For a trivially copyable custom type:

  • The reset reads the indicator passed to its OutputColumn(). A binder that binds an indicator of its own instead must still write SQL_NULL_DATA (or the length) to the one it was passed, or the reset reads a stale indicator.
  • The reset overwrites whatever the binder wrote into the value on a NULL row (a NULL sentinel, say) with T{}. There is no opt-out; read such a column into a std::optional<T> instead.

<tt>SqlGuid</tt> and <tt>SqlTime</tt>: what a read returns

  • **SqlGuid on SQLite.** SQLite stores a GUID as text. Reading a column whose text is not a GUID (see SqlGuid::TryParse()) as a SqlGuid fails with a SqlException, SQLSTATE 22018 (invalid character value for cast specification), through GetColumn() and a bound output column (the fetch fails). It used to read as the all-zero GUID. A SqlVariant read does not fail: the SQLite driver reports the column as text, so the variant holds a SqlGuid where the text is one, and the text as a std::string otherwise. A variant reads through the SqlGuid binder, and so fails with 22018, only where the driver reports the column as SQL_GUID.
  • **SqlDate and SqlDateTime with a negative year are not written.** SQLite would store text no reader accepts, SQL Server rejects such a date, and PostgreSQL stores a BC date its driver reads back without the sign; so binding one fails with a SqlException, SQLSTATE 22008, also inside a std::optional, a Field or a SqlVariant. A batch checks every row first, also where it executes row by row (a column batch whose range is not contiguous or whose element type has no array binding, a row batch with a column that is not bound in place, an accessor that returns its value by value, or a driver without row-wise parameter arrays), so no row of it is stored. Years 0 to 9999 are written as before (PostgreSQL itself refuses year 0).
  • **SqlTime carries whole seconds.** It is bound as SQL_C_TYPE_TIME, whose structure has no fraction, so after a read the fraction is always 0, on every database and path; a fraction set before writing is not stored.

Integer types: full range on every database

Every built-in integer type round-trips its full range through an input parameter, an output column, GetColumn() and the batch paths, given a column wide enough to hold it:

  • An input parameter declares an SQL type that holds the whole range: int8_t as SMALLINT, uint16_t as INTEGER, uint32_t as BIGINT. SQL Server checks a value against the declared type, so a narrower one rejected -1 as an int8_t and anything above INT32_MAX as a uint32_t with SQLSTATE 22003.
  • The SQLite ODBC driver does not convert the C types of int8_t and uint32_t over their range (it stored -1 as 255 and 4294967295 as -1, and read a uint32_t above INT32_MAX back as INT32_MAX). There, selected by SqlQueryFormatter::ConvertsNarrowIntegerCTypes(), those two binders stage each value through a wider C type: an 8-byte staging buffer per input parameter, one buffer per column of a column-wise batch, one staging value plus a copy per row for an output column. A row-wise ExecuteBatch(rows, accessors...) carrying such a column executes row by row on SQLite, and the DataMapper and FetchAllRowWise() read a record with such a member per row there. PostgreSQL and SQL Server bind them in place, as before.

The column types the DataMapper creates for these records are unchanged (int8_t → TINYINT, uint16_t → SMALLINT, uint32_t → INTEGER), and they do not hold the type's whole range on every database (TINYINT is 0..255 on SQL Server; INTEGER is 32-bit signed on SQL Server and PostgreSQL). Declare a wider column where the full range matters.

On SQLite a staged read checks the range too, on the per-row path and under block prefetch alike: it accepts the type's own range and the form an older version stored (below), and fails with SQLSTATE 22003 for anything else (300 or -129 read as an int8_t, 4294967296 or -2147483649 as a uint32_t), as SQL Server reports a value outside the type. A NULL read into a bound non-optional int8_t or uint32_t sets it to 0, as the block prefetch does. Through PostgreSQL's driver such a read converts without an error. A value passed through BindInputParameter() on SQLite is copied when it is bound, so bind it again after changing it.

SQLite databases written by an older version. Before, int8_t -128..-1 was stored as 128..255 and a uint32_t above INT32_MAX as its negative 32-bit pattern (4294967295 as -1). Those rows read back unchanged: a read into int8_t takes 128..255 as -128..-1, and a read into uint32_t takes -2147483648..-1 as 2147483648..4294967295. The other narrow types (uint8_t, int16_t, uint16_t, bool, char) were stored as they are now. A query that compares such a column with a value (WHERE c = ? with -1) binds the true value, so it does not match the old rows until they are rewritten. Rewriting them once per affected column is recommended, not required for reading; both statements are idempotent:

UPDATE "Table" SET "SmallColumn" = "SmallColumn" - 256 WHERE "SmallColumn" BETWEEN 128 AND 255; -- int8_t
UPDATE "Table" SET "LargeColumn" = "LargeColumn" + 4294967296 WHERE "LargeColumn" < 0; -- uint32_t

<tt>bool</tt>

A bool is never written by the driver into the bool itself: a bool holding any byte but 0 or 1 is undefined behaviour, and PostgreSQL's driver converts a number to SQL_C_BIT by writing its low byte (2 as 2, -1 as 0xFF, 256 as 0). A per-row read (GetColumn, a bound column, ExecuteDirectScalar, SqlRowIterator) reads into a value the statement stages, through the C type that fits the column's described SQL type (a SqlVariant reads a column described as SQL_BIT through the same bool read):

Column type Read as Reads as true / false
integer or bit (BIT, BOOLEAN, SMALLINT … BIGINT) SQL_C_SBIGINT 1 / 0; -1 is true on PostgreSQL (see below); else 22003
floating point or decimal (REAL, FLOAT, NUMERIC …) SQL_C_DOUBLE [1, 2) / [0, 1); else 22003, as ODBC converts to SQL_C_BIT
text and anything else SQL_C_BIT byte 1 / 0 (0xFF as -1 above); else 22003

The block prefetch, including a prefetched SqlVariant of a bit column, applies the same rule to the number it holds, so a single read gives the same result with and without prefetch on every database: anything but 0 and 1 (and -1 on PostgreSQL) fails with 22003. Text goes through SQL_C_BIT because the drivers parse ‘'true’only there (throughSQL_C_SBIGINTSQLite reports it asNULLand PostgreSQL as 0). On SQLite, text in a column described as integer or bit ('true'in aBOOLEANcolumn) therefore reads asNULL, per row as under prefetch; earlier versions read it astrueper row. Choosing the C type costs a look-up of the column's type, which the statement asks the driver once per result set and column; a column bound beforeExecute()describes the prepared statement. ANULLread into a bound non-optionalboolsets it tofalse`, as the block prefetch does.

PostgreSQL: a boolean true as -1. psqlODBC with the connection option TrueIsMinus1=1 reports a BOOLEAN true as -1 (through SQL_C_BIT the byte 0xFF). Since the option is not visible to the library, a bool read on PostgreSQL accepts -1 as true whatever the connection string says (SqlQueryFormatter::BooleanTrueMayBeMinusOne); in particular, -1 in an INTEGER or BIGINT column reads as true there, where it fails with 22003 on SQL Server and SQLite. For single reads, any other number (2, 255, 256, -2 …) still fails with 22003; the row-wise fetch below takes what the driver writes instead.

The row-wise fetch differs. FetchAllRowWise — and the DataMapper's All(), First(n), Range() and the two-record JOIN, which use it for a record whose columns are all fixed-width — binds each record's bool in place as SQL_C_BIT, so it takes what the driver's bit conversion writes, then checks that byte before the record is used: 0 and 1 read as they are, 0xFF as true on PostgreSQL, any other byte fails with 22003. For a number other than 0 or 1 that means:

  • SQL Server fails the row with 22003, as a single read does.
  • PostgreSQL writes the number's low byte: a number whose low byte is 1 or 0xFF reads true (257 and -255 via 0x01; 255, 511, -1 and -257 via 0xFF), one whose low byte is 0 reads false (256, 512, -256), and any other fails with 22003 (2, 254).
  • SQLite writes 1 for any positive number and 0 otherwise: 2, 255 and 256 read true, -1 reads false. A record that also has an int8_t or uint32_t member is read per row on SQLite (see above), so there 2 fails with 22003 as in a single read.
Value in an integer column Single read, with or without prefetch Row-wise: SQL Server PostgreSQL SQLite
2 22003 22003 22003 true
255 22003 22003 true true
256 22003 22003 false true
-1 22003 (true on PostgreSQL) 22003 true false

When a row-wise block fails, the vector keeps the rows of the blocks before it, and none of the failing block.

<tt>SqlNumeric<Precision, Scale></tt> precision limits

Precision is a count of decimal digits. It may be at most Lightweight::SqlMaxNumericPrecision, which is 19 on every supported toolchain:

Toolchain SqlMaxNumericPrecision Widest column
GCC / Clang (native __int128) 19 DECIMAL(19, s) — including MS SQL Server's money
MSVC, clang-cl (software Int128Soft) 19 DECIMAL(19, s) — including MS SQL Server's money

The bound is deliberately toolchain-independent. A column's precision comes from the database schema, so a ddl2cpp-generated record has to compile wherever it is consumed — a header that builds under GCC and fails under MSVC would make the generator useless. Lightweight::Int128, the type that carries the unscaled value, is __int128_t where the compiler has one and a software stand-in (detail::Int128Soft) where it does not.

Scale counts the digits after the decimal point and may be anywhere in [0, Precision]. Scale == Precision is the purely fractional case: SqlNumeric<4, 4> is SQL's DECIMAL(4, 4) and covers [0.0000, 0.9999].

Note that SQL_MAX_NUMERIC_LEN (16) is a byte count, not a digit count — do not use it as a precision bound. It is the size of SQL_NUMERIC_STRUCT::val, a 128-bit mantissa, which is 38 decimal digits. 38 is not the bound either: it is what the ODBC struct could hold, not what this implementation can read back. What narrows it is the readable width — every accessor except ToUnscaledValue() and ToString() divides through long double, so no more digits can be read back through those than that type's significand holds. The widest long double in use is the 80-bit x87 one, whose 64-bit significand gives 19 digits; past that nothing is readable on any platform — a fetched SqlNumeric<20, 0> holding 99999999999999999999 would come back as 100000000000000000000.

A column wider than the bound must be read as a string.

What each accessor delivers

Even inside the bound the accessors do not all carry the same number of digits. For a value obtained by fetching (i.e. one whose mantissa arrived intact):

Accessor Significant digits Notes
ToUnscaledValue() up to Precision Returns Lightweight::Int128. The only accessor that yields the raw integer.
ToString() up to Precision Rendered from the unscaled integer, not by formatting a long double, so every digit survives on every toolchain.
ToLongDouble() 15 guaranteed; up to 19 in practice Bounded by long double: at most 19 (x87 80-bit); 15 where long double is a double (MSVC, Clang on Apple Silicon).
ToDouble(), operator<=> 15 std::numeric_limits<double>::digits10.
ToFloat(), operator== 7 std::numeric_limits<float>::digits10. operator== compares via ToFloat(), so SqlNumeric<19, 4> values 1234567890.1234 and 1234567890.9999 compare equal. Compare ToUnscaledValue() if you need exactness.

So ToUnscaledValue() and ToString() are exact to the declared precision everywhere, including MSVC; the floating-point accessors are not. If you need more than 15 digits out of a SqlNumeric, use one of those two rather than ToDouble().

Neither Int128 implementation is formattable by std::format (the native __int128_t is not either), so render an unscaled value with Lightweight::detail::Int128ToString(value.ToUnscaledValue()), or just use ToString().

How many of those digits survive a round-trip

Declaring a wide Precision does not by itself guarantee that every digit is transferred. What you can rely on:

  • Up to std::numeric_limits<double>::digits10 (15) significant decimal digits: exact everywhere. Every backend and driver combination round-trips such a value unchanged. Beyond that, note that narrowing to 15 significant digits can round into the integral part — 123456789012345.6789 becomes 123456789012346 — so a wide value is not merely "right up to the decimal point".
  • Beyond 15 significant digits: only on the native SQL_C_NUMERIC path. Two independent things can narrow the value to a double (≈15 significant digits):

    • The binder deliberately falls back to SQL_C_DOUBLE for SQLite and MS SQL Server, whose drivers do not handle SQL_NUMERIC_STRUCT usably (see NativeNumericSupportIsBroken). This is why MS SQL Server's own money loses precision on MS SQL Server: its maximum 922337203685477.5807 reads back as 922337203685477.6250.
    • Some driver builds narrow internally even on the native path. The psqlODBC that ships for Windows converts through a double before filling SQL_NUMERIC_STRUCT, so a 19-digit value comes back as the mantissa of its nearest double; the Linux build of the same driver transfers the mantissa verbatim.

    PostgreSQL on Linux is therefore the only combination that carries a full 19-digit value end to end today.

One further limit is independent of the driver: assigning from a float/double — the only value-setting API besides fetching — is bounded by that floating-point type, so SqlNumeric<19, 4> { 922337203685477.5807 } already holds 922337203685477.6250 before any database is involved.

If you need exactness above 15 digits on an arbitrary backend, read the column as a string instead.

How <tt>SqlVariant</tt> decides which alternative to fill

SqlDataBinder<SqlVariant>::GetColumn asks the driver for the column's concise ODBC SQL type code with **SQLDescribeCol** and dispatches into the matching variant alternative. It does not ask SQLColAttribute(SQL_DESC_CONCISE_TYPE), which the SQLite ODBC driver answers with SQL_WCHAR for a BLOB column. A statement asks it once per result set and column, so the rows after the first cost no describe call.

The verbose SQL_DESC_TYPE collapses every datetime subtype into the single value SQL_DATETIME (9) and every interval subtype into SQL_INTERVAL (10), so it cannot distinguish DATE from TIME from TIMESTAMP. The concise type does:

Column kind SQL_DESC_CONCISE_TYPE Variant alternative
DATE SQL_TYPE_DATE (91) SqlDate
TIME SQL_TYPE_TIME (92) SqlTime
TIMESTAMP SQL_TYPE_TIMESTAMP (93) SqlDateTime
DECIMAL / NUMERIC SQL_DECIMAL (3), SQL_NUMERIC (2) SqlDynamicNumeric
BINARY / VARBINARY / LONGVARBINARY SQL_BINARY (-2), SQL_VARBINARY (-3), SQL_LONGVARBINARY (-4) SqlBinary

SQLite: a cell whose value is not of its column's type

SQLite lets a cell hold a value of another type than its column's, such as the text ‘'hello’in anINTEGER` column. The SQLite ODBC driver reports such a cell as NULL when it is read as the column's type. The per-row variant read then reads the cell again as text, so it comes back as the text, and a real NULL stays NULL.

Known limit. A block-prefetched result set cannot read a cell again. A raw cursor.GetColumn<SqlVariant>(column) on a SQLite result set that was already block-prefetched reads such a cell as NULL. The following read it as text:

  • SqlVariantRowCursor, and DataMapper::Query<SqlVariantRow>(), which reads through it;
  • ExecuteDirectScalar<SqlVariant>();
  • any read on a connection with SetDefaultPrefetchDepth(1).

SqlVariantRowCursor and ExecuteDirectScalar<SqlVariant>() keep the result set on the per-row path on SQLite. SQL Server and PostgreSQL enforce column types, so no such cell exists there.

<tt>SqlDynamicNumeric</tt>: exact decimals in a <tt>SqlVariant</tt>

SqlNumeric<Precision, Scale> fixes both at compile time. A value arriving through a SqlVariant learns its precision and scale from the result-set metadata instead, so DECIMAL/NUMERIC columns fill a SqlDynamicNumeric, which carries them alongside the value.

The number is stored as the unscaled integer value * 10^scale and never passes through a binary floating-point type:

auto const amount = value.TryGetNumeric().value();
amount.unscaledValue; // 92233720368547 — exact
amount.scale; // 4
amount.ToString(); // "9223372036.8547"
amount.ToDouble(); // approximation; lossy beyond a double's 15–16 significant digits

TryGetLongLong() still works for a DECIMAL(p, 0) column, which has no fractional part.

Both directions use the column's decimal literal rather than SQL_C_NUMERIC. Retrieving SQL_C_NUMERIC requires the application to publish precision and scale on the descriptor before each call and a driver that honours them — SQL Server returns scale-0 values otherwise, and SQLite has no native SQL_NUMERIC_STRUCT support at all. These are the same two backends SqlDataBinder<SqlNumeric<P, S>> routes around via NativeNumericSupportIsBroken(). Every supported driver converts a decimal column to and from its literal exactly, so the literal is the portable representation.

This is why SqlNumeric<P, S> is not simply reused here. On those same two backends its own binder falls back to SQL_C_DOUBLE, so it is the exact type only where the driver's SQL_NUMERIC_STRUCT support is sound — precisely the backends LASTRADA does not run on. SqlDynamicNumeric also carries precision and scale as runtime values, which a variant filled from a column described only at runtime needs.

When a column does not fit

SqlDynamicNumeric holds the unscaled value in an int64_t, so it represents at most SqlMaxDynamicNumericPrecision (19) significant digits. A wider column — DECIMAL(38, 0) is legal ODBC — cannot be read exactly, and the binder refuses rather than returning a rounded number. The driver does not fail in that case, so no ODBC diagnostic exists to report:

Entry point On an unrepresentable value
GetColumn Throws SqlException with a synthesized SQLSTATE 22003 and a message naming the limit. Reading the statement's last error instead would yield an empty — or stale — diagnostic. Consequently it is not noexcept.
TryGetColumn Returns SQL_ERROR and posts nothing. For callers that can degrade.
SqlVariant Falls back to double, so such a column stays readable (approximately) exactly as it was before this arm became exact.

Retrieving the column is split from interpreting it — ReadLiteral and FromColumnLiteral — because ODBC does not let you read the same column twice. A second SQLGetData is permitted only while a character or binary value is still being delivered in parts; once it has arrived in full, a conforming driver answers SQL_NO_DATA, and SQL Server's and PostgreSQL's both do. So SqlVariant derives the exact value and its double fallback from one retrieved literal rather than re-reading the column.

Because GetColumn can now throw, the generic forwarders that wrap an arbitrary binder — SqlDataBinder<std::optional<T>>, Field<T>, BelongsTo<T> — are no longer noexcept either. They never could honour it: SqlDataBinder<SqlNumeric<P, S>>::GetColumn has always thrown from RequireSuccess on a failed descriptor call, so a std::optional<SqlNumeric<19, 4>> column was a latent std::terminate.

Binary columns keep their own SqlBinary alternative rather than collapsing into std::string: InputParameter dispatches on the alternative, so a value read from a binary column and written straight back must stay distinguishable from text to bind as SQL_C_BINARY instead of SQL_C_CHAR. TryGetBinary() hands back a copy; TryGetStringView() is the zero-copy view over the same bytes.

Driver-specific connection-string requirements

When using SqlVariant (or any binder that dispatches on the driver-reported column type) against PostgreSQL via psqlODBC, the following options must appear in the connection string:

Option Required value What it controls
BoolsAsChar 0 Reports BOOLEAN columns as SQL_BIT so they dispatch into the bool alternative. The driver default reports them as SQL_CHAR.
LFConversion 0 Disables LF↔CRLF translation. Required for byte-exact round-trips of TEXT/VARCHAR values containing \n.

TrueIsMinus1=1 is not required and is accepted: a bool read on PostgreSQL takes the -1 it then reports for a BOOLEAN true as true (see `bool`).

The canonical postgres entry with these options is in scripts/tests/.test-env.yml.