Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qsql_firebird_helpers.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// Copyright (C) 2026 Andreas Bacher
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
6
7#include <QtCore/qtimezone.h>
8#include <QtCore/private/qflatmap_p.h>
9
10#include <firebird/impl/blr.h> // BLR type constants for array element types
11
12#include <algorithm>
13#include <cstring>
14#include <limits>
15#include <iterator>
16
17QT_BEGIN_NAMESPACE
18
19// Firebird OO API types are used throughout; avoid full Firebird:: qualification.
20using namespace Firebird;
21
22Q_LOGGING_CATEGORY(lcFirebird, "qt.sql.firebird")
23
24using namespace Qt::StringLiterals;
25
26// Helper: convert Firebird status to a QSqlError string
27
28QString fbErrorString(IMaster *master, IStatus *status)
29{
30 IUtil *util = master->getUtilInterface();
31 char buf[1024];
32 util->formatStatus(buf, sizeof(buf), status);
33 return QString::fromUtf8(buf);
34}
35
36/*! \internal
37 Convert a Firebird status vector into a QSqlError. `type` is the context in
38 which the error occurred, supplied by the caller (open() -> ConnectionError,
39 prepare()/exec() -> StatementError, begin/commit/rollback ->
40 TransactionError); QSqlError::ErrorType categorises errors by that context,
41 not by the underlying Firebird cause. The SQLCODE is carried through as the
42 native error code.
43*/
44QSqlError fbError(IMaster *master, IStatus *status, QSqlError::ErrorType type)
45{
46 const QString msg = fbErrorString(master, status);
47 const ISC_LONG sqlcode = isc_sqlcode(status->getErrors());
48 const QString code = (sqlcode != -1 && sqlcode != 0)
49 ? QString::number(sqlcode) : QString();
50
51 return QSqlError({}, msg, type, code);
52}
53
54QString fbErrorLog(const QSqlError &err)
55{
56 static const char *typeNames[] = {
57 "NoError", "ConnectionError", "StatementError", "TransactionError", "UnknownError"
58 };
59 const int ti = std::clamp(static_cast<int>(err.type()), 0,
60 static_cast<int>(std::size(typeNames)) - 1);
61 const QString code = err.nativeErrorCode();
62 const QString text = err.databaseText().isEmpty() ? err.driverText() : err.databaseText();
63 return QString::fromLatin1("[%1, %2] %3").arg(QLatin1StringView(typeNames[ti]), code, text);
64}
65
66/*! \internal
67 Commit (or roll back) a transaction whose handle must not outlive a failure:
68 on a throw the interface is released and the member cleared before the
69 rethrow, on success commit/rollback already released it, so the member is
70 cleared too. Taking the handle by reference makes "released implies cleared"
71 structural — every finish site shares this discipline instead of repeating
72 it. (The bare-COMMIT path in exec() intentionally does NOT use this: a
73 failed user COMMIT keeps the still-valid handle so it can be retried.)
74*/
75void finishAndClear(Firebird::ThrowStatusWrapper &st,
76 Firebird::ITransaction *&tr, TxnEnd end)
77{
78 try {
79 if (end == TxnEnd::Commit)
80 tr->commit(&st);
81 else
82 tr->rollback(&st);
83 } catch (...) {
84 tr->release();
85 tr = nullptr;
86 throw;
87 }
88 tr = nullptr;
89}
90
91/*! \internal
92 Start a transaction with the driver's default TPB: read-committed,
93 record-version, read-write. wait selects isc_tpb_wait vs isc_tpb_nowait —
94 the only axis on which the auto-started transaction (wait) and the explicit
95 user transaction (nowait) differ.
96*/
97ITransaction *startDefaultTransaction(IAttachment *att, ThrowStatusWrapper &st,
98 TxnWait wait)
99{
100 const unsigned char tpb[] = {
101 isc_tpb_version3, isc_tpb_write, isc_tpb_read_committed, isc_tpb_rec_version,
102 static_cast<unsigned char>(wait == TxnWait::Wait ? isc_tpb_wait : isc_tpb_nowait)
103 };
104 return att->startTransaction(&st, sizeof(tpb), tpb);
105}
106
107// Map BLR element type (from ISC_ARRAY_DESC) to QMetaType
108QMetaType::Type blrTypeToQt(unsigned char blrType, bool hasScale)
109{
110 switch (blrType) {
111 case blr_text:
112 case blr_varying:
113 case blr_cstring: return QMetaType::QString;
114 case blr_short:
115 case blr_long: return hasScale ? QMetaType::Double : QMetaType::Int;
116 case blr_quad:
117 case blr_int64: return hasScale ? QMetaType::Double : QMetaType::LongLong;
118 case blr_float:
119 case blr_double:
120 case blr_d_float:
121 case blr_dec64:
122 case blr_dec128: return QMetaType::Double;
123 case blr_int128: return QMetaType::QString;
124 case blr_sql_date: return QMetaType::QDate;
125 case blr_sql_time: return QMetaType::QTime;
126 case blr_sql_time_tz: return QMetaType::QDateTime;
127 case blr_timestamp:
128 case blr_timestamp_tz: return QMetaType::QDateTime;
129 case blr_bool: return QMetaType::Bool;
130 /* Note: no blr_blob case. blr_blob (261) exceeds unsigned char range and
131 Firebird has no array-of-BLOB type, so the element dtype is never a blob. */
132 default: return QMetaType::QString;
133 }
134}
135
136// Numeric codecs
137
138QMetaType::Type fbTypeToQt(int fbType, int scale)
139{
140 if (scale != 0) {
141 /* Scaled NUMERIC/DECIMAL. INT128-backed values cannot be faithfully
142 represented as Double, so report them as String. */
143 if (fbBaseType(fbType) == SQL_INT128)
144 return QMetaType::QString;
145 return QMetaType::Double;
146 }
147 switch (fbBaseType(fbType)) {
148 case SQL_SHORT:
149 case SQL_LONG: return QMetaType::Int;
150 case SQL_INT64: return QMetaType::LongLong;
151 case SQL_INT128: return QMetaType::QString; // 128-bit; QVariant has no such type — exact decimal string
152 case SQL_FLOAT: return QMetaType::Double;
153 case SQL_DOUBLE: return QMetaType::Double;
154 case SQL_DEC16:
155 case SQL_DEC34: return QMetaType::QString; // DECFLOAT; no native Qt type
156 case SQL_BOOLEAN: return QMetaType::Bool;
157 case SQL_TYPE_DATE: return QMetaType::QDate;
158 case SQL_TYPE_TIME: return QMetaType::QTime;
159 case SQL_TIMESTAMP:
160 case SQL_TIMESTAMP_TZ:
161 case SQL_TIME_TZ: return QMetaType::QDateTime;
162 case SQL_BLOB: return QMetaType::QByteArray;
163 case SQL_ARRAY: return QMetaType::QVariantList;
164 case SQL_TEXT:
165 case SQL_VARYING: return QMetaType::QString;
166 default:
167 qCWarning(lcFirebird, "fbTypeToQt: unknown Firebird type %d", fbType);
168 return QMetaType::QString;
169 }
170}
171
172// INT128 codec — see the header for the design
173
174#ifndef QSQL_HAS_INT128
175
176// Firebird's IInt128 converts via a caller buffer; 64 chars covers INT128's 39 digits.
177static QString int128SlotToString(const char *slot, int scale, IMaster *master, IStatus *status)
178{
179 ThrowStatusWrapper st(status);
180 char buf[64];
181 master->getUtilInterface()->getInt128(&st)->toString(
182 &st, reinterpret_cast<const FB_I128 *>(slot), scale, sizeof(buf), buf);
183 return QString::fromLatin1(buf);
184}
185
186#endif // QSQL_HAS_INT128
187
188bool encodeInt128Slot(const QVariant &val, int scale, char *slot,
189 IMaster *master, IStatus *status, QString &errorText)
190{
191#ifdef QSQL_HAS_INT128
192 Q_UNUSED(master);
193 Q_UNUSED(status);
194 qinternalint128 v = 0;
195 if (!QtPrivate::sqlScaledFromVariant(val, scale, &v, &errorText))
196 return false;
197 /* FB_I128 is two 64-bit words, fb_data[0] low and fb_data[1] high, at
198 8-byte alignment in the message buffer: copy the words, never dereference
199 a 16-byte-aligned type in place. */
200 static_assert(std::is_same_v<ISC_UINT64, quint64>,
201 "the FB_I128 words are written through quint64 pointers");
202 FB_I128 raw;
203 QtPrivate::sqlInt128ToWords(v, &raw.fb_data[0], &raw.fb_data[1]);
204 std::memcpy(slot, &raw, sizeof(raw));
205 return true;
206#else
207 /* No 128-bit integer type: let IInt128::fromString scale the decimal
208 string. It would also accept exponent notation, so pre-validate with
209 the exact codec's grammar (the same canonical text, so a Bool is "1" here
210 too), and report its out-of-range exception with the exact codec's
211 wording - "out of range" for an integral input, "cannot encode" for text.
212 Both builds then accept the same values and fail with the same message. */
213 const QByteArray strVal = QtPrivate::sqlNumericInputString(val);
214 if (!QtPrivate::sqlIsPlainDecimal(strVal)) {
215 errorText = QtPrivate::sqlCannotEncodeError(strVal, scale);
216 return false;
217 }
218 try {
219 ThrowStatusWrapper st(status);
220 master->getUtilInterface()->getInt128(&st)->fromString(
221 &st, scale, strVal.constData(), reinterpret_cast<FB_I128 *>(slot));
222 return true;
223 } catch (const FbException &) {
224 status->init();
225 errorText = QtPrivate::sqlIsIntegralVariant(val.typeId())
226 ? QtPrivate::sqlOutOfRangeError(val, scale)
227 : QtPrivate::sqlCannotEncodeError(strVal, scale);
228 return false;
229 }
230#endif
231}
232
233QVariant decodeInt128Slot(const char *slot, int scale, QSql::NumericalPrecisionPolicy policy,
234 IMaster *master, IStatus *status, QString *overflowText)
235{
236#ifdef QSQL_HAS_INT128
237 Q_UNUSED(master);
238 Q_UNUSED(status);
239 // Copy the FB_I128 words out of the slot (see encodeInt128Slot for the layout)
240 FB_I128 raw;
241 std::memcpy(&raw, slot, sizeof(raw));
242 const qinternalint128 value = QtPrivate::sqlInt128FromWords(raw.fb_data[0], raw.fb_data[1]);
243 bool overflow = false;
244 const QVariant result = QtPrivate::sqlApplyScale(value, scale, policy, &overflow);
245 // A double beats a wrapped or zero value; the caller decides when to say so.
246 if (overflow && overflowText)
247 *overflowText = QtPrivate::sqlScaledToString(value, scale);
248 return result;
249#else
250 const QString str = int128SlotToString(slot, scale, master, status);
251 switch (policy) {
252 case QSql::HighPrecision:
253 return str;
254 case QSql::LowPrecisionDouble:
255 return QVariant(str.toDouble());
256 case QSql::LowPrecisionInt32:
257 case QSql::LowPrecisionInt64: {
258 /* Take the integer part straight from the decimal string (truncating
259 toward zero) rather than via double, so 128-bit values keep full
260 integer precision up to the target type's range. */
261 const qsizetype dot = str.indexOf(u'.');
262 const QStringView intPart = dot < 0 ? QStringView(str) : QStringView(str).first(dot);
263 bool ok = false;
264 if (policy == QSql::LowPrecisionInt32) {
265 const int v = intPart.toInt(&ok);
266 if (ok)
267 return QVariant(v);
268 } else {
269 const qint64 v = intPart.toLongLong(&ok);
270 if (ok)
271 return QVariant(v);
272 }
273 // Same fallback as the native codec: a double beats a wrapped or zero value.
274 if (overflowText)
275 *overflowText = str;
276 return QVariant(str.toDouble());
277 }
278 }
279 return QVariant(str.toDouble());
280#endif
281}
282
283// ---- Date/time encode helpers ----
284
285ISC_DATE encodeQDate(IUtil *util, const QDate &d)
286{
287 /* An invalid date reaches here when a non-date value is bound to a DATE
288 parameter — most often a date string in a format QVariant can't parse
289 (e.g. "25.05.2020"; QVariant only parses ISO). encodeDate(0,0,0) would
290 produce an out-of-range value the engine rejects ("value exceeds the
291 range for valid dates"). The legacy QIBASE driver instead maps an invalid
292 QDate to ISC_DATE 0 (the 1858-11-17 epoch) and stores it without error;
293 match that so such statements succeed identically. */
294 if (!d.isValid())
295 return 0;
296 return util->encodeDate(static_cast<unsigned>(d.year()),
297 static_cast<unsigned>(d.month()),
298 static_cast<unsigned>(d.day()));
299}
300
301ISC_TIME encodeQTime(IUtil *util, const QTime &t)
302{
303 if (!t.isValid())
304 return 0; // see encodeQDate: invalid time -> midnight, matching QIBASE
305 return util->encodeTime(static_cast<unsigned>(t.hour()),
306 static_cast<unsigned>(t.minute()),
307 static_cast<unsigned>(t.second()),
308 static_cast<unsigned>(t.msec()) * 10);
309}
310
311ISC_TIMESTAMP encodeQDateTime(IUtil *util, const QDateTime &dt)
312{
313 /* A plain TIMESTAMP carries no zone; Firebird just stores whatever wall-clock
314 date/time it is given and returns the same values back verbatim. Treat the
315 QDateTime as naive and pass its date()/time() straight through with no
316 conversion or relabeling - this matches Firebird's own semantics and how
317 other drivers; see decodeFirebirdTimestamp for the matching read side. */
318 ISC_TIMESTAMP ts;
319 ts.timestamp_date = encodeQDate(util, dt.date());
320 ts.timestamp_time = encodeQTime(util, dt.time());
321 return ts;
322}
323
324/*! \internal
325 Firebird names fixed-offset zones by their bare displacement ("+05:30"),
326 while Qt uses "UTC+05:30"-style ids for them. Map between the two so
327 offset-tagged QDateTimes bind and read back cleanly.
328*/
329static QByteArray toFirebirdZoneId(const QTimeZone &zone)
330{
331 QByteArray id = zone.id();
332 if (id.size() > 3 && id.startsWith("UTC") && (id.at(3) == '+' || id.at(3) == '-'))
333 id.remove(0, 3);
334 return id;
335}
336
337static QTimeZone fromFirebirdZoneId(const QByteArray &id)
338{
339 if (id.isEmpty())
340 return QTimeZone::utc();
341 if (id.at(0) == '+' || id.at(0) == '-')
342 return QTimeZone("UTC" + id);
343 return QTimeZone(id);
344}
345
346/*! \internal
347 QTimeZone for the zone of a decoded TIMESTAMP/TIME WITH TIME ZONE value.
348 Constructing a QTimeZone from its id is a lookup in the system's zone
349 database and by far the most expensive step of decoding such a value, while
350 a result set typically carries only a handful of distinct zones. Firebird's
351 numeric zone id identifies the zone process-wide (region ids are fixed,
352 offset ids encode the displacement), so resolve each id once per thread.
353 tzName is the name fbclient decoded for zoneId.
354*/
355static QTimeZone zoneForFirebirdId(ISC_USHORT zoneId, const char *tzName)
356{
357 static thread_local QVarLengthFlatMap<ISC_USHORT, QTimeZone, 8> zones;
358 const auto it = zones.find(zoneId);
359 if (it != zones.end())
360 return it.value();
361 const QTimeZone zone = fromFirebirdZoneId(QByteArray(tzName));
362 zones.insert(zoneId, zone);
363 return zone;
364}
365
366ISC_TIMESTAMP_TZ encodeQDateTimeTz(IStatus *iStatus, IUtil *util, const QDateTime &dt)
367{
368 ThrowStatusWrapper st(iStatus);
369 ISC_TIMESTAMP_TZ tstz;
370 // Invalid input -> epoch (see encodeQDate), so the engine doesn't reject it.
371 const bool valid = dt.isValid();
372 const QDate d = valid ? dt.date() : QDate(1858, 11, 17);
373 const QTime t = valid ? dt.time() : QTime(0, 0, 0);
374 const QByteArray ianaId =
375 (valid && dt.timeZone().isValid()) ? toFirebirdZoneId(dt.timeZone()) : "UTC"_ba;
376 util->encodeTimeStampTz(&st, &tstz,
377 static_cast<unsigned>(d.year()),
378 static_cast<unsigned>(d.month()),
379 static_cast<unsigned>(d.day()),
380 static_cast<unsigned>(t.hour()),
381 static_cast<unsigned>(t.minute()),
382 static_cast<unsigned>(t.second()),
383 static_cast<unsigned>(t.msec()) * 10,
384 ianaId.constData());
385 return tstz;
386}
387
388ISC_TIME_TZ encodeQTimeTz(IStatus *iStatus, IUtil *util, const QDateTime &dt)
389{
390 ThrowStatusWrapper st(iStatus);
391 ISC_TIME_TZ ttz;
392 const bool valid = dt.isValid();
393 const QTime t = valid ? dt.time() : QTime(0, 0, 0);
394 const QByteArray ianaId =
395 (valid && dt.timeZone().isValid()) ? toFirebirdZoneId(dt.timeZone()) : "UTC"_ba;
396 util->encodeTimeTz(&st, &ttz,
397 static_cast<unsigned>(t.hour()),
398 static_cast<unsigned>(t.minute()),
399 static_cast<unsigned>(t.second()),
400 static_cast<unsigned>(t.msec()) * 10,
401 ianaId.constData());
402 return ttz;
403}
404
405// ---- Date/time decode helpers ----
406
407QDate decodeFirebirdDate(IUtil *util, ISC_DATE date)
408{
409 unsigned year = 0;
410 unsigned month = 0;
411 unsigned day = 0;
412 util->decodeDate(date, &year, &month, &day);
413 return QDate(static_cast<int>(year), static_cast<int>(month), static_cast<int>(day));
414}
415
416QTime decodeFirebirdTime(IUtil *util, ISC_TIME time)
417{
418 unsigned hour = 0;
419 unsigned minute = 0;
420 unsigned sec = 0;
421 unsigned frac = 0;
422 util->decodeTime(time, &hour, &minute, &sec, &frac);
423 return QTime(static_cast<int>(hour), static_cast<int>(minute),
424 static_cast<int>(sec), static_cast<int>(frac / 10));
425}
426
427QDateTime decodeFirebirdTimestamp(IUtil *util, const ISC_TIMESTAMP &ts)
428{
429 /* A plain TIMESTAMP is naive: return its wall-clock date/time components
430 as-is, with no zone conversion or relabeling. This mirrors encodeQDateTime
431 (which stores the input's own date()/time() unmodified) and matches
432 Firebird's own semantics plus common driver behavior */
433 return QDateTime(decodeFirebirdDate(util, ts.timestamp_date),
434 decodeFirebirdTime(util, ts.timestamp_time));
435}
436
437QDateTime decodeFirebirdTimestampTz(IStatus *iStatus, IUtil *util,
438 const ISC_TIMESTAMP_TZ &tstz)
439{
440 CheckStatusWrapper st(iStatus);
441 unsigned year = 0;
442 unsigned month = 0;
443 unsigned day = 0;
444 unsigned hour = 0;
445 unsigned minute = 0;
446 unsigned sec = 0;
447 unsigned frac = 0;
448 char tzName[64] = {};
449 util->decodeTimeStampTz(&st, &tstz, &year, &month, &day, &hour, &minute, &sec, &frac,
450 sizeof(tzName), tzName);
451 const QTimeZone tz = zoneForFirebirdId(tstz.time_zone, tzName);
452 return QDateTime(QDate(static_cast<int>(year), static_cast<int>(month), static_cast<int>(day)),
453 QTime(static_cast<int>(hour), static_cast<int>(minute),
454 static_cast<int>(sec), static_cast<int>(frac / 10)),
455 tz);
456}
457
458QDateTime decodeFirebirdTimeTz(IStatus *iStatus, IUtil *util,
459 const ISC_TIME_TZ &ttz)
460{
461 CheckStatusWrapper st(iStatus);
462 unsigned hour = 0;
463 unsigned minute = 0;
464 unsigned sec = 0;
465 unsigned frac = 0;
466 char tzName[64] = {};
467 util->decodeTimeTz(&st, &ttz, &hour, &minute, &sec, &frac, sizeof(tzName), tzName);
468 const QTimeZone tz = zoneForFirebirdId(ttz.time_zone, tzName);
469 return QDateTime(QDate(1970, 1, 1),
470 QTime(static_cast<int>(hour), static_cast<int>(minute),
471 static_cast<int>(sec), static_cast<int>(frac / 10)),
472 tz);
473}
474
475/*! \internal
476 Encode a UTF-8 string into a CHAR/VARCHAR message slot: VARYING gets a
477 2-byte length prefix, TEXT is space-padded; data beyond the declared length
478 is truncated. Shared by fillInputBuffer and lookupArrayDesc's bind loop so
479 the Firebird text wire format lives in one place.
480*/
481void encodeTextValue(char *data, int fbType, qsizetype length, const QByteArray &bytes)
482{
483 if (fbBaseType(fbType) == SQL_VARYING) {
484 // VARY header: 2-byte length then data
485 const qsizetype len = std::min(length, bytes.size());
486 *reinterpret_cast<unsigned short *>(data) = static_cast<unsigned short>(len);
487 std::memcpy(data + 2, bytes.constData(), len);
488 } else {
489 const qsizetype len = std::min(bytes.size(), length);
490 std::memcpy(data, bytes.constData(), len);
491 if (len < length)
492 std::memset(data + len, ' ', length - len);
493 }
494}
495
496QT_END_NAMESPACE
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
static QString int128SlotToString(const char *slot, int scale, IMaster *master, IStatus *status)
QSqlError fbError(IMaster *master, IStatus *status, QSqlError::ErrorType type)
static QTimeZone zoneForFirebirdId(ISC_USHORT zoneId, const char *tzName)
static QByteArray toFirebirdZoneId(const QTimeZone &zone)
static QTimeZone fromFirebirdZoneId(const QByteArray &id)
QDateTime decodeFirebirdTimestamp(Firebird::IUtil *util, const ISC_TIMESTAMP &ts)
int fbBaseType(int t)
bool encodeInt128Slot(const QVariant &val, int scale, char *slot, Firebird::IMaster *master, Firebird::IStatus *status, QString &errorText)
QString fbErrorLog(const QSqlError &err)
Firebird::ITransaction * startDefaultTransaction(Firebird::IAttachment *att, Firebird::ThrowStatusWrapper &st, TxnWait wait)
QString fbErrorString(Firebird::IMaster *master, Firebird::IStatus *status)
ISC_TIMESTAMP encodeQDateTime(Firebird::IUtil *util, const QDateTime &dt)
ISC_TIME encodeQTime(Firebird::IUtil *util, const QTime &t)
QDate decodeFirebirdDate(Firebird::IUtil *util, ISC_DATE date)
QDateTime decodeFirebirdTimeTz(Firebird::IStatus *iStatus, Firebird::IUtil *util, const ISC_TIME_TZ &ttz)
void encodeTextValue(char *data, int fbType, qsizetype length, const QByteArray &bytes)
void finishAndClear(Firebird::ThrowStatusWrapper &st, Firebird::ITransaction *&tr, TxnEnd end)
QDateTime decodeFirebirdTimestampTz(Firebird::IStatus *iStatus, Firebird::IUtil *util, const ISC_TIMESTAMP_TZ &tstz)
QMetaType::Type blrTypeToQt(unsigned char blrType, bool hasScale)
QTime decodeFirebirdTime(Firebird::IUtil *util, ISC_TIME time)
ISC_TIMESTAMP_TZ encodeQDateTimeTz(Firebird::IStatus *iStatus, Firebird::IUtil *util, const QDateTime &dt)
ISC_TIME_TZ encodeQTimeTz(Firebird::IStatus *iStatus, Firebird::IUtil *util, const QDateTime &dt)
ISC_DATE encodeQDate(Firebird::IUtil *util, const QDate &d)
QMetaType::Type fbTypeToQt(int fbType, int scale)
QVariant decodeInt128Slot(const char *slot, int scale, QSql::NumericalPrecisionPolicy policy, Firebird::IMaster *master, Firebird::IStatus *status, QString *overflowText=nullptr)