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_array.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
8
9#include <QtCore/qvarlengtharray.h>
10
11#include <firebird/impl/blr.h> // BLR type constants for array element types
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// Query Firebird system tables to populate ISC_ARRAY_DESC using OO API directly
25static bool lookupArrayDesc(IAttachment *att, ITransaction *tra, IStatus *iStatus,
26 IMaster *master, const QByteArray &relName,
27 const QByteArray &fldName, ISC_ARRAY_DESC *desc)
28{
29 std::memset(desc, 0, sizeof(ISC_ARRAY_DESC));
30
31 // ISC_ARRAY_DESC expects space-padded names (31 chars)
32 const QByteArray relPadded = relName.leftJustified(31, ' ');
33 const QByteArray fldPadded = fldName.leftJustified(31, ' ');
34 std::memcpy(desc->array_desc_relation_name, relPadded.constData(), 31);
35 std::memcpy(desc->array_desc_field_name, fldPadded.constData(), 31);
36
37 try {
38 ThrowStatusWrapper st(iStatus);
39
40 /* Run a metadata SELECT with relName/fldName bound as the two text
41 parameters — identifiers may legally contain quotes or non-ASCII, so
42 they are never spliced into the SQL text. rowFn(buf, meta) is invoked
43 for each fetched row until it returns false or the cursor is
44 exhausted. The statement, metadata and cursor handles are freed by
45 FbGuard on every path (close on the happy path, release on a throw)
46 — no manual unwinding needed. */
47 auto runQuery = [&](const QByteArray &sql, auto rowFn) {
48 FbGuard<IStatement> stmtG(
49 att->prepare(&st, tra, 0, sql.constData(), SQL_DIALECT_V6,
50 IStatement::PREPARE_PREFETCH_METADATA),
51 fbRelease<IStatement>);
52
53 FbGuard<IMessageMetadata> inMetaG(stmtG->getInputMetadata(&st),
54 fbRelease<IMessageMetadata>);
55 IMessageMetadata *inMeta = inMetaG.get();
56 QByteArray inBuf(inMeta->getMessageLength(&st), '\0');
57 const QByteArray *binds[2] = { &relName, &fldName };
58 const unsigned paramCount = std::min(inMeta->getCount(&st), 2u);
59 for (unsigned i = 0; i < paramCount; ++i) {
60 char *data = inBuf.data() + inMeta->getOffset(&st, i);
61 *reinterpret_cast<short *>(inBuf.data()
62 + inMeta->getNullOffset(&st, i)) = 0;
63 encodeTextValue(data, static_cast<int>(inMeta->getType(&st, i)),
64 inMeta->getLength(&st, i), *binds[i]);
65 }
66
67 FbGuard<IMessageMetadata> metaG(stmtG->getOutputMetadata(&st),
68 fbRelease<IMessageMetadata>);
69 IMessageMetadata *meta = metaG.get();
70 QByteArray outBuf(meta->getMessageLength(&st), '\0');
71 FbGuard<IResultSet> rsG(
72 stmtG->openCursor(&st, tra, inMeta,
73 reinterpret_cast<unsigned char *>(inBuf.data()),
74 meta, 0),
75 fbRelease<IResultSet>);
76 while (rsG->fetchNext(&st, outBuf.data()) == IStatus::RESULT_OK) {
77 if (!rowFn(outBuf, meta))
78 break;
79 }
80 rsG.closeWith([&](IResultSet *r) { r->close(&st); });
81 stmtG.closeWith([&](IStatement *s) { s->free(&st); });
82 };
83
84 /* Query 1: field type/scale/length and dimension count. The names are
85 compared against the bare CHAR columns — a CHAR comparison ignores
86 the padding and keeps the case of quoted identifiers, and unlike a
87 TRIM() around the column it lets the engine use the system index. */
88 const QByteArray sql1 = QByteArrayLiteral(
89 "SELECT f.RDB$FIELD_TYPE, f.RDB$FIELD_SCALE, f.RDB$FIELD_LENGTH, "
90 "f.RDB$DIMENSIONS "
91 "FROM RDB$RELATION_FIELDS rf "
92 "JOIN RDB$FIELDS f ON f.RDB$FIELD_NAME = rf.RDB$FIELD_SOURCE "
93 "WHERE rf.RDB$RELATION_NAME = ? AND rf.RDB$FIELD_NAME = ?");
94
95 bool found = false;
96 runQuery(sql1, [&](const QByteArray &buf, IMessageMetadata *meta) {
97 const unsigned o0 = meta->getOffset(&st, 0);
98 const unsigned o1 = meta->getOffset(&st, 1);
99 const unsigned o2 = meta->getOffset(&st, 2);
100 const unsigned o3 = meta->getOffset(&st, 3);
101 desc->array_desc_dtype = static_cast<ISC_UCHAR>(
102 *reinterpret_cast<const short *>(buf.constData() + o0));
103 desc->array_desc_scale = static_cast<ISC_SCHAR>(
104 *reinterpret_cast<const short *>(buf.constData() + o1));
105 desc->array_desc_length = static_cast<unsigned short>(
106 *reinterpret_cast<const short *>(buf.constData() + o2));
107 desc->array_desc_dimensions = static_cast<short>(
108 *reinterpret_cast<const short *>(buf.constData() + o3));
109 found = true;
110 return false; // only the first row is needed
111 });
112
113 /* Reject dimension counts the array_desc_bounds array cannot hold
114 (Firebird DDL enforces the same maximum; more means a corrupt or
115 hostile database). */
116 if (!found || desc->array_desc_dimensions <= 0
117 || desc->array_desc_dimensions
118 > static_cast<int>(std::size(desc->array_desc_bounds)))
119 return false;
120
121 // Query 2: dimension bounds.
122 const QByteArray sql2 = QByteArrayLiteral(
123 "SELECT fd.RDB$DIMENSION, fd.RDB$LOWER_BOUND, fd.RDB$UPPER_BOUND "
124 "FROM RDB$RELATION_FIELDS rf "
125 "JOIN RDB$FIELDS f ON f.RDB$FIELD_NAME = rf.RDB$FIELD_SOURCE "
126 "JOIN RDB$FIELD_DIMENSIONS fd ON fd.RDB$FIELD_NAME = f.RDB$FIELD_NAME "
127 "WHERE rf.RDB$RELATION_NAME = ? AND rf.RDB$FIELD_NAME = ? "
128 "ORDER BY fd.RDB$DIMENSION");
129
130 runQuery(sql2, [&](const QByteArray &buf, IMessageMetadata *meta) {
131 const unsigned d0 = meta->getOffset(&st, 0);
132 const unsigned d1 = meta->getOffset(&st, 1);
133 const unsigned d2 = meta->getOffset(&st, 2);
134 const int dim = *reinterpret_cast<const short *>(buf.constData() + d0);
135 if (dim >= 0 && dim < 16) {
136 desc->array_desc_bounds[dim].array_bound_lower =
137 *reinterpret_cast<const short *>(buf.constData() + d1);
138 desc->array_desc_bounds[dim].array_bound_upper =
139 *reinterpret_cast<const short *>(buf.constData() + d2);
140 }
141 return true; // read every row
142 });
143
144 } catch (const FbException &e) {
145 const auto lerr = fbError(master, e.getStatus(), QSqlError::StatementError);
146 qCWarning(lcFirebird) << "lookupArrayDesc:" << fbErrorLog(lerr);
147 iStatus->init();
148 return false;
149 }
150
151 return true;
152}
153
154/*! \internal
155 A column's array descriptor is immutable while the statement lives (it
156 mirrors the column's DDL), so resolve it through a per-result cache:
157 lookupArrayDesc costs two server-side metadata SELECTs per call, which would
158 otherwise be paid for every row fetched and every parameter bound.
159*/
160static bool cachedArrayDesc(IAttachment *att, ITransaction *tra, IStatus *iStatus,
161 IMaster *master,
162 ArrayDescCache &descCache,
163 const QByteArray &relName, const QByteArray &fldName,
164 ISC_ARRAY_DESC *desc)
165{
166 const ArrayFieldKey key = { relName, fldName };
167 const auto it = descCache.constFind(key);
168 if (it != descCache.constEnd()) {
169 *desc = it.value();
170 return true;
171 }
172 if (!lookupArrayDesc(att, tra, iStatus, master, relName, fldName, desc))
173 return false;
174 descCache.insert(key, *desc);
175 return true;
176}
177
178/*! \internal
179 Byte width the array codecs read and write per element of a fixed-width
180 BLR type; 0 for the text types, whose stride is the descriptor's own
181 length, and for types the codecs do not handle.
182*/
183static unsigned fixedElementSize(unsigned char dtype)
184{
185 switch (dtype) {
186 case blr_short: return sizeof(qint16);
187 case blr_long: return sizeof(qint32);
188 case blr_int64: return sizeof(qint64);
189 case blr_int128: return sizeof(FB_I128);
190 case blr_float: return sizeof(float);
191 case blr_double:
192 case blr_d_float: return sizeof(double);
193 case blr_sql_date: return sizeof(ISC_DATE);
194 case blr_sql_time: return sizeof(ISC_TIME);
195 case blr_timestamp: return sizeof(ISC_TIMESTAMP);
196 case blr_timestamp_tz: return sizeof(ISC_TIMESTAMP_TZ);
197 case blr_bool: return sizeof(FB_BOOLEAN);
198 default: return 0;
199 }
200}
201
202/*! \internal
203 Validate the descriptor's dimension bounds and compute the per-dimension
204 element counts and the total slice byte length in 64-bit: bounds come from
205 system tables, and a wrapped or non-positive total would otherwise allocate
206 a short buffer that the read/write helpers overrun. get/putSlice take an
207 int length, so INT_MAX is the hard upper limit. Shared by fetchArray and
208 writeArray so the safety checks cannot drift apart.
209*/
210static bool arraySliceSize(const ISC_ARRAY_DESC &desc, const char *who,
211 const QByteArray &relName, const QByteArray &fldName,
212 QVarLengthArray<int> *numElements, qint64 *bufLen)
213{
214 qint64 arraySize = 1;
215 const short dimensions = desc.array_desc_dimensions;
216 if (numElements)
217 numElements->resize(dimensions);
218 for (short i = 0; i < dimensions; ++i) {
219 const int sub = desc.array_desc_bounds[i].array_bound_upper -
220 desc.array_desc_bounds[i].array_bound_lower + 1;
221 if (sub <= 0) {
222 qCWarning(lcFirebird, "%s: invalid bounds for dimension %d of %s.%s",
223 who, i, relName.constData(), fldName.constData());
224 return false;
225 }
226 if (numElements)
227 (*numElements)[i] = sub;
228 arraySize *= sub;
229 }
230 /* The codecs read and write sizeof(<element type>) bytes per element of a
231 fixed-width type, while the buffer is sized from the metadata-supplied
232 element length: reject a descriptor where the two disagree (corrupt or
233 hostile database), or the element loops would overrun the slice buffer. */
234 if (const unsigned fixed = fixedElementSize(desc.array_desc_dtype);
235 fixed != 0 && desc.array_desc_length != fixed) {
236 qCWarning(lcFirebird, "%s: element length %d of %s.%s does not match its type (%u bytes)",
237 who, int(desc.array_desc_length), relName.constData(), fldName.constData(),
238 fixed);
239 return false;
240 }
241 *bufLen = qint64(desc.array_desc_length) * arraySize;
242 if (*bufLen <= 0 || *bufLen > (std::numeric_limits<int>::max)()) {
243 qCWarning(lcFirebird, "%s: array %s.%s too large (%lld bytes)",
244 who, relName.constData(), fldName.constData(),
245 static_cast<long long>(*bufLen));
246 return false;
247 }
248 return true;
249}
250
251// Recursive: parse flat buffer into QVariantList according to array dimensions
252static const char *readArrayBuffer(QList<QVariant> &list, const char *buffer,
253 short curDim, const int *numElements,
254 ISC_ARRAY_DESC *desc, IMaster *master,
255 IStatus *iStatus)
256{
257 const short dims = desc->array_desc_dimensions;
258 const unsigned char dtype = desc->array_desc_dtype;
259 unsigned short strLen = desc->array_desc_length;
260
261 if (curDim < dims - 1) {
262 // Non-leaf dimension: build sublists
263 for (int i = 0; i < numElements[curDim]; ++i) {
264 QList<QVariant> subList;
265 buffer = readArrayBuffer(subList, buffer, curDim + 1, numElements, desc, master,
266 iStatus);
267 list.append(QVariant(subList));
268 }
269 } else {
270 // Leaf dimension: read actual values directly into list
271 switch (dtype) {
272 case blr_varying:
273 case blr_text: {
274 for (int i = 0; i < numElements[curDim]; ++i) {
275 // Trim trailing spaces and nulls (text/varying delivered as blr_text via SDL)
276 int o = strLen;
277 while (o > 0 && (buffer[o - 1] == ' ' || buffer[o - 1] == '\0'))
278 --o;
279 list.append(QString::fromUtf8(buffer, o));
280 buffer += strLen;
281 }
282 break;
283 }
284 /* Integer elements; a scaled one (NUMERIC/DECIMAL array) surfaces as the
285 double blrTypeToQt reports for it, an unscaled one as the integer. */
286 case blr_short:
287 for (int i = 0; i < numElements[curDim]; ++i) {
288 const auto v = *reinterpret_cast<const qint16 *>(buffer);
289 list.append(QtPrivate::sqlApplyScale(v, desc->array_desc_scale,
290 QSql::LowPrecisionDouble));
291 buffer += sizeof(qint16);
292 }
293 break;
294 case blr_long:
295 for (int i = 0; i < numElements[curDim]; ++i) {
296 const auto v = *reinterpret_cast<const qint32 *>(buffer);
297 list.append(QtPrivate::sqlApplyScale(v, desc->array_desc_scale,
298 QSql::LowPrecisionDouble));
299 buffer += sizeof(qint32);
300 }
301 break;
302 case blr_int64:
303 for (int i = 0; i < numElements[curDim]; ++i) {
304 const auto v = *reinterpret_cast<const qint64 *>(buffer);
305 list.append(QtPrivate::sqlApplyScale(v, desc->array_desc_scale,
306 QSql::LowPrecisionDouble));
307 buffer += sizeof(qint64);
308 }
309 break;
310 case blr_int128:
311 // Exact decimal strings, scaled like the column (see INT128 codec)
312 for (int i = 0; i < numElements[curDim]; ++i) {
313 list.append(decodeInt128Slot(buffer, desc->array_desc_scale,
314 QSql::HighPrecision, master, iStatus));
315 buffer += sizeof(FB_I128);
316 }
317 break;
318 case blr_float:
319 for (int i = 0; i < numElements[curDim]; ++i) {
320 list.append(static_cast<double>(*reinterpret_cast<const float *>(buffer)));
321 buffer += sizeof(float);
322 }
323 break;
324 case blr_double:
325 case blr_d_float:
326 for (int i = 0; i < numElements[curDim]; ++i) {
327 list.append(*reinterpret_cast<const double *>(buffer));
328 buffer += sizeof(double);
329 }
330 break;
331 case blr_sql_date:
332 for (int i = 0; i < numElements[curDim]; ++i) {
333 list.append(decodeFirebirdDate(master->getUtilInterface(),
334 *reinterpret_cast<const ISC_DATE *>(buffer)));
335 buffer += sizeof(ISC_DATE);
336 }
337 break;
338 case blr_sql_time:
339 for (int i = 0; i < numElements[curDim]; ++i) {
340 list.append(decodeFirebirdTime(master->getUtilInterface(),
341 *reinterpret_cast<const ISC_TIME *>(buffer)));
342 buffer += sizeof(ISC_TIME);
343 }
344 break;
345 case blr_timestamp:
346 for (int i = 0; i < numElements[curDim]; ++i) {
347 list.append(decodeFirebirdTimestamp(master->getUtilInterface(),
348 *reinterpret_cast<const ISC_TIMESTAMP *>(buffer)));
349 buffer += sizeof(ISC_TIMESTAMP);
350 }
351 break;
352 case blr_timestamp_tz:
353 for (int i = 0; i < numElements[curDim]; ++i) {
354 list.append(decodeFirebirdTimestampTz(iStatus, master->getUtilInterface(),
355 *reinterpret_cast<const ISC_TIMESTAMP_TZ *>(buffer)));
356 buffer += sizeof(ISC_TIMESTAMP_TZ);
357 }
358 break;
359 case blr_bool:
360 for (int i = 0; i < numElements[curDim]; ++i) {
361 list.append(*reinterpret_cast<const FB_BOOLEAN *>(buffer) != FB_FALSE);
362 buffer += sizeof(FB_BOOLEAN);
363 }
364 break;
365 default:
366 qCWarning(lcFirebird, "readArrayBuffer: unsupported BLR type %d", dtype);
367 buffer += strLen * numElements[curDim];
368 break;
369 }
370 }
371 return buffer;
372}
373
374// Recursive: serialize QVariantList into flat buffer
375static char *createArrayBuffer(char *buffer, const QList<QVariant> &list,
376 QMetaType::Type type, short curDim,
377 ISC_ARRAY_DESC *desc, IMaster *master,
378 IStatus *iStatus, QString &error)
379{
380 ISC_ARRAY_BOUND *bounds = desc->array_desc_bounds;
381 short dim = desc->array_desc_dimensions - 1;
382
383 const qsizetype elements = bounds[curDim].array_bound_upper
384 - bounds[curDim].array_bound_lower + 1;
385 if (list.size() != elements) {
386 error = QString::fromLatin1("Array size mismatch: expected %1, got %2")
387 .arg(elements).arg(list.size());
388 return nullptr;
389 }
390
391 if (curDim != dim) {
392 for (const auto &elem : list) {
393 if (elem.typeId() != QMetaType::QVariantList) {
394 error = u"Array dimensions mismatch"_s;
395 return nullptr;
396 }
397 buffer = createArrayBuffer(buffer, elem.toList(), type, curDim + 1, desc, master,
398 iStatus, error);
399 if (!buffer)
400 return nullptr;
401 }
402 } else {
403 /* Scaled SMALLINT/INTEGER/BIGINT elements (NUMERIC/DECIMAL arrays) map
404 to QMetaType::Double, but the slice holds the backing integer at its
405 own width. Encode each element exactly at that width, like the INT128
406 branch below, so the stride matches the descriptor; the Double case
407 would write 8 bytes into 2- or 4-byte slots. */
408 const unsigned char dtype = desc->array_desc_dtype;
409 const int scale = desc->array_desc_scale;
410 if (scale != 0 && (dtype == blr_short || dtype == blr_long || dtype == blr_int64)) {
411 for (const auto &v : list) {
412 bool ok = false;
413 if (dtype == blr_short) {
414 ok = QtPrivate::sqlScaledFromVariant(v, scale, reinterpret_cast<qint16 *>(buffer),
415 &error);
416 buffer += sizeof(qint16);
417 } else if (dtype == blr_long) {
418 ok = QtPrivate::sqlScaledFromVariant(v, scale, reinterpret_cast<qint32 *>(buffer),
419 &error);
420 buffer += sizeof(qint32);
421 } else {
422 ok = QtPrivate::sqlScaledFromVariant(v, scale, reinterpret_cast<qint64 *>(buffer),
423 &error);
424 buffer += sizeof(qint64);
425 }
426 if (!ok)
427 return nullptr;
428 }
429 return buffer;
430 }
431 switch (type) {
432 case QMetaType::Short:
433 case QMetaType::UShort:
434 case QMetaType::Int:
435 case QMetaType::UInt:
436 if (desc->array_desc_dtype == blr_short) {
437 for (const auto &v : list) {
438 *reinterpret_cast<qint16 *>(buffer) = static_cast<qint16>(v.toInt());
439 buffer += sizeof(qint16);
440 }
441 } else {
442 for (const auto &v : list) {
443 *reinterpret_cast<qint32 *>(buffer) = v.toInt();
444 buffer += sizeof(qint32);
445 }
446 }
447 break;
448 case QMetaType::Float:
449 case QMetaType::Double:
450 if (desc->array_desc_dtype == blr_float) {
451 for (const auto &v : list) {
452 *reinterpret_cast<float *>(buffer) = static_cast<float>(v.toDouble());
453 buffer += sizeof(float);
454 }
455 } else {
456 for (const auto &v : list) {
457 *reinterpret_cast<double *>(buffer) = v.toDouble();
458 buffer += sizeof(double);
459 }
460 }
461 break;
462 case QMetaType::LongLong:
463 for (const auto &v : list) {
464 *reinterpret_cast<qint64 *>(buffer) = v.toLongLong();
465 buffer += sizeof(qint64);
466 }
467 break;
468 case QMetaType::QString:
469 for (const auto &v : list) {
470 if (desc->array_desc_dtype == blr_int128) {
471 // INT128 elements arrive as strings or numbers; encode exactly
472 if (!encodeInt128Slot(v, desc->array_desc_scale, buffer,
473 master, iStatus, error)) {
474 return nullptr;
475 }
476 buffer += sizeof(FB_I128);
477 continue;
478 }
479 if (desc->array_desc_dtype != blr_varying && desc->array_desc_dtype != blr_text) {
480 // Never silently skip: a non-advanced slot misaligns every later element.
481 error = QString::fromLatin1("Unsupported array element type %1 for string values")
482 .arg(static_cast<int>(desc->array_desc_dtype));
483 return nullptr;
484 }
485 const QByteArray utf8 = v.toString().toUtf8();
486 unsigned short len = desc->array_desc_length;
487 // Both varying and text use blr_text format in SDL: raw data, space-padded
488 int copyLen = (std::min)(static_cast<int>(utf8.size()), static_cast<int>(len));
489 std::memcpy(buffer, utf8.constData(), copyLen);
490 if (copyLen < static_cast<int>(len))
491 std::memset(buffer + copyLen, ' ', len - copyLen);
492 buffer += len;
493 }
494 break;
495 case QMetaType::QDate:
496 for (const auto &v : list) {
497 *reinterpret_cast<ISC_DATE *>(buffer) =
498 encodeQDate(master->getUtilInterface(), v.toDate());
499 buffer += sizeof(ISC_DATE);
500 }
501 break;
502 case QMetaType::QTime:
503 for (const auto &v : list) {
504 *reinterpret_cast<ISC_TIME *>(buffer) =
505 encodeQTime(master->getUtilInterface(), v.toTime());
506 buffer += sizeof(ISC_TIME);
507 }
508 break;
509 case QMetaType::QDateTime:
510 for (const auto &v : list) {
511 QDateTime dt = v.toDateTime();
512 if (desc->array_desc_dtype == blr_timestamp_tz) {
513 *reinterpret_cast<ISC_TIMESTAMP_TZ *>(buffer) =
514 encodeQDateTimeTz(iStatus, master->getUtilInterface(), dt);
515 buffer += sizeof(ISC_TIMESTAMP_TZ);
516 } else {
517 *reinterpret_cast<ISC_TIMESTAMP *>(buffer) =
518 encodeQDateTime(master->getUtilInterface(), dt);
519 buffer += sizeof(ISC_TIMESTAMP);
520 }
521 }
522 break;
523 case QMetaType::Bool:
524 for (const auto &v : list) {
525 *reinterpret_cast<FB_BOOLEAN *>(buffer) = v.toBool() ? FB_TRUE : FB_FALSE;
526 buffer += sizeof(FB_BOOLEAN);
527 }
528 break;
529 default:
530 error = QString::fromLatin1("Unsupported array element type %1").arg(static_cast<int>(type));
531 return nullptr;
532 }
533 }
534 return buffer;
535}
536
537/*! \internal
538 Build SDL (Slice Description Language) binary for array get/putSlice.
539 Supports identifiers up to 255 chars (unlike isc_array_gen_sdl which is limited to 31).
540*/
541static QByteArray buildArraySdl(const ISC_ARRAY_DESC &desc,
542 const QByteArray &relationName,
543 const QByteArray &fieldName)
544{
545 QByteArray sdl;
546 sdl.append(char(isc_sdl_version1));
547 // struct with 1 element type descriptor
548 sdl.append(char(isc_sdl_struct));
549 sdl.append(char(1));
550 // BLR-style element type encoding (varies by type)
551 unsigned char dtype = desc.array_desc_dtype;
552 // For varying columns, request text format in SDL to avoid ISC_VARYING prefix complexity
553 unsigned char sdlDtype = (dtype == blr_varying) ? blr_text : dtype;
554 sdl.append(char(sdlDtype));
555 switch (sdlDtype) {
556 case blr_short: // 7: type + scale
557 case blr_long: // 8: type + scale
558 case blr_int64: // 16: type + scale
559 case blr_int128: // 26: type + scale
560 sdl.append(char(desc.array_desc_scale));
561 break;
562 case blr_text: // 14: type + length(2 LE)
563 case blr_varying: // 37: type + length(2 LE)
564 case blr_cstring: // 40: type + length(2 LE)
565 sdl.append(char(desc.array_desc_length & 0xFF));
566 sdl.append(char((desc.array_desc_length >> 8) & 0xFF));
567 break;
568 // Types with no extra bytes: float, double, date, time, timestamp, bool, etc.
569 default:
570 break;
571 }
572 // relation name
573 sdl.append(char(isc_sdl_relation));
574 sdl.append(char(relationName.size()));
575 sdl.append(relationName);
576 // field name
577 sdl.append(char(isc_sdl_field));
578 sdl.append(char(fieldName.size()));
579 sdl.append(fieldName);
580 /* dimension loops (nested: outermost first, each body is next instruction)
581 Use do1 (lower=1) or do2 (explicit lower), NOT do3 (which adds increment) */
582 short dims = desc.array_desc_dimensions;
583 for (short d = 0; d < dims; ++d) {
584 short lo = desc.array_desc_bounds[d].array_bound_lower;
585 short hi = desc.array_desc_bounds[d].array_bound_upper;
586 if (lo == 1) {
587 // do1: only upper bound, lower defaults to 1, increment defaults to 1
588 sdl.append(char(isc_sdl_do1));
589 sdl.append(char(d));
590 } else {
591 // do2: lower + upper bounds, increment defaults to 1
592 sdl.append(char(isc_sdl_do2));
593 sdl.append(char(d));
594 // lower bound
595 if (lo >= -128 && lo <= 127) {
596 sdl.append(char(isc_sdl_tiny_integer));
597 sdl.append(char(static_cast<signed char>(lo)));
598 } else {
599 sdl.append(char(isc_sdl_short_integer));
600 sdl.append(char(lo & 0xFF));
601 sdl.append(char((lo >> 8) & 0xFF));
602 }
603 }
604 // upper bound
605 if (hi >= -128 && hi <= 127) {
606 sdl.append(char(isc_sdl_tiny_integer));
607 sdl.append(char(static_cast<signed char>(hi)));
608 } else {
609 sdl.append(char(isc_sdl_short_integer));
610 sdl.append(char(hi & 0xFF));
611 sdl.append(char((hi >> 8) & 0xFF));
612 }
613 }
614 // element accessor: element 1, scalar 0 ndim, variable per dim
615 sdl.append(char(isc_sdl_element));
616 sdl.append(char(1));
617 sdl.append(char(isc_sdl_scalar));
618 sdl.append(char(0));
619 sdl.append(char(dims));
620 for (short d = 0; d < dims; ++d) {
621 sdl.append(char(isc_sdl_variable));
622 sdl.append(char(d));
623 }
624 sdl.append(char(isc_sdl_eoc));
625 return sdl;
626}
627
628// Fetch array data via OO API (IAttachment::getSlice)
629QVariant fetchArray(IAttachment *att, ITransaction *tra, IStatus *iStatus,
630 IMaster *master,
631 ArrayDescCache &descCache,
632 const ISC_QUAD &arrayId, const QString &relation,
633 const QString &field)
634{
635 QList<QVariant> list;
636 if (arrayId.gds_quad_high == 0 && arrayId.gds_quad_low == 0)
637 return QVariant(list);
638
639 QByteArray relBytes = relation.trimmed().toUtf8();
640 QByteArray fldBytes = field.trimmed().toUtf8();
641
642 ISC_ARRAY_DESC desc;
643 if (!cachedArrayDesc(att, tra, iStatus, master, descCache, relBytes, fldBytes, &desc)) {
644 qCWarning(lcFirebird, "fetchArray: could not look up array descriptor for %s.%s",
645 relBytes.constData(), fldBytes.constData());
646 return QVariant(list);
647 }
648
649 // With blr_text SDL for varying, no +2 prefix needed
650 QVarLengthArray<int> numElements;
651 qint64 bufLen = 0;
652 if (!arraySliceSize(desc, "fetchArray", relBytes, fldBytes, &numElements, &bufLen))
653 return QVariant(list);
654
655 // Generate SDL with original desc_length
656 QByteArray sdlBuf = buildArraySdl(desc, relBytes, fldBytes);
657
658 // Read array data via OO API
659 QByteArray ba(bufLen, '\0');
660 ISC_QUAD id = arrayId;
661 try {
662 ThrowStatusWrapper st(iStatus);
663 int bytesRead = att->getSlice(&st, tra, &id,
664 static_cast<unsigned>(sdlBuf.size()),
665 reinterpret_cast<const unsigned char *>(sdlBuf.constData()),
666 0, nullptr,
667 static_cast<int>(bufLen),
668 reinterpret_cast<unsigned char *>(ba.data()));
669 Q_UNUSED(bytesRead);
670 } catch (const FbException &e) {
671 /* Surface to the caller (QFirebirdResult::data) rather than returning a
672 silently empty array on a read failure. */
673 qCWarning(lcFirebird) << "fetchArray: getSlice:"
674 << fbErrorLog(fbError(master, e.getStatus(), QSqlError::StatementError));
675 throw;
676 }
677
678 readArrayBuffer(list, ba.constData(), 0, numElements.constData(), &desc, master, iStatus);
679 return QVariant(list);
680}
681
682// Write array data via OO API (IAttachment::putSlice)
683bool writeArray(IAttachment *att, ITransaction *tra, IStatus *iStatus,
684 IMaster *master,
685 ArrayDescCache &descCache,
686 ISC_QUAD *arrayId, const QString &relation,
687 const QString &field, const QList<QVariant> &list)
688{
689 QByteArray relBytes = relation.trimmed().toUtf8();
690 QByteArray fldBytes = field.trimmed().toUtf8();
691
692 ISC_ARRAY_DESC desc;
693 if (!cachedArrayDesc(att, tra, iStatus, master, descCache, relBytes, fldBytes, &desc)) {
694 qCWarning(lcFirebird, "writeArray: could not look up array descriptor for %s.%s",
695 relBytes.constData(), fldBytes.constData());
696 return false;
697 }
698
699 // With blr_text SDL for varying, no +2 prefix needed
700 qint64 bufLen = 0;
701 if (!arraySliceSize(desc, "writeArray", relBytes, fldBytes, nullptr, &bufLen))
702 return false;
703
704 // Generate SDL with original desc_length
705 QByteArray sdlBuf = buildArraySdl(desc, relBytes, fldBytes);
706
707 QByteArray ba(bufLen, '\0');
708
709 QMetaType::Type elType = blrTypeToQt(desc.array_desc_dtype, desc.array_desc_scale < 0);
710 QString error;
711 if (!createArrayBuffer(ba.data(), list, elType, 0, &desc, master, iStatus, error)) {
712 qCWarning(lcFirebird) << "writeArray:" << error;
713 return false;
714 }
715
716 try {
717 ThrowStatusWrapper st(iStatus);
718 att->putSlice(&st, tra, arrayId,
719 static_cast<unsigned>(sdlBuf.size()),
720 reinterpret_cast<const unsigned char *>(sdlBuf.constData()),
721 0, nullptr,
722 static_cast<int>(bufLen),
723 reinterpret_cast<unsigned char *>(ba.data()));
724 } catch (const FbException &e) {
725 const auto werr = fbError(master, e.getStatus(), QSqlError::StatementError);
726 qCWarning(lcFirebird) << "writeArray: putSlice:" << fbErrorLog(werr);
727 return false;
728 }
729
730 return true;
731}
732
733QT_END_NAMESPACE
bool writeArray(IAttachment *att, ITransaction *tra, IStatus *iStatus, IMaster *master, ArrayDescCache &descCache, ISC_QUAD *arrayId, const QString &relation, const QString &field, const QList< QVariant > &list)
QVariant fetchArray(IAttachment *att, ITransaction *tra, IStatus *iStatus, IMaster *master, ArrayDescCache &descCache, const ISC_QUAD &arrayId, const QString &relation, const QString &field)
static const char * readArrayBuffer(QList< QVariant > &list, const char *buffer, short curDim, const int *numElements, ISC_ARRAY_DESC *desc, IMaster *master, IStatus *iStatus)
static bool arraySliceSize(const ISC_ARRAY_DESC &desc, const char *who, const QByteArray &relName, const QByteArray &fldName, QVarLengthArray< int > *numElements, qint64 *bufLen)
static QByteArray buildArraySdl(const ISC_ARRAY_DESC &desc, const QByteArray &relationName, const QByteArray &fieldName)
static unsigned fixedElementSize(unsigned char dtype)
static bool lookupArrayDesc(IAttachment *att, ITransaction *tra, IStatus *iStatus, IMaster *master, const QByteArray &relName, const QByteArray &fldName, ISC_ARRAY_DESC *desc)
static char * createArrayBuffer(char *buffer, const QList< QVariant > &list, QMetaType::Type type, short curDim, ISC_ARRAY_DESC *desc, IMaster *master, IStatus *iStatus, QString &error)
static bool cachedArrayDesc(IAttachment *att, ITransaction *tra, IStatus *iStatus, IMaster *master, ArrayDescCache &descCache, const QByteArray &relName, const QByteArray &fldName, ISC_ARRAY_DESC *desc)