-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg-clickhouse-decode.h
More file actions
2321 lines (2033 loc) · 66.7 KB
/
Copy pathpg-clickhouse-decode.h
File metadata and controls
2321 lines (2033 loc) · 66.7 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
/*
* Decode ClickHouse Native blocks into PostgreSQL Datums
*
* Define PGCH_IMPLEMENTATION in one translation unit. Include this header
* without that definition everywhere else
*/
#ifndef PG_CLICKHOUSE_DECODE_H
#define PG_CLICKHOUSE_DECODE_H
#include "pg-clickhouse.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Decode one value and store returned Datum type in *valtype
* Set *valtype to JSONOID to preserve JSON text, or OID8OID on PostgreSQL 19+
* to accept full UInt64 range
*/
extern Datum
pgch_read_value(
const chc_column* col,
const chc_type* type,
uint64_t row,
Oid* valtype,
bool* is_null
);
/* Return palloc'd signature for comparing decoded Datum shapes */
extern char*
pgch_type_shape(const chc_type* type);
/*
* Supply blocks to pgch_reader
* Transfer block ownership from next_block to reader
* Return NULL at end, set error callback result when stream fails
*/
typedef struct pgch_block_source {
void* ud;
const chc_block* (*next_block)(void* ud);
const char* (*error)(void* ud);
} pgch_block_source;
/*
* Supply Native byte chunks to pgch_reader_init_chunks
* Available when implementation translation unit defines CHC_IMPLEMENTATION
*/
typedef struct pgch_chunk_source {
void* ud;
/*
* Return next chunk, keep bytes valid until following call
* Set *n to zero at end, return false and set *error on failure
*/
bool (*next_chunk)(void* ud, const void** p, size_t* n, char** error);
bool (*cancelled)(void* ud); /* Optional cancellation check between chunks */
} pgch_chunk_source;
/*
* Read rows from block stream
* Consume values before next pgch_reader_next call
*/
typedef struct pgch_reader {
pgch_block_source src;
Oid* coltypes; /* Returned Datum OIDs, caller may override JSON and UInt64 */
char** colshapes;
Datum* values;
bool* nulls;
size_t ncols;
size_t row;
const chc_block* cur;
MemoryContext cxt;
char* error;
bool done;
} pgch_reader;
/*
* Initialize reader and load first block
* Allocate reader state in CurrentMemoryContext
* Check reader->error when initialization leaves reader done
*/
extern void
pgch_reader_init(pgch_reader* r, const pgch_block_source* src);
/*
* Initialize reader from Native byte chunks
* Pass NULL opts to use pgch_block_opts_local
*/
extern void
pgch_reader_init_chunks(
pgch_reader* r,
const pgch_chunk_source* src,
const chc_block_opts* opts
);
/*
* Fill values and nulls with next row
* Return false at end or when reader->error is set
* Reject unsupported types, incompatible schema changes between blocks, and
* columns failing chc_column_validate
*/
extern bool
pgch_reader_next(pgch_reader* r);
extern size_t
pgch_reader_columns(const pgch_reader* r);
/* Release current block and clear error pointer without freeing context storage */
extern void
pgch_reader_free(pgch_reader* r);
/*
* Prepare reusable conversion from intype to outtype
* Pass representative value for arrays and tuples
* Pass target type modifier to enforce length and precision, or -1 for none
* Return NULL when conversion is unnecessary
* Allocate state in CurrentMemoryContext
*/
extern void*
pgch_convert_init(Datum val, Oid intype, Oid outtype, int32 outtypmod);
/*
* Prepare conversion from ClickHouse column type
* Use pgch_reader_convert_init to read type and valtype override from reader
*/
extern void*
pgch_convert_init_type(const chc_type* in, Oid outtype, int32 outtypmod);
extern void*
pgch_reader_convert_init(
const pgch_reader* r,
size_t col,
Oid outtype,
int32 outtypmod
);
extern Datum
pgch_convert(void* state, Datum val);
extern void
pgch_convert_free(void* state);
/* Copy current row through optional per-column conversion states */
extern void
pgch_reader_fill(const pgch_reader* r, void** states, Datum* values, bool* nulls);
/*
* Copy current row into dest[i] of values and nulls
* Leave unmapped positions untouched, pass NULL dest for column order
*/
extern void
pgch_reader_fill_map(
const pgch_reader* r,
void** states,
const int* dest,
Datum* values,
bool* nulls
);
/* Return decoded value as palloc'd C string */
extern char*
pgch_value_to_cstring(Oid coltype, Datum value);
#ifdef PGCH_IMPLEMENTATION
#include <string.h>
#include <sys/socket.h> /* PostgreSQL inet macros require AF_INET */
#include "access/htup_details.h"
#include "access/tupconvert.h"
#include "catalog/pg_type_d.h"
#include "common/int.h"
#include "fmgr.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "parser/parse_coerce.h"
#include "port/pg_bswap.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/float.h"
#include "utils/fmgroids.h"
#include "utils/geo_decls.h"
#include "utils/inet.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/timestamp.h"
#include "utils/typcache.h"
#include "utils/uuid.h"
#if PG_VERSION_NUM >= 190000
#include "varatt.h"
#endif
/* ---- little-endian fixed-width reads at row offset ------------------- */
static inline int8_t
pgch__rd_i8(const uint8_t* p, uint64_t row) {
return (int8_t)p[row];
}
static inline uint8_t
pgch__rd_u8(const uint8_t* p, uint64_t row) {
return p[row];
}
static inline bool
pgch__rd_bool(const bool* p, uint64_t row) {
return (bool)p[row];
}
/*
* Generate fixed-width scalar readers. For example, i16 invocation below
* defines pgch__rd_i16(), which reads two bytes at row offset, converts them
* from little-endian to host order, and returns int16_t
*/
#define PGCH__RD_FIXED(suffix, T, U, LE) \
static inline T pgch__rd_##suffix(const uint8_t* p, uint64_t row) { \
T v; \
U u; \
\
memcpy(&u, p + row * sizeof(T), sizeof u); \
u = LE(u); \
memcpy(&v, &u, sizeof v); \
return v; \
}
PGCH__RD_FIXED(i16, int16_t, uint16_t, PGCH__LE16)
PGCH__RD_FIXED(u16, uint16_t, uint16_t, PGCH__LE16)
PGCH__RD_FIXED(i32, int32_t, uint32_t, PGCH__LE32)
PGCH__RD_FIXED(u32, uint32_t, uint32_t, PGCH__LE32)
PGCH__RD_FIXED(i64, int64_t, uint64_t, PGCH__LE64)
PGCH__RD_FIXED(f32, float, uint32_t, PGCH__LE32)
PGCH__RD_FIXED(f64, double, uint64_t, PGCH__LE64)
PGCH__RD_FIXED(u64, uint64_t, uint64_t, PGCH__LE64)
static inline void
pgch__slice_str(
const chc_column* col,
uint64_t row,
const char** out_ptr,
size_t* out_len
) {
const uint64_t* offs = chc_column_string_offsets(col);
const uint8_t* data = chc_column_string_data(col);
uint64_t start = row == 0 ? 0 : offs[row - 1];
uint64_t end = offs[row];
*out_ptr = (const char*)data + start;
*out_len = (size_t)(end - start);
}
/* ---- per-kind readers ----------------------------------------------- */
/* ClickHouse stores Decimal as a scaled, little-endian signed integer */
static int
pgch__format_decimal(
const uint8_t* bytes,
size_t width,
uint32_t scale,
char* out,
size_t out_cap
) {
uint32_t mag[8];
char buf[80];
size_t nwords = width / 4;
bool neg = false;
if (width == 0 || width > 32 || width % 4 != 0 || scale >= sizeof(buf)) {
return -1;
}
for (size_t i = 0; i < nwords; i++) {
mag[i] = pgch__rd_u32(bytes, i);
}
if (mag[nwords - 1] & 0x80000000u) {
neg = true;
for (size_t i = 0; i < nwords; i++) {
mag[i] = ~mag[i];
}
uint64_t carry = 1;
for (size_t i = 0; i < nwords && carry; i++) {
uint64_t v = (uint64_t)mag[i] + carry;
mag[i] = (uint32_t)v;
carry = v >> 32;
}
}
int n = 0;
bool nonzero;
do {
uint64_t rem = 0;
nonzero = false;
for (ssize_t i = (ssize_t)nwords - 1; i >= 0; i--) {
uint64_t v = (rem << 32) | mag[i];
mag[i] = (uint32_t)(v / 10);
rem = v % 10;
if (mag[i]) {
nonzero = true;
}
}
buf[n++] = (char)('0' + (uint32_t)rem);
} while (nonzero && n < (int)sizeof(buf));
while (n <= (int)scale) {
buf[n++] = '0';
}
size_t need = (size_t)neg + (size_t)n + (scale ? 1 : 0) + 1;
if (need > out_cap) {
return -1;
}
char* p = out;
if (neg) {
*p++ = '-';
}
for (int i = n - 1; i >= 0; i--) {
if (i + 1 == (int)scale) {
*p++ = '.';
}
*p++ = buf[i];
}
*p = '\0';
return (int)(p - out);
}
static Datum
pgch__read_decimal(const chc_column* col, const chc_type* type, uint64_t row) {
size_t es;
const uint8_t* p = (const uint8_t*)chc_column_fixed_data(col, &es);
uint32_t scale = (uint32_t)chc_type_decimal_scale(type);
char buf[80];
int rc;
#if PG_VERSION_NUM >= 140000
if (es == 4) {
return NumericGetDatum(
int64_div_fast_to_numeric(pgch__rd_i32(p, row), (int)scale)
);
}
if (es == 8) {
return NumericGetDatum(
int64_div_fast_to_numeric(pgch__rd_i64(p, row), (int)scale)
);
}
#endif
rc = pgch__format_decimal(p + row * es, es, scale, buf, sizeof(buf));
if (rc < 0) {
pgch_error(ERRCODE_FDW_ERROR, "decimal too wide");
}
return DirectFunctionCall3(
numeric_in, CStringGetDatum(buf), ObjectIdGetDatum(0), Int32GetDatum(-1)
);
}
static Datum
pgch__read_string(const chc_column* col, uint64_t row) {
const char* p;
size_t len;
pgch__slice_str(col, row, &p, &len);
return PointerGetDatum(cstring_to_text_with_len(p, len));
}
static Datum
pgch__read_fixedstring(const chc_column* col, uint64_t row) {
size_t width;
const uint8_t* base = chc_column_fixed_data(col, &width);
return PointerGetDatum(
cstring_to_text_with_len((const char*)base + row * width, width)
);
}
static Datum
pgch__read_uuid(const chc_column* col, uint64_t row) {
pg_uuid_t* u = (pg_uuid_t*)palloc(sizeof(pg_uuid_t));
const uint8_t* p = (uint8_t*)chc_column_fixed_data(col, NULL) + row * 16;
uint64_t a, b;
memcpy(&a, p, 8);
memcpy(&b, p + 8, 8);
a = pg_bswap64(a);
b = pg_bswap64(b);
memcpy(u->data, &a, 8);
memcpy(u->data + 8, &b, 8);
return UUIDPGetDatum(u);
}
/* ClickHouse Point is Tuple(Float64, Float64), one column per axis */
static Datum
pgch__read_point(const chc_column* col, uint64_t row) {
Point* p = (Point*)palloc(sizeof(Point));
p->x = pgch__rd_f64(
(const uint8_t*)chc_column_fixed_data(chc_column_tuple_child(col, 0), NULL), row
);
p->y = pgch__rd_f64(
(const uint8_t*)chc_column_fixed_data(chc_column_tuple_child(col, 1), NULL), row
);
return PointPGetDatum(p);
}
/* Ring and LineString are Array(Point), so a row is a slice of the axis columns */
static int
pgch__read_axes(
const chc_column* col,
uint64_t row,
const uint8_t** xs,
const uint8_t** ys
) {
const uint64_t* offs = chc_column_array_offsets(col);
uint64_t start = row == 0 ? 0 : offs[row - 1];
uint64_t npts = offs[row] - start;
const chc_column* pts = chc_column_array_values(col);
/* PostgreSQL counts points in an int32 and stores them inline */
if (npts > (INT_MAX - offsetof(POLYGON, p)) / sizeof(Point)) {
pgch_error(ERRCODE_PROGRAM_LIMIT_EXCEEDED, "too many points requested");
}
*xs = (const uint8_t*)chc_column_fixed_data(chc_column_tuple_child(pts, 0), NULL) +
start * sizeof(double);
*ys = (const uint8_t*)chc_column_fixed_data(chc_column_tuple_child(pts, 1), NULL) +
start * sizeof(double);
return (int)npts;
}
static void
pgch__fill_points(Point* out, const uint8_t* xs, const uint8_t* ys, int npts) {
for (int i = 0; i < npts; i++) {
out[i].x = pgch__rd_f64(xs, i);
out[i].y = pgch__rd_f64(ys, i);
}
}
/* make_bound_box from src/backend/utils/adt/geo_ops.c, static there */
static void
pgch__bound_box(POLYGON* poly) {
float8 x1 = poly->p[0].x, x2 = x1;
float8 y1 = poly->p[0].y, y2 = y1;
for (int i = 1; i < poly->npts; i++) {
if (float8_lt(poly->p[i].x, x1)) {
x1 = poly->p[i].x;
}
if (float8_gt(poly->p[i].x, x2)) {
x2 = poly->p[i].x;
}
if (float8_lt(poly->p[i].y, y1)) {
y1 = poly->p[i].y;
}
if (float8_gt(poly->p[i].y, y2)) {
y2 = poly->p[i].y;
}
}
poly->boundbox.low.x = x1;
poly->boundbox.high.x = x2;
poly->boundbox.low.y = y1;
poly->boundbox.high.y = y2;
}
/* A Ring is closed by definition, as a PostgreSQL polygon is */
static Datum
pgch__read_polygon(const chc_column* col, uint64_t row, bool* is_null) {
const uint8_t *xs, *ys;
int npts = pgch__read_axes(col, row, &xs, &ys);
size_t size;
POLYGON* poly;
/* PostgreSQL has no pointless polygon, so an empty ring reads as NULL */
if (npts == 0) {
*is_null = true;
return (Datum)0;
}
size = offsetof(POLYGON, p) + sizeof(Point) * npts;
poly = (POLYGON*)palloc0(size);
SET_VARSIZE(poly, size);
poly->npts = npts;
pgch__fill_points(poly->p, xs, ys, npts);
pgch__bound_box(poly);
return PolygonPGetDatum(poly);
}
/* A LineString repeating its first point is the closed path that wrote it */
static Datum
pgch__read_path(const chc_column* col, uint64_t row, bool* is_null) {
const uint8_t *xs, *ys;
int npts = pgch__read_axes(col, row, &xs, &ys);
bool closed = npts > 1 &&
float8_eq(pgch__rd_f64(xs, 0), pgch__rd_f64(xs, npts - 1)) &&
float8_eq(pgch__rd_f64(ys, 0), pgch__rd_f64(ys, npts - 1));
size_t size;
PATH* path;
npts -= closed;
/* PostgreSQL has no pointless path, so an empty line reads as NULL */
if (npts == 0) {
*is_null = true;
return (Datum)0;
}
size = offsetof(PATH, p) + sizeof(Point) * npts;
path = (PATH*)palloc0(size);
SET_VARSIZE(path, size);
path->npts = npts;
path->closed = closed;
pgch__fill_points(path->p, xs, ys, npts);
return PathPGetDatum(path);
}
/* ClickHouse stores IPv4 as native uint32, PostgreSQL inet uses network order */
static Datum
pgch__read_ipv4(const chc_column* col, uint64_t row) {
inet* res = (inet*)palloc0(sizeof(inet));
uint32_t addr =
pg_hton32(pgch__rd_u32((const uint8_t*)chc_column_fixed_data(col, NULL), row));
ip_family(res) = PGSQL_AF_INET;
ip_bits(res) = 32;
memcpy(ip_addr(res), &addr, 4);
SET_INET_VARSIZE(res);
return InetPGetDatum(res);
}
/* ClickHouse and PostgreSQL store IPv6 in network order */
static Datum
pgch__read_ipv6(const chc_column* col, uint64_t row) {
inet* res = (inet*)palloc0(sizeof(inet));
ip_family(res) = PGSQL_AF_INET6;
ip_bits(res) = 128;
memcpy(
ip_addr(res), (const uint8_t*)chc_column_fixed_data(col, NULL) + row * 16, 16
);
SET_INET_VARSIZE(res);
return InetPGetDatum(res);
}
static Datum
pgch__read_enum(const chc_column* col, const chc_type* type, uint64_t row) {
size_t es;
const uint8_t* p = (const uint8_t*)chc_column_fixed_data(col, &es);
int64_t v = 0;
if (es == 1) {
v = (int8_t)p[row];
} else {
v = pgch__rd_i16(p, row);
}
size_t n = chc_type_enum_count(type);
for (size_t i = 0; i < n; i++) {
const char* en;
size_t el;
int64_t ev;
chc_type_enum_at(type, i, &en, &el, &ev);
if (ev == v) {
return PointerGetDatum(cstring_to_text_with_len(en ? en : "", el));
}
}
return PointerGetDatum(cstring_to_text_with_len("", 0));
}
/* PGCH_NATIVE_SETTINGS makes ClickHouse serialize JSON as document text */
static Datum
pgch__read_json(const chc_column* col, uint64_t row, Oid valtype) {
const char* p;
size_t len;
char* cstr;
Datum ret;
pgch__slice_str(col, row, &p, &len);
cstr = pnstrdup(p, len);
ret = DirectFunctionCall1(
valtype == JSONOID ? json_in : jsonb_in, CStringGetDatum(cstr)
);
pfree(cstr);
return ret;
}
/* Nullable LowCardinality reserves dictionary entry zero for NULL */
static Datum
pgch__read_lc(
const chc_column* col,
const chc_type* type,
uint64_t row,
Oid* valtype,
bool* is_null
) {
int ks = chc_column_lc_key_size(col);
const uint8_t* kp = (const uint8_t*)chc_column_lc_keys(col) + (size_t)row * ks;
uint64_t k = 0;
switch (ks) {
case 1:
k = kp[0];
break;
case 2: {
uint16_t v;
memcpy(&v, kp, 2);
k = v;
break;
}
case 4: {
uint32_t v;
memcpy(&v, kp, 4);
k = v;
break;
}
case 8:
memcpy(&k, kp, 8);
break;
default:
pgch_errorf(ERRCODE_FDW_ERROR, "unexpected LowCardinality key size %d", ks);
}
const chc_column* dict = chc_column_lc_dict(col);
const chc_type* inner_t = chc_type_child(type, 0);
if (chc_type_kind(inner_t) == CHC_NULLABLE &&
chc_column_layout(dict) == CHC_COL_NULLABLE) {
const uint8_t* dnm = chc_column_null_map(dict);
if (dnm && dnm[k]) {
*valtype = TEXTOID;
*is_null = true;
return (Datum)0;
}
dict = chc_column_nullable_inner(dict);
}
*valtype = TEXTOID;
*is_null = false;
if (chc_column_layout(dict) != CHC_COL_STRING) {
pgch_error(
ERRCODE_FDW_INVALID_DATA_TYPE, "unsupported LowCardinality inner type"
);
}
return pgch__read_string(dict, k);
}
/*
* Walk an array shaped type to element pgch_array, reporting how many
* PostgreSQL dimensions it spans and type walk stopped on.
* Includes CH types which are represented by arrays in native format.
*/
static Oid
pgch__array_item(const chc_type* type, const chc_type** leaf, int* ndim) {
int dims = 0;
for (;;) {
type = pgch_unwrap(type, NULL);
*leaf = type;
switch (chc_type_kind(type)) {
case CHC_ARRAY:
dims++;
type = chc_type_child(type, 0);
continue;
/* Map holds Tuple(K, V) pairs */
case CHC_MAP:
*ndim = dims + 1;
return RECORDOID;
case CHC_POLYGON:
*ndim = dims + 1;
return pgch_kind_oids[CHC_RING];
/* MultiPolygon nests its rings one level deeper than Polygon */
case CHC_MULTI_POLYGON:
*ndim = dims + 2;
return pgch_kind_oids[CHC_RING];
case CHC_MULTI_LINE_STRING:
*ndim = dims + 1;
return pgch_kind_oids[CHC_LINE_STRING];
default:
*ndim = dims;
return pgch_datum_oid(type);
}
}
}
static Datum
pgch__read_array(
const chc_column* col,
const chc_type* type,
uint64_t row,
Oid* valtype,
bool* is_null
) {
const uint64_t* offs = chc_column_array_offsets(col);
uint64_t start = row == 0 ? 0 : offs[row - 1];
uint64_t end = offs[row];
uint64_t len = end - start;
const chc_type* inner_t = chc_type_child(type, 0);
const chc_column* inner = chc_column_array_values(col);
pgch_array* slot = (pgch_array*)palloc(sizeof(pgch_array));
const chc_type* leaf;
int ndim;
slot->len = len;
/* PostgreSQL uses one array type for every nesting depth */
slot->item_type = pgch__array_item(type, &leaf, &ndim);
slot->ndim = ndim;
slot->array_type = get_array_type(slot->item_type);
if (!OidIsValid(slot->array_type)) {
pgch_errorf(
ERRCODE_FDW_INVALID_DATA_TYPE,
"no PG array type for column type \"%s\"",
chc_type_name(leaf, NULL)
);
}
if (len > 0) {
Oid scratch = slot->item_type;
slot->datums = (Datum*)palloc0(sizeof(Datum) * len);
slot->nulls = (bool*)palloc0(sizeof(bool) * len);
for (uint64_t i = 0; i < len; ++i) {
slot->datums[i] =
pgch_read_value(inner, inner_t, start + i, &scratch, &slot->nulls[i]);
}
} else {
slot->datums = NULL;
slot->nulls = NULL;
}
*valtype = ANYARRAYOID;
*is_null = false;
return PointerGetDatum(slot);
}
/* Geo types carry no children, so a level's element kind follows from the kind */
static chc_kind
pgch__geo_child(chc_kind kind) {
switch (kind) {
case CHC_MULTI_POLYGON:
return CHC_POLYGON;
case CHC_POLYGON:
return CHC_RING;
case CHC_MULTI_LINE_STRING:
return CHC_LINE_STRING;
case CHC_RING:
case CHC_LINE_STRING:
return CHC_POINT;
default:
pg_unreachable();
}
}
static Datum
pgch__read_geo(
const chc_column* col,
chc_kind kind,
uint64_t row,
Oid* valtype,
bool* is_null
);
/* PostgreSQL has no multi-geometry types, so their members become array items */
static Datum
pgch__read_geo_array(
const chc_column* col,
chc_kind kind,
uint64_t row,
Oid* valtype,
bool* is_null
) {
const uint64_t* offs = chc_column_array_offsets(col);
uint64_t start = row == 0 ? 0 : offs[row - 1];
uint64_t len = offs[row] - start;
const chc_column* inner = chc_column_array_values(col);
chc_kind child = pgch__geo_child(kind);
pgch_array* slot = (pgch_array*)palloc(sizeof(pgch_array));
slot->len = len;
slot->ndim = kind == CHC_MULTI_POLYGON ? 2 : 1;
slot->item_type =
pgch_kind_oids[kind == CHC_MULTI_LINE_STRING ? CHC_LINE_STRING : CHC_RING];
slot->array_type = get_array_type(slot->item_type);
slot->datums = len ? (Datum*)palloc0(sizeof(Datum) * len) : NULL;
slot->nulls = len ? (bool*)palloc0(sizeof(bool) * len) : NULL;
for (uint64_t i = 0; i < len; i++) {
Oid scratch = slot->item_type;
slot->datums[i] =
pgch__read_geo(inner, child, start + i, &scratch, &slot->nulls[i]);
}
*valtype = ANYARRAYOID;
*is_null = false;
return PointerGetDatum(slot);
}
static Datum
pgch__read_geo(
const chc_column* col,
chc_kind kind,
uint64_t row,
Oid* valtype,
bool* is_null
) {
*valtype = pgch_kind_oids[kind];
switch (kind) {
case CHC_POINT:
return pgch__read_point(col, row);
case CHC_RING:
return pgch__read_polygon(col, row, is_null);
case CHC_LINE_STRING:
return pgch__read_path(col, row, is_null);
case CHC_POLYGON:
case CHC_MULTI_POLYGON:
case CHC_MULTI_LINE_STRING:
return pgch__read_geo_array(col, kind, row, valtype, is_null);
default:
pg_unreachable();
}
}
static Datum
pgch__read_tuple(
const chc_column* col,
const chc_type* type,
uint64_t row,
Oid* valtype,
bool* is_null
) {
size_t n = chc_type_n_children(type);
pgch_tuple* slot;
if (n == 0) {
pgch_error(ERRCODE_FDW_ERROR, "returned tuple is empty");
}
slot = (pgch_tuple*)palloc(sizeof(pgch_tuple));
slot->datums = (Datum*)palloc(sizeof(Datum) * n);
slot->nulls = (bool*)palloc0(sizeof(bool) * n);
slot->types = (Oid*)palloc0(sizeof(Oid) * n);
slot->len = n;
slot->ch_type_name = chc_type_name(type, NULL);
for (size_t i = 0; i < n; ++i) {
const chc_type* ft = chc_type_child(type, i);
const chc_column* fc = chc_column_tuple_child(col, i);
slot->datums[i] =
pgch_read_value(fc, ft, row, &slot->types[i], &slot->nulls[i]);
}
*valtype = RECORDOID;
*is_null = false;
return PointerGetDatum(slot);
}
/*
* Map is Array(Tuple(K, V)) carrying no Tuple type of its own, so the pair
* reads against the Map type, whose two children are the field types
*/
static Datum
pgch__read_map(
const chc_column* col,
const chc_type* type,
uint64_t row,
Oid* valtype,
bool* is_null
) {
const uint64_t* offs = chc_column_array_offsets(col);
uint64_t start = row == 0 ? 0 : offs[row - 1];
uint64_t len = offs[row] - start;
const chc_column* entries = chc_column_array_values(col);
pgch_array* slot = (pgch_array*)palloc(sizeof(pgch_array));
slot->len = len;
slot->ndim = 1;
slot->item_type = RECORDOID;
slot->array_type = RECORDARRAYOID;
slot->datums = len ? (Datum*)palloc0(sizeof(Datum) * len) : NULL;
slot->nulls = len ? (bool*)palloc0(sizeof(bool) * len) : NULL;
for (uint64_t i = 0; i < len; i++) {
Oid scratch = RECORDOID;
slot->datums[i] =
pgch__read_tuple(entries, type, start + i, &scratch, &slot->nulls[i]);
}
*valtype = ANYARRAYOID;
*is_null = false;
return PointerGetDatum(slot);
}
Datum
pgch_read_value(
const chc_column* col,
const chc_type* type,
uint64_t row,
Oid* valtype,
bool* is_null
) {
if (chc_type_kind(type) == CHC_NULLABLE) {
const chc_type* inner_t = chc_type_child(type, 0);
if (chc_column_layout(col) == CHC_COL_NULLABLE) {
const uint8_t* nm = chc_column_null_map(col);
if (nm && nm[row]) {
*valtype = pgch_datum_oid(inner_t);
*is_null = true;
return (Datum)0;
}
col = chc_column_nullable_inner(col);
}
type = inner_t;
}
chc_kind kind = chc_type_kind(type);
Oid want = *valtype;
*valtype = pgch_kind_oids[kind];
*is_null = false;
switch (kind) {
case CHC_VOID:
case CHC_NOTHING:
*is_null = true;
return (Datum)0;
case CHC_UINT8:
return Int16GetDatum(
pgch__rd_u8((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_BOOL:
return BoolGetDatum(
pgch__rd_bool((const bool*)chc_column_fixed_data(col, NULL), row)
);
case CHC_INT8:
return Int16GetDatum(
pgch__rd_i8((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_INT16:
return Int16GetDatum(
pgch__rd_i16((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_UINT16:
return Int32GetDatum(
pgch__rd_u16((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_INT32:
return Int32GetDatum(
pgch__rd_i32((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_UINT32:
return Int64GetDatum(
(int64)pgch__rd_u32((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_INT64:
return Int64GetDatum(
pgch__rd_i64((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_UINT64: {
uint64_t v =
pgch__rd_u64((const uint8_t*)chc_column_fixed_data(col, NULL), row);
#if PG_VERSION_NUM >= 190000
/* PostgreSQL oid8 supports full UInt64 range */
if (want == OID8OID) {
*valtype = OID8OID;
return ObjectId8GetDatum(v);
}
#endif
if (v > (uint64_t)PG_INT64_MAX) {
pgch_errorf(
ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE,
"value " UINT64_FORMAT " is out of range of bigint",
v
);
}
return Int64GetDatum((int64)v);
}
case CHC_FLOAT32:
return Float4GetDatum(
pgch__rd_f32((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_FLOAT64:
return Float8GetDatum(
pgch__rd_f64((const uint8_t*)chc_column_fixed_data(col, NULL), row)
);
case CHC_DECIMAL32: