-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebird_driver.cpp
2860 lines (2490 loc) · 85.6 KB
/
firebird_driver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
** Modified:
** 2019 Pavel Karelin (hkarel), <hkarel@yandex.ru>
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSql module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** $QT_END_LICENSE$**
****************************************************************************/
#include "firebird_driver.h"
#include "shared/break_point.h"
#include "shared/safe_singleton.h"
#include "shared/logger/logger.h"
#include "shared/logger/format.h"
#include "shared/qt/quuidex.h"
#include "shared/qt/logger_operators.h"
#include "shared/thread/thread_utils.h"
#include <QDateTime>
#include <QVariant>
#include <QSqlField>
#include <QSqlIndex>
#include <QVarLengthArray>
#include <cstdlib>
#include <utility>
#define log_error_m alog::logger().error (alog_line_location, "FirebirdDrv")
#define log_warn_m alog::logger().warn (alog_line_location, "FirebirdDrv")
#define log_info_m alog::logger().info (alog_line_location, "FirebirdDrv")
#define log_verbose_m alog::logger().verbose (alog_line_location, "FirebirdDrv")
#define log_debug_m alog::logger().debug (alog_line_location, "FirebirdDrv")
#define log_debug2_m alog::logger().debug2 (alog_line_location, "FirebirdDrv")
#define FBVERSION SQL_DIALECT_V6
#ifndef SQLDA_CURRENT_VERSION
#define SQLDA_CURRENT_VERSION SQLDA_VERSION1
#endif
namespace db {
namespace firebird {
namespace {
enum {FirebirdChunkSize = SHRT_MAX / 2};
bool firebirdError(const ISC_STATUS* status, const QTextCodec* tc,
ISC_LONG& sqlcode, QString& msg)
{
if (status[0] != 1 || status[1] <= 0)
return false;
msg.clear();
sqlcode = isc_sqlcode(status);
char buf[512];
while (fb_interpret(buf, 512, &status))
{
if (!msg.isEmpty())
msg += QLatin1String(" - ");
if (tc)
msg += tc->toUnicode(buf);
else
msg += QString::fromUtf8(buf);
}
return true;
}
void deleteDA(XSQLDA*& sqlda)
{
if (!sqlda)
return;
//for (int i = 0; i < sqlda->sqld; ++i)
for (int i = 0; i < sqlda->sqln; ++i)
{
delete [] sqlda->sqlvar[i].sqlind;
delete [] sqlda->sqlvar[i].sqldata;
}
free(sqlda);
sqlda = 0;
}
bool createDA(XSQLDA*& sqlda)
{
if (sqlda != (XSQLDA*)0)
deleteDA(sqlda);
sqlda = (XSQLDA*) malloc(XSQLDA_LENGTH(1));
if (sqlda == (XSQLDA*)0)
{
log_error_m << "Call createDA(): failed to allocate memory";
return false;
}
memset(sqlda, 0, XSQLDA_LENGTH(1));
sqlda->sqln = 1;
//sqlda->sqld = 0;
sqlda->version = SQLDA_CURRENT_VERSION;
//sqlda->sqlvar[0].sqlind = 0;
//sqlda->sqlvar[0].sqldata = 0;
return true;
}
bool enlargeDA(XSQLDA*& sqlda, int n)
{
if (sqlda != (XSQLDA*)0)
deleteDA(sqlda);
sqlda = (XSQLDA*) malloc(XSQLDA_LENGTH(n));
if (sqlda == (XSQLDA*)0)
{
log_error_m << "Call enlargeDA(): failed to allocate memory";
return false;
}
memset(sqlda, 0, XSQLDA_LENGTH(n));
sqlda->sqln = n;
sqlda->version = SQLDA_CURRENT_VERSION;
return true;
}
void initDA(XSQLDA* sqlda)
{
for (int i = 0; i < sqlda->sqld; ++i)
{
switch (sqlda->sqlvar[i].sqltype & ~1)
{
case SQL_INT64:
case SQL_LONG:
case SQL_SHORT:
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_TIMESTAMP:
case SQL_TYPE_TIME:
case SQL_TYPE_DATE:
case SQL_TEXT:
case SQL_BLOB:
sqlda->sqlvar[i].sqldata = new char[sqlda->sqlvar[i].sqllen];
break;
case SQL_ARRAY:
sqlda->sqlvar[i].sqldata = new char[sizeof(ISC_QUAD)];
memset(sqlda->sqlvar[i].sqldata, 0, sizeof(ISC_QUAD));
break;
case SQL_VARYING:
sqlda->sqlvar[i].sqldata = new char[sqlda->sqlvar[i].sqllen + sizeof(short)];
break;
default:
// not supported - do not bind.
sqlda->sqlvar[i].sqldata = 0;
break;
}
if (sqlda->sqlvar[i].sqltype & 1)
{
sqlda->sqlvar[i].sqlind = new short[1];
*(sqlda->sqlvar[i].sqlind) = 0;
}
else
sqlda->sqlvar[i].sqlind = 0;
}
}
QVariant::Type qFirebirdTypeName(int iType, bool hasScale)
{
switch (iType)
{
case blr_varying:
case blr_varying2:
case blr_text:
case blr_cstring:
case blr_cstring2:
//break_point
return QVariant::String;
case blr_sql_time:
return QVariant::Time;
case blr_sql_date:
return QVariant::Date;
case blr_timestamp:
return QVariant::DateTime;
case blr_blob:
{
// Отладить
break_point
return QVariant::ByteArray;
}
case blr_quad:
case blr_short:
case blr_long:
return (hasScale) ? QVariant::Double : QVariant::Int;
case blr_int64:
return (hasScale) ? QVariant::Double : QVariant::LongLong;
case blr_float:
return QVariant::Type(qMetaTypeId<float>());
case blr_d_float:
case blr_double:
return QVariant::Double;
}
log_warn_m << "qFirebirdTypeName(): unknown datatype: " << iType;
return QVariant::Invalid;
}
QVariant::Type qFirebirdTypeName2(int iType, bool hasScale, int subType, int subLength)
{
switch (iType & ~1)
{
case SQL_VARYING:
case SQL_TEXT:
// [Karelin]
// return QVariant::String;
// return (subType == 1 /*OCTET*/) ? QVariant::ByteArray : QVariant::String;
if (subType == 1 /*OCTET*/)
{
if (subLength == 16)
{
//int varType1 = QMetaTypeId<Uuid>::qt_metatype_id();
//int varType2 = qMetaTypeId<Uuid>();
return QVariant::Type(qMetaTypeId<QUuidEx>());
}
else
return QVariant::ByteArray;
}
else
return QVariant::String;
case SQL_LONG:
case SQL_SHORT:
return (hasScale) ? QVariant::Double : QVariant::Int;
case SQL_INT64:
return (hasScale) ? QVariant::Double : QVariant::LongLong;
case SQL_FLOAT:
return QVariant::Type(qMetaTypeId<float>());
case SQL_DOUBLE:
return QVariant::Double;
case SQL_TIMESTAMP:
return QVariant::DateTime;
case SQL_TYPE_TIME:
return QVariant::Time;
case SQL_TYPE_DATE:
return QVariant::Date;
case SQL_ARRAY:
return QVariant::List;
case SQL_BLOB:
return QVariant::ByteArray;
}
log_warn_m << "qFirebirdTypeName2(): unknown datatype: " << iType;
return QVariant::Invalid;
}
ISC_TIMESTAMP toTimeStamp(const QDateTime& dt)
{
static const QTime midnight {0, 0, 0, 0};
static const QDate basedate {1858, 11, 17};
ISC_TIMESTAMP ts;
ts.timestamp_time = midnight.msecsTo(dt.time()) * 10;
ts.timestamp_date = basedate.daysTo(dt.date());
return ts;
}
QDateTime fromTimeStamp(const char* buffer)
{
static const QTime midnight {0, 0, 0, 0};
static const QDate basedate {1858, 11, 17};
// have to demangle the structure ourselves because isc_decode_time
// strips the msecs
QTime t = midnight.addMSecs(int(((ISC_TIMESTAMP*)buffer)->timestamp_time / 10));
QDate d = basedate.addDays (int(((ISC_TIMESTAMP*)buffer)->timestamp_date));
return QDateTime(d, t);
}
ISC_TIME toTime(const QTime& t)
{
static const QTime midnight {0, 0, 0, 0};
return (ISC_TIME)midnight.msecsTo(t) * 10;
}
QTime fromTime(const char* buffer)
{
static const QTime midnight {0, 0, 0, 0};
// have to demangle the structure ourselves because isc_decode_time
// strips the msecs
QTime t = midnight.addMSecs(int((*(ISC_TIME*)buffer) / 10));
return t;
}
ISC_DATE toDate(const QDate& t)
{
static const QDate basedate {1858, 11, 17};
ISC_DATE date = basedate.daysTo(t);
return date;
}
QDate fromDate(const char* buffer)
{
static const QDate basedate {1858, 11, 17};
// have to demangle the structure ourselves because isc_decode_time
// strips the msecs
QDate d = basedate.addDays(int(((ISC_TIMESTAMP*)buffer)->timestamp_date));
return d;
}
QByteArray encodeString(const QTextCodec* tc, const QString& str)
{
return (tc) ? tc->fromUnicode(str) : str.toUtf8();
}
template<typename T>
QList<QVariant> toList(char** buf, int count)
{
QList<QVariant> res;
for (int i = 0; i < count; ++i)
{
T value = *(T*)(*buf);
res.append(value);
*buf += sizeof(T);
}
return res;
}
/* char** ? seems like bad influence from oracle ... */
QList<QVariant> toListLong(char** buf, int count)
{
QList<QVariant> res;
for (int i = 0; i < count; ++i)
{
if (sizeof(int) == sizeof(long))
res.append(int(*(long*)(*buf)));
else
res.append(qint64(*(long*)(*buf)));
*buf += sizeof(long);
}
return res;
}
char* readArrayBuffer(QList<QVariant>& list, char* buffer, short curDim,
short* numElements, ISC_ARRAY_DESC* arrayDesc,
const QTextCodec* tc)
{
const short dim = arrayDesc->array_desc_dimensions - 1;
const unsigned char dataType = arrayDesc->array_desc_dtype;
QList<QVariant> valList;
unsigned short strLen = arrayDesc->array_desc_length;
if (curDim != dim)
{
for (int i = 0; i < numElements[curDim]; ++i)
buffer = readArrayBuffer(list, buffer, curDim + 1,
numElements, arrayDesc, tc);
}
else
{
switch (dataType)
{
case blr_varying:
case blr_varying2:
break_point
strLen += 2; // for the two terminating null values
/* FALLTHRU - reserved words for fix GCC 7 warning */
case blr_text:
case blr_text2:
for (int i = 0; i < numElements[dim]; ++i)
{
int o;
for (o = 0; o < strLen && buffer[o] != 0; ++o) {}
if (tc)
valList.append(tc->toUnicode(buffer, o));
else
valList.append(QString::fromUtf8(buffer, o));
buffer += strLen;
}
break;
case blr_long:
valList = toListLong(&buffer, numElements[dim]);
break;
case blr_short:
valList = toList<short>(&buffer, numElements[dim]);
break;
case blr_int64:
valList = toList<qint64>(&buffer, numElements[dim]);
break;
case blr_float:
valList = toList<float>(&buffer, numElements[dim]);
break;
case blr_double:
valList = toList<double>(&buffer, numElements[dim]);
break;
case blr_timestamp:
for (int i = 0; i < numElements[dim]; ++i)
{
valList.append(fromTimeStamp(buffer));
buffer += sizeof(ISC_TIMESTAMP);
}
break;
case blr_sql_time:
for (int i = 0; i < numElements[dim]; ++i)
{
valList.append(fromTime(buffer));
buffer += sizeof(ISC_TIME);
}
break;
case blr_sql_date:
for (int i = 0; i < numElements[dim]; ++i)
{
valList.append(fromDate(buffer));
buffer += sizeof(ISC_DATE);
}
break;
}
}
if (dim > 0)
{
// Отладить
break_point
list.append(valList);
}
else
{
// Отладить
break_point
list += valList;
}
return buffer;
}
template<typename T>
char* fillList(char* buffer, const QList<QVariant>& list)
{
for (int i = 0; i < list.size(); ++i)
{
T val;
val = qvariant_cast<T>(list.at(i));
memcpy(buffer,& val, sizeof(T));
buffer += sizeof(T);
}
return buffer;
}
char* fillListFloat(char* buffer, const QList<QVariant>& list)
{
for (int i = 0; i < list.size(); ++i)
{
double val;
float val2 = 0;
val = qvariant_cast<double>(list.at(i));
val2 = (float)val;
memcpy(buffer,& val2, sizeof(float));
buffer += sizeof(float);
}
return buffer;
}
char* qFillBufferWithString(char* buffer, short buflen, const QString& string,
bool varying, bool array, const QTextCodec* tc)
{
// keep a copy of the string alive in this scope
QByteArray ba = encodeString(tc, string);
if (varying)
{
short tmpBuflen = buflen;
if (ba.length() < buflen)
buflen = ba.length();
if (array) // interbase stores varying arrayelements different than normal varying elements
{
// [Karelin]
// memcpy(buffer, str.data(), buflen);
memcpy(buffer, (char*)ba.constData(), buflen);
memset(buffer + buflen, 0, tmpBuflen - buflen);
}
else
{
*(short*)buffer = buflen; // first two bytes is the length
// [Karelin]
// memcpy(buffer + sizeof(short), str.data(), buflen);
memcpy(buffer + sizeof(short), (char*)ba.constData(), buflen);
}
buffer += tmpBuflen;
}
else
{
ba = ba.leftJustified(buflen, ' ', true);
// [Karelin]
// memcpy(buffer, str.data(), buflen);
memcpy(buffer, (char*)ba.constData(), buflen);
buffer += buflen;
}
return buffer;
}
// [Karelin]
char* qFillBufferWithByteArray(char* buffer, short buflen, const QByteArray& ba,
bool varying)
{
if (varying)
{
short tmpBuflen = buflen;
if (ba.length() < buflen)
buflen = ba.length();
//if (array) { // interbase stores varying arrayelements different than normal varying elements
// memcpy(buffer, str.data(), buflen);
// memset(buffer + buflen, 0, tmpBuflen - buflen);
//} else {
*(short*)buffer = buflen; // first two bytes is the length
memcpy(buffer + sizeof(short), (char*)ba.constData(), buflen);
//}
buffer += tmpBuflen;
}
else
{
const QByteArray& str2 = ba.leftJustified(buflen, 0, true);
memcpy(buffer, (char*)str2.constData(), buflen);
buffer += buflen;
}
return buffer;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"
char* createArrayBuffer(char* buffer, const QList<QVariant>& list,
QVariant::Type type, short curDim, ISC_ARRAY_DESC* arrayDesc,
QString& error, const QTextCodec* tc)
{
int i;
ISC_ARRAY_BOUND* bounds = arrayDesc->array_desc_bounds;
short dim = arrayDesc->array_desc_dimensions - 1;
int elements = (bounds[curDim].array_bound_upper -
bounds[curDim].array_bound_lower + 1);
if (list.size() != elements) // size mismatch
{
// Отладить
break_point
error = QLatin1String("Array size mismatch. Fieldname: %1. ")
+ QString("Expected size: %1, supplied size: %2").arg(elements)
.arg(list.size());
return 0;
}
if (curDim != dim)
{
for (i = 0; i < list.size(); ++i)
{
if (list.at(i).type() != QVariant::List) // dimensions mismatch
{
error = QLatin1String("Array dimensons mismatch. Fieldname: %1");
return 0;
}
buffer = createArrayBuffer(buffer, list.at(i).toList(), type,
curDim + 1, arrayDesc, error, tc);
if (!buffer)
return 0;
}
}
else
{
switch (type)
{
case QVariant::Int:
case QVariant::UInt:
if (arrayDesc->array_desc_dtype == blr_short)
buffer = fillList<short>(buffer, list);
else
buffer = fillList<int>(buffer, list);
break;
case QVariant::Double:
if (arrayDesc->array_desc_dtype == blr_float)
buffer = fillListFloat(buffer, list);
else
buffer = fillList<double>(buffer, list);
break;
case QVariant::LongLong:
buffer = fillList<qint64>(buffer, list);
break;
case QVariant::ULongLong:
buffer = fillList<quint64>(buffer, list);
break;
case QVariant::String:
for (i = 0; i < list.size(); ++i)
buffer = qFillBufferWithString(buffer, arrayDesc->array_desc_length,
list.at(i).toString(),
arrayDesc->array_desc_dtype == blr_varying,
true, tc);
break;
case QVariant::Date:
for (i = 0; i < list.size(); ++i)
{
*((ISC_DATE*)buffer) = toDate(list.at(i).toDate());
buffer += sizeof(ISC_DATE);
}
break;
case QVariant::Time:
for (i = 0; i < list.size(); ++i)
{
*((ISC_TIME*)buffer) = toTime(list.at(i).toTime());
buffer += sizeof(ISC_TIME);
}
break;
case QVariant::DateTime:
for (i = 0; i < list.size(); ++i)
{
*((ISC_TIMESTAMP*)buffer) = toTimeStamp(list.at(i).toDateTime());
buffer += sizeof(ISC_TIMESTAMP);
}
break;
default:
break;
}
}
return buffer;
}
#pragma GCC diagnostic pop
//typedef QMap<void*, Driver*> QFirebirdBufferDriverMap;
//Q_GLOBAL_STATIC(QFirebirdBufferDriverMap, qBufferDriverMap)
//Q_GLOBAL_STATIC(QMutex, qMutex);
//void qFreeEventBuffer(QFirebirdEventBuffer* eBuffer)
//{
// qMutex()->lock();
// qBufferDriverMap()->remove(reinterpret_cast<void*>(eBuffer->resultBuffer));
// qMutex()->unlock();
// delete eBuffer;
//}
} // namespace
//------------------------------- Transaction --------------------------------
Transaction::Transaction(const DriverPtr& drv) : _drv(drv)
{
log_debug2_m << "Transaction ctor";
Q_ASSERT(_drv.get());
}
Transaction::~Transaction()
{
log_debug2_m << "Transaction dtor";
if (isActive())
rollback();
}
bool Transaction::begin()
{
if (_drv->operationIsAborted())
{
log_error_m << "Failed begin transaction, sql-operation aborted"
<< ". Connect: " << _drv->_ibase;
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
log_error_m << "Failed begin transaction, database not open";
return false;
}
if (_trans)
{
log_error_m << "Transaction already begun: " << _drv->_ibase << "/" << _trans;
return false;
}
ISC_STATUS status[20] = {0};
isc_start_transaction(status, &_trans, 1, _drv->ibase(), 0, NULL);
ISC_LONG sqlcode; QString msg;
if (firebirdError(status, _drv->_textCodec, sqlcode, msg))
{
log_error_m << "Failed begin transaction. Connect: " << _drv->_ibase
<< ". Detail: " << msg << "; SqlCode: " << sqlcode;
// Прерываем использование данного подключения
_drv->abortOperation();
return false;
}
log_debug2_m << "Transaction begin: " << _drv->_ibase << "/" << _trans;
return true;
}
bool Transaction::commit()
{
if (_drv->operationIsAborted())
{
log_error_m << "Failed commit transaction, sql-operation aborted"
<< ". Connect: " << _drv->_ibase;
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
log_error_m << "Failed commit transaction, database not open";
return false;
}
if (!_trans)
{
log_error_m << "Failed commit transaction, transaction not begun"
<< ". Connect: " << _drv->_ibase;
return false;
}
ISC_STATUS status[20] = {0};
isc_tr_handle trans = _trans;
isc_commit_transaction(status, &_trans);
_trans = 0;
ISC_LONG sqlcode; QString msg;
if (firebirdError(status, _drv->_textCodec, sqlcode, msg))
{
log_error_m << "Failed commit transaction: " << _drv->_ibase << "/" << trans
<< ". Detail: " << msg << "; SqlCode: " << sqlcode;
return false;
}
log_debug2_m << "Transaction commit: " << _drv->_ibase << "/" << trans;
return true;
}
bool Transaction::rollback()
{
if (!_drv->isOpen() || _drv->isOpenError())
{
log_error_m << "Failed rollback transaction, database not open";
return false;
}
if (!_trans)
{
log_error_m << "Failed rollback transaction, transaction not begun"
<< ". Connect: " << _drv->_ibase;
return false;
}
ISC_STATUS status[20] = {0};
isc_tr_handle trans = _trans;
isc_rollback_transaction(status, &_trans);
_trans = 0;
ISC_LONG sqlcode; QString msg;
if (firebirdError(status, _drv->_textCodec, sqlcode, msg))
{
log_error_m << "Failed rollback transaction: " << _drv->_ibase << "/" << trans
<< ". Detail: " << msg << "; SqlCode: " << sqlcode;
return false;
}
log_debug2_m << "Transaction rollback: " << _drv->_ibase << "/" << trans;
return true;
}
bool Transaction::isActive() const
{
return bool(_trans);
}
AutoRollbackTransact::AutoRollbackTransact(const Transaction::Ptr& t)
: transact(t)
{}
AutoRollbackTransact::~AutoRollbackTransact()
{
log_debug2_m << "AutoRollbackTransact dtor";
if (transact->isActive())
transact->rollback();
}
//---------------------------------- Result ----------------------------------
#define CHECK_ERROR(MSG, ERR_TYPE) \
checkError(MSG, ERR_TYPE, status, __func__, __LINE__)
#define SET_LAST_ERROR(MSG, ERR_TYPE) { \
setLastError(QSqlError("FirebirdResult", MSG, ERR_TYPE, 1)); \
alog::logger().error(alog_line_location, "FirebirdDrv") << MSG; \
}
Result::Result(const DriverPtr& drv, ForwardOnly forwardOnly)
: SqlCachedResult(drv.get()),
_drv(drv)
{
Q_ASSERT(_drv.get());
setForwardOnly(forwardOnly == ForwardOnly::Yes);
}
Result::Result(const Transaction::Ptr& trans, ForwardOnly forwardOnly)
: SqlCachedResult(trans->_drv.get()),
_drv(trans->_drv),
_externalTransact(trans)
{
Q_ASSERT(_drv.get());
setForwardOnly(forwardOnly == ForwardOnly::Yes);
}
Result::~Result()
{
cleanup();
}
bool Result::isSelectSql() const
{
if (_queryType == isc_info_sql_stmt_select)
{
return true;
}
else if (_queryType == isc_info_sql_stmt_exec_procedure)
{
if (_sqlda && (_sqlda->sqld != 0))
return true;
}
return false;
}
bool Result::checkError(const char* msg, QSqlError::ErrorType type,
ISC_STATUS* status, const char* func, int line)
{
ISC_LONG sqlcode; QString err;
if (firebirdError(status, _drv->_textCodec, sqlcode, err))
{
setLastError(QSqlError("FirebirdResult", msg, type, 1));
alog::logger().error(alog::detail::file_name(__FILE__), func, line, "FirebirdDrv")
<< msg
<< ". Transact: " << _drv->_ibase << "/" << *transact()
<< ". Detail: " << err
<< ". SqlCode: " << sqlcode;
return true;
}
return false;
}
void Result::cleanup()
{
log_debug2_m << "Begin dataset cleanup. Connect: " << _drv->_ibase;
if (!_externalTransact)
if (_internalTransact && _internalTransact->isActive())
{
if (isSelectSql())
rollbackInternalTransact();
else
commitInternalTransact();
}
if (_stmt)
{
ISC_STATUS status[20] = {0};
isc_dsql_free_statement(status, &_stmt, DSQL_drop);
CHECK_ERROR("Failed free statement", QSqlError::StatementError);
_stmt = 0;
}
deleteDA(_sqlda);
deleteDA(_inda);
_queryType = -1;
_preparedQuery.clear();
SqlCachedResult::cleanup();
log_debug2_m << "End dataset cleanup. Connect: " << _drv->_ibase;
}
bool Result::beginInternalTransact()
{
if (_externalTransact)
return true;
if (_internalTransact && _internalTransact->isActive())
{
log_debug2_m << "Internal transaction already begun";
return true;
}
if (_internalTransact.empty())
_internalTransact = createTransact(_drv);
if (!_internalTransact->begin())
{
// Детали сообщения об ошибке пишутся в лог внутри метода begin()
SET_LAST_ERROR("Failed begin internal transaction", QSqlError::TransactionError)
return false;
}
log_debug2_m << "Internal transaction begin";
return true;
}
bool Result::commitInternalTransact()
{
if (_externalTransact)
return true;
if (!_internalTransact)
{
log_error_m << "Failed commit internal transaction"
<< ". Detail: Internal transaction not created";
return false;
}
if (!_internalTransact->isActive())
{
log_error_m << "Failed commit internal transaction"
<< ". Detail: Internal transaction not begun";
return false;
}
if (!_internalTransact->commit())
{
// Детали сообщения об ошибке пишутся в лог внутри метода commit()
SET_LAST_ERROR("Failed commit internal transaction", QSqlError::TransactionError)
return false;
}
log_debug2_m << "Internal transaction commit";
return true;
}
bool Result::rollbackInternalTransact()
{
if (_externalTransact)
return true;
if (!_internalTransact)
{
log_error_m << "Failed rollback internal transaction"
<< ". Detail: Internal transaction not created";
return false;
}
if (!_internalTransact->isActive())
{
log_error_m << "Failed rollback internal transaction"
<< ". Detail: Internal transaction not begun";
return false;
}
if (!_internalTransact->rollback())
{
// Детали сообщения об ошибке пишутся в лог внутри метода rollback()
SET_LAST_ERROR("Failed rollback internal transaction", QSqlError::TransactionError)
return false;
}
log_debug2_m << "Internal transaction rollback";
return true;