forked from heterodb/pg-strom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrow_fdw.c
4724 lines (4280 loc) · 127 KB
/
arrow_fdw.c
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
/*
* arrow_fdw.c
*
* Routines to map Apache Arrow files as PG's Foreign-Table.
* ----
* Copyright 2011-2023 (C) KaiGai Kohei <[email protected]>
* Copyright 2014-2023 (C) PG-Strom Developers Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the PostgreSQL License.
*/
#include "pg_strom.h"
#include "arrow_defs.h"
#include "arrow_ipc.h"
#include "xpu_numeric.h"
/*
* min/max statistics datum
*/
typedef struct
{
bool isnull;
union {
Datum datum;
NumericData numeric; /* if NUMERICOID */
} min;
union {
Datum datum;
NumericData numeric; /* if NUMERICOID */
} max;
} MinMaxStatDatum;
/*
* RecordBatchState
*/
typedef struct RecordBatchFieldState
{
/* common fields with cache */
Oid atttypid;
int atttypmod;
ArrowTypeOptions attopts;
int64 nitems; /* usually, same with rb_nitems */
int64 null_count;
off_t nullmap_offset;
size_t nullmap_length;
off_t values_offset;
size_t values_length;
off_t extra_offset;
size_t extra_length;
MinMaxStatDatum stat_datum;
/* sub-fields if any */
int num_children;
struct RecordBatchFieldState *children;
} RecordBatchFieldState;
typedef struct RecordBatchState
{
struct ArrowFileState *af_state; /* reference to ArrowFileState */
int rb_index; /* index number in a file */
off_t rb_offset; /* offset from the head */
size_t rb_length; /* length of the entire RecordBatch */
int64 rb_nitems; /* number of items */
/* per column information */
int nfields;
RecordBatchFieldState fields[FLEXIBLE_ARRAY_MEMBER];
} RecordBatchState;
typedef struct ArrowFileState
{
const char *filename;
const char *dpu_path; /* relative pathname, if DPU */
struct stat stat_buf;
List *rb_list; /* list of RecordBatchState */
} ArrowFileState;
/*
* ArrowFdwState - executor state to run apache arrow
*/
typedef struct
{
Bitmapset *stat_attrs;
Bitmapset *load_attrs;
List *orig_quals; /* for EXPLAIN */
List *eval_quals;
ExprState *eval_state;
ExprContext *econtext;
} arrowStatsHint;
struct ArrowFdwState
{
Bitmapset *referenced; /* referenced columns */
arrowStatsHint *stats_hint; /* min/max statistics, if any */
pg_atomic_uint32 *rbatch_index;
pg_atomic_uint32 __rbatch_index_local; /* if single process */
pg_atomic_uint32 *rbatch_nload;
pg_atomic_uint32 __rbatch_nload_local; /* if single process */
pg_atomic_uint32 *rbatch_nskip;
pg_atomic_uint32 __rbatch_nskip_local; /* if single process */
StringInfoData chunk_buffer; /* buffer to load record-batch */
File curr_filp; /* current arrow file to read */
kern_data_store *curr_kds; /* current chunk to read */
uint32_t curr_index; /* current index on the chunk */
List *af_states_list; /* list of ArrowFileState */
uint32_t rb_nitems; /* number of record-batches */
RecordBatchState *rb_states[FLEXIBLE_ARRAY_MEMBER]; /* flatten RecordBatchState */
};
/*
* Metadata Cache (on shared memory)
*/
#define ARROW_METADATA_BLOCKSZ (128 * 1024) /* 128kB */
typedef struct
{
dlist_node chain; /* link to free_blocks; NULL if active */
int32_t unitsz; /* unit size of slab items */
int32_t n_actives; /* number of active items */
char data[FLEXIBLE_ARRAY_MEMBER];
} arrowMetadataCacheBlock;
#define ARROW_METADATA_CACHE_FREE_MAGIC (0xdeadbeafU)
#define ARROW_METADATA_CACHE_ACTIVE_MAGIC (0xcafebabeU)
typedef struct arrowMetadataFieldCache arrowMetadataFieldCache;
typedef struct arrowMetadataCache arrowMetadataCache;
struct arrowMetadataFieldCache
{
arrowMetadataCacheBlock *owner;
dlist_node chain; /* link to free/fields[children] list */
/* common fields with cache */
Oid atttypid;
int atttypmod;
ArrowTypeOptions attopts;
int64 nitems; /* usually, same with rb_nitems */
int64 null_count;
off_t nullmap_offset;
size_t nullmap_length;
off_t values_offset;
size_t values_length;
off_t extra_offset;
size_t extra_length;
MinMaxStatDatum stat_datum;
/* sub-fields if any */
int num_children;
dlist_head children;
uint32_t magic;
};
struct arrowMetadataCache
{
arrowMetadataCacheBlock *owner;
dlist_node chain; /* link to free/hash list */
dlist_node lru_chain; /* link to lru_list */
struct timeval lru_tv; /* last access time */
arrowMetadataCache *next; /* next record-batch if any */
struct stat stat_buf; /* result of stat(2) */
int rb_index; /* index number in a file */
off_t rb_offset; /* offset from the head */
size_t rb_length; /* length of the entire RecordBatch */
int64 rb_nitems; /* number of items */
/* per column information */
int nfields;
dlist_head fields; /* list of arrowMetadataFieldCache */
uint32_t magic;
};
/*
* Metadata cache management
*/
#define ARROW_METADATA_HASH_NSLOTS 2000
typedef struct
{
LWLock mutex;
slock_t lru_lock; /* protect lru related stuff */
dlist_head lru_list;
dlist_head free_blocks; /* list of arrowMetadataCacheBlock */
dlist_head free_mcaches; /* list of arrowMetadataCache */
dlist_head free_fcaches; /* list of arrowMetadataFieldCache */
dlist_head hash_slots[ARROW_METADATA_HASH_NSLOTS];
} arrowMetadataCacheHead;
/*
* Static variables
*/
static FdwRoutine pgstrom_arrow_fdw_routine;
static shmem_request_hook_type shmem_request_next = NULL;
static shmem_startup_hook_type shmem_startup_next = NULL;
static arrowMetadataCacheHead *arrow_metadata_cache = NULL;
static bool arrow_fdw_enabled; /* GUC */
static bool arrow_fdw_stats_hint_enabled; /* GUC */
static int arrow_metadata_cache_size_kb; /* GUC */
/* ----------------------------------------------------------------
*
* Apache Arrow <--> PG Types Mapping Routines
*
* ----------------------------------------------------------------
*/
/*
* arrowFieldGetPGTypeHint
*/
static Oid
arrowFieldGetPGTypeHint(const ArrowField *field)
{
for (int i=0; i < field->_num_custom_metadata; i++)
{
ArrowKeyValue *kv = &field->custom_metadata[i];
Oid extension_oid = InvalidOid;
Oid namespace_oid = PG_CATALOG_NAMESPACE;
Oid hint_oid;
bool namespace_specified = false;
char *namebuf, *pos;
/* pg_type = NAMESPACE.TYPENAME@EXTENSION */
if (strcmp(kv->key, "pg_type") != 0)
continue;
namebuf = alloca(kv->_value_len + 10);
strcpy(namebuf, kv->value);
pos = strchr(namebuf, '.');
if (pos)
{
*pos++ = '\0';
namespace_oid = get_namespace_oid(namebuf, true);
if (!OidIsValid(namespace_oid))
continue;
namebuf = pos;
namespace_specified = true;
}
pos = strchr(namebuf, '@');
if (pos)
{
*pos++ = '\0';
extension_oid = get_extension_oid(pos, true);
if (!OidIsValid(extension_oid))
continue;
}
/* 1st try: user specified namespace or 'pg_catalog' */
hint_oid = GetSysCacheOid2(TYPENAMENSP,
Anum_pg_type_oid,
CStringGetDatum(namebuf),
ObjectIdGetDatum(namespace_oid));
if (OidIsValid(hint_oid))
{
if (!OidIsValid(extension_oid) ||
getExtensionOfObject(TypeRelationId,
hint_oid) == extension_oid)
return hint_oid;
}
/* 2nd try: any namespace (if not specified) */
if (!namespace_specified)
{
CatCList *typelist;
HeapTuple htup;
typelist = SearchSysCacheList1(TYPENAMENSP,
CStringGetDatum(namebuf));
for (int k=0; k < typelist->n_members; k++)
{
htup = &typelist->members[k]->tuple;
hint_oid = ((Form_pg_type) GETSTRUCT(htup))->oid;
if (!OidIsValid(extension_oid) ||
getExtensionOfObject(TypeRelationId,
hint_oid) == extension_oid)
{
ReleaseCatCacheList(typelist);
return hint_oid;
}
}
ReleaseCatCacheList(typelist);
}
}
return InvalidOid;
}
/* ------------------------------------------------
* Metadata Cache Management Routines
*
* MEMO: all of them requires the caller must have exclusive lock
* on the arrowMetadataCache::mutex
* ------------------------------------------------
*/
static void
__releaseMetadataFieldCache(arrowMetadataFieldCache *fcache)
{
arrowMetadataCacheBlock *mc_block = fcache->owner;
Assert(fcache->magic == ARROW_METADATA_CACHE_ACTIVE_MAGIC);
/* also release sub-fields if any */
while (!dlist_is_empty(&fcache->children))
{
arrowMetadataFieldCache *__fcache
= dlist_container(arrowMetadataFieldCache, chain,
dlist_pop_head_node(&fcache->children));
__releaseMetadataFieldCache(__fcache);
}
fcache->magic = ARROW_METADATA_CACHE_FREE_MAGIC;
dlist_push_tail(&arrow_metadata_cache->free_fcaches,
&fcache->chain);
/* also back the owner block if all slabs become free */
Assert(mc_block->n_actives > 0);
if (--mc_block->n_actives == 0)
{
char *pos = mc_block->data;
char *end = (char *)mc_block + ARROW_METADATA_BLOCKSZ;
Assert(mc_block->unitsz == MAXALIGN(sizeof(arrowMetadataFieldCache)));
while (pos + mc_block->unitsz <= end)
{
arrowMetadataFieldCache *__fcache = (arrowMetadataFieldCache *)pos;
Assert(__fcache->owner == mc_block &&
__fcache->magic == ARROW_METADATA_CACHE_FREE_MAGIC);
dlist_delete(&__fcache->chain);
pos += mc_block->unitsz;
}
Assert(!mc_block->chain.prev &&
!mc_block->chain.next); /* must be active block */
dlist_push_tail(&arrow_metadata_cache->free_blocks,
&mc_block->chain);
}
}
static void
__releaseMetadataCache(arrowMetadataCache *mcache)
{
while (mcache)
{
arrowMetadataCacheBlock *mc_block = mcache->owner;
arrowMetadataCache *__mcache_next = mcache->next;
Assert(mcache->magic == ARROW_METADATA_CACHE_ACTIVE_MAGIC);
/*
* MEMO: Caller already detach the leader mcache from the hash-
* slot and the LRU-list. The follower mcaches should never be
* linked to hash-slot and LRU-list.
* So, we just put Assert() here.
*/
Assert(!mcache->chain.prev && !mcache->chain.next &&
!mcache->lru_chain.prev && !mcache->lru_chain.next);
/* also release arrowMetadataFieldCache */
while (!dlist_is_empty(&mcache->fields))
{
arrowMetadataFieldCache *fcache
= dlist_container(arrowMetadataFieldCache, chain,
dlist_pop_head_node(&mcache->fields));
__releaseMetadataFieldCache(fcache);
}
mcache->magic = ARROW_METADATA_CACHE_FREE_MAGIC;
dlist_push_tail(&arrow_metadata_cache->free_mcaches,
&mcache->chain);
/* also back the owner block if all slabs become free */
Assert(mc_block->n_actives > 0);
if (--mc_block->n_actives == 0)
{
char *pos = mc_block->data;
char *end = (char *)mc_block + ARROW_METADATA_BLOCKSZ;
Assert(mc_block->unitsz == MAXALIGN(sizeof(arrowMetadataCache)));
while (pos + mc_block->unitsz <= end)
{
arrowMetadataCache *__mcache = (arrowMetadataCache *)pos;
Assert(__mcache->owner == mc_block &&
__mcache->magic == ARROW_METADATA_CACHE_FREE_MAGIC);
dlist_delete(&__mcache->chain);
pos += mc_block->unitsz;
}
Assert(!mc_block->chain.prev &&
!mc_block->chain.next); /* must be active block */
dlist_push_tail(&arrow_metadata_cache->free_blocks,
&mc_block->chain);
}
mcache = __mcache_next;
}
}
static bool
__reclaimMetadataCache(void)
{
SpinLockAcquire(&arrow_metadata_cache->lru_lock);
if (!dlist_is_empty(&arrow_metadata_cache->lru_list))
{
arrowMetadataCache *mcache;
dlist_node *dnode;
struct timeval curr_tv;
int64_t elapsed;
gettimeofday(&curr_tv, NULL);
dnode = dlist_tail_node(&arrow_metadata_cache->lru_list);
mcache = dlist_container(arrowMetadataCache, lru_chain, dnode);
elapsed = ((curr_tv.tv_sec - mcache->lru_tv.tv_sec) * 1000000 +
(curr_tv.tv_usec - mcache->lru_tv.tv_usec));
if (elapsed > 30000000UL) /* > 30s */
{
dlist_delete(&mcache->lru_chain);
memset(&mcache->lru_chain, 0, sizeof(dlist_node));
SpinLockRelease(&arrow_metadata_cache->lru_lock);
dlist_delete(&mcache->chain);
memset(&mcache->chain, 0, sizeof(dlist_node));
__releaseMetadataCache(mcache);
return true;
}
}
SpinLockRelease(&arrow_metadata_cache->lru_lock);
return false;
}
static arrowMetadataFieldCache *
__allocMetadataFieldCache(void)
{
arrowMetadataFieldCache *fcache;
dlist_node *dnode;
while (dlist_is_empty(&arrow_metadata_cache->free_fcaches))
{
arrowMetadataCacheBlock *mc_block;
char *pos, *end;
while (dlist_is_empty(&arrow_metadata_cache->free_blocks))
{
if (!__reclaimMetadataCache())
return NULL;
}
dnode = dlist_pop_head_node(&arrow_metadata_cache->free_blocks);
mc_block = dlist_container(arrowMetadataCacheBlock, chain, dnode);
memset(mc_block, 0, offsetof(arrowMetadataCacheBlock, data));
mc_block->unitsz = MAXALIGN(sizeof(arrowMetadataFieldCache));
for (pos = mc_block->data, end = (char *)mc_block + ARROW_METADATA_BLOCKSZ;
pos + mc_block->unitsz <= end;
pos += mc_block->unitsz)
{
fcache = (arrowMetadataFieldCache *)pos;
fcache->owner = mc_block;
fcache->magic = ARROW_METADATA_CACHE_FREE_MAGIC;
dlist_push_tail(&arrow_metadata_cache->free_fcaches,
&fcache->chain);
}
}
dnode = dlist_pop_head_node(&arrow_metadata_cache->free_fcaches);
fcache = dlist_container(arrowMetadataFieldCache, chain, dnode);
fcache->owner->n_actives++;
Assert(fcache->magic == ARROW_METADATA_CACHE_FREE_MAGIC);
memset(&fcache->chain, 0, (offsetof(arrowMetadataFieldCache, magic) -
offsetof(arrowMetadataFieldCache, chain)));
fcache->magic = ARROW_METADATA_CACHE_ACTIVE_MAGIC;
return fcache;
}
static arrowMetadataCache *
__allocMetadataCache(void)
{
arrowMetadataCache *mcache;
dlist_node *dnode;
if (dlist_is_empty(&arrow_metadata_cache->free_mcaches))
{
arrowMetadataCacheBlock *mc_block;
char *pos, *end;
while (dlist_is_empty(&arrow_metadata_cache->free_blocks))
{
if (!__reclaimMetadataCache())
return NULL;
}
dnode = dlist_pop_head_node(&arrow_metadata_cache->free_blocks);
mc_block = dlist_container(arrowMetadataCacheBlock, chain, dnode);
memset(mc_block, 0, offsetof(arrowMetadataCacheBlock, data));
mc_block->unitsz = MAXALIGN(sizeof(arrowMetadataCache));
for (pos = mc_block->data, end = (char *)mc_block + ARROW_METADATA_BLOCKSZ;
pos + mc_block->unitsz <= end;
pos += mc_block->unitsz)
{
mcache = (arrowMetadataCache *)pos;
mcache->owner = mc_block;
mcache->magic = ARROW_METADATA_CACHE_FREE_MAGIC;
dlist_push_tail(&arrow_metadata_cache->free_mcaches,
&mcache->chain);
}
}
dnode = dlist_pop_head_node(&arrow_metadata_cache->free_mcaches);
mcache = dlist_container(arrowMetadataCache, chain, dnode);
mcache->owner->n_actives++;
Assert(mcache->magic == ARROW_METADATA_CACHE_FREE_MAGIC);
memset(&mcache->chain, 0, (offsetof(arrowMetadataCache, magic) -
offsetof(arrowMetadataCache, chain)));
mcache->magic = ARROW_METADATA_CACHE_ACTIVE_MAGIC;
return mcache;
}
/*
* lookupArrowMetadataCache
*
* caller must hold "at least" shared lock on the arrow_metadata_cache->mutex.
* if exclusive lock is held, it may invalidate legacy cache if any.
*/
static inline uint32_t
arrowMetadataHashIndex(struct stat *stat_buf)
{
struct {
dev_t st_dev;
ino_t st_ino;
} hkey;
uint32_t hash;
hkey.st_dev = stat_buf->st_dev;
hkey.st_ino = stat_buf->st_ino;
hash = hash_bytes((unsigned char *)&hkey, sizeof(hkey));
return hash % ARROW_METADATA_HASH_NSLOTS;
}
static arrowMetadataCache *
lookupArrowMetadataCache(struct stat *stat_buf, bool has_exclusive)
{
arrowMetadataCache *mcache;
uint32_t hindex;
dlist_mutable_iter iter;
hindex = arrowMetadataHashIndex(stat_buf);
dlist_foreach_modify(iter, &arrow_metadata_cache->hash_slots[hindex])
{
mcache = dlist_container(arrowMetadataCache, chain, iter.cur);
if (stat_buf->st_dev == mcache->stat_buf.st_dev &&
stat_buf->st_ino == mcache->stat_buf.st_ino)
{
/*
* Is the metadata cache still valid?
*/
if (stat_buf->st_mtim.tv_sec < mcache->stat_buf.st_mtim.tv_sec ||
(stat_buf->st_mtim.tv_sec == mcache->stat_buf.st_mtim.tv_sec &&
stat_buf->st_mtim.tv_nsec <= mcache->stat_buf.st_mtim.tv_nsec))
{
/* ok, found */
SpinLockAcquire(&arrow_metadata_cache->lru_lock);
gettimeofday(&mcache->lru_tv, NULL);
dlist_move_head(&arrow_metadata_cache->lru_list,
&mcache->lru_chain);
SpinLockRelease(&arrow_metadata_cache->lru_lock);
return mcache;
}
else if (has_exclusive)
{
/*
* Unfortunatelly, metadata cache is already invalid.
* If caller has exclusive lock, we release it.
*/
SpinLockAcquire(&arrow_metadata_cache->lru_lock);
dlist_delete(&mcache->lru_chain);
memset(&mcache->lru_chain, 0, sizeof(dlist_node));
SpinLockRelease(&arrow_metadata_cache->lru_lock);
dlist_delete(&mcache->chain);
memset(&mcache->chain, 0, sizeof(dlist_node));
__releaseMetadataCache(mcache);
}
}
}
return NULL;
}
/* ----------------------------------------------------------------
*
* buildArrowStatsBinary
*
* ...and, routines related to Arrow Min/Max statistics
*
* ----------------------------------------------------------------
*/
typedef struct arrowFieldStatsBinary
{
uint32 nrooms; /* number of record-batches */
MinMaxStatDatum *stat_values;
int nfields; /* if List/Struct data type */
struct arrowFieldStatsBinary *subfields;
} arrowFieldStatsBinary;
typedef struct
{
int nitems; /* number of record-batches */
int nfields; /* number of columns */
arrowFieldStatsBinary fields[FLEXIBLE_ARRAY_MEMBER];
} arrowStatsBinary;
static void
__releaseArrowFieldStatsBinary(arrowFieldStatsBinary *bstats)
{
if (bstats->subfields)
{
for (int j=0; j < bstats->nfields; j++)
__releaseArrowFieldStatsBinary(&bstats->subfields[j]);
pfree(bstats->subfields);
}
if (bstats->stat_values)
pfree(bstats->stat_values);
}
static void
releaseArrowStatsBinary(arrowStatsBinary *arrow_bstats)
{
if (arrow_bstats)
{
for (int j=0; j < arrow_bstats->nfields; j++)
__releaseArrowFieldStatsBinary(&arrow_bstats->fields[j]);
pfree(arrow_bstats);
}
}
static int128_t
__atoi128(const char *tok, bool *p_isnull)
{
int128_t ival = 0;
bool is_minus = false;
if (*tok == '-')
{
is_minus = true;
tok++;
}
while (isdigit(*tok))
{
ival = 10 * ival + (*tok - '0');
tok++;
}
if (*tok != '\0')
*p_isnull = true;
if (is_minus)
{
if (ival == 0)
*p_isnull = true;
ival = -ival;
}
return ival;
}
static bool
__parseArrowFieldStatsBinary(arrowFieldStatsBinary *bstats,
ArrowField *field,
const char *min_tokens,
const char *max_tokens)
{
MinMaxStatDatum *stat_values;
char *min_buffer;
char *max_buffer;
char *tok1, *pos1;
char *tok2, *pos2;
uint32_t index;
/* parse the min_tokens/max_tokens */
min_buffer = alloca(strlen(min_tokens) + 1);
max_buffer = alloca(strlen(max_tokens) + 1);
strcpy(min_buffer, min_tokens);
strcpy(max_buffer, max_tokens);
stat_values = palloc0(sizeof(MinMaxStatDatum) * bstats->nrooms);
for (tok1 = strtok_r(min_buffer, ",", &pos1),
tok2 = strtok_r(max_buffer, ",", &pos2), index = 0;
tok1 != NULL && tok2 != NULL && index < bstats->nrooms;
tok1 = strtok_r(NULL, ",", &pos1),
tok2 = strtok_r(NULL, ",", &pos2), index++)
{
bool __isnull = false;
int128_t __min = __atoi128(__trim(tok1), &__isnull);
int128_t __max = __atoi128(__trim(tok2), &__isnull);
int64_t __drift;
if (__isnull)
{
stat_values[index].isnull = true;
continue;
}
switch (field->type.node.tag)
{
case ArrowNodeTag__Int:
case ArrowNodeTag__FloatingPoint:
stat_values[index].min.datum = (Datum)__min;
stat_values[index].max.datum = (Datum)__max;
break;
case ArrowNodeTag__Decimal:
__xpu_numeric_to_varlena((char *)&stat_values[index].min.numeric,
field->type.Decimal.scale,
__min);
__xpu_numeric_to_varlena((char *)&stat_values[index].max.numeric,
field->type.Decimal.scale,
__max);
break;
case ArrowNodeTag__Date:
switch (field->type.Date.unit)
{
case ArrowDateUnit__Day:
stat_values[index].min.datum = __min
- (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE);
stat_values[index].max.datum = __max
- (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE);
break;
case ArrowDateUnit__MilliSecond:
stat_values[index].min.datum = __min / (SECS_PER_DAY * 1000)
- (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE);
stat_values[index].max.datum = __max / (SECS_PER_DAY * 1000)
- (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE);
break;
default:
goto bailout;
}
break;
case ArrowNodeTag__Time:
switch (field->type.Time.unit)
{
case ArrowTimeUnit__Second:
stat_values[index].min.datum = __min * 1000000L;
stat_values[index].max.datum = __max * 1000000L;
break;
case ArrowTimeUnit__MilliSecond:
stat_values[index].min.datum = __min * 1000L;
stat_values[index].max.datum = __max * 1000L;
break;
case ArrowTimeUnit__MicroSecond:
stat_values[index].min.datum = __min;
stat_values[index].max.datum = __max;
break;
case ArrowTimeUnit__NanoSecond:
stat_values[index].min.datum = __min / 1000;
stat_values[index].max.datum = __max / 1000;
break;
default:
goto bailout;
}
break;
case ArrowNodeTag__Timestamp:
__drift = (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * USECS_PER_DAY;
switch (field->type.Timestamp.unit)
{
case ArrowTimeUnit__Second:
stat_values[index].min.datum = __min * 1000000L - __drift;
stat_values[index].max.datum = __max * 1000000L - __drift;
break;
case ArrowTimeUnit__MilliSecond:
stat_values[index].min.datum = __min * 1000L - __drift;
stat_values[index].max.datum = __max * 1000L - __drift;
break;
case ArrowTimeUnit__MicroSecond:
stat_values[index].min.datum = __min - __drift;
stat_values[index].max.datum = __max - __drift;
break;
case ArrowTimeUnit__NanoSecond:
stat_values[index].min.datum = __min / 1000 - __drift;
stat_values[index].max.datum = __max / 1000 - __drift;
break;
default:
goto bailout;
}
break;
default:
goto bailout;
}
}
/* sanity checks */
if (!tok1 && !tok2 && index == bstats->nrooms)
{
bstats->stat_values = stat_values;
return true;
}
bailout:
pfree(stat_values);
return false;
}
static bool
__buildArrowFieldStatsBinary(arrowFieldStatsBinary *bstats,
ArrowField *field,
uint32 numRecordBatches)
{
const char *min_tokens = NULL;
const char *max_tokens = NULL;
int j, k;
bool retval = false;
for (k=0; k < field->_num_custom_metadata; k++)
{
ArrowKeyValue *kv = &field->custom_metadata[k];
if (strcmp(kv->key, "min_values") == 0)
min_tokens = kv->value;
else if (strcmp(kv->key, "max_values") == 0)
max_tokens = kv->value;
}
bstats->nrooms = numRecordBatches;
if (min_tokens && max_tokens)
{
if (__parseArrowFieldStatsBinary(bstats, field,
min_tokens,
max_tokens))
{
retval = true;
}
}
if (field->_num_children > 0)
{
bstats->nfields = field->_num_children;
bstats->subfields = palloc0(sizeof(arrowFieldStatsBinary) * bstats->nfields);
for (j=0; j < bstats->nfields; j++)
{
if (__buildArrowFieldStatsBinary(&bstats->subfields[j],
&field->children[j],
numRecordBatches))
retval = true;
}
}
return retval;
}
static arrowStatsBinary *
buildArrowStatsBinary(const ArrowFooter *footer, Bitmapset **p_stat_attrs)
{
arrowStatsBinary *arrow_bstats;
int nfields = footer->schema._num_fields;
bool found = false;
arrow_bstats = palloc0(offsetof(arrowStatsBinary,
fields[nfields]));
arrow_bstats->nitems = footer->_num_recordBatches;
arrow_bstats->nfields = nfields;
for (int j=0; j < nfields; j++)
{
if (__buildArrowFieldStatsBinary(&arrow_bstats->fields[j],
&footer->schema.fields[j],
footer->_num_recordBatches))
{
if (p_stat_attrs)
*p_stat_attrs = bms_add_member(*p_stat_attrs, j+1);
found = true;
}
}
if (!found)
{
releaseArrowStatsBinary(arrow_bstats);
return NULL;
}
return arrow_bstats;
}
/*
* applyArrowStatsBinary
*/
static void
__applyArrowFieldStatsBinary(RecordBatchFieldState *rb_field,
arrowFieldStatsBinary *bstats,
int rb_index)
{
int j;
if (bstats->stat_values)
{
memcpy(&rb_field->stat_datum,
&bstats->stat_values[rb_index], sizeof(MinMaxStatDatum));
}
else
{
rb_field->stat_datum.isnull = true;
}
Assert(rb_field->num_children == bstats->nfields);
for (j=0; j < rb_field->num_children; j++)
{
RecordBatchFieldState *__rb_field = &rb_field->children[j];
arrowFieldStatsBinary *__bstats = &bstats->subfields[j];
__applyArrowFieldStatsBinary(__rb_field, __bstats, rb_index);
}
}
static void
applyArrowStatsBinary(RecordBatchState *rb_state, arrowStatsBinary *arrow_bstats)
{
Assert(rb_state->nfields == arrow_bstats->nfields &&
rb_state->rb_index < arrow_bstats->nitems);
for (int j=0; j < rb_state->nfields; j++)
{
__applyArrowFieldStatsBinary(&rb_state->fields[j],
&arrow_bstats->fields[j],
rb_state->rb_index);
}
}
/*
* execInitArrowStatsHint / execCheckArrowStatsHint / execEndArrowStatsHint
*
* ... are executor routines for min/max statistics.
*/
static bool
__buildArrowStatsOper(arrowStatsHint *as_hint,
ScanState *ss,
OpExpr *op,
bool reverse)
{
Scan *scan = (Scan *)ss->ps.plan;
Oid opcode;
Var *var;
Node *arg;
Expr *expr;
Oid opfamily = InvalidOid;
StrategyNumber strategy = InvalidStrategy;
CatCList *catlist;
int i;
if (!reverse)
{
opcode = op->opno;
var = linitial(op->args);
arg = lsecond(op->args);
}
else
{
opcode = get_commutator(op->opno);
var = lsecond(op->args);
arg = linitial(op->args);
}
/*
* Is it VAR <OPER> ARG form?
*
* MEMO: expression nodes (like Var) might be rewritten to INDEX_VAR +
* resno on the custom_scan_tlist by setrefs.c, so we should reference
* Var::varnosyn and ::varattnosyn, instead of ::varno and ::varattno.
*/
if (!IsA(var, Var) || !OidIsValid(opcode))
return false;
if (var->varnosyn != scan->scanrelid)
return false;
if (!bms_is_member(var->varattnosyn, as_hint->stat_attrs))
return false;
if (contain_var_clause(arg) ||
contain_volatile_functions(arg))
return false;
catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opcode));
for (i=0; i < catlist->n_members; i++)
{
HeapTuple tuple = &catlist->members[i]->tuple;
Form_pg_amop amop = (Form_pg_amop) GETSTRUCT(tuple);
if (amop->amopmethod == BRIN_AM_OID)
{
opfamily = amop->amopfamily;
strategy = amop->amopstrategy;
break;
}
}
ReleaseSysCacheList(catlist);
if (strategy == BTLessStrategyNumber ||
strategy == BTLessEqualStrategyNumber)
{
/* if (VAR < ARG) --> (Min >= ARG), can be skipped */
/* if (VAR <= ARG) --> (Min > ARG), can be skipped */
opcode = get_negator(opcode);
if (!OidIsValid(opcode))
return false;
expr = make_opclause(opcode,
op->opresulttype,
op->opretset,
(Expr *)makeVar(INNER_VAR,
var->varattno,
var->vartype,
var->vartypmod,
var->varcollid,
0),
(Expr *)copyObject(arg),
op->opcollid,
op->inputcollid);
set_opfuncid((OpExpr *)expr);
as_hint->eval_quals = lappend(as_hint->eval_quals, expr);
}
else if (strategy == BTGreaterEqualStrategyNumber ||
strategy == BTGreaterStrategyNumber)
{
/* if (VAR > ARG) --> (Max <= ARG), can be skipped */
/* if (VAR >= ARG) --> (Max < ARG), can be skipped */
opcode = get_negator(opcode);
if (!OidIsValid(opcode))
return false;
expr = make_opclause(opcode,
op->opresulttype,
op->opretset,
(Expr *)makeVar(OUTER_VAR,
var->varattno,
var->vartype,
var->vartypmod,
var->varcollid,
0),
(Expr *)copyObject(arg),
op->opcollid,