-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres_driver.cpp
2156 lines (1861 loc) · 67.1 KB
/
postgres_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
/*****************************************************************************
The MIT License
Copyright © 2020 Pavel Karelin (hkarel), <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*****************************************************************************/
#include "postgres_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 <cstdlib>
#include <utility>
#include <byteswap.h>
#define log_error_m alog::logger().error (alog_line_location, "PostgresDrv")
#define log_warn_m alog::logger().warn (alog_line_location, "PostgresDrv")
#define log_info_m alog::logger().info (alog_line_location, "PostgresDrv")
#define log_verbose_m alog::logger().verbose (alog_line_location, "PostgresDrv")
#define log_debug_m alog::logger().debug (alog_line_location, "PostgresDrv")
#define log_debug2_m alog::logger().debug2 (alog_line_location, "PostgresDrv")
#define PG_TYPE_BOOL 16 // QBOOLOID
#define PG_TYPE_INT8 18 // OINT1OID
#define PG_TYPE_INT16 21 // QINT2OID
#define PG_TYPE_INT32 23 // QINT4OID
#define PG_TYPE_INT64 20 // QINT8OID
#define PG_TYPE_BYTEARRAY 17 // QBYTEARRAY (BINARY)
#define PG_TYPE_STRING 25 // STRING (NOT BIN)
#define PG_TYPE_FLOAT 700 // QFLOAT4OID
#define PG_TYPE_DOUBLE 701 // QFLOAT8OID
#define PG_TYPE_DATE 1082 // QDATEOID
#define PG_TYPE_TIME 1083 // QTIMEOID
#define PG_TYPE_TIMESTAMP 1114 // QTIMESTAMPOID
#define PG_TYPE_TIMESTAMPTZ 1184 // QTIMESTAMPTZOID
#define PG_TYPE_UUID 2950
#define PG_TYPE_UUID_ARRAY 2951
#define PG_TYPE_INT4_ARRAY 1007
#define PG_TYPE_FLOAT_ARRAY 1021
#define PG_TYPE_DOUBLE_ARRAY 1022
namespace db {
namespace postgres {
namespace {
inline quint64 addrToNumber(void* addr)
{
return reinterpret_cast<QIntegerForSizeof<void*>::Unsigned>(addr);
}
inline PGresultPtr pqexec(PGconn* connect, const char* cmd)
{
return PGresultPtr(PQexec(connect, cmd));
}
inline ExecStatusType pqexecStatus(const PGresultPtr& result)
{
return (result) ? PQresultStatus(result) : PGRES_BAD_RESPONSE;
}
QByteArray genStmtName()
{
static std::atomic_int a {1};
int i = a++;
char buff[20] = {0};
snprintf(buff, sizeof(buff) - 1, "stmt%04d", i);
return QByteArray(buff);
}
QVariant::Type qPostgresTypeName(int pgType)
{
switch (pgType)
{
case PG_TYPE_BOOL:
return QVariant::Bool;
case PG_TYPE_INT8:
case PG_TYPE_INT16:
case PG_TYPE_INT32:
return QVariant::Int;
case PG_TYPE_INT64:
return QVariant::LongLong;
case PG_TYPE_FLOAT:
return QVariant::Type(qMetaTypeId<float>());
case PG_TYPE_DOUBLE:
return QVariant::Double;
case PG_TYPE_DATE:
return QVariant::Date;
case PG_TYPE_TIME:
return QVariant::Time;
case PG_TYPE_TIMESTAMP:
return QVariant::DateTime;
case PG_TYPE_TIMESTAMPTZ:
return QVariant::DateTime;
case PG_TYPE_BYTEARRAY:
return QVariant::ByteArray;
case PG_TYPE_STRING:
return QVariant::String;
case PG_TYPE_UUID:
return QVariant::Uuid;
case PG_TYPE_INT4_ARRAY:
return QVariant::Type(qMetaTypeId<QVector<qint32>>());
case PG_TYPE_FLOAT_ARRAY:
return QVariant::Type(qMetaTypeId<QVector<float>>());
case PG_TYPE_DOUBLE_ARRAY:
return QVariant::Type(qMetaTypeId<QVector<double>>());
case PG_TYPE_UUID_ARRAY:
return QVariant::Type(qMetaTypeId<QVector<QUuid>>());
}
return QVariant::Invalid;
}
inline QDate baseDate() {return {2000, 01, 01};}
inline QDateTime baseDateTimeUtc()
{
QDateTime baseDt = {baseDate(), QTime()};
baseDt.setOffsetFromUtc(0);
return baseDt;
}
qint64 toTimeStamp(const QDateTime& dt)
{
static const qint64 baseMSecs {QDateTime{baseDate(), QTime()}.toMSecsSinceEpoch()};
return (dt.toMSecsSinceEpoch() - baseMSecs) * 1000;
}
qint64 toTimeStampUtc(const QDateTime& dt)
{
static const qint64 baseMSecs {baseDateTimeUtc().toMSecsSinceEpoch()};
return (dt.toMSecsSinceEpoch() - baseMSecs) * 1000;
}
QDateTime fromTimeStamp(qint64 ts)
{
static const QDateTime basedate {baseDate(), QTime()};
return basedate.addMSecs(ts / 1000);
}
QDateTime fromTimeStampUtc(qint64 ts)
{
static const QDateTime basedate {baseDateTimeUtc()};
return basedate.addMSecs(ts / 1000);
}
qint64 toTime(const QTime& t)
{
static const QTime midnight {0, 0, 0, 0};
return qint64(midnight.msecsTo(t)) * 1000;
}
QTime fromTime(qint64 pgtime)
{
static const QTime midnight {0, 0, 0, 0};
return midnight.addMSecs(int(pgtime / 1000));
}
qint32 toDate(const QDate& d)
{
static const QDate basedate {baseDate()};
return basedate.daysTo(d);
}
QDate fromDate(qint32 pgdate)
{
static const QDate basedate {baseDate()};
return basedate.addDays(pgdate);
}
struct QueryParams
{
int nparams = {0};
char** paramValues = {0};
int* paramLengths = {0};
int* paramFormats = {0};
QueryParams() = default;
DISABLE_DEFAULT_COPY(QueryParams)
~QueryParams()
{
for (int i = 0; i < nparams; ++i)
free(paramValues[i]);
delete [] paramValues;
delete [] paramLengths;
delete [] paramFormats;
}
void init(int nparams)
{
this->nparams = nparams;
paramValues = new char* [nparams];
paramLengths = new int [nparams];
paramFormats = new int [nparams];
for (int i = 0; i < nparams; ++i)
{
paramValues [i] = 0;
paramLengths[i] = 0;
paramFormats[i] = 1;
}
}
};
template<typename T>
using ArrayFillingFunc = std::function<void (qint32* /*ptrArray*/, QVector<T>& /*array*/)>;
template<typename T>
bool getArray(const PGresultPtr& pgres, qint32 fieldType, const char* fieldTypeName,
qint32 fieldIndex, ArrayFillingFunc<T> fillingFunc, QVector<T>& array /*out*/)
{
const char* valueBuff = PQgetvalue(pgres, 0, fieldIndex);
qint32* pArray = (qint32*) valueBuff;
// Считываем базовые поля заголовка: ndim, ign, elemtype.
qint32 ndim = bswap_32(*pArray++); // Мерность массива
qint32 ign = bswap_32(*pArray++); // offset for data, removed by libpq
qint32 elemtype = bswap_32(*pArray++); // Тип PG
(void) ign;
// Для пустого массива ndim равен 0. Это верно для любой размерности массива.
if (ndim == 0)
{
array.clear();
return true;
}
if (ndim > 1)
{
log_error_m << "Driver support only one-dimension arrays"
<< ". Field index: " << fieldIndex;
return false;
}
// Считываем дополнительные поля заголовка
qint32 size = bswap_32(*pArray++); // Количество элементов в массиве
qint32 index = bswap_32(*pArray++); // Индекс первого элемента массива ??
(void) index;
if (elemtype != fieldType /*PG_TYPE_INT32*/)
{
log_error_m << "Type of array not " << fieldTypeName // "PG_TYPE_INT32"
<< ". Field index: " << fieldIndex;
return false;
}
// Контрольная проверка размера массива
int len = PQgetlength(pgres, 0, fieldIndex);
int arraySize = (len - 5 * sizeof(qint32)) / (sizeof(qint32) + sizeof(T));
if (arraySize != size)
{
// Отладить
break_point
log_error_m << "Size of array incorrect"
<< ". Field index: " << fieldIndex;
return false;
}
// Считываем массив данных
array.resize(size);
fillingFunc(pArray, array);
return true;
}
template<typename T>
bool setArray(qint32 paramType, const char* paramTypeName, qint32 paramIndex,
const QVariant& value, ArrayFillingFunc<T> fillingFunc, QueryParams& params)
{
typedef QVector<T> ArrayType;
if (!value.canConvert<ArrayType>())
{
log_error_m << log_format("Query param%? can't convert to Vector<%?> type",
paramIndex, paramTypeName);
return false;
}
ArrayType array = value.value<ArrayType>();
int sz = 3 * sizeof(qint32);
if (!array.empty())
{
// размер заголовка размер массива данных
sz = 5 * sizeof(qint32) + array.count() * (sizeof(quint32) + sizeof(T));
}
params.paramValues[paramIndex] = (char*)malloc(sz);
params.paramLengths[paramIndex] = sz;
qint32* pArray = (qint32*)params.paramValues[paramIndex];
qint32 ndim = (array.empty()) ? 0 : 1; // Размерность массива
qint32 ign = 0; // ?
qint32 elemtype = paramType; // Тип PG
qint32 size = array.count(); // Длина массива
qint32 index = 0; // Индекс первого элемента массива
// Записываем базовые поля заголовка: ndim, ign, elemtype.
*pArray++ = bswap_32(ndim);
*pArray++ = bswap_32(ign);
*pArray++ = bswap_32(elemtype);
if (!array.empty())
{
// Записываем дополнительные поля заголовка
*pArray++ = bswap_32(size);
*pArray++ = bswap_32(index);
// Записываем массив данных
fillingFunc(pArray, array);
}
return true;
}
} // namespace
//------------------------------- Transaction --------------------------------
Transaction::Transaction(const DriverPtr& drv) : _drv(drv)
{
log_debug2_m << "Transaction ctor. Address: " << addrToNumber(this);
Q_ASSERT(_drv.get());
_drv->captureTransactAddr(this);
}
Transaction::~Transaction()
{
log_debug2_m << "Transaction dtor. Address: " << addrToNumber(this);
if (isActive())
rollback();
_drv->releaseTransactAddr(this);
}
bool Transaction::begin(IsolationLevel isolationLevel, WritePolicy writePolicy)
{
pid_t threadId = trd::gettid();
if (_drv->threadId() != threadId)
{
log_error_m << "Failed begin transaction, threads identifiers not match"
<< ". Connection thread id: " << _drv->threadId()
<< ", current thread id: " << threadId;
return false;
}
if (!_drv->transactAddrIsEqual(this))
{
log_error_m << "Failed begin transaction, transaction not captured";
return false;
}
if (_drv->operationIsAborted())
{
log_error_m << "Failed begin transaction, sql-operation aborted"
<< ". Connect: " << addrToNumber(_drv->_connect);
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
log_error_m << "Failed begin transaction, database not open";
return false;
}
if (_isActive)
{
log_error_m << log_format("Transaction already begun: %?/%?",
addrToNumber(_drv->_connect), _transactId);
return false;
}
const char* beginCmd = "BEGIN";
if (isolationLevel == IsolationLevel::ReadCommitted
&& writePolicy == WritePolicy::ReadOnly)
{
beginCmd = "BEGIN READ ONLY";
}
else if (isolationLevel == IsolationLevel::RepeatableRead
&& writePolicy == WritePolicy::ReadWrite)
{
beginCmd = "BEGIN ISOLATION LEVEL REPEATABLE READ";
}
else if (isolationLevel == IsolationLevel::RepeatableRead
&& writePolicy == WritePolicy::ReadOnly)
{
beginCmd = "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY";
}
else if (isolationLevel == IsolationLevel::Serializable
&& writePolicy == WritePolicy::ReadWrite)
{
beginCmd = "BEGIN ISOLATION LEVEL SERIALIZABLE";
}
else if (isolationLevel == IsolationLevel::Serializable
&& writePolicy == WritePolicy::ReadOnly)
{
beginCmd = "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY";
}
PGresultPtr pgres = pqexec(_drv->_connect, beginCmd);
ExecStatusType status = pqexecStatus(pgres);
if (status != PGRES_COMMAND_OK)
{
const char* detail = PQerrorMessage(_drv->_connect);
log_error_m << "Failed begin transaction"
<< ". Connect: " << addrToNumber(_drv->_connect)
<< ". " << detail;
// Прерываем использование данного подключения
_drv->abortOperation();
return false;
}
pgres = pqexec(_drv->_connect, "SELECT txid_current()");
status = pqexecStatus(pgres);
if (status != PGRES_TUPLES_OK)
{
// Отладить
break_point
const char* detail = PQerrorMessage(_drv->_connect);
log_error_m << "Failed get transaction id"
<< ". Connect: " << addrToNumber(_drv->_connect)
<< ". " << detail;
pgres = pqexec(_drv->_connect, "ROLLBACK");
status = pqexecStatus(pgres);
if (status != PGRES_COMMAND_OK)
{
detail = PQerrorMessage(_drv->_connect);
log_error_m << "Failed rollback transaction"
<< ". Connect: " << addrToNumber(_drv->_connect)
<< ". " << detail;
}
// Прерываем использование данного подключения
_drv->abortOperation();
return false;
}
char* val = PQgetvalue(pgres, 0, 0);
_transactId = strtoull(val, nullptr, 10);
_isActive = true;
log_debug2_m << log_format("Transaction begin: %?/%?",
addrToNumber(_drv->_connect), _transactId);
return true;
}
bool Transaction::commit()
{
pid_t threadId = trd::gettid();
if (_drv->threadId() != threadId)
{
log_error_m << "Failed commit transaction, threads identifiers not match"
<< ". Connection thread id: " << _drv->threadId()
<< ", current thread id: " << threadId;
return false;
}
if (!_drv->transactAddrIsEqual(this))
{
log_error_m << "Failed commit transaction, transaction not captured";
return false;
}
if (_drv->operationIsAborted())
{
log_error_m << "Failed commit transaction, sql-operation aborted"
<< ". Connect: " << addrToNumber(_drv->_connect);
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
log_error_m << "Failed commit transaction, database not open";
return false;
}
if (!_isActive)
{
log_error_m << "Failed commit transaction, transaction not begun"
<< ". Connect: " << addrToNumber(_drv->_connect);
return false;
}
PGresultPtr pgres = pqexec(_drv->_connect, "COMMIT");
ExecStatusType status = pqexecStatus(pgres);
if (status != PGRES_COMMAND_OK)
{
const char* detail = PQerrorMessage(_drv->_connect);
log_error_m << log_format("Failed commit transaction: %?/%?. %?",
addrToNumber(_drv->_connect), _transactId, detail);
_isActive = false;
_transactId = -1;
return false;
}
log_debug2_m << log_format("Transaction commit: %?/%?",
addrToNumber(_drv->_connect), _transactId);
_isActive = false;
_transactId = -1;
return true;
}
bool Transaction::rollback()
{
pid_t threadId = trd::gettid();
if (_drv->threadId() != threadId)
{
log_error_m << "Failed rollback transaction, threads identifiers not match"
<< ". Connection thread id: " << _drv->threadId()
<< ", current thread id: " << threadId;
return false;
}
if (!_drv->transactAddrIsEqual(this))
{
log_error_m << "Failed rollback transaction, transaction not captured";
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
log_error_m << "Failed rollback transaction, database not open";
return false;
}
if (!_isActive)
{
log_error_m << "Failed rollback transaction, transaction not begun"
<< ". Connect: " << addrToNumber(_drv->_connect);
return false;
}
PGresultPtr result = pqexec(_drv->_connect, "ROLLBACK");
ExecStatusType status = pqexecStatus(result);
if (status != PGRES_COMMAND_OK)
{
const char* detail = PQerrorMessage(_drv->_connect);
log_error_m << log_format("Failed rollback transaction: %?/%?. %?",
addrToNumber(_drv->_connect), _transactId, detail);
_isActive = false;
_transactId = -1;
return false;
}
log_debug2_m << log_format("Transaction rollback: %?/%?",
addrToNumber(_drv->_connect), _transactId);
_isActive = false;
_transactId = -1;
return true;
}
bool Transaction::isActive() const
{
return _isActive;
}
//---------------------------------- Result ----------------------------------
// Выводит в лог сокращенное описание ошибки без идентификатора транзакции
#define SET_LAST_ERROR1(MSG, ERR_TYPE) \
setLastError1(MSG, ERR_TYPE, __func__, __LINE__);
// Выводит в лог детализированное описание ошибки с идентификатором транзакции
#define SET_LAST_ERROR2(MSG, ERR_TYPE, DETAIL) \
setLastError2(MSG, ERR_TYPE, __func__, __LINE__, DETAIL);
#define CHECK_ERROR(MSG, ERR_TYPE) \
checkError(MSG, ERR_TYPE, pgres, __func__, __LINE__)
#define PGR(CMD) PGresultPtr{CMD}
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();
}
void Result::setLastError1(const QString& msg, QSqlError::ErrorType type,
const char* func, int line)
{
setLastError(QSqlError("PostgresResult", msg, type, "1"));
constexpr const char* file_name = alog::detail::file_name(__FILE__);
alog::logger().error(file_name, func, line, "PostgresDrv") << msg;
}
void Result::setLastError2(const QString& msg, QSqlError::ErrorType type,
const char* func, int line, const char* detail)
{
setLastError(QSqlError("PostgresResult", msg, type, "1"));
constexpr const char* file_name = alog::detail::file_name(__FILE__);
quint64 connectId = addrToNumber(_drv->_connect);
alog::Line logLine = alog::logger().error(file_name, func, line, "PostgresDrv")
<< log_format("%?. Transact: %?/%?", msg, connectId, transactId());
if (detail)
logLine << ". " << detail;
}
bool Result::checkError(const char* msg, QSqlError::ErrorType type,
const PGresult* result, const char* func, int line)
{
int status = PQresultStatus(result);
if (status == PGRES_FATAL_ERROR)
{
const char* detail = PQerrorMessage(_drv->_connect);
setLastError2(msg, type, func, line, detail);
return true;
}
return false;
}
bool Result::isSelectSql() const
{
return isSelect();
}
void Result::cleanup()
{
log_debug2_m << "Begin dataset cleanup. Connect: " << addrToNumber(_drv->_connect);
if (!_externalTransact)
if (_internalTransact && _internalTransact->isActive())
{
if (isSelectSql())
rollbackInternalTransact();
else
commitInternalTransact();
}
_stmt.reset();
if (!_stmtName.isEmpty())
{
QByteArray sql = "DEALLOCATE " + _stmtName;
PGresultPtr pgres = pqexec(_drv->_connect, sql);
QByteArray msg = "Failed deallocate statement " + _stmtName;
CHECK_ERROR(msg, QSqlError::StatementError);
}
_stmtName.clear();
_preparedQuery.clear();
_numRowsAffected = -1;
SqlCachedResult::cleanup();
log_debug2_m << "End dataset cleanup. Connect: " << addrToNumber(_drv->_connect);
}
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_ERROR1("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_ERROR1("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_ERROR1("Failed rollback internal transaction",
QSqlError::TransactionError)
return false;
}
log_debug2_m << "Internal transaction rollback";
return true;
}
quint64 Result::transactId() const
{
if (_externalTransact)
return _externalTransact->transactId();
if (_internalTransact)
return _internalTransact->transactId();
return 0;
}
bool Result::prepare(const QString& query)
{
pid_t threadId = trd::gettid();
if (_drv->threadId() != threadId)
{
log_error_m << "Failed prepare query, threads identifiers not match"
<< ". Connection thread id: " << _drv->threadId()
<< ", current thread id: " << threadId;
return false;
}
if (_drv->operationIsAborted())
{
SET_LAST_ERROR1("Sql-operation aborted", QSqlError::UnknownError)
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
SET_LAST_ERROR1("Database not open", QSqlError::ConnectionError)
return false;
}
QString pgQuery;
pgQuery.reserve(query.length() * 1.2);
int ind = 1;
for (QChar ch : query)
{
if (ch == '?')
{
pgQuery += QChar('$');
pgQuery += QString::number(ind++);
}
else
pgQuery += ch;
}
cleanup();
setActive(false);
setAt(QSql::BeforeFirstRow);
if (!beginInternalTransact())
return false;
if (alog::logger().level() == alog::Level::Debug2)
{
QString sql = pgQuery;
static QRegularExpression reg {R"(\s{2,})"};
sql.replace(reg, " ");
sql.replace(" ,", ",");
if (!sql.isEmpty() && (sql[0] == QChar(' ')))
sql.remove(0, 1);
log_debug2_m << log_format("Begin prepare query. Transact: %?/%?. %?",
addrToNumber(_drv->_connect), transactId(), sql);
}
PGresultPtr pgres;
QByteArray stmtName = genStmtName();
pgres = PGR(PQprepare(_drv->_connect, stmtName, pgQuery.toUtf8(), 0, nullptr));
if (CHECK_ERROR("Could not prepare statement", QSqlError::StatementError))
{
rollbackInternalTransact();
return false;
}
_stmtName = stmtName;
pgres = PGR(PQdescribePrepared(_drv->_connect, _stmtName));
if (CHECK_ERROR("Could not get describe for prepared statement",
QSqlError::StatementError))
{
rollbackInternalTransact();
return false;
}
_stmt = pgres;
// nfields - число столбцов (полей) в каждой строке полученной выборки.
// При выполнении INSERT или UPDATE запросов, количество столбцов будет
// равно 0. В этом случае запрос будет установлен как "Not Select"
int nfields = PQnfields(_stmt);
setSelect(nfields != 0);
_preparedQuery = pgQuery;
log_debug2_m << log_format("End prepare query. Transact: %?/%?",
addrToNumber(_drv->_connect), transactId());
return true;
}
bool Result::exec()
{
pid_t threadId = trd::gettid();
if (_drv->threadId() != threadId)
{
log_error_m << "Failed exec query, threads identifiers not match"
<< ". Connection thread id: " << _drv->threadId()
<< ", current thread id: " << threadId;
return false;
}
if (_drv->operationIsAborted())
{
SET_LAST_ERROR1("Sql-operation aborted", QSqlError::UnknownError)
return false;
}
if (!_drv->isOpen() || _drv->isOpenError())
{
SET_LAST_ERROR1("Database not open", QSqlError::ConnectionError)
return false;
}
if (!beginInternalTransact())
return false;
log_debug2_m << log_format("Start exec query. Transact: %?/%?",
addrToNumber(_drv->_connect), transactId());
setActive(false);
setAt(QSql::BeforeFirstRow);
QueryParams params;
int nparams = PQnparams(_stmt);
if (nparams != 0)
{
params.init(nparams);
const QVector<QVariant>& values = boundValues();
if (alog::logger().level() == alog::Level::Debug2)
{
for (int i = 0; i < values.count(); ++i)
log_debug2_m << "Query param" << i << ": " << values[i];
}
if (values.count() != nparams)
{
QString msg = "Parameter mismatch, expected %1, got %2 parameters";
msg = msg.arg(nparams).arg(values.count());
SET_LAST_ERROR2(msg, QSqlError::StatementError, 0)
rollbackInternalTransact();
return false;
}
for (int i = 0; i < nparams; ++i)
{
const QVariant& val = values[i];
if (val.isNull())
continue;
if (!val.isValid())
{
QString msg = "Query param%1 is invalid";
SET_LAST_ERROR2(msg.arg(i), QSqlError::StatementError, 0)
rollbackInternalTransact();
return false;
}
else if (val.userType() == qMetaTypeId<QUuidEx>())
{
const QUuidEx& uuid = val.value<QUuidEx>();
if (uuid.isNull())
continue;
}
else if (val.type() == QVariant::Uuid)
{
const QUuid& uuid = val.value<QUuid>();
if (uuid.isNull())
continue;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
int paramtype = PQparamtype(_stmt, i);
switch (paramtype)
{
case PG_TYPE_BOOL:
{
bool v = val.toBool();
int sz = 1;
params.paramValues[i] = (char*)malloc(sz);
params.paramLengths[i] = sz;
*(params.paramValues[i]) = v;
break;
}
case PG_TYPE_INT8:
{
qint8 v = val.toInt();
int sz = sizeof(v);
params.paramValues[i] = (char*)malloc(sz);
params.paramLengths[i] = sz;
*((qint8*)params.paramValues[i]) = v;
break;
}
case PG_TYPE_INT16:
{
qint16 v = val.toInt();
int sz = sizeof(v);
params.paramValues[i] = (char*)malloc(sz);
params.paramLengths[i] = sz;
*((qint16*)params.paramValues[i]) = bswap_16(v);
break;
}
case PG_TYPE_INT32:
{
qint32 v = val.toInt();
int sz = sizeof(v);
params.paramValues[i] = (char*)malloc(sz);
params.paramLengths[i] = sz;
*((qint32*)params.paramValues[i]) = bswap_32(v);
break;