-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathpgduckdb_types.cpp
More file actions
1494 lines (1359 loc) · 45.5 KB
/
pgduckdb_types.cpp
File metadata and controls
1494 lines (1359 loc) · 45.5 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
#include "duckdb.hpp"
#include "duckdb/common/shared_ptr.hpp"
#include "duckdb/common/extra_type_info.hpp"
#include "duckdb/common/types/uuid.hpp"
#include "duckdb/common/types/blob.hpp"
#include "pgduckdb/pgduckdb_types.hpp"
#include "pgduckdb/pgduckdb_utils.hpp"
#include "pgduckdb/scan/postgres_scan.hpp"
extern "C" {
#include "pgduckdb/vendor/pg_numeric_c.hpp"
#include "postgres.h"
#include "fmgr.h"
#include "miscadmin.h"
#include "access/tupdesc_details.h"
#include "catalog/pg_type.h"
#include "executor/tuptable.h"
#include "utils/builtins.h"
#include "utils/numeric.h"
#include "utils/uuid.h"
#include "utils/array.h"
#include "fmgr.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/date.h"
#include "utils/timestamp.h"
#include "utils/jsonb.h"
}
#include "pgduckdb/pgduckdb_detoast.hpp"
namespace pgduckdb {
NumericVar FromNumeric(Numeric num);
struct NumericAsDouble : public duckdb::ExtraTypeInfo {
// Dummy struct to indicate at conversion that the source is a Numeric
public:
NumericAsDouble() : ExtraTypeInfo(duckdb::ExtraTypeInfoType::INVALID_TYPE_INFO) {
}
};
// FIXME: perhaps we want to just make a generic ExtraTypeInfo that holds the Postgres type OID
struct IsBpChar : public duckdb::ExtraTypeInfo {
public:
IsBpChar() : ExtraTypeInfo(duckdb::ExtraTypeInfoType::INVALID_TYPE_INFO) {
}
};
using duckdb::hugeint_t;
using duckdb::uhugeint_t;
struct DecimalConversionInteger {
static int64_t
GetPowerOfTen(idx_t index) {
static const int64_t POWERS_OF_TEN[] {1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000};
if (index >= 19) {
throw duckdb::InternalException("DecimalConversionInteger::GetPowerOfTen - Out of range");
}
return POWERS_OF_TEN[index];
}
template <class T>
static T
Finalize(const NumericVar &, T result) {
return result;
}
};
struct DecimalConversionHugeint {
static hugeint_t
GetPowerOfTen(idx_t index) {
static const hugeint_t POWERS_OF_TEN[] {
hugeint_t(1),
hugeint_t(10),
hugeint_t(100),
hugeint_t(1000),
hugeint_t(10000),
hugeint_t(100000),
hugeint_t(1000000),
hugeint_t(10000000),
hugeint_t(100000000),
hugeint_t(1000000000),
hugeint_t(10000000000),
hugeint_t(100000000000),
hugeint_t(1000000000000),
hugeint_t(10000000000000),
hugeint_t(100000000000000),
hugeint_t(1000000000000000),
hugeint_t(10000000000000000),
hugeint_t(100000000000000000),
hugeint_t(1000000000000000000),
hugeint_t(1000000000000000000) * hugeint_t(10),
hugeint_t(1000000000000000000) * hugeint_t(100),
hugeint_t(1000000000000000000) * hugeint_t(1000),
hugeint_t(1000000000000000000) * hugeint_t(10000),
hugeint_t(1000000000000000000) * hugeint_t(100000),
hugeint_t(1000000000000000000) * hugeint_t(1000000),
hugeint_t(1000000000000000000) * hugeint_t(10000000),
hugeint_t(1000000000000000000) * hugeint_t(100000000),
hugeint_t(1000000000000000000) * hugeint_t(1000000000),
hugeint_t(1000000000000000000) * hugeint_t(10000000000),
hugeint_t(1000000000000000000) * hugeint_t(100000000000),
hugeint_t(1000000000000000000) * hugeint_t(1000000000000),
hugeint_t(1000000000000000000) * hugeint_t(10000000000000),
hugeint_t(1000000000000000000) * hugeint_t(100000000000000),
hugeint_t(1000000000000000000) * hugeint_t(1000000000000000),
hugeint_t(1000000000000000000) * hugeint_t(10000000000000000),
hugeint_t(1000000000000000000) * hugeint_t(100000000000000000),
hugeint_t(1000000000000000000) * hugeint_t(1000000000000000000),
hugeint_t(1000000000000000000) * hugeint_t(1000000000000000000) * hugeint_t(10),
hugeint_t(1000000000000000000) * hugeint_t(1000000000000000000) * hugeint_t(100)};
if (index >= 39) {
throw duckdb::InternalException("DecimalConversionHugeint::GetPowerOfTen - Out of range");
}
return POWERS_OF_TEN[index];
}
static hugeint_t
Finalize(const NumericVar &, hugeint_t result) {
return result;
}
};
struct DecimalConversionDouble {
static double
GetPowerOfTen(idx_t index) {
return pow(10, double(index));
}
static double
Finalize(const NumericVar &numeric, double result) {
return result / GetPowerOfTen(numeric.dscale);
}
};
static inline Datum
ConvertBoolDatum(const duckdb::Value &value) {
return value.GetValue<bool>();
}
static inline Datum
ConvertCharDatum(const duckdb::Value &value) {
return value.GetValue<int8_t>();
}
static inline Datum
ConvertInt2Datum(const duckdb::Value &value) {
if (value.type().id() == duckdb::LogicalTypeId::UTINYINT) {
return UInt8GetDatum(value.GetValue<uint8_t>());
}
return Int16GetDatum(value.GetValue<int16_t>());
}
static inline Datum
ConvertInt4Datum(const duckdb::Value &value) {
if (value.type().id() == duckdb::LogicalTypeId::USMALLINT) {
return UInt16GetDatum(value.GetValue<uint16_t>());
}
return Int32GetDatum(value.GetValue<int32_t>());
}
static inline Datum
ConvertInt8Datum(const duckdb::Value &value) {
if (value.type().id() == duckdb::LogicalTypeId::UINTEGER) {
return UInt32GetDatum(value.GetValue<uint32_t>());
}
return Int64GetDatum(value.GetValue<int64_t>());
}
static Datum
ConvertVarCharDatum(const duckdb::Value &value) {
auto str = value.GetValue<duckdb::string>();
auto varchar = str.c_str();
auto varchar_len = str.size();
text *result = (text *)palloc0(varchar_len + VARHDRSZ);
SET_VARSIZE(result, varchar_len + VARHDRSZ);
memcpy(VARDATA(result), varchar, varchar_len);
return PointerGetDatum(result);
}
static Datum
ConvertBinaryDatum(const duckdb::Value &value) {
auto str = value.GetValueUnsafe<duckdb::string_t>();
auto blob_len = str.GetSize();
auto blob = str.GetDataUnsafe();
bytea *result = (bytea *)palloc0(blob_len + VARHDRSZ);
SET_VARSIZE(result, blob_len + VARHDRSZ);
memcpy(VARDATA(result), blob, blob_len);
return PointerGetDatum(result);
}
inline Datum
ConvertDateDatum(const duckdb::Value &value) {
duckdb::date_t date = value.GetValue<duckdb::date_t>();
return date.days - pgduckdb::PGDUCKDB_DUCK_DATE_OFFSET;
}
static Datum
ConvertIntervalDatum(const duckdb::Value &value) {
duckdb::interval_t duckdb_interval = value.GetValue<duckdb::interval_t>();
Interval *pg_interval = static_cast<Interval *>(palloc(sizeof(Interval)));
pg_interval->month = duckdb_interval.months;
pg_interval->day = duckdb_interval.days;
pg_interval->time = duckdb_interval.micros;
return IntervalPGetDatum(pg_interval);
}
inline Datum
ConvertTimestampDatum(const duckdb::Value &value) {
// Extract raw int64_t value of timestamp
int64_t rawValue = value.GetValue<int64_t>();
// Handle specific Timestamp unit(sec, ms, ns) types
switch (value.type().id()) {
case duckdb::LogicalType::TIMESTAMP_MS:
// 1 ms = 10^3 micro-sec
rawValue *= 1000;
break;
case duckdb::LogicalType::TIMESTAMP_NS:
// 1 ns = 10^-3 micro-sec
rawValue /= 1000;
break;
case duckdb::LogicalType::TIMESTAMP_S:
// 1 s = 10^6 micro-sec
rawValue *= 1000000;
break;
default:
// Since we don't want to handle anything here
break;
}
return rawValue - pgduckdb::PGDUCKDB_DUCK_TIMESTAMP_OFFSET;
}
inline Datum
ConvertFloatDatum(const duckdb::Value &value) {
return Float4GetDatum(value.GetValue<float>());
}
inline Datum
ConvertDoubleDatum(const duckdb::Value &value) {
return Float8GetDatum(value.GetValue<double>());
}
template <class T, class OP = DecimalConversionInteger>
void
ConvertNumeric(const duckdb::Value &ddb_value, idx_t scale, NumericVar &result) {
result.dscale = scale;
T value = ddb_value.GetValueUnsafe<T>();
if (value < 0) {
value = -value;
result.sign = NUMERIC_NEG;
} else {
result.sign = NUMERIC_POS;
}
// divide the decimal into the integer part (before the decimal point) and fractional part (after the point)
T integer_part;
T fractional_part;
if (scale == 0) {
integer_part = value;
fractional_part = 0;
} else {
integer_part = value / OP::GetPowerOfTen(scale);
fractional_part = value % OP::GetPowerOfTen(scale);
}
constexpr idx_t MAX_DIGITS = sizeof(T) * 4;
uint16_t integral_digits[MAX_DIGITS];
uint16_t fractional_digits[MAX_DIGITS];
int32_t integral_ndigits;
// split the integral part into parts of up to NBASE (4 digits => 0..9999)
integral_ndigits = 0;
while (integer_part > 0) {
integral_digits[integral_ndigits++] = uint16_t(integer_part % T(NBASE));
integer_part /= T(NBASE);
}
result.weight = integral_ndigits - 1;
// split the fractional part into parts of up to NBASE (4 digits => 0..9999)
// count the amount of digits required for the fractional part
// note that while it is technically possible to leave out zeros here this adds even more complications
// so we just always write digits for the full "scale", even if not strictly required
idx_t fractional_ndigits = (scale + DEC_DIGITS - 1) / DEC_DIGITS;
// fractional digits are LEFT aligned (for some unknown reason)
// that means if we write ".12" with a scale of 2 we actually need to write "1200", instead of "12"
// this means we need to "correct" the number 12 by multiplying by 100 in this case
// this correction factor is the "number of digits to the next full number"
int32_t correction = fractional_ndigits * DEC_DIGITS - scale;
fractional_part *= OP::GetPowerOfTen(correction);
for (idx_t i = 0; i < fractional_ndigits; i++) {
fractional_digits[i] = uint16_t(fractional_part % NBASE);
fractional_part /= NBASE;
}
result.ndigits = integral_ndigits + fractional_ndigits;
result.buf = (NumericDigit *)palloc(result.ndigits * sizeof(NumericDigit));
result.digits = result.buf;
auto &digits = result.digits;
idx_t digits_idx = 0;
for (idx_t i = integral_ndigits; i > 0; i--) {
digits[digits_idx++] = integral_digits[i - 1];
}
for (idx_t i = fractional_ndigits; i > 0; i--) {
digits[digits_idx++] = fractional_digits[i - 1];
}
}
static Datum
ConvertNumericDatum(const duckdb::Value &value) {
auto value_type_id = value.type().id();
if (value_type_id == duckdb::LogicalTypeId::DOUBLE) {
return ConvertDoubleDatum(value);
}
NumericVar numeric_var;
D_ASSERT(value_type_id == duckdb::LogicalTypeId::DECIMAL || value_type_id == duckdb::LogicalTypeId::HUGEINT ||
value_type_id == duckdb::LogicalTypeId::UBIGINT || value_type_id == duckdb::LogicalTypeId::UHUGEINT);
const bool is_decimal = value_type_id == duckdb::LogicalTypeId::DECIMAL;
uint8_t scale = is_decimal ? duckdb::DecimalType::GetScale(value.type()) : 0;
switch (value.type().InternalType()) {
case duckdb::PhysicalType::INT16:
ConvertNumeric<int16_t>(value, scale, numeric_var);
break;
case duckdb::PhysicalType::INT32:
ConvertNumeric<int32_t>(value, scale, numeric_var);
break;
case duckdb::PhysicalType::INT64:
ConvertNumeric<int64_t>(value, scale, numeric_var);
break;
case duckdb::PhysicalType::UINT64:
ConvertNumeric<uint64_t>(value, scale, numeric_var);
break;
case duckdb::PhysicalType::INT128:
ConvertNumeric<hugeint_t, DecimalConversionHugeint>(value, scale, numeric_var);
break;
case duckdb::PhysicalType::UINT128:
ConvertNumeric<uhugeint_t, DecimalConversionHugeint>(value, scale, numeric_var);
break;
default:
throw duckdb::InvalidInputException(
"(PGDuckDB/ConvertNumericDatum) Unrecognized physical type for DECIMAL value");
}
auto numeric = PostgresFunctionGuard(make_result, &numeric_var);
return NumericGetDatum(numeric);
}
static Datum
ConvertUUIDDatum(const duckdb::Value &value) {
D_ASSERT(value.type().id() == duckdb::LogicalTypeId::UUID);
D_ASSERT(value.type().InternalType() == duckdb::PhysicalType::INT128);
auto duckdb_uuid = value.GetValue<hugeint_t>();
pg_uuid_t *postgres_uuid = (pg_uuid_t *)palloc(sizeof(pg_uuid_t));
duckdb_uuid.upper ^= (uint64_t(1) << 63);
// Convert duckdb_uuid to bytes and store in postgres_uuid.data
uint8_t *uuid_bytes = (uint8_t *)&duckdb_uuid;
for (int i = 0; i < UUID_LEN; ++i) {
postgres_uuid->data[i] = uuid_bytes[UUID_LEN - 1 - i];
}
return UUIDPGetDatum(postgres_uuid);
}
static duckdb::interval_t
DatumGetInterval(Datum value) {
Interval *pg_interval = DatumGetIntervalP(value);
duckdb::interval_t duck_interval;
duck_interval.months = pg_interval->month;
duck_interval.days = pg_interval->day;
duck_interval.micros = pg_interval->time;
return duck_interval;
}
template <int32_t OID>
struct PostgresTypeTraits;
// Specializations for each type
// BOOL type
template <>
struct PostgresTypeTraits<BOOLOID> {
static constexpr int16_t typlen = 1;
static constexpr bool typbyval = true;
static constexpr char typalign = 'c';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertBoolDatum(val);
}
};
// CHAR type
template <>
struct PostgresTypeTraits<CHAROID> {
static constexpr int16_t typlen = 1;
static constexpr bool typbyval = true;
static constexpr char typalign = 'c';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertCharDatum(val);
}
};
// INT2 type (smallint)
template <>
struct PostgresTypeTraits<INT2OID> {
static constexpr int16_t typlen = 2;
static constexpr bool typbyval = true;
static constexpr char typalign = 's';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertInt2Datum(val);
}
};
// INT4 type (integer)
template <>
struct PostgresTypeTraits<INT4OID> {
static constexpr int16_t typlen = 4;
static constexpr bool typbyval = true;
static constexpr char typalign = 'i';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertInt4Datum(val);
}
};
// INT8 type (bigint)
template <>
struct PostgresTypeTraits<INT8OID> {
static constexpr int16_t typlen = 8;
static constexpr bool typbyval = true;
static constexpr char typalign = 'd';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertInt8Datum(val);
}
};
// FLOAT4 type (real)
template <>
struct PostgresTypeTraits<FLOAT4OID> {
static constexpr int16_t typlen = 4;
static constexpr bool typbyval = true;
static constexpr char typalign = 'i';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertFloatDatum(val);
}
};
// FLOAT8 type (double precision)
template <>
struct PostgresTypeTraits<FLOAT8OID> {
static constexpr int16_t typlen = 8;
static constexpr bool typbyval = true;
static constexpr char typalign = 'd';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertDoubleDatum(val);
}
};
// TIMESTAMP type
template <>
struct PostgresTypeTraits<TIMESTAMPOID> {
static constexpr int16_t typlen = 8;
static constexpr bool typbyval = true;
static constexpr char typalign = 'd';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertTimestampDatum(val);
}
};
// INTERVAL type
template <>
struct PostgresTypeTraits<INTERVALOID> {
static constexpr int16_t typlen = 16;
static constexpr bool typbyval = false;
static constexpr char typalign = 'c';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertIntervalDatum(val);
}
};
// DATE type
template <>
struct PostgresTypeTraits<DATEOID> {
static constexpr int16_t typlen = 4;
static constexpr bool typbyval = true;
static constexpr char typalign = 'i';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertDateDatum(val);
}
};
// UUID type
template <>
struct PostgresTypeTraits<UUIDOID> {
static constexpr int16_t typlen = 16;
static constexpr bool typbyval = false;
static constexpr char typalign = 'c';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertUUIDDatum(val);
}
};
// NUMERIC type
template <>
struct PostgresTypeTraits<NUMERICOID> {
static constexpr int16_t typlen = -1; // variable-length
static constexpr bool typbyval = false;
static constexpr char typalign = 'i';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertNumericDatum(val);
}
};
// VARCHAR type
template <>
struct PostgresTypeTraits<VARCHAROID> {
static constexpr int16_t typlen = -1; // variable-length
static constexpr bool typbyval = false;
static constexpr char typalign = 'i';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertVarCharDatum(val);
}
};
// BLOB type
template <>
struct PostgresTypeTraits<BYTEAOID> {
static constexpr int16_t typlen = -1; // variable-length
static constexpr bool typbyval = false;
static constexpr char typalign = 'i';
static inline Datum
ToDatum(const duckdb::Value &val) {
return ConvertBinaryDatum(val);
}
};
template <int32_t OID>
struct PostgresOIDMapping {
static constexpr int32_t postgres_oid = OID;
static constexpr int16_t typlen = PostgresTypeTraits<OID>::typlen;
static constexpr bool typbyval = PostgresTypeTraits<OID>::typbyval;
static constexpr char typalign = PostgresTypeTraits<OID>::typalign;
static inline Datum
ToDatum(const duckdb::Value &val) {
return PostgresTypeTraits<OID>::ToDatum(val);
}
};
template <class MAPPING>
struct PODArray {
public:
static ArrayType *
ConstructArray(Datum *datums, bool *nulls, int ndims, int *dims, int *lower_bound) {
return construct_md_array(datums, nulls, ndims, dims, lower_bound, MAPPING::postgres_oid, MAPPING::typlen,
MAPPING::typbyval, MAPPING::typalign);
}
static Datum
ConvertToPostgres(const duckdb::Value &val) {
return MAPPING::ToDatum(val);
}
};
using BoolArray = PODArray<PostgresOIDMapping<BOOLOID>>;
using CharArray = PODArray<PostgresOIDMapping<CHAROID>>;
using Int2Array = PODArray<PostgresOIDMapping<INT2OID>>;
using Int4Array = PODArray<PostgresOIDMapping<INT4OID>>;
using Int8Array = PODArray<PostgresOIDMapping<INT8OID>>;
using Float4Array = PODArray<PostgresOIDMapping<FLOAT4OID>>;
using Float8Array = PODArray<PostgresOIDMapping<FLOAT8OID>>;
using DateArray = PODArray<PostgresOIDMapping<DATEOID>>;
using TimestampArray = PODArray<PostgresOIDMapping<TIMESTAMPOID>>;
using IntervalArray = PODArray<PostgresOIDMapping<INTERVALOID>>;
using UUIDArray = PODArray<PostgresOIDMapping<UUIDOID>>;
using VarCharArray = PODArray<PostgresOIDMapping<VARCHAROID>>;
using NumericArray = PODArray<PostgresOIDMapping<NUMERICOID>>;
using ByteArray = PODArray<PostgresOIDMapping<BYTEAOID>>;
static idx_t
GetDuckDBListDimensionality(const duckdb::LogicalType &list_type, idx_t depth = 0) {
D_ASSERT(list_type.id() == duckdb::LogicalTypeId::LIST);
auto &child = duckdb::ListType::GetChildType(list_type);
if (child.id() == duckdb::LogicalTypeId::LIST) {
return GetDuckDBListDimensionality(child, depth + 1);
}
return depth + 1;
}
namespace {
template <class OP>
struct PostgresArrayAppendState {
public:
PostgresArrayAppendState(idx_t _number_of_dimensions) : number_of_dimensions(_number_of_dimensions) {
dimensions = (int *)palloc(number_of_dimensions * sizeof(int));
lower_bounds = (int *)palloc(number_of_dimensions * sizeof(int));
for (idx_t i = 0; i < number_of_dimensions; i++) {
// Initialize everything at -1 to indicate that it isn't set yet
dimensions[i] = -1;
}
for (idx_t i = 0; i < number_of_dimensions; i++) {
// Lower bounds have no significance for us
lower_bounds[i] = 1;
}
}
public:
void
AppendValueAtDimension(const duckdb::Value &value, idx_t dimension) {
// FIXME: verify that the amount of values does not overflow an `int` ?
auto &values = duckdb::ListValue::GetChildren(value);
int to_append = values.size();
D_ASSERT(dimension < number_of_dimensions);
if (dimensions[dimension] == -1) {
// This dimension is not set yet
dimensions[dimension] = to_append;
// FIXME: verify that the amount of expected_values does not overflow an `int` ?
expected_values *= to_append;
}
if (dimensions[dimension] != to_append) {
throw duckdb::InvalidInputException("Expected %d values in list at dimension %d, found %d instead",
dimensions[dimension], dimension, to_append);
}
auto &child_type = duckdb::ListType::GetChildType(value.type());
if (child_type.id() == duckdb::LogicalTypeId::LIST) {
for (auto &child_val : values) {
if (child_val.IsNull()) {
// Postgres arrays can not contains nulls at the array level
// i.e {{1,2}, NULL, {3,4}} is not supported
throw duckdb::InvalidInputException("Returned LIST contains a NULL at an intermediate dimension "
"(not the value level), which is not supported in Postgres");
}
AppendValueAtDimension(child_val, dimension + 1);
}
} else {
if (!datums) {
// First time we get to the outer most child
// Because we traversed all dimensions we know how many values we have to allocate for
datums = (Datum *)palloc(expected_values * sizeof(Datum));
nulls = (bool *)palloc(expected_values * sizeof(bool));
}
for (auto &child_val : values) {
nulls[count] = child_val.IsNull();
if (!nulls[count]) {
datums[count] = OP::ConvertToPostgres(child_val);
}
++count;
}
}
}
private:
idx_t count = 0;
public:
idx_t expected_values = 1;
Datum *datums = nullptr;
bool *nulls = nullptr;
int *dimensions;
int *lower_bounds;
idx_t number_of_dimensions;
};
} // namespace
template <class OP>
static void
ConvertDuckToPostgresArray(TupleTableSlot *slot, duckdb::Value &value, idx_t col) {
D_ASSERT(value.type().id() == duckdb::LogicalTypeId::LIST);
auto number_of_dimensions = GetDuckDBListDimensionality(value.type());
PostgresArrayAppendState<OP> append_state(number_of_dimensions);
append_state.AppendValueAtDimension(value, 0);
// Create the array
auto datums = append_state.datums;
auto nulls = append_state.nulls;
auto dimensions = append_state.dimensions;
auto lower_bounds = append_state.lower_bounds;
// When we insert an empty array into multi-dimensions array,
// the dimensions[1] to dimension[number_of_dimensions-1] will not be set and always be -1.
for (idx_t i = 0; i < number_of_dimensions; i++) {
if (dimensions[i] == -1) {
// This dimension is not set yet, we should set them to 0.
// Otherwise, it will cause some issues when we call ConstructArray.
dimensions[i] = 0;
}
}
auto arr = OP::ConstructArray(datums, nulls, number_of_dimensions, dimensions, lower_bounds);
// Free allocated memory
if (append_state.expected_values > 0) {
pfree(datums);
pfree(nulls);
}
pfree(dimensions);
pfree(lower_bounds);
slot->tts_values[col] = PointerGetDatum(arr);
}
bool
ConvertDuckToPostgresValue(TupleTableSlot *slot, duckdb::Value &value, idx_t col) {
Oid oid = slot->tts_tupleDescriptor->attrs[col].atttypid;
switch (oid) {
case BOOLOID:
slot->tts_values[col] = ConvertBoolDatum(value);
break;
case CHAROID:
slot->tts_values[col] = ConvertCharDatum(value);
break;
case INT2OID: {
slot->tts_values[col] = ConvertInt2Datum(value);
break;
}
case INT4OID: {
slot->tts_values[col] = ConvertInt4Datum(value);
break;
}
case INT8OID: {
slot->tts_values[col] = ConvertInt8Datum(value);
break;
}
case BPCHAROID:
case TEXTOID:
case JSONOID:
case VARCHAROID: {
slot->tts_values[col] = ConvertVarCharDatum(value);
break;
}
case DATEOID: {
slot->tts_values[col] = ConvertDateDatum(value);
break;
}
case TIMESTAMPOID: {
slot->tts_values[col] = ConvertTimestampDatum(value);
break;
}
case TIMESTAMPTZOID: {
duckdb::timestamp_tz_t timestamp = value.GetValue<duckdb::timestamp_tz_t>();
slot->tts_values[col] = timestamp.value - pgduckdb::PGDUCKDB_DUCK_TIMESTAMP_OFFSET;
break;
}
case INTERVALOID: {
slot->tts_values[col] = ConvertIntervalDatum(value);
break;
}
case FLOAT4OID: {
slot->tts_values[col] = ConvertFloatDatum(value);
break;
}
case FLOAT8OID: {
slot->tts_values[col] = ConvertDoubleDatum(value);
break;
}
case NUMERICOID: {
slot->tts_values[col] = ConvertNumericDatum(value);
break;
}
case UUIDOID: {
slot->tts_values[col] = ConvertUUIDDatum(value);
break;
}
case BYTEAOID: {
slot->tts_values[col] = ConvertBinaryDatum(value);
break;
}
case BOOLARRAYOID: {
ConvertDuckToPostgresArray<BoolArray>(slot, value, col);
break;
}
case CHARARRAYOID: {
ConvertDuckToPostgresArray<CharArray>(slot, value, col);
break;
}
case INT2ARRAYOID: {
ConvertDuckToPostgresArray<Int2Array>(slot, value, col);
break;
}
case INT4ARRAYOID: {
ConvertDuckToPostgresArray<Int4Array>(slot, value, col);
break;
}
case INT8ARRAYOID: {
ConvertDuckToPostgresArray<Int8Array>(slot, value, col);
break;
}
case BPCHARARRAYOID:
case TEXTARRAYOID:
case JSONARRAYOID:
case VARCHARARRAYOID: {
ConvertDuckToPostgresArray<VarCharArray>(slot, value, col);
break;
}
case DATEARRAYOID: {
ConvertDuckToPostgresArray<DateArray>(slot, value, col);
break;
}
case TIMESTAMPARRAYOID: {
ConvertDuckToPostgresArray<TimestampArray>(slot, value, col);
break;
}
case INTERVALARRAYOID: {
ConvertDuckToPostgresArray<IntervalArray>(slot, value, col);
break;
}
case FLOAT4ARRAYOID: {
ConvertDuckToPostgresArray<Float4Array>(slot, value, col);
break;
}
case FLOAT8ARRAYOID: {
ConvertDuckToPostgresArray<Float8Array>(slot, value, col);
break;
}
case NUMERICARRAYOID: {
ConvertDuckToPostgresArray<NumericArray>(slot, value, col);
break;
}
case UUIDARRAYOID: {
ConvertDuckToPostgresArray<UUIDArray>(slot, value, col);
break;
}
case BYTEAARRAYOID: {
ConvertDuckToPostgresArray<ByteArray>(slot, value, col);
break;
}
default:
elog(WARNING, "(PGDuckDB/ConvertDuckToPostgresValue) Unsuported pgduckdb type: %d", oid);
return false;
}
return true;
}
static inline int32
make_numeric_typmod(int precision, int scale) {
return ((precision << 16) | (scale & 0x7ff)) + VARHDRSZ;
}
static inline int
numeric_typmod_precision(int32 typmod) {
return ((typmod - VARHDRSZ) >> 16) & 0xffff;
}
static inline int
numeric_typmod_scale(int32 typmod) {
return (((typmod - VARHDRSZ) & 0x7ff) ^ 1024) - 1024;
}
duckdb::LogicalType
ConvertPostgresToBaseDuckColumnType(Form_pg_attribute &attribute) {
switch (attribute->atttypid) {
case BOOLOID:
case BOOLARRAYOID:
return duckdb::LogicalTypeId::BOOLEAN;
case CHAROID:
case CHARARRAYOID:
return duckdb::LogicalTypeId::TINYINT;
case INT2OID:
case INT2ARRAYOID:
return duckdb::LogicalTypeId::SMALLINT;
case INT4OID:
case INT4ARRAYOID:
return duckdb::LogicalTypeId::INTEGER;
case INT8OID:
case INT8ARRAYOID:
return duckdb::LogicalTypeId::BIGINT;
case BPCHAROID:
case BPCHARARRAYOID:
case TEXTOID:
case TEXTARRAYOID:
case VARCHAROID:
case VARCHARARRAYOID:
return duckdb::LogicalTypeId::VARCHAR;
case DATEOID:
case DATEARRAYOID:
return duckdb::LogicalTypeId::DATE;
case TIMESTAMPOID:
case TIMESTAMPARRAYOID:
return duckdb::LogicalTypeId::TIMESTAMP;
case TIMESTAMPTZOID:
return duckdb::LogicalTypeId::TIMESTAMP_TZ;
case INTERVALOID:
case INTERVALARRAYOID:
return duckdb::LogicalTypeId::INTERVAL;
case FLOAT4OID:
case FLOAT4ARRAYOID:
return duckdb::LogicalTypeId::FLOAT;
case FLOAT8OID:
case FLOAT8ARRAYOID:
return duckdb::LogicalTypeId::DOUBLE;
case NUMERICOID:
case NUMERICARRAYOID: {
auto &typmod = attribute->atttypmod;
auto precision = numeric_typmod_precision(typmod);
auto scale = numeric_typmod_scale(typmod);
if (typmod == -1 || precision < 0 || scale < 0 || precision > 38) {
auto extra_type_info = duckdb::make_shared_ptr<NumericAsDouble>();
return duckdb::LogicalType(duckdb::LogicalTypeId::DOUBLE, std::move(extra_type_info));
}
return duckdb::LogicalType::DECIMAL(precision, scale);
}
case UUIDOID:
case UUIDARRAYOID:
return duckdb::LogicalTypeId::UUID;
case JSONOID:
case JSONARRAYOID:
case JSONBOID:
case JSONBARRAYOID:
return duckdb::LogicalType::JSON();
case REGCLASSOID:
case REGCLASSARRAYOID:
return duckdb::LogicalTypeId::UINTEGER;
case BYTEAOID:
case BYTEAARRAYOID:
return duckdb::LogicalTypeId::BLOB;
default:
return duckdb::LogicalType::USER("UnsupportedPostgresType (Oid=" + std::to_string(attribute->atttypid) + ")");
}
}
duckdb::LogicalType
ConvertPostgresToDuckColumnType(Form_pg_attribute &attribute) {
auto base_type = ConvertPostgresToBaseDuckColumnType(attribute);
auto dimensions = attribute->attndims;
if (dimensions == 0) {
return base_type;
}
for (int i = 0; i < dimensions; i++) {
base_type = duckdb::LogicalType::LIST(base_type);
}
return base_type;
}
Oid
GetPostgresArrayDuckDBType(const duckdb::LogicalType &type) {
switch (type.id()) {
case duckdb::LogicalTypeId::BOOLEAN:
return BOOLARRAYOID;