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_result.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
9
10#include <QtCore/qvarlengtharray.h>
11#include <QtSql/qsqlfield.h>
12
13#include <algorithm>
14#include <cstring>
15#include <limits>
16
17QT_BEGIN_NAMESPACE
18
19// Firebird OO API types are used throughout; avoid full Firebird:: qualification.
20using namespace Firebird;
21
22using namespace Qt::StringLiterals;
23
24// Helpers used only by the result implementation
25
26// Build columns metadata from IMessageMetadata
27static QList<ColumnInfo> buildColumns(IMessageMetadata *meta, ThrowStatusWrapper &st)
28{
29 QList<ColumnInfo> cols;
30 unsigned count = meta->getCount(&st);
31 cols.reserve(count);
32 for (unsigned i = 0; i < count; ++i) {
33 ColumnInfo ci;
34 ci.name = QString::fromUtf8(meta->getAlias(&st, i));
35 if (ci.name.isEmpty())
36 ci.name = QString::fromUtf8(meta->getField(&st, i));
37 ci.relation = QString::fromUtf8(meta->getRelation(&st, i));
38 ci.field = QString::fromUtf8(meta->getField(&st, i));
39 ci.fbType = static_cast<int>(meta->getType(&st, i));
40 ci.fbSubType = meta->getSubType(&st, i);
41 ci.scale = meta->getScale(&st, i);
42 ci.length = meta->getLength(&st, i);
43 ci.offset = meta->getOffset(&st, i);
44 ci.nullOffset = meta->getNullOffset(&st, i);
45 ci.nullable = (meta->isNullable(&st, i) != FB_FALSE);
46 ci.qtType = fbTypeToQt(ci.fbType, ci.scale);
47 cols.append(ci);
48 }
49 return cols;
50}
51
52/*! \internal
53 Read a BLOB into QByteArray. Uses ThrowStatusWrapper so a read error throws
54 FbException (caught by QFirebirdResult::data) instead of being swallowed and
55 returning a silently truncated buffer.
56*/
57static QByteArray readBlob(IAttachment *att, ITransaction *tra, IStatus *st,
58 const ISC_QUAD &blobId)
59{
60 ThrowStatusWrapper tsw(st);
61 FbGuard<IBlob> blob(att->openBlob(&tsw, tra, const_cast<ISC_QUAD *>(&blobId), 0, nullptr),
62 fbRelease<IBlob>);
63 if (!blob)
64 return {};
65
66 QByteArray result;
67 unsigned char seg[16384];
68 result.reserve(sizeof(seg)); // avoid reallocations for the common small-BLOB case
69 unsigned segLen = 0;
70 int code;
71 /* A getSegment or close failure throws; FbGuard releases the handle on the
72 way out (and closeWith rethrows after releasing on a failed close). */
73 do {
74 code = blob->getSegment(&tsw, sizeof(seg), seg, &segLen);
75 result.append(reinterpret_cast<const char *>(seg), segLen);
76 } while (code == IStatus::RESULT_OK || code == IStatus::RESULT_SEGMENT);
77 blob.closeWith([&](IBlob *b) { b->close(&tsw); });
78 /* The result is handed to the application as is: release the capacity
79 beyond its size, or the reserved buffer would stay pinned behind every
80 value, however small the BLOB. */
81 result.squeeze();
82 return result;
83}
84
85// QFirebirdResultPrivate implementation
86
88{
89 /* Only touch the Firebird handles while the driver is alive AND its
90 attachment is still open. If the connection was closed while this result
91 was still around (QSqlDatabase::close() with a QSqlQuery in scope),
92 detach() has already invalidated the statement/cursor/transaction; if the
93 driver object itself was destroyed (driverAlive == false), the driver
94 private is freed and must not be dereferenced at all. In either case just
95 drop the now-dangling pointers. driverAlive is checked first so att()
96 (which reads the driver private) is never called on a freed driver. */
97 const bool attached = driverAlive && att() != nullptr;
98
99 /* Close a handle gracefully while the attachment is alive (release it if the
100 close throws); when detached, the engine has already invalidated it, so
101 just drop the now-dangling pointer. closeFn performs the type's graceful
102 shutdown (IResultSet::close, IStatement::free, ITransaction::commit). */
103 auto closeHandle = [&](auto *&handle, auto closeFn) {
104 if (!handle)
105 return;
106 if (attached) {
107 try {
108 ThrowStatusWrapper tsw(status());
109 closeFn(handle, tsw);
110 } catch (...) {
111 handle->release();
112 }
113 }
114 handle = nullptr;
115 };
116
117 closeHandle(cursor, [](IResultSet *c, ThrowStatusWrapper &st) { c->close(&st); });
118 closeHandle(stmt, [](IStatement *s, ThrowStatusWrapper &st) { s->free(&st); });
119 closeHandle(autoTrans, [](ITransaction *t, ThrowStatusWrapper &st) { t->commit(&st); });
120
121 if (outMeta) {
122 if (attached)
123 outMeta->release();
124 outMeta = nullptr;
125 }
126 if (inMeta) {
127 if (attached)
128 inMeta->release();
129 inMeta = nullptr;
130 }
131 outBuffer.clear();
132 inBuffer.clear();
133 cols.clear();
134 inCols.clear();
135 arrayDescCache.clear();
136 cachedRecord.clear();
137 recordCached = false;
138 affectedRows = -1;
139 isSelect = false;
140 isProcExec = false;
141 procRowFetched = false;
142 txnOp = TxnOp::None;
143 useRowCache = false;
144 cacheComplete = false;
145 rowCache.clear();
147}
148
150{
152 overflowWarnedFields.clear();
153}
154
155bool QFirebirdResultPrivate::firstOverflowWarning(int row, int field) const
156{
157 if (row != overflowWarnedRow) {
158 overflowWarnedRow = row;
159 overflowWarnedFields.clear();
160 }
161 if (overflowWarnedFields.contains(field))
162 return false;
163 overflowWarnedFields.insert(field);
164 return true;
165}
166
168{
169 if (!cursor)
170 return;
171 try {
172 ThrowStatusWrapper tsw(status());
173 cursor->close(&tsw);
174 } catch (...) {
175 cursor->release();
176 }
177 cursor = nullptr;
178}
179
181{
182 if (index < 0)
183 return false;
184 while (!cacheComplete && rowCache.size() <= index) {
185 ThrowStatusWrapper st(status());
186 /* fetchNext writes into outBuffer; detaching it (COW) on the next
187 iteration keeps the snapshot just appended to rowCache intact. */
188 const int code = cursor->fetchNext(&st, outBuffer.data());
189 if (code == IStatus::RESULT_OK)
190 rowCache.append(outBuffer);
191 else
192 cacheComplete = true; // RESULT_NO_DATA (or non-OK): end of set
193 }
194 return index < rowCache.size();
195}
196
198{
199 QString msg = ctx + u": " + fbErrorString(master(), status());
200 status()->init();
201 return msg;
202}
203
205{
206 // User-managed transaction takes priority.
207 if (drv_d_func()->iTrans)
208 return drv_d_func()->iTrans;
209 if (!autoTrans) {
210 ThrowStatusWrapper st(status());
211 autoTrans = startDefaultTransaction(att(), st, TxnWait::Wait);
212 }
213 return autoTrans;
214}
215
216// QFirebirdResult
217
220{
221 /* Register with the driver so it can neutralise this result if it is
222 destroyed while the result is still alive (see ~QFirebirdDriver). */
223 Q_D(QFirebirdResult);
224 d->drv_d_func()->activeResults.append(d);
225}
226
228{
229 Q_D(QFirebirdResult);
230 d->cleanup();
231}
232
233void QFirebirdResult::cleanup()
234{
235 Q_D(QFirebirdResult);
236 d->cleanup();
237 setAt(QSql::BeforeFirstRow);
238 setActive(false);
239}
240
242{
243 Q_D(const QFirebirdResult);
244 return QVariant::fromValue(d->stmt);
245}
246
247/*! \internal
248 FinishQuery support: QSqlQuery::finish() routes here. Release the server
249 cursor and the client-side row cache, but keep the prepared statement and
250 its metadata caches so exec() can re-run the query without a new prepare().
251 The auto transaction (if any) stays open on purpose: BLOB/array ids already
252 handed to the application remain resolvable until the next exec()/cleanup().
253*/
255{
256 Q_D(QFirebirdResult);
257 d->closeCursor();
258 d->rowCache.clear();
259 d->cacheComplete = false;
260}
261
262/*! \internal
263 Classify a bare transaction-control statement (COMMIT/ROLLBACK [WORK]). These
264 appear in SQL scripts but cannot be executed as DSQL against the driver's
265 managed transaction (Firebird rejects it with "invalid transaction handle");
266 they are applied via the ITransaction API instead. COMMIT/ROLLBACK RETAIN
267 are not treated specially.
268*/
269static TxnOp classifyTxnControl(const QString &query)
270{
271 QString s = query.trimmed();
272 while (s.endsWith(u';'))
273 s.chop(1);
274 s = s.trimmed().toLower().simplified();
275 if (s == "commit"_L1 || s == "commit work"_L1)
276 return TxnOp::Commit;
277 if (s == "rollback"_L1 || s == "rollback work"_L1)
278 return TxnOp::Rollback;
279 return TxnOp::None;
280}
281
282bool QFirebirdResult::prepare(const QString &query)
283{
284 Q_D(QFirebirdResult);
285 cleanup();
286
287 /* Bare COMMIT/ROLLBACK is handled in exec() via the transaction API; don't
288 prepare it as a DSQL statement (the engine rejects executing it against a
289 driver-managed transaction). */
290 if (const TxnOp op = classifyTxnControl(query); op != TxnOp::None) {
291 d->txnOp = op;
292 setSelect(false);
293 return true;
294 }
295
296 const QByteArray utf8 = query.toUtf8();
297 try {
298 ThrowStatusWrapper st(d->status());
299 ITransaction *tr = d->ensureTransaction();
300 d->stmt = d->att()->prepare(&st, tr, 0, utf8.constData(),
301 SQL_DIALECT_V6,
302 IStatement::PREPARE_PREFETCH_METADATA);
303 unsigned flags = d->stmt->getFlags(&st);
304 d->isSelect = (flags & IStatement::FLAG_HAS_CURSOR) != 0;
305 setSelect(d->isSelect); // required: QSqlQuery::next() checks base-class isSelect()
306
307 d->inMeta = d->stmt->getInputMetadata(&st);
308 if (d->inMeta && d->inMeta->getCount(&st) == 0) {
309 d->inMeta->release();
310 d->inMeta = nullptr;
311 }
312 d->outMeta = d->stmt->getOutputMetadata(&st);
313 if (d->outMeta) {
314 if (d->outMeta->getCount(&st) == 0) {
315 d->outMeta->release();
316 d->outMeta = nullptr;
317 } else {
318 d->cols = buildColumns(d->outMeta, st);
319 d->outBuffer.resize(static_cast<qsizetype>(d->outMeta->getAlignedLength(&st)));
320 }
321 }
322 if (!d->isSelect && d->outMeta) {
323 // EXECUTE PROCEDURE with RETURNS clause: expose as single-row result set
324 d->isProcExec = true;
325 setSelect(true);
326 }
327 if (d->inMeta) {
328 d->inBuffer.resize(static_cast<qsizetype>(d->inMeta->getAlignedLength(&st)));
329 d->inCols = buildColumns(d->inMeta, st);
330 }
331 } catch (const FbException &e) {
332 const QSqlError err = fbError(d->master(), e.getStatus(), QSqlError::StatementError);
333 qCInfo(lcFirebird) << "prepare:" << fbErrorLog(err);
334 /* Release any partially-acquired statement/metadata so a failed prepare
335 leaves the result non-executable (exec() guards on a null stmt) instead
336 of running against a half-initialised statement. */
337 d->cleanup();
338 setSelect(false);
339 setLastError(err);
340 return false;
341 }
342 return true;
343}
344
346{
347 if (!inMeta)
348 return true;
349 inBuffer.fill(0);
350 return fillInputBuffer(values, errorText);
351}
352
353bool QFirebirdResultPrivate::encodeScaledNumeric(char *data, int fbType, int scale,
354 const QVariant &val, QString &errorText)
355{
356 /* Numeric/decimal — stored as a scaled integer of the column's width
357 (actual = stored * 10^scale, so stored = value / 10^scale); plain INT128
358 parameters come through here with scale 0. The scaled integer is derived
359 exactly from the value and range-checked for the target width by
360 QtPrivate::sqlScaledFromVariant, which writes the slot only on success;
361 out-of-range values are reported instead of silently wrapped. */
362 switch (fbBaseType(fbType)) {
363 case SQL_INT128:
364 return encodeInt128Slot(val, scale, data, master(), status(), errorText);
365 case SQL_SHORT:
366 return QtPrivate::sqlScaledFromVariant(val, scale, reinterpret_cast<qint16 *>(data),
367 &errorText);
368 case SQL_LONG:
369 return QtPrivate::sqlScaledFromVariant(val, scale, reinterpret_cast<qint32 *>(data),
370 &errorText);
371 default:
372 return QtPrivate::sqlScaledFromVariant(val, scale, reinterpret_cast<qint64 *>(data),
373 &errorText);
374 }
375}
376
377void QFirebirdResultPrivate::writeInlineBlob(ISC_QUAD &blobId, const QByteArray &blobData)
378{
379 /* Create the blob via IAttachment. On failure the handle is released and the
380 exception propagates to exec()/execBatch, which report it — we never bind
381 SQL NULL in place of the caller's data. */
382 ThrowStatusWrapper bst(status());
383 ITransaction *tr = ensureTransaction();
384 FbGuard<IBlob> blob(att()->createBlob(&bst, tr, &blobId, 0, nullptr), fbRelease<IBlob>);
385 const char *src = blobData.constData();
386 qsizetype remaining = blobData.size();
387 while (remaining > 0) {
388 const unsigned segSize = static_cast<unsigned>(
389 std::min(remaining, static_cast<qsizetype>(65535)));
390 blob->putSegment(&bst, segSize, reinterpret_cast<const void *>(src));
391 src += segSize;
392 remaining -= segSize;
393 }
394 /* A putSegment or close failure throws; FbGuard frees the handle on the way
395 out, so the caller's data is never silently replaced with SQL NULL. */
396 blob.closeWith([&](IBlob *b) { b->close(&bst); });
397}
398
400 ITransaction *newTr)
401{
402 if (!newTr || newTr == executedTr)
403 return;
404 /* Update whichever member actually held the executed transaction (it came
405 from ensureTransaction(), so it is exactly one of these), releasing the
406 old handle once and never touching the unrelated transaction — otherwise
407 the stale, engine-invalidated handle would be left for a later
408 double-release. */
409 if (executedTr == drv_d_func()->iTrans) {
410 drv_d_func()->iTrans->release();
411 drv_d_func()->iTrans = newTr;
412 } else if (executedTr == autoTrans) {
413 autoTrans->release();
414 autoTrans = newTr;
415 }
416}
417
418bool QFirebirdResultPrivate::fillInputBuffer(const QList<QVariant> &vals,
419 QString &errorText,
420 BlobWriter blobWriter)
421{
422 if (!inMeta)
423 return true;
424
425 const qsizetype count = inCols.size();
426
427 /* Reject under-binding instead of silently executing the missing
428 parameters as zero-filled NOT NULL values (inBuffer is pre-zeroed, so an
429 unwritten parameter would bind 0/''/epoch rather than fail). Matches the
430 parameter-mismatch error other Qt SQL drivers report. */
431 if (vals.size() < count) {
432 errorText = u"Parameter count mismatch: statement expects %1, %2 bound"_s
433 .arg(count).arg(vals.size());
434 return false;
435 }
436
437 for (qsizetype i = 0; i < count; ++i) {
438 const ColumnInfo &ci = inCols.at(i);
439 short *nullFlag = reinterpret_cast<short *>(inBuffer.data() + ci.nullOffset);
440 const QVariant &val = vals[i];
441
442 /* Decide whether the value is "null". In Qt 6, a QVariant holding a
443 default-constructed value (e.g. QVariant(QString()), QVariant(QDate()))
444 reports isNull()==false even though the contained value is null/invalid,
445 so check the common types explicitly. */
446 bool valueIsNull = val.isNull();
447 if (!valueIsNull) {
448 switch (val.metaType().id()) {
449 case QMetaType::QString: valueIsNull = val.toString().isNull(); break;
450 case QMetaType::QByteArray: valueIsNull = val.toByteArray().isNull(); break;
451 case QMetaType::QDateTime: valueIsNull = !val.toDateTime().isValid(); break;
452 case QMetaType::QDate: valueIsNull = !val.toDate().isValid(); break;
453 case QMetaType::QTime: valueIsNull = !val.toTime().isValid(); break;
454 default: break;
455 }
456 }
457
458 /* Bind SQL NULL whenever the value is null, regardless of whether the
459 target column is nullable. For a NOT NULL column this lets the engine
460 raise its own constraint violation (surfaced as a QSqlError) instead
461 of silently coercing the null to a default (0/''/epoch) and inserting
462 a bogus row. The legacy QIBASE driver substituted the default here,
463 which masked the constraint — see QTBUG-114683. */
464 if (valueIsNull) {
465 *nullFlag = -1; // SQL NULL
466 continue;
467 }
468 *nullFlag = 0;
469
470 char *data = inBuffer.data() + ci.offset;
471
472 // Scaled numerics and INT128 share one exact encoder (INT128 = scale 0).
473 if (ci.scale != 0 || fbBaseType(ci.fbType) == SQL_INT128) {
474 QString numError;
475 if (!encodeScaledNumeric(data, ci.fbType, ci.scale, val, numError)) {
476 errorText = u"Parameter %1: %2"_s.arg(QString::number(i + 1), numError);
477 return false;
478 }
479 continue;
480 }
481
482 switch (fbBaseType(ci.fbType)) {
483 case SQL_SHORT:
484 *reinterpret_cast<qint16 *>(data) = static_cast<qint16>(val.toInt());
485 break;
486 case SQL_LONG:
487 *reinterpret_cast<qint32 *>(data) = static_cast<qint32>(val.toInt());
488 break;
489 case SQL_INT64:
490 *reinterpret_cast<qint64 *>(data) = val.toLongLong();
491 break;
492 case SQL_FLOAT:
493 *reinterpret_cast<float *>(data) = static_cast<float>(val.toDouble());
494 break;
495 case SQL_DOUBLE:
496 *reinterpret_cast<double *>(data) = val.toDouble();
497 break;
498 case SQL_DEC16: {
499 ThrowStatusWrapper innerSt(status());
500 decFloatFromString(master()->getUtilInterface()->getDecFloat16(&innerSt), innerSt,
501 QtPrivate::sqlNumericInputString(val), reinterpret_cast<FB_DEC16 *>(data));
502 break;
503 }
504 case SQL_DEC34: {
505 ThrowStatusWrapper innerSt(status());
506 decFloatFromString(master()->getUtilInterface()->getDecFloat34(&innerSt), innerSt,
507 QtPrivate::sqlNumericInputString(val), reinterpret_cast<FB_DEC34 *>(data));
508 break;
509 }
510 case SQL_BOOLEAN:
511 *reinterpret_cast<FB_BOOLEAN *>(data) =
512 val.toBool() ? FB_TRUE : FB_FALSE;
513 break;
514 case SQL_TYPE_DATE:
515 *reinterpret_cast<ISC_DATE *>(data) =
516 encodeQDate(master()->getUtilInterface(), val.toDate());
517 break;
518 case SQL_TYPE_TIME:
519 *reinterpret_cast<ISC_TIME *>(data) =
520 encodeQTime(master()->getUtilInterface(), val.toTime());
521 break;
522 case SQL_TIMESTAMP:
523 *reinterpret_cast<ISC_TIMESTAMP *>(data) =
524 encodeQDateTime(master()->getUtilInterface(), val.toDateTime());
525 break;
526 case SQL_TIMESTAMP_TZ:
527 *reinterpret_cast<ISC_TIMESTAMP_TZ *>(data) =
528 encodeQDateTimeTz(status(), master()->getUtilInterface(), val.toDateTime());
529 break;
530 case SQL_TIME_TZ:
531 *reinterpret_cast<ISC_TIME_TZ *>(data) =
532 encodeQTimeTz(status(), master()->getUtilInterface(), val.toDateTime());
533 break;
534 case SQL_TEXT:
535 case SQL_VARYING:
536 encodeTextValue(data, ci.fbType, ci.length, val.toString().toUtf8());
537 break;
538 case SQL_BLOB: {
539 const QByteArray blobData = val.toByteArray();
540 ISC_QUAD &blobId = *reinterpret_cast<ISC_QUAD *>(data);
541 if (blobWriter) {
542 /* Batch mode: delegate blob creation to the caller (IBatch::addBlob).
543 A failure must abort the statement, not silently bind SQL NULL. */
544 if (!blobWriter(blobId, blobData)) {
545 errorText = u"Failed to write BLOB for parameter %1"_s.arg(i + 1);
546 return false;
547 }
548 } else {
549 writeInlineBlob(blobId, blobData);
550 }
551 break;
552 }
553 case SQL_ARRAY: {
554 if (val.typeId() != QMetaType::QVariantList) {
555 errorText = u"Cannot bind non-list value to ARRAY parameter %1"_s.arg(i + 1);
556 return false;
557 }
558 ISC_QUAD &arrId = *reinterpret_cast<ISC_QUAD *>(data);
559 ITransaction *tr = ensureTransaction();
560 if (!writeArray(att(), tr, status(), master(), arrayDescCache,
561 &arrId, ci.relation, ci.field, val.toList())) {
562 errorText = u"Failed to write ARRAY parameter %1"_s.arg(i + 1);
563 return false;
564 }
565 break;
566 }
567 default:
568 break;
569 }
570 }
571 return true;
572}
573
574/*! \internal
575 After an EXECUTE PROCEDURE, copy the procedure's output columns back into the
576 bound QSql::Out / QSql::InOut parameters, mapped positionally in declaration
577 order (output column 0 -> first OUT param, and so on). The single-row result
578 set remains available via value(); this just additionally lets callers read
579 the outputs through QSqlQuery::boundValue(). Bind the OUT parameters after
580 the procedure's IN arguments.
581*/
582void QFirebirdResult::writeOutValues()
583{
584 Q_D(QFirebirdResult);
585 if (!d->isProcExec)
586 return;
587 const int columnCount = d->cols.size();
588 const int boundCount = boundValueCount();
589 int outCol = 0;
590 for (int p = 0; p < boundCount && outCol < columnCount; ++p) {
591 const QSql::ParamType type = bindValueType(p);
592 if (type.testFlag(QSql::Out)) {
593 bindValue(p, data(outCol), type);
594 ++outCol;
595 }
596 }
597}
598
600{
601 Q_D(QFirebirdResult);
602
603 /* Bare COMMIT/ROLLBACK: finish the active transaction via the API. A user
604 transaction (iTrans) takes priority; otherwise the auto-transaction. If
605 none is open (e.g. the previous statement already auto-committed) this is
606 a no-op success. The handle is reset so the next statement starts fresh. */
607 if (d->txnOp != TxnOp::None) {
608 ITransaction *&iTrans = d->drv_d_func()->iTrans;
609 ITransaction *tr = iTrans ? iTrans : d->autoTrans;
610 if (tr) {
611 try {
612 ThrowStatusWrapper st(d->status());
613 if (d->txnOp == TxnOp::Commit)
614 tr->commit(&st);
615 else
616 tr->rollback(&st);
617 } catch (const FbException &e) {
618 const QSqlError err = fbError(d->master(), e.getStatus(), QSqlError::TransactionError);
619 qCInfo(lcFirebird) << "exec(txn):" << fbErrorLog(err);
620 setLastError(err);
621 return false;
622 }
623 if (tr == iTrans)
624 iTrans = nullptr;
625 else
626 d->autoTrans = nullptr;
627 }
628 setActive(true);
629 setAt(QSql::AfterLastRow);
630 return true;
631 }
632
633 if (!d->stmt) {
634 setLastError(QSqlError(u"Statement not prepared"_s, QString(), QSqlError::StatementError));
635 return false;
636 }
637
638 /* Reject over-binding: more input values bound than the statement has
639 parameters. OUT-only parameters of a stored procedure are returned in the
640 output message and do not consume an input slot, so exclude them from the
641 count. (Under-binding is rejected in fillInputBuffer.) */
642 {
643 const qsizetype paramCount = d->inMeta ? d->inCols.size() : 0;
644 int inputCount = 0;
645 for (int p = 0, bc = boundValueCount(); p < bc; ++p) {
646 if (bindValueType(p).testFlag(QSql::In))
647 ++inputCount;
648 }
649 if (inputCount > paramCount) {
650 setLastError(QSqlError(
651 u"Parameter count mismatch: statement expects %1 input parameter(s), %2 bound"_s
652 .arg(paramCount).arg(inputCount),
653 QString(), QSqlError::StatementError));
654 return false;
655 }
656 }
657
658 // Close any open cursor from a previous execution
659 d->closeCursor();
660 d->affectedRows = -1;
661 d->resetOverflowWarnings(); // new result set, whatever the statement kind
662
663 try {
664 ThrowStatusWrapper st(d->status());
665 ITransaction *tr = d->ensureTransaction();
666 QString bindError;
667 if (!d->buildInputMessage(bindError)) {
668 setLastError(QSqlError(bindError, QString(), QSqlError::StatementError));
669 return false;
670 }
671
672 if (d->isSelect) {
673 d->cursor = d->stmt->openCursor(&st, tr,
674 d->inMeta,
675 d->inBuffer.isEmpty() ? nullptr : d->inBuffer.data(),
676 d->outMeta,
677 isForwardOnly() ? 0 : IStatement::CURSOR_TYPE_SCROLLABLE);
678 // Opt-in client-side caching applies only to scrollable SELECTs.
679 d->rowCache.clear();
680 d->cacheComplete = false;
681 d->useRowCache = d->drv_d_func()->cacheScrollableResults && !isForwardOnly();
682 setAt(QSql::BeforeFirstRow);
683 setActive(true);
684 } else {
685 d->isProcExec = false;
686 d->procRowFetched = false;
687 /* Zero the output buffer so stale null indicators from a previous
688 execution (e.g. a prior call that returned NULL for a field) don't
689 bleed through when Firebird only writes the value and not the flag. */
690 if (!d->outBuffer.isEmpty())
691 d->outBuffer.fill(0);
692 ITransaction *newTr = d->stmt->execute(&st, tr,
693 d->inMeta,
694 d->inBuffer.isEmpty() ? nullptr : d->inBuffer.data(),
695 d->outMeta,
696 d->outBuffer.isEmpty() ? nullptr : d->outBuffer.data());
697 /* execute() may return a transaction that replaces the one we ran
698 under; adopt it, releasing the replaced handle exactly once. */
699 d->adoptReplacementTransaction(tr, newTr);
700 d->affectedRows = QFirebirdResultPrivate::AffectedPending;
701 if (d->outMeta) {
702 /* EXECUTE PROCEDURE output: expose the filled buffer as a single
703 row (read via value()) and also copy it back to any bound
704 QSql::Out/InOut parameters (read via boundValue()). */
705 d->isProcExec = true;
706 setAt(QSql::BeforeFirstRow);
707 writeOutValues();
708 } else {
709 // Auto-commit non-SELECT statements that used an auto transaction
710 if (d->autoTrans && !d->drv_d_func()->iTrans)
711 finishAndClear(st, d->autoTrans, TxnEnd::Commit);
712 setAt(QSql::AfterLastRow);
713 }
714 setActive(true);
715 }
716 } catch (const FbException &e) {
717 const QSqlError err = fbError(d->master(), e.getStatus(), QSqlError::StatementError);
718 qCInfo(lcFirebird) << "exec:" << fbErrorLog(err);
719 setLastError(err);
720 return false;
721 }
722 return true;
723}
724
725bool QFirebirdResult::execBatch(bool arrayBind)
726{
727 Q_D(QFirebirdResult);
728
729 if (!d->stmt || !d->inMeta) {
730 // No prepared statement or no input parameters — fall back to default loop
731 return QSqlResult::execBatch(arrayBind);
732 }
733
734 const QList<QVariant> &batchValues = d->values;
735 if (batchValues.isEmpty()) {
736 setLastError(QSqlError(u"No values bound for batch execution"_s,
737 QString(), QSqlError::StatementError));
738 return false;
739 }
740
741 const qsizetype paramCount = batchValues.size();
742 const QVariantList firstList = batchValues.at(0).toList();
743 const qsizetype batchCount = firstList.size();
744 if (batchCount == 0)
745 return true;
746
747 // Close any open cursor from a previous execution
748 d->closeCursor();
749 d->affectedRows = -1;
750 d->resetOverflowWarnings(); // new result set, whatever the statement kind
751
752 IUtil *utl = d->master()->getUtilInterface();
753
754 try {
755 ThrowStatusWrapper st(d->status());
756 ITransaction *tr = d->ensureTransaction();
757
758 /* Build batch parameters block. The builder, batch and completion-state
759 handles are freed by FbGuard on every path (including the FbException
760 catch below), so no manual unwinding is needed. */
761 FbGuard<IXpbBuilder> pb(utl->getXpbBuilder(&st, IXpbBuilder::BATCH, nullptr, 0),
762 fbDispose<IXpbBuilder>);
763 pb->insertInt(&st, IBatch::TAG_RECORD_COUNTS, 1);
764
765 // Check if any parameter is a BLOB — enable inline blob IDs
766 bool hasBlobs = false;
767 for (const ColumnInfo &ci : std::as_const(d->inCols)) {
768 if (fbBaseType(ci.fbType) == SQL_BLOB) {
769 hasBlobs = true;
770 break;
771 }
772 }
773 if (hasBlobs)
774 pb->insertInt(&st, IBatch::TAG_BLOB_POLICY, IBatch::BLOB_ID_ENGINE);
775
776 /* Create batch from the prepared statement (pb is disposed by its guard
777 on scope exit; its buffer was already consumed by createBatch). */
778 FbGuard<IBatch> batch(d->stmt->createBatch(&st, d->inMeta,
779 pb->getBufferLength(&st), pb->getBuffer(&st)),
780 fbRelease<IBatch>);
781
782 /* Extract each parameter's value list once before the row loop —
783 toList() per (row, param) would convert the same QVariant for every
784 row of the batch. */
785 QVarLengthArray<QVariantList, 16> paramLists;
786 paramLists.reserve(paramCount);
787 for (qsizetype p = 0; p < paramCount; ++p)
788 paramLists.append(batchValues.at(p).toList());
789
790 for (qsizetype row = 0; row < batchCount; ++row) {
791 QList<QVariant> rowValues;
792 rowValues.reserve(paramCount);
793 for (qsizetype p = 0; p < paramCount; ++p) {
794 const QVariantList &col = paramLists[p];
795 rowValues.append(row < col.size() ? col.at(row) : QVariant());
796 }
797
798 d->inBuffer.fill(0);
799
800 // BlobWriter lambda for batch mode: uses IBatch::addBlob
801 auto blobWriter = [&](ISC_QUAD &blobId, const QByteArray &data) -> bool {
802 try {
803 batch->addBlob(&st, static_cast<unsigned>(data.size()),
804 data.constData(), &blobId, 0, nullptr);
805 return true;
806 } catch (const FbException &e) {
807 const auto berr = fbError(d->master(), e.getStatus(), QSqlError::StatementError);
808 qCWarning(lcFirebird) << "batch addBlob:" << fbErrorLog(berr);
809 return false;
810 }
811 };
812
813 QString bindError;
814 if (!d->fillInputBuffer(rowValues, bindError,
815 hasBlobs ? blobWriter : QFirebirdResultPrivate::BlobWriter{})) {
816 setLastError(QSqlError(bindError, QString(), QSqlError::StatementError));
817 return false; // batch guard releases the handle
818 }
819
820 batch->add(&st, 1, d->inBuffer.data());
821 }
822
823 FbGuard<IBatchCompletionState> cs(batch->execute(&st, tr),
824 fbDispose<IBatchCompletionState>);
825
826 unsigned total = cs->getSize(&st);
827 int totalAffected = 0;
828 bool hadError = false;
829 for (unsigned p = 0; p < total; ++p) {
830 int state = cs->getState(&st, p);
831 if (state == IBatchCompletionState::EXECUTE_FAILED) {
832 hadError = true;
833 } else if (state != IBatchCompletionState::SUCCESS_NO_INFO) {
834 totalAffected += state;
835 } else {
836 // SUCCESS_NO_INFO: count as 1 affected row
837 totalAffected += 1;
838 }
839 }
840 d->affectedRows = totalAffected;
841
842 if (hadError) {
843 unsigned errPos = cs->findError(&st, 0);
844 if (errPos != IBatchCompletionState::NO_MORE_ERRORS) {
845 IStatus *errStatus = d->master()->getStatus();
846 try {
847 cs->getStatus(&st, errStatus, errPos);
848 setLastError(fbError(d->master(), errStatus, QSqlError::StatementError));
849 } catch (...) {
850 setLastError(QSqlError(u"Batch execution failed at message %1"_s
851 .arg(errPos),
852 QString(), QSqlError::StatementError));
853 }
854 errStatus->dispose();
855 } else {
856 /* EXECUTE_FAILED was reported but findError returned no
857 position — should not happen, but never fail silently. */
858 setLastError(QSqlError(u"Batch execution failed"_s,
859 QString(), QSqlError::StatementError));
860 }
861 }
862
863 /* Close the batch gracefully (its guard is dismissed on success, releases
864 on a failed close); the completion state is disposed by its guard on
865 scope exit. */
866 batch.closeWith([&](IBatch *b) { b->close(&st); });
867
868 // Auto-commit if using an auto-transaction
869 if (d->autoTrans && !d->drv_d_func()->iTrans)
870 finishAndClear(st, d->autoTrans, TxnEnd::Commit);
871
872 setAt(QSql::AfterLastRow);
873 setActive(true);
874 return !hadError;
875
876 } catch (const FbException &e) {
877 const QSqlError err = fbError(d->master(), e.getStatus(), QSqlError::StatementError);
878 qCInfo(lcFirebird) << "execBatch:" << fbErrorLog(err);
879 setLastError(err);
880 return false;
881 }
882}
883
884bool QFirebirdResult::reset(const QString &query)
885{
886 if (!prepare(query))
887 return false;
888 return exec();
889}
890
891// ---------- Fetch helpers ----------
892
893/*! \internal
894 Largest non-negative row-position sentinel. Two uses, same value:
895 - passed to ensureCachedRow() to force the cache to pull every remaining row;
896 - the at() position set after fetchLast() on a server-side scrollable cursor,
897 which exposes no row count so the true last index is unknown (QSqlQuery
898 only needs a valid non-negative position; the row data comes from outBuffer).
899*/
900static constexpr int kMaxRowSentinel = 0x7FFFFFFE;
901
902bool QFirebirdResult::fetchCached(int target)
903{
904 Q_D(QFirebirdResult);
905 if (target < 0)
906 return false;
907 try {
908 if (d->ensureCachedRow(target)) {
909 /* Restore the snapshot so data()/isNull() read it unchanged. QByteArray
910 assignment is a cheap COW share, not a copy. */
911 d->outBuffer = d->rowCache.at(target);
912 setAt(target);
913 return true;
914 }
915 } catch (const FbException &e) {
916 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
917 }
918 return false;
919}
920
922{
923 Q_D(QFirebirdResult);
924 if (d->isProcExec) {
925 if (d->procRowFetched)
926 return false;
927 d->procRowFetched = true;
928 setAt(0);
929 return true;
930 }
931 if (!d->cursor)
932 return false;
933 if (d->useRowCache)
934 return fetchCached(at() == QSql::BeforeFirstRow ? 0 : at() + 1);
935 try {
936 ThrowStatusWrapper st(d->status());
937 int code = d->cursor->fetchNext(&st, d->outBuffer.data());
938 if (code == IStatus::RESULT_OK) {
939 setAt(at() == QSql::BeforeFirstRow ? 0 : at() + 1);
940 return true;
941 }
942 } catch (const FbException &e) {
943 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
944 }
945 return false;
946}
947
949{
950 Q_D(QFirebirdResult);
951 if (d->isProcExec) {
952 if (d->procRowFetched)
953 return false;
954 d->procRowFetched = true;
955 setAt(0);
956 return true;
957 }
958 if (!d->cursor)
959 return false;
960 if (d->useRowCache)
961 return fetchCached(0);
962 try {
963 ThrowStatusWrapper st(d->status());
964 int code;
965 if (isForwardOnly())
966 code = d->cursor->fetchNext(&st, d->outBuffer.data());
967 else
968 code = d->cursor->fetchFirst(&st, d->outBuffer.data());
969 if (code == IStatus::RESULT_OK) {
970 setAt(0);
971 return true;
972 }
973 } catch (const FbException &e) {
974 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
975 }
976 return false;
977}
978
980{
981 Q_D(QFirebirdResult);
982 if (d->isProcExec) {
983 // EXECUTE PROCEDURE exposes a single output row at index 0.
984 d->procRowFetched = true;
985 setAt(0);
986 return true;
987 }
988 if (!d->cursor)
989 return false;
990 if (d->useRowCache) {
991 /* Pull the whole set, then position on the real last index. Unlike the
992 server-cursor path below, cache mode therefore gives last() a genuine
993 absolute at() (and lets size() report a row count). */
994 try {
995 d->ensureCachedRow(kMaxRowSentinel);
996 } catch (const FbException &e) {
997 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
998 return false;
999 }
1000 if (d->rowCache.isEmpty())
1001 return false;
1002 return fetchCached(int(d->rowCache.size()) - 1);
1003 }
1004 if (isForwardOnly()) {
1005 /* Forward-only cursors cannot jump to the end, so walk there with
1006 fetchNext(): the last successful fetch leaves the final row in the
1007 buffer with at() at its index. Mirrors QSqlCachedResult. */
1008 if (at() == QSql::AfterLastRow)
1009 return false;
1010 if (!fetchNext())
1011 return false; // empty result set (or already exhausted)
1012 while (fetchNext())
1013 ;
1014 return true;
1015 }
1016 try {
1017 ThrowStatusWrapper st(d->status());
1018 int code = d->cursor->fetchLast(&st, d->outBuffer.data());
1019 if (code == IStatus::RESULT_OK) {
1020 /* The last row's absolute index is unknown (see kMaxRowSentinel), so
1021 use the sentinel as the position: QSqlQuery::value() treats it as
1022 valid and the row data (read from outBuffer) is correct. at() is
1023 therefore NOT a meaningful absolute index after last(); relative
1024 navigation from here (previous()) still returns correct row data
1025 but at() stays sentinel-relative. Use forward iteration from
1026 first()/next() if a true row index is required. */
1027 setAt(kMaxRowSentinel);
1028 return true;
1029 }
1030 } catch (const FbException &e) {
1031 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
1032 }
1033 return false;
1034}
1035
1037{
1038 Q_D(QFirebirdResult);
1039 if (d->isProcExec)
1040 return false; // single-row proc result: nothing precedes the one row
1041 if (!d->cursor)
1042 return false;
1043 if (d->useRowCache) {
1044 if (at() <= 0) {
1045 setAt(QSql::BeforeFirstRow);
1046 return false;
1047 }
1048 return fetchCached(at() - 1);
1049 }
1050 if (isForwardOnly())
1051 return false; // cannot move backwards on a forward-only cursor
1052 try {
1053 ThrowStatusWrapper st(d->status());
1054 int code = d->cursor->fetchPrior(&st, d->outBuffer.data());
1055 if (code == IStatus::RESULT_OK) {
1056 /* The cursor moves correctly and the row data is valid; at() is
1057 decremented from the previous position. After last() the previous
1058 position is the sentinel (see fetchLast), so at() stays
1059 sentinel-relative rather than a true absolute index. */
1060 setAt(at() > 0 ? at() - 1 : QSql::BeforeFirstRow);
1061 return true;
1062 }
1063 } catch (const FbException &e) {
1064 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
1065 }
1066 return false;
1067}
1068
1070{
1071 Q_D(QFirebirdResult);
1072 if (i < 0)
1073 return false;
1074 if (d->isProcExec) {
1075 /* EXECUTE PROCEDURE exposes a single output row at index 0, so only
1076 seek(0) is valid — this makes QSqlQuery::seek()/first() work on
1077 procedure results, not just next(). */
1078 if (i != 0)
1079 return false;
1080 d->procRowFetched = true;
1081 setAt(0);
1082 return true;
1083 }
1084 if (!d->cursor)
1085 return false;
1086 if (d->useRowCache)
1087 return fetchCached(i);
1088 if (isForwardOnly()) {
1089 /* Forward-only cursors have no random access, but absolute *forward*
1090 seeks can be emulated by iterating with fetchNext(). Backward seeks
1091 are rejected by QSqlQuery before reaching here. Mirrors the
1092 forward-only behaviour of QSqlCachedResult. */
1093 if (i < at())
1094 return false;
1095 while (at() < i) {
1096 if (!fetchNext())
1097 return false;
1098 }
1099 return true;
1100 }
1101 // IResultSet supports absolute positioning
1102 try {
1103 ThrowStatusWrapper st(d->status());
1104 int code = d->cursor->fetchAbsolute(&st, i + 1, d->outBuffer.data());
1105 if (code == IStatus::RESULT_OK) {
1106 setAt(i);
1107 return true;
1108 }
1109 } catch (const FbException &e) {
1110 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
1111 }
1112 return false;
1113}
1114
1115// ---------- Data access ----------
1116
1117bool QFirebirdResult::isNull(int field)
1118{
1119 Q_D(const QFirebirdResult);
1120 if (field < 0 || field >= d->cols.size())
1121 return true;
1122 const ColumnInfo &ci = d->cols.at(field);
1123 const short *nullFlag =
1124 reinterpret_cast<const short *>(d->outBuffer.constData() + ci.nullOffset);
1125 qCDebug(lcFirebird, "isNull(%d): nullOffset=%u nullFlag=%d", field, ci.nullOffset, int(*nullFlag));
1126 return *nullFlag != 0;
1127}
1128
1130{
1131 Q_D(const QFirebirdResult);
1132
1133 if (field < 0 || field >= d->cols.size()) {
1134 qCDebug(lcFirebird, "data(%d): out of range, cols.size()=%d", field, int(d->cols.size()));
1135 return {};
1136 }
1137
1138 const ColumnInfo &ci = d->cols.at(field);
1139
1140 /* SQL NULL: return a valid but null QVariant of the correct type.
1141 Returning {} (invalid QVariant) would violate Qt SQL conventions and
1142 break code that checks QVariant::isValid() to detect present-but-null values. */
1143 if (isNull(field)) {
1144 qCDebug(lcFirebird, "data(%d): SQL NULL, fbType=%d qtType=%d", field, ci.fbType, int(ci.qtType));
1145 return QVariant(QMetaType(ci.qtType));
1146 }
1147
1148 qCDebug(lcFirebird, "data(%d): fbType=%d qtType=%d", field, ci.fbType, int(ci.qtType));
1149 const char *ptr = d->outBuffer.constData() + ci.offset;
1150
1151 /* The Firebird OO-API conversions below (IInt128/IDecFloat, BLOB and array
1152 reads) use ThrowStatusWrapper, so any conversion or fetch failure raises
1153 FbException. Catch it here and surface a QSqlError instead of returning a
1154 silently corrupt or truncated value. */
1155 try {
1156 // Scaled numerics — honour numericalPrecisionPolicy (any non-zero scale)
1157 if (ci.scale != 0) {
1158 const auto policy = numericalPrecisionPolicy();
1159 switch (fbBaseType(ci.fbType)) {
1160 case SQL_SHORT:
1161 return QtPrivate::sqlApplyScale(*reinterpret_cast<const qint16 *>(ptr), ci.scale, policy);
1162 case SQL_LONG:
1163 return QtPrivate::sqlApplyScale(*reinterpret_cast<const qint32 *>(ptr), ci.scale, policy);
1164 case SQL_INT128: {
1165 QString overflowText;
1166 const QVariant value = decodeInt128Slot(ptr, ci.scale, policy, d->master(),
1167 d->status(), &overflowText);
1168 // data() runs on every access of the cell: warn once per row and field.
1169 // The single EXECUTE PROCEDURE output row is read at BeforeFirstRow by
1170 // writeOutValues() and at 0 after next(); key it as one row.
1171 const int row = d->isProcExec ? 0 : at();
1172 if (!overflowText.isEmpty() && d->firstOverflowWarning(row, field))
1173 QtPrivate::sqlWarnLowPrecisionOverflow(lcFirebird, overflowText, policy);
1174 return value;
1175 }
1176 default:
1177 return QtPrivate::sqlApplyScale(*reinterpret_cast<const qint64 *>(ptr), ci.scale, policy);
1178 }
1179 }
1180
1181 switch (fbBaseType(ci.fbType)) {
1182 case SQL_SHORT:
1183 return static_cast<int>(*reinterpret_cast<const qint16 *>(ptr));
1184 case SQL_LONG:
1185 return static_cast<int>(*reinterpret_cast<const qint32 *>(ptr));
1186 case SQL_INT64:
1187 return *reinterpret_cast<const qint64 *>(ptr);
1188 case SQL_INT128:
1189 // 128-bit integer → exact decimal string (QVariant has no 128-bit type)
1190 return decodeInt128Slot(ptr, 0, QSql::HighPrecision, d->master(), d->status());
1191 case SQL_FLOAT:
1192 return static_cast<double>(*reinterpret_cast<const float *>(ptr));
1193 case SQL_DOUBLE:
1194 return *reinterpret_cast<const double *>(ptr);
1195 case SQL_DEC16: {
1196 ThrowStatusWrapper st(d->status());
1197 return decFloatToString(d->master()->getUtilInterface()->getDecFloat16(&st), st,
1198 reinterpret_cast<const FB_DEC16 *>(ptr));
1199 }
1200 case SQL_DEC34: {
1201 ThrowStatusWrapper st(d->status());
1202 return decFloatToString(d->master()->getUtilInterface()->getDecFloat34(&st), st,
1203 reinterpret_cast<const FB_DEC34 *>(ptr));
1204 }
1205 case SQL_BOOLEAN:
1206 return *reinterpret_cast<const FB_BOOLEAN *>(ptr) != FB_FALSE;
1207 case SQL_TYPE_DATE:
1208 return decodeFirebirdDate(d->master()->getUtilInterface(),
1209 *reinterpret_cast<const ISC_DATE *>(ptr));
1210 case SQL_TYPE_TIME:
1211 return decodeFirebirdTime(d->master()->getUtilInterface(),
1212 *reinterpret_cast<const ISC_TIME *>(ptr));
1213 case SQL_TIMESTAMP:
1214 return decodeFirebirdTimestamp(d->master()->getUtilInterface(),
1215 *reinterpret_cast<const ISC_TIMESTAMP *>(ptr));
1216 case SQL_TIMESTAMP_TZ:
1217 return decodeFirebirdTimestampTz(d->status(), d->master()->getUtilInterface(),
1218 *reinterpret_cast<const ISC_TIMESTAMP_TZ *>(ptr));
1219 case SQL_TIME_TZ:
1220 return decodeFirebirdTimeTz(d->status(), d->master()->getUtilInterface(),
1221 *reinterpret_cast<const ISC_TIME_TZ *>(ptr));
1222 case SQL_BLOB: {
1223 const ISC_QUAD &blobId = *reinterpret_cast<const ISC_QUAD *>(ptr);
1224 QByteArray ba = readBlob(d->att(), d->activeTransaction(),
1225 d->status(), blobId);
1226 // TEXT blob (sub_type 1) → return as QString
1227 if (ci.fbSubType == 1)
1228 return QString::fromUtf8(ba);
1229 return ba;
1230 }
1231 case SQL_ARRAY: {
1232 const ISC_QUAD &arrayId = *reinterpret_cast<const ISC_QUAD *>(ptr);
1233 ITransaction *tra = d->activeTransaction();
1234 return fetchArray(d->att(), tra, d->status(), d->master(),
1235 d->arrayDescCache, arrayId, ci.relation, ci.field);
1236 }
1237 case SQL_VARYING: {
1238 /* First 2 bytes are the length. Clamp it to the field's data
1239 capacity (byte length minus the 2-byte prefix) so a corrupt or
1240 oversized length indicator cannot read past the row buffer. */
1241 const unsigned short len = *reinterpret_cast<const unsigned short *>(ptr);
1242 const qsizetype maxLen =
1243 std::max(qsizetype(0), static_cast<qsizetype>(ci.length) - 2);
1244 return QString::fromUtf8(ptr + 2, std::min(static_cast<qsizetype>(len), maxLen));
1245 }
1246 case SQL_TEXT: {
1247 /* ci.length is the byte length cached from the output metadata in
1248 buildColumns(); reuse it instead of a per-row getLength() call. */
1249 QString s = QString::fromUtf8(ptr, static_cast<qsizetype>(ci.length));
1250 while (s.endsWith(u' '))
1251 s.chop(1);
1252 return s;
1253 }
1254 default:
1255 qCWarning(lcFirebird, "data: unhandled Firebird type %d for field %d", ci.fbType, field);
1256 return QString::fromUtf8(ptr);
1257 }
1258 } catch (const FbException &e) {
1259 setLastError(fbError(d->master(), e.getStatus(), QSqlError::StatementError));
1260 return {};
1261 }
1262}
1263
1265{
1266 Q_D(const QFirebirdResult);
1267 if (d->recordCached)
1268 return d->cachedRecord;
1269 QSqlRecord rec;
1270 for (const ColumnInfo &ci : d->cols) {
1271 /* Pass the source relation as the field's table name so table-qualified
1272 lookups (QSqlRecord::indexOf("TABLE.COLUMN")) can disambiguate columns
1273 that share a name across joined tables — matching the QIBASE driver. */
1274 QSqlField f(ci.name, QMetaType(ci.qtType), ci.relation);
1275 const int base = fbBaseType(ci.fbType);
1276 if (base == SQL_TEXT || base == SQL_VARYING) {
1277 /* ci.length is the UTF-8 byte length (the connection charset is
1278 UTF-8); report the declared character length instead. Integer
1279 division also absorbs the 2-byte VARYING prefix. */
1280 f.setLength(static_cast<int>(ci.length) / 4);
1281 } else {
1282 f.setLength(static_cast<int>(ci.length));
1283 }
1284 /* Precision (fractional digits) only applies to scaled numeric types;
1285 leave it unset (-1) for everything else. */
1286 if (ci.scale != 0)
1287 f.setPrecision(qAbs(ci.scale));
1288 f.setRequiredStatus(ci.nullable ? QSqlField::Optional : QSqlField::Required);
1289 rec.append(f);
1290 }
1291 d->cachedRecord = rec;
1292 d->recordCached = true;
1293 return rec;
1294}
1295
1297{
1298 Q_D(QFirebirdResult);
1299 /* The row count is only available in cache mode (FB_SCROLLABLE_CACHE=1),
1300 where the result buffers its rows client-side anyway: pull the remaining
1301 rows into the cache and report its size. Firebird cursors cannot report
1302 cardinality without fetching, so every other path returns -1. */
1303 if (!d->useRowCache)
1304 return -1;
1305 if (!d->cacheComplete) {
1306 if (!d->cursor) // e.g. after finish() released the cursor
1307 return -1;
1308 try {
1309 d->ensureCachedRow((std::numeric_limits<int>::max)());
1310 } catch (const FbException &e) {
1311 const QSqlError err = fbError(d->master(), e.getStatus(), QSqlError::StatementError);
1312 qCInfo(lcFirebird) << "size:" << fbErrorLog(err);
1313 setLastError(err);
1314 return -1;
1315 }
1316 }
1317 return int(d->rowCache.size());
1318}
1319
1321{
1322 Q_D(QFirebirdResult);
1323 if (d->affectedRows == QFirebirdResultPrivate::AffectedPending) {
1324 d->affectedRows = -1;
1325 if (d->stmt) {
1326 try {
1327 ThrowStatusWrapper st(d->status());
1328 d->affectedRows = static_cast<int>(d->stmt->getAffectedRecords(&st));
1329 } catch (const FbException &e) {
1330 qCInfo(lcFirebird) << "numRowsAffected:"
1331 << fbErrorLog(fbError(d->master(), e.getStatus(),
1332 QSqlError::StatementError));
1333 d->status()->init();
1334 }
1335 }
1336 }
1337 return d->affectedRows;
1338}
1339
1340QT_END_NAMESPACE
QString formatFbError(const QString &ctx)
void adoptReplacementTransaction(Firebird::ITransaction *executedTr, Firebird::ITransaction *newTr)
bool encodeScaledNumeric(char *data, int fbType, int scale, const QVariant &val, QString &errorText)
bool fillInputBuffer(const QList< QVariant > &vals, QString &errorText, BlobWriter blobWriter={})
static constexpr int NoWarnedRow
bool firstOverflowWarning(int row, int field) const
Firebird::ITransaction * ensureTransaction()
bool buildInputMessage(QString &errorText)
void writeInlineBlob(ISC_QUAD &blobId, const QByteArray &blobData)
bool execBatch(bool arrayBind=false) override
bool fetchNext() override
Positions the result to the next available record (row) in the result.
bool fetchLast() override
Positions the result to the last record (last row) in the result.
QFirebirdResult(const QFirebirdDriver *driver)
bool isNull(int field) override
Returns true if the field at position index in the current row is null; otherwise returns false.
int numRowsAffected() override
Returns the number of rows affected by the last query executed, or -1 if it cannot be determined or i...
void detachFromResultSet() override
bool fetchFirst() override
Positions the result to the first record (row 0) in the result.
QSqlRecord record() const override
Returns the current record if the query is active; otherwise returns an empty QSqlRecord.
bool fetchPrevious() override
Positions the result to the previous record (row) in the result.
bool fetch(int i) override
Positions the result to an arbitrary (zero-based) row index.
int size() override
Returns the size of the SELECT result, or -1 if it cannot be determined or if the query is not a SELE...
bool exec() override
Executes the query, returning true if successful; otherwise returns false.
bool reset(const QString &query) override
Sets the result to use the SQL statement query for subsequent data retrieval.
QVariant data(int field) override
Returns the data for field index in the current row as a QVariant.
QVariant handle() const override
Returns the low-level database handle for this result set wrapped in a QVariant or an invalid QVarian...
bool prepare(const QString &query) override
Prepares the given query for execution; the query will normally use placeholders so that it can be ex...
int fbBaseType(int t)
static TxnOp classifyTxnControl(const QString &query)
static QByteArray readBlob(IAttachment *att, ITransaction *tra, IStatus *st, const ISC_QUAD &blobId)
static constexpr int kMaxRowSentinel
static QList< ColumnInfo > buildColumns(IMessageMetadata *meta, ThrowStatusWrapper &st)