-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQorePGConnection.cpp
More file actions
3394 lines (2989 loc) · 118 KB
/
QorePGConnection.cpp
File metadata and controls
3394 lines (2989 loc) · 118 KB
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
/* -*- indent-tabs-mode: nil -*- */
/*
QorePGConnection.cpp
Qore Programming Language
Copyright 2003 - 2026 Qore Technologies, s.r.o.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "pgsql.h"
#include "QorePGConnection.h"
#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <cmath>
#include <limits>
#include <ctype.h>
#include <memory>
#include <typeinfo>
// postgresql uses an epoch starting at 2000-01-01, which is
// 10,957 days after the UNIX and Qore epoch of 1970-01-01
// there are 86,400 seconds in the average day (w/o DST changes)
#define PGSQL_EPOCH_OFFSET (10957 * 86400)
//------------------------------------------------------------------------------
// QorePGCancelHelper implementation
//------------------------------------------------------------------------------
QorePGCancelHelper::QorePGCancelHelper(PGconn* conn)
: conn(conn), cancel_obj(nullptr) {
if (smh && conn) {
// Get a cancel object that can be used from another thread
PGcancel* co = PQgetCancel(conn);
cancel_obj.store(co, std::memory_order_release);
if (co) {
// Register cancel callback
smh->registerCancelCallback(this, [this]() -> bool {
// Load pointer atomically - it may be set to nullptr by destructor
PGcancel* co = this->cancel_obj.load(std::memory_order_acquire);
if (co) {
char errbuf[256];
int result = PQcancel(co, errbuf, sizeof(errbuf));
return result != 0;
}
return false;
});
}
}
}
QorePGCancelHelper::~QorePGCancelHelper() {
// Get the cancel object and set to nullptr atomically before unregistering
// to prevent use-after-free if a callback is currently being invoked
PGcancel* co = cancel_obj.exchange(nullptr, std::memory_order_acq_rel);
if (smh && co) {
// Unregister the callback
smh->unregisterCancelCallback(this);
}
if (co) {
PQfreeCancel(co);
}
}
// Helper function to check for interrupt before connection attempt
static PGconn* pgsql_connect_with_interrupt_check(const char* str, ExceptionSink* xsink) {
if (qore_check_cancel(xsink)) {
return nullptr;
}
return PQconnectdb(str);
}
// declare static members
qore_pg_data_map_t QorePgsqlStatement::data_map;
qore_pg_array_data_map_t QorePgsqlStatement::array_data_map;
qore_pg_array_type_map_t QorePgsqlStatement::array_type_map;
#ifdef DEBUG
void do_output(char* p, unsigned len) {
for (unsigned i = 0; i < len; ++i)
printd(0, "do_output: %2d: %02x\n", i, (int)p[i]);
}
#endif
void qore_pg_numeric::convertToHost() {
ndigits = ntohs(ndigits);
weight = ntohs(weight);
sign = ntohs(sign);
dscale = ntohs(dscale);
#ifdef DEBUG_1
printd(0, "qpg_data_numeric::convertToHost() ndigits: %hd weight: %hd sign: %hd dscale: %hd\n", ndigits, weight, sign, dscale);
for (unsigned i = 0; i < ndigits; ++i)
printd(0, " + %hu\n", ntohs(digits[i]));
#endif
}
QoreValue qore_pg_numeric::toOptimal() const {
QoreString str;
toStr(str);
//printd(5, "qore_pg_numeric::toOptimal() processing %s ndigits: %d weight: %d sign: %d cmp: %d\n", str.c_str(), ndigits, weight, sign, strcmp(str.c_str(), "-9223372036854775808"));
// return an integer if the number can be converted to a 64-bit integer
if ((ndigits <= (weight + 1)) && (ndigits < 4
|| (ndigits == 5 &&
((!sign && strcmp(str.c_str(), "9223372036854775807") <= 0)
||(sign && strcmp(str.c_str(), "-9223372036854775808") <= 0)))))
return str.toBigInt();
return new QoreNumberNode(str.c_str());
}
QoreStringNode* qore_pg_numeric::toString() const {
QoreStringNode* str = new QoreStringNode;
toStr(*str);
return str;
}
QoreNumberNode* qore_pg_numeric::toNumber() const {
QoreString str;
toStr(str);
return new QoreNumberNode(str.c_str());
}
void qore_pg_numeric::toStr(QoreString& str) const {
if (!ndigits) {
str.concat('0');
return;
}
if (sign)
str.concat('-');
//printd(5, "qore_pg_numeric::toStr() ndigits: %d dscale: %d\n", ndigits, dscale);
int i;
for (i = 0; i < ndigits; ++i) {
if (i == weight + 1)
str.concat('.');
if (i || weight < 0)
str.sprintf("%04d", ntohs(digits[i]));
else
str.sprintf("%d", ntohs(digits[i]));
//printd(5, "qore_pg_numeric::toStr() digit %d: %d\n", i, ntohs(digits[i]));
}
//printd(5, "qore_pg_numeric::toStr() i: %d weight: %d str: %s\n", i, weight, str.c_str());
// now add significant zeros for remaining decimal places
if (weight >= i)
str.addch('0', (weight - i + 1) * 4);
else if (weight < -1) {
for (int i = weight; i < -1; ++i)
str.insert("0000", 0);
str.prepend(".");
}
//printd(5, "qore_pg_numeric::toStr() str: '%s'\n", str.c_str());
}
size_t qore_pg_numeric::rawSize() const {
return sizeof(qore_pg_numeric_base) + sizeof(short) * ntohs(ndigits);
}
qore_pg_numeric_out::qore_pg_numeric_out(const QoreNumberNode* n) {
QoreString str;
n->getStringRepresentation(str);
//printd(5, "qore_pg_numeric_out::qore_pg_numeric_out() this %p str: '%s'\n", this, str.c_str());
// populate structure
int nsign = n->sign();
if (nsign < 0) {
// this is what the server sends for negative numbers
sign = 0x4000;
// remove the minus sign from the string
str.trim_leading('-');
}
qore_offset_t di = str.find('.');
if (di == -1)
di = str.strlen();
//printd(5, "find: '%s' di: %lld\n", str.c_str(), di);
char buf[5];
int i = 0;
if (di != 1 || str[0] != '0') {
while (i < di) {
// get the remaining number of digits up to the decimal place
int nd = (di - i) % 4;
if (!nd)
nd = 4;
for (int j = 0; j < nd; ++j)
buf[j] = (str.c_str() + i)[j];
buf[nd] = '\0';
digits[ndigits++] = atoi(buf);
if (ndigits > 1)
++weight;
//printd(5, "adding digits: '%s' (%d)\n", buf, atoi(buf));
i += nd;
}
} else {
weight = -1;
i = 1;
}
// now add digits after the decimal point
if (i != (int)str.size()) {
// skip decimal point
++i;
di = str.size();
while (i < di) {
int nd = di - i;
dscale += nd;
if (nd > 4)
nd = 4;
for (int j = 0; j < nd; ++j)
buf[j] = (str.c_str() + i)[j];
while (nd < 4)
buf[nd++] = '0';
buf[nd] = '\0';
digits[ndigits++] = atoi(buf);
//printd(5, "adding (after decimal point) digits: '%s' (%d)\n", buf, atoi(buf));
i += 4;
}
} else if (ndigits) {
// trim off trailing zeros when there are no digits after the decimal point
while (!digits[ndigits - 1]) {
--ndigits;
}
}
convertToNet();
}
void qore_pg_numeric_out::convertToNet() {
size = sizeof(short) * (4 + ndigits);
printd(5, "qore_pg_numeric_out::convertToNet() ndigits: %hd weight: %hd sign: %hd dscale: %hd size: %d\n",
ndigits, weight, sign, dscale, size);
assert(ndigits >= 0 && ndigits < QORE_MAX_DIGITS);
for (unsigned i = 0; i < (unsigned)ndigits; ++i) {
//printd(5, " + %hu\n", digits[i]);
digits[i] = htons(digits[i]);
}
ndigits = htons(ndigits);
weight = htons(weight);
sign = htons(sign);
dscale = htons(dscale);
//do_output((char*)this, size);
}
// bind functions
static QoreValue qpg_data_bool(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
return *((bool*)data);
}
static QoreValue qpg_data_bytea(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
void* dc = malloc(len);
memcpy(dc, data, len);
return new BinaryNode(dc, len);
}
static QoreValue qpg_data_char(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
QoreStringNode* rv = new QoreStringNode(data, len);
rv->trim_trailing();
return rv;
}
static QoreValue qpg_data_int8(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
return MSBi8(*((uint64_t *)data));
}
static QoreValue qpg_data_int4(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
// Cast to signed to handle negative values correctly
return (int32_t)ntohl(*((uint32_t *)data));
}
static QoreValue qpg_data_int2(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
// Cast to signed to handle negative values correctly
return (int16_t)ntohs(*((uint16_t *)data));
}
static QoreValue qpg_data_text(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
return new QoreStringNode((char*)data, len, enc);
}
static QoreValue qpg_data_jsonb(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
// skip initial 0x01 byte at the beginning of JSONB data returned
if (data[0] == 1) {
++data;
--len;
}
return new QoreStringNode((char*)data, len, enc);
}
static QoreValue qpg_data_float4(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
float fv = MSBf4(*((float *)data));
return (double)fv;
}
static QoreValue qpg_data_float8(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
double fv = MSBf8(*((double *)data));
return fv;
}
static QoreValue qpg_data_abstime(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
int val = ntohl(*((uint32_t *)data));
return DateTimeNode::makeAbsolute(conn->getTZ(), (int64)val, 0);
}
static QoreValue qpg_data_reltime(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
int val = ntohl(*((uint32_t *)data));
return new DateTimeNode(0, 0, 0, 0, 0, val, 0, true);
}
static QoreValue qpg_data_timestamptz(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
if (conn->has_integer_datetimes()) {
int64 val = MSBi8(*((uint64_t *)data));
int64 secs = val / 1000000;
int us = val % 1000000;
secs += PGSQL_EPOCH_OFFSET;
return DateTimeNode::makeAbsolute(conn->getTZ(), secs, us);
}
double fv = MSBf8(*((double *)data));
int64 nv = (int64)fv;
int us = (int)((fv - (double)nv) * 1000000.0);
nv += PGSQL_EPOCH_OFFSET;
return DateTimeNode::makeAbsolute(conn->getTZ(), nv, us);
}
static QoreValue qpg_data_timestamp(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
if (conn->has_integer_datetimes()) {
int64 val = MSBi8(*((uint64_t *)data));
// convert from u-secs to seconds and milliseconds
int64 secs = val / 1000000;
int us = val % 1000000;
secs += PGSQL_EPOCH_OFFSET;
return DateTimeNode::makeAbsoluteLocal(conn->getTZ(), secs, us);
}
double fv = MSBf8(*((double *)data));
int64 nv = (int64)fv;
int us = (int)((fv - (double)nv) * 1000000.0);
nv += PGSQL_EPOCH_OFFSET;
return DateTimeNode::makeAbsolute(conn->getTZ(), nv, us);
}
// the DATEOID format is a signed 32-bit integer giving the day offset from 2000-01-01
static QoreValue qpg_data_date(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
int32_t val = ntohl(*((int32_t*)data));
int64 v = (static_cast<int64>(val) + 10957) * 86400;
return new DateTimeNode(v);
}
static QoreValue qpg_data_interval(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
int64 secs;
int hours;
int minutes;
qore_pg_interval *iv = (qore_pg_interval *)data;
// create interval with microsecond resolution
int64 us;
if (conn->has_integer_datetimes()) {
us = MSBi8(iv->time.i);
secs = us / 1000000;
us %= 1000000;
//printd(5, "got interval %lld: secs: %lld us: %lld (day: %d)\n", MSBi8(iv->time.i), secs, us, conn->has_interval_day());
} else {
double f = MSBf8(iv->time.f);
secs = (int64)f;
us = (int)((f - (double)secs) * 1000000.0);
}
hours = secs / 3600;
if (hours)
secs -= hours * 3600;
minutes = secs / 60;
if (minutes)
secs -= minutes* 60;
if (conn->has_interval_day())
return DateTimeNode::makeRelative(0, ntohl(iv->rest.with_day.month), ntohl(iv->rest.with_day.day), hours, minutes, secs, us);
return DateTimeNode::makeRelative(0, ntohl(iv->rest.month), 0, hours, minutes, secs, us);
}
static QoreValue qpg_data_time(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
int64 secs;
int us;
if (conn->has_integer_datetimes()) {
int64 val = MSBi8(*((uint64_t *)data));
secs = val / 1000000;
us = val % 1000000;
} else {
double val = MSBf8(*((double *)data));
secs = (int64)val;
us = (int)((val - (double)secs) * 1000000.0);
}
//printd(5, "qpg_data_time() %lld.%06d\n", secs, us);
// create the date/time value from an offset in the current time zone
return DateTimeNode::makeAbsoluteLocal(conn->getTZ(), secs, us);
}
static QoreValue qpg_data_timetz(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
qore_pg_time_tz_adt *tm = (qore_pg_time_tz_adt *)data;
int64 secs;
// postgresql gives the time zone in seconds west of UTC
int zone = ntohl(tm->zone);
int us;
if (conn->has_integer_datetimes()) {
int64 val = MSBi8(tm->time.i);
secs = val / 1000000;
us = val % 1000000;
} else {
double val = MSBf8(tm->time.f);
secs = (int64)val;
us = (int)((val - (double)secs) * 1000000.0);
}
//printd(5, "zone: %d secs: %lld.%06d\n", zone, secs, us);
return DateTimeNode::makeAbsoluteLocal(findCreateOffsetZone(-zone), secs, us);
}
static QoreValue qpg_data_tinterval(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
//printd(5, "qpg_data_tinterval(row: %d, col: %d, type: %d) this: %p len: %d\n", row, col, type, this, len);
TimeIntervalData *td = (TimeIntervalData*)data;
int64 i = (int64)(int)ntohl(td->data[0]);
DateTime dt(i);
QoreStringNode* str = new QoreStringNode();
str->sprintf("[\"%04d-%02d-%02d %02d:%02d:%02d\" ", dt.getYear(), dt.getMonth(), dt.getDay(), dt.getHour(), dt.getMinute(), dt.getSecond());
dt.setDate((int64)ntohl(td->data[1]));
str->sprintf("\"%04d-%02d-%02d %02d:%02d:%02d\"]", dt.getYear(), dt.getMonth(), dt.getDay(), dt.getHour(), dt.getMinute(), dt.getSecond());
// NOTE: ignoring tinverval->status, it is assumed that any value here will be valid
//printd(5, "status: %d s0: %d s1: %d\n", ntohl(td->status), s0, s1);
return str;
}
static QoreValue qpg_data_numeric(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
// issue #4249: we cannot write directly to the data, as we may be called multiple times on the same data
qore_pg_numeric* num = reinterpret_cast<qore_pg_numeric*>(data);
size_t size = num->rawSize();
qore_pg_numeric* nd = (qore_pg_numeric*)malloc(size);
ON_BLOCK_EXIT(free, nd);
memcpy(nd, num, size);
nd->convertToHost();
int nc = conn->getNumeric();
if (nc == OPT_NUM_OPTIMAL)
return nd->toOptimal();
if (nc == OPT_NUM_NUMERIC)
return nd->toNumber();
assert(nc == OPT_NUM_STRING);
return nd->toString();
}
static QoreValue qpg_data_cash(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
double f = (double)ntohl(*((uint32_t*)data)) / 100.0;
//printd(5, "qpg_data_cash() f: %g\n", f);
return f;
}
static QoreValue qpg_data_macaddr(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
QoreStringNode* str = new QoreStringNode;
for (int i = 0; i < 5; i++) {
str->concatHex((char*)data + i, 1);
str->concat(':');
}
str->concatHex((char*)data+5, 1);
return str;
}
static QoreValue qpg_data_inet(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
qore_pg_inet_struct *is = (qore_pg_inet_struct *)data;
QoreStringNode* str = new QoreStringNode();
if (is->family == PGSQL_AF_INET) {
for (int i = 0, e = is->length - 1; i < e; i++)
str->sprintf("%d.", is->ipaddr[i]);
str->sprintf("%d/%d", is->ipaddr[3], is->bits);
} else {
short *sp;
int i, val, e, last = 0;
if (type == CIDROID)
e = is->bits / 8;
else
e = is->length;
if (e == 16) {
e -= 2;
last = 1;
}
for (i = 0; i < e; i += 2) {
sp = (short *)&is->ipaddr[i];
val = ntohs(*sp);
str->sprintf("%x:", val);
}
if (last) {
sp = (short *)&is->ipaddr[i];
val = ntohs(*sp);
str->sprintf("%x", val);
} else
str->concat(':');
str->sprintf("/%d", is->bits);
}
return str;
}
static QoreValue qpg_data_tid(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
qore_pg_tuple_id *ti = (qore_pg_tuple_id *)data;
unsigned block = ntohl(ti->block);
unsigned index = ntohs(ti->index);
QoreStringNode* str = new QoreStringNode;
str->sprintf("(%u,%u)", block, index);
return str;
}
static QoreValue qpg_data_bit(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
qore_pg_bit *bp = (qore_pg_bit *)data;
int num = (ntohl(bp->size) - 1) / 8 + 1;
BinaryNode* b = new BinaryNode;
b->append(bp->data, num);
return b;
}
static QoreValue qpg_data_point(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
Point p;
assign_point(p, (Point*)data);
QoreStringNode* str = new QoreStringNode;
str->sprintf("%g,%g", p.x, p.y);
return str;
}
static QoreValue qpg_data_lseg(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
Point p;
assign_point(p, &((LSEG *)data)->p[0]);
QoreStringNode* str = new QoreStringNode;
str->sprintf("(%g,%g),", p.x, p.y);
assign_point(p, &((LSEG *)data)->p[1]);
str->sprintf("(%g,%g)", p.x, p.y);
return str;
}
// NOTE: This is functionally identical to LSEG above
static QoreValue qpg_data_box(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
Point p0, p1;
assign_point(p0, &((BOX *)data)->high);
assign_point(p1, &((BOX *)data)->low);
QoreStringNode* str = new QoreStringNode;
str->sprintf("(%g,%g),(%g,%g)", p0.x, p0.y, p1.x, p1.y);
return str;
}
static QoreValue qpg_data_path(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
unsigned npts = ntohl(*((int*)((char*)data + 1)));
bool closed = ntohl(*((char*)data));
//printd(5, "npts: %d closed: %d\n", npts, closed);
QoreStringNode* str = new QoreStringNode();
str->concat(closed ? '(' : '[');
Point p;
for (unsigned i = 0; i < npts; ++i) {
assign_point(p, (Point*)(((char*)data) + 5 + (sizeof(Point)) * i));
str->sprintf("(%g,%g)", p.x, p.y);
if (i != (npts - 1))
str->concat(',');
}
str->concat(closed ? ')' : ']');
return str;
}
static QoreValue qpg_data_polygon(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
unsigned npts = ntohl(*((int*)data));
QoreStringNode* str = new QoreStringNode('(');
Point p;
for (unsigned i = 0; i < npts; ++i) {
assign_point(p, (Point*)(((char*)data) + 4 + (sizeof(Point)) * i));
str->sprintf("(%g,%g)", p.x, p.y);
if (i != (npts - 1))
str->concat(',');
}
str->concat(')');
return str;
}
static QoreValue qpg_data_circle(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
//printd(5, "qpg_data_circle(row: %d, col: %d, type: %d) this: %p len: %d\n", row, col, type, this, len);
QoreStringNode* str = new QoreStringNode;
Point p;
assign_point(p, &((CIRCLE *)data)->center);
double radius = MSBf8(((CIRCLE *)data)->radius);
str->sprintf("<(%g,%g),%g>", p.x, p.y, radius);
return str;
}
static QoreValue qpg_data_uuid(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
// UUID is 16 bytes in binary format
if (len != 16) {
return new QoreStringNode(data, len, enc);
}
unsigned char* uuid = (unsigned char*)data;
QoreStringNode* str = new QoreStringNode;
str->sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
uuid[0], uuid[1], uuid[2], uuid[3],
uuid[4], uuid[5],
uuid[6], uuid[7],
uuid[8], uuid[9],
uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
return str;
}
//! Converts an IEEE 754 half-precision (16-bit) float to double
static double half_to_double(uint16_t h) {
uint32_t sign = (h >> 15) & 0x1;
uint32_t exponent = (h >> 10) & 0x1f;
uint32_t mantissa = h & 0x3ff;
double result;
if (exponent == 0) {
// subnormal or zero
result = std::ldexp((double)mantissa, -24);
} else if (exponent == 31) {
// inf or NaN
if (mantissa == 0) {
result = std::numeric_limits<double>::infinity();
} else {
result = std::numeric_limits<double>::quiet_NaN();
}
} else {
// normalized
result = std::ldexp((double)(mantissa + 1024), exponent - 25);
}
return sign ? -result : result;
}
//! Converts pgvector binary format to Qore list<float>
/** Binary format: [int16: dim][int16: unused][float4 x dim: elements]
*/
static QoreValue qpg_data_vector(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
if (len < 4) {
return new QoreStringNode(data, len, enc);
}
int16_t dim = ntohs(*((int16_t*)data));
// skip unused field at data + 2
if (dim < 0) {
return new QoreStringNode(data, len, enc);
}
int expected_len = 4 + dim * (int)sizeof(float);
if (len < expected_len) {
return new QoreStringNode(data, len, enc);
}
ReferenceHolder<QoreListNode> l(new QoreListNode(floatTypeInfo), nullptr);
float* elements = (float*)(data + 4);
for (int i = 0; i < dim; ++i) {
float val = MSBf4(elements[i]);
l->push((double)val, nullptr);
}
return l.release();
}
//! Converts pgvector halfvec binary format to Qore list<float>
/** Binary format: [int16: dim][int16: unused][uint16 (IEEE 754 half) x dim: elements]
*/
static QoreValue qpg_data_halfvec(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
if (len < 4) {
return new QoreStringNode(data, len, enc);
}
int16_t dim = ntohs(*((int16_t*)data));
// skip unused field at data + 2
if (dim < 0) {
return new QoreStringNode(data, len, enc);
}
int expected_len = 4 + dim * 2;
if (len < expected_len) {
return new QoreStringNode(data, len, enc);
}
ReferenceHolder<QoreListNode> l(new QoreListNode(floatTypeInfo), nullptr);
uint16_t* elements = (uint16_t*)(data + 4);
for (int i = 0; i < dim; ++i) {
uint16_t raw = ntohs(elements[i]);
double val = half_to_double(raw);
l->push(val, nullptr);
}
return l.release();
}
//! Converts pgvector sparsevec binary format to Qore hash
/** Binary format: [int32: dim][int32: nnz][int32 x nnz: indices][float4 x nnz: values]
*/
static QoreValue qpg_data_sparsevec(char* data, int type, int len, QorePGConnection* conn, const QoreEncoding* enc) {
if (len < 8) {
return new QoreStringNode(data, len, enc);
}
int32_t dim = ntohl(*((int32_t*)data));
int32_t nnz = ntohl(*((int32_t*)(data + 4)));
if (nnz < 0) {
return new QoreStringNode(data, len, enc);
}
int expected_len = 8 + nnz * (int)(sizeof(int32_t) + sizeof(float));
if (len < expected_len) {
return new QoreStringNode(data, len, enc);
}
ReferenceHolder<QoreHashNode> h(new QoreHashNode(autoTypeInfo), nullptr);
h->setKeyValue("dim", (int64)dim, nullptr);
h->setKeyValue("nnz", (int64)nnz, nullptr);
ReferenceHolder<QoreListNode> indices(new QoreListNode(bigIntTypeInfo), nullptr);
ReferenceHolder<QoreListNode> values(new QoreListNode(floatTypeInfo), nullptr);
int32_t* idx_ptr = (int32_t*)(data + 8);
float* val_ptr = (float*)(data + 8 + nnz * sizeof(int32_t));
for (int i = 0; i < nnz; ++i) {
indices->push((int64)ntohl(idx_ptr[i]), nullptr);
float val = MSBf4(val_ptr[i]);
values->push((double)val, nullptr);
}
h->setKeyValue("indices", indices.release(), nullptr);
h->setKeyValue("values", values.release(), nullptr);
return h.release();
}
//! Converts a Qore list of floats to pgvector text format "[1.5,2.3,4.1]"
static QoreString* qpg_vector_to_text(const QoreListNode* l) {
std::unique_ptr<QoreString> str(new QoreString("["));
ConstListIterator li(l);
while (li.next()) {
if (!li.first()) {
str->concat(',');
}
QoreValue v = li.getValue();
str->sprintf("%.9g", v.getAsFloat());
}
str->concat(']');
return str.release();
}
// static initialization
void QorePgsqlStatement::static_init() {
data_map[BOOLOID] = qpg_data_bool;
data_map[BYTEAOID] = qpg_data_bytea;
data_map[CHAROID] = qpg_data_char;
data_map[BPCHAROID] = qpg_data_char;
// treat UNKNOWNOID as string
data_map[UNKNOWNOID] = qpg_data_char;
data_map[INT8OID] = qpg_data_int8;
data_map[INT4OID] = qpg_data_int4;
data_map[OIDOID] = qpg_data_int4;
data_map[XIDOID] = qpg_data_int4;
data_map[CIDOID] = qpg_data_int4;
//data_map[REGPROCOID] = qpg_data_int4;
data_map[INT2OID] = qpg_data_int2;
data_map[TEXTOID] = qpg_data_text;
data_map[VARCHAROID] = qpg_data_text;
data_map[NAMEOID] = qpg_data_text;
data_map[FLOAT4OID] = qpg_data_float4;
data_map[FLOAT8OID] = qpg_data_float8;
data_map[ABSTIMEOID] = qpg_data_abstime;
data_map[RELTIMEOID] = qpg_data_reltime;
data_map[TIMESTAMPOID] = qpg_data_timestamp;
data_map[TIMESTAMPTZOID] = qpg_data_timestamptz;
data_map[DATEOID] = qpg_data_date;
data_map[INTERVALOID] = qpg_data_interval;
data_map[TIMEOID] = qpg_data_time;
data_map[TIMETZOID] = qpg_data_timetz;
data_map[TINTERVALOID] = qpg_data_tinterval;
data_map[NUMERICOID] = qpg_data_numeric;
data_map[CASHOID] = qpg_data_cash;
data_map[MACADDROID] = qpg_data_macaddr;
data_map[INETOID] = qpg_data_inet;
data_map[CIDROID] = qpg_data_inet;
data_map[TIDOID] = qpg_data_tid;
data_map[BITOID] = qpg_data_bit;
data_map[VARBITOID] = qpg_data_bit;
data_map[POINTOID] = qpg_data_point;
data_map[LSEGOID] = qpg_data_lseg;
data_map[BOXOID] = qpg_data_box;
data_map[PATHOID] = qpg_data_path;
data_map[POLYGONOID] = qpg_data_polygon;
data_map[CIRCLEOID] = qpg_data_circle;
data_map[XMLOID] = qpg_data_text;
data_map[JSONOID] = qpg_data_text;
data_map[JSONBOID] = qpg_data_jsonb;
data_map[UUIDOID] = qpg_data_uuid;
//data_map[INT2VECTOROID] = qpg_data_int2vector;
//data_map[OIDVECTOROID] = qpg_data_oidvector;
//array_data_map[INT2VECTOROID] = std::make_pair(INT2OID, qpg_data_int2);
// NOTE: the casts are necessary with SunPro CC 5.8...
array_data_map[QPGT_INT4ARRAYOID] = std::make_pair(INT4OID, (qore_pg_data_func_t)qpg_data_int4);
array_data_map[QPGT_CIRCLEARRAYOID] = std::make_pair(CIRCLEOID, (qore_pg_data_func_t)qpg_data_circle);
array_data_map[QPGT_MONEYARRAYOID] = std::make_pair(CASHOID, (qore_pg_data_func_t)qpg_data_cash);
array_data_map[QPGT_BOOLARRAYOID] = std::make_pair(BOOLOID, (qore_pg_data_func_t)qpg_data_bool);
array_data_map[QPGT_BYTEAARRAYOID] = std::make_pair(BYTEAOID, (qore_pg_data_func_t)qpg_data_bytea);
array_data_map[QPGT_NAMEARRAYOID] = std::make_pair(NAMEOID, (qore_pg_data_func_t)qpg_data_text);
array_data_map[QPGT_INT2ARRAYOID] = std::make_pair(INT2OID, (qore_pg_data_func_t)qpg_data_int2);
//array_data_map[QPGT_INT2VECTORARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_REGPROCARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
array_data_map[QPGT_TEXTARRAYOID] = std::make_pair(TEXTOID, (qore_pg_data_func_t)qpg_data_text);
array_data_map[QPGT_OIDARRAYOID] = std::make_pair(OIDOID, (qore_pg_data_func_t)qpg_data_int4);
array_data_map[QPGT_TIDARRAYOID] = std::make_pair(TIDOID, (qore_pg_data_func_t)qpg_data_tid);
array_data_map[QPGT_XIDARRAYOID] = std::make_pair(XIDOID, (qore_pg_data_func_t)qpg_data_int4);
array_data_map[QPGT_CIDARRAYOID] = std::make_pair(CIDOID, (qore_pg_data_func_t)qpg_data_int4);
//array_data_map[QPGT_OIDVECTORARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
array_data_map[QPGT_BPCHARARRAYOID] = std::make_pair(BPCHAROID, (qore_pg_data_func_t)qpg_data_char);
array_data_map[QPGT_VARCHARARRAYOID] = std::make_pair(VARCHAROID, (qore_pg_data_func_t)qpg_data_text);
array_data_map[QPGT_INT8ARRAYOID] = std::make_pair(INT8OID, (qore_pg_data_func_t)qpg_data_int8);
array_data_map[QPGT_POINTARRAYOID] = std::make_pair(POINTOID, (qore_pg_data_func_t)qpg_data_point);
array_data_map[QPGT_LSEGARRAYOID] = std::make_pair(LSEGOID, (qore_pg_data_func_t)qpg_data_lseg);
array_data_map[QPGT_PATHARRAYOID] = std::make_pair(PATHOID, (qore_pg_data_func_t)qpg_data_path);
array_data_map[QPGT_BOXARRAYOID] = std::make_pair(BOXOID, (qore_pg_data_func_t)qpg_data_box);
array_data_map[QPGT_FLOAT4ARRAYOID] = std::make_pair(FLOAT4OID, (qore_pg_data_func_t)qpg_data_float4);
array_data_map[QPGT_FLOAT8ARRAYOID] = std::make_pair(FLOAT8OID, (qore_pg_data_func_t)qpg_data_float8);
array_data_map[QPGT_ABSTIMEARRAYOID] = std::make_pair(ABSTIMEOID, (qore_pg_data_func_t)qpg_data_abstime);
array_data_map[QPGT_RELTIMEARRAYOID] = std::make_pair(RELTIMEOID, (qore_pg_data_func_t)qpg_data_reltime);
array_data_map[QPGT_TINTERVALARRAYOID] = std::make_pair(TINTERVALOID, (qore_pg_data_func_t)qpg_data_tinterval);
array_data_map[QPGT_POLYGONARRAYOID] = std::make_pair(POLYGONOID, (qore_pg_data_func_t)qpg_data_polygon);
//array_data_map[QPGT_ACLITEMARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
array_data_map[QPGT_MACADDRARRAYOID] = std::make_pair(MACADDROID, (qore_pg_data_func_t)qpg_data_macaddr);
array_data_map[QPGT_INETARRAYOID] = std::make_pair(INETOID, (qore_pg_data_func_t)qpg_data_inet);
array_data_map[QPGT_CIDRARRAYOID] = std::make_pair(CIDROID, (qore_pg_data_func_t)qpg_data_inet);
array_data_map[QPGT_TIMESTAMPARRAYOID] = std::make_pair(TIMESTAMPOID, (qore_pg_data_func_t)qpg_data_timestamp);
array_data_map[QPGT_DATEARRAYOID] = std::make_pair(DATEOID, (qore_pg_data_func_t)qpg_data_date);
array_data_map[QPGT_TIMEARRAYOID] = std::make_pair(TIMEOID, (qore_pg_data_func_t)qpg_data_time);
array_data_map[QPGT_TIMESTAMPTZARRAYOID] = std::make_pair(TIMESTAMPTZOID, (qore_pg_data_func_t)qpg_data_timestamptz);
array_data_map[QPGT_INTERVALARRAYOID] = std::make_pair(INTERVALOID, (qore_pg_data_func_t)qpg_data_interval);
array_data_map[QPGT_NUMERICARRAYOID] = std::make_pair(NUMERICOID, (qore_pg_data_func_t)qpg_data_numeric);
array_data_map[QPGT_TIMETZARRAYOID] = std::make_pair(TIMETZOID, (qore_pg_data_func_t)qpg_data_timetz);
array_data_map[QPGT_BITARRAYOID] = std::make_pair(BITOID, (qore_pg_data_func_t)qpg_data_bit);
array_data_map[QPGT_VARBITARRAYOID] = std::make_pair(VARBITOID, (qore_pg_data_func_t)qpg_data_bit);
//array_data_map[QPGT_REFCURSORARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_REGPROCEDUREARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_REGOPERARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_REGOPERATORARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_REGCLASSARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_REGTYPEARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
//array_data_map[QPGT_ANYARRAYOID] = std::make_pair(OID, (qore_pg_data_func_t)qpg_data_);
array_data_map[XMLARRAYOID] = std::make_pair(XMLOID, (qore_pg_data_func_t)qpg_data_text);
array_data_map[JSONARRAYOID] = std::make_pair(JSONOID, (qore_pg_data_func_t)qpg_data_text);
array_data_map[JSONBARRAYOID] = std::make_pair(JSONBOID, (qore_pg_data_func_t)qpg_data_jsonb);
array_data_map[QPGT_UUIDARRAYOID] = std::make_pair(UUIDOID, (qore_pg_data_func_t)qpg_data_uuid);
array_type_map[INT4OID] = QPGT_INT4ARRAYOID;
array_type_map[CIRCLEOID] = QPGT_CIRCLEARRAYOID;
array_type_map[CASHOID] = QPGT_MONEYARRAYOID;
array_type_map[BOOLOID] = QPGT_BOOLARRAYOID;
array_type_map[BYTEAOID] = QPGT_BYTEAARRAYOID;
array_type_map[NAMEOID] = QPGT_NAMEARRAYOID;
array_type_map[INT2OID] = QPGT_INT2ARRAYOID;
array_type_map[TEXTOID] = QPGT_TEXTARRAYOID;
array_type_map[OIDOID] = QPGT_OIDARRAYOID;
array_type_map[TIDOID] = QPGT_TIDARRAYOID;
array_type_map[XIDOID] = QPGT_XIDARRAYOID;
array_type_map[CIDOID] = QPGT_CIDARRAYOID;
array_type_map[BPCHAROID] = QPGT_BPCHARARRAYOID;
array_type_map[VARCHAROID] = QPGT_VARCHARARRAYOID;
array_type_map[INT8OID] = QPGT_INT8ARRAYOID;
array_type_map[POINTOID] = QPGT_POINTARRAYOID;
array_type_map[LSEGOID] = QPGT_LSEGARRAYOID;
array_type_map[PATHOID] = QPGT_PATHARRAYOID;
array_type_map[BOXOID] = QPGT_BOXARRAYOID;
array_type_map[FLOAT4OID] = QPGT_FLOAT4ARRAYOID;
array_type_map[FLOAT8OID] = QPGT_FLOAT8ARRAYOID;
array_type_map[ABSTIMEOID] = QPGT_ABSTIMEARRAYOID;
array_type_map[RELTIMEOID] = QPGT_RELTIMEARRAYOID;
array_type_map[TINTERVALOID] = QPGT_TINTERVALARRAYOID;
array_type_map[POLYGONOID] = QPGT_POLYGONARRAYOID;
array_type_map[MACADDROID] = QPGT_MACADDRARRAYOID;
array_type_map[INETOID] = QPGT_INETARRAYOID;
array_type_map[CIDROID] = QPGT_CIDRARRAYOID;
array_type_map[TIMESTAMPOID] = QPGT_TIMESTAMPARRAYOID;
array_type_map[DATEOID] = QPGT_DATEARRAYOID;
array_type_map[TIMEOID] = QPGT_TIMEARRAYOID;
array_type_map[TIMESTAMPTZOID] = QPGT_TIMESTAMPTZARRAYOID;
array_type_map[INTERVALOID] = QPGT_INTERVALARRAYOID;
array_type_map[NUMERICOID] = QPGT_NUMERICARRAYOID;
array_type_map[TIMETZOID] = QPGT_TIMETZARRAYOID;
array_type_map[BITOID] = QPGT_BITARRAYOID;
array_type_map[VARBITOID] = QPGT_VARBITARRAYOID;
array_type_map[XMLOID] = XMLARRAYOID;
array_type_map[JSONOID] = JSONARRAYOID;
array_type_map[JSONBOID] = JSONBARRAYOID;
array_type_map[UUIDOID] = QPGT_UUIDARRAYOID;
}
QorePgsqlStatement::QorePgsqlStatement(QorePGConnection* r_conn, const QoreEncoding* r_enc)
: res(0), nParams(0), allocated(0), paramTypes(0), paramValues(0),
paramLengths(0), paramFormats(0), paramArray(0), conn(r_conn), enc(r_enc), array_size(-1) {
}
QorePgsqlStatement::QorePgsqlStatement(Datasource* ds)
: res(0), nParams(0), allocated(0), paramTypes(0), paramValues(0),
paramLengths(0), paramFormats(0), paramArray(0), conn((QorePGConnection*)ds->getPrivateData()),
enc(ds->getQoreEncoding()), array_size(-1) {
}
QorePgsqlStatement::~QorePgsqlStatement() {
reset();
}
void QorePgsqlStatement::reset() {
if (res) {
PQclear(res);
res = 0;
}
if (allocated) {
parambuf_list_t::iterator i = parambuf_list.begin();
for (int j = 0; j < nParams; ++i, ++j) {
//printd(5, "QorePgsqlStatement::reset() deleting type %d (NUMERICOID = %d)\n", paramTypes[j], NUMERICOID);
if (paramFormats[j] == 0 && !paramArray[j] && (*i)->str) {
// free text-format scalar bind string buffers (TEXTOID, typed text binds, etc.)
free((*i)->str);
} else if (paramTypes[j] == NUMERICOID && (*i)->num) {
//printd(5, "QorePgsqlStatement::reset() deleting num: %p\n", (*i)->num);
delete (*i)->num;
} else if (paramArray[j] && (*i)->ptr) {
free((*i)->ptr);
}
delete *i;
}
// delete any remaining parambufs beyond nParams (e.g. from an error in add())
while (i != parambuf_list.end()) {
delete *i;
++i;
}
parambuf_list.clear();
free(paramTypes);
paramTypes = 0;
free(paramValues);
paramValues = 0;
free(paramLengths);
paramLengths = 0;
free(paramFormats);
paramFormats = 0;
free(paramArray);
paramArray = 0;
allocated = 0;
nParams = 0;
}
array_size = -1;
}
int QorePgsqlStatement::rowsAffected() {
assert(res);
return atoi(PQcmdTuples(res));
}
bool QorePgsqlStatement::hasResultData() {
return PQnfields(res);
}
QoreListNode* QorePgsqlStatement::getArray(int type, qore_pg_data_func_t func, char*& array_data, int current,
int ndim, int dim[]) {
//printd(5, "getArray(type: %d, array_data: %p, current: %d, ndim: %d, dim[%d]: %d)\n", type, array_data, current,
// ndim, current, dim[current]);
QoreListNode* l = new QoreListNode(autoTypeInfo);