-
Notifications
You must be signed in to change notification settings - Fork 38
/
parquet_impl.cpp
2379 lines (2029 loc) · 73.6 KB
/
parquet_impl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Parquet processing implementation
*/
// basename comes from string.h on Linux,
// but from libgen.h on other POSIX systems (see man basename)
#ifndef GNU_SOURCE
#include <libgen.h>
#endif
#include <sys/stat.h>
#include <math.h>
#include <list>
#include <set>
#include "parquet/arrow/reader.h"
#include "parquet/arrow/schema.h"
#include "parquet/file_reader.h"
#include "parquet/statistics.h"
#include "exec_state.hpp"
#include "reader.hpp"
#include "common.hpp"
extern "C"
{
#include "postgres.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "executor/spi.h"
#include "executor/tuptable.h"
#include "foreign/foreign.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/execnodes.h"
#include "nodes/makefuncs.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "utils/builtins.h"
#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/regproc.h"
#include "utils/rel.h"
#include "utils/typcache.h"
#if PG_VERSION_NUM < 120000
#include "nodes/relation.h"
#include "optimizer/var.h"
#else
#include "access/table.h"
#include "optimizer/optimizer.h"
#endif
#if PG_VERSION_NUM < 110000
#include "catalog/pg_am.h"
#else
#include "catalog/pg_am_d.h"
#endif
}
/* from costsize.c */
#define LOG2(x) (log(x) / 0.693147180559945)
#if PG_VERSION_NUM < 110000
#define PG_GETARG_JSONB_P PG_GETARG_JSONB
#endif
bool enable_multifile;
bool enable_multifile_merge;
static void find_cmp_func(FmgrInfo *finfo, Oid type1, Oid type2);
static void destroy_parquet_state(void *arg);
/*
* Restriction
*/
struct RowGroupFilter
{
AttrNumber attnum;
bool is_key; /* for maps */
Const *value;
int strategy;
};
/*
* Plain C struct for fdw_state
*/
struct ParquetFdwPlanState
{
List *filenames;
List *attrs_sorted;
Bitmapset *attrs_used; /* attributes actually used in query */
bool use_mmap;
bool use_threads;
int32 max_open_files;
bool files_in_order;
List *rowgroups; /* List of Lists (per filename) */
uint64 matched_rows;
ReaderType type;
};
static int
get_strategy(Oid type, Oid opno, Oid am)
{
Oid opclass;
Oid opfamily;
opclass = GetDefaultOpClass(type, am);
if (!OidIsValid(opclass))
return 0;
opfamily = get_opclass_family(opclass);
return get_op_opfamily_strategy(opno, opfamily);
}
/*
* extract_rowgroup_filters
* Build a list of expressions we can use to filter out row groups.
*/
static void
extract_rowgroup_filters(List *scan_clauses,
std::list<RowGroupFilter> &filters)
{
ListCell *lc;
foreach (lc, scan_clauses)
{
Expr *clause = (Expr *) lfirst(lc);
OpExpr *expr;
Expr *left, *right;
int strategy;
bool is_key = false;
Const *c;
Var *v;
Oid opno;
if (IsA(clause, RestrictInfo))
clause = ((RestrictInfo *) clause)->clause;
if (IsA(clause, OpExpr))
{
expr = (OpExpr *) clause;
/* Only interested in binary opexprs */
if (list_length(expr->args) != 2)
continue;
left = (Expr *) linitial(expr->args);
right = (Expr *) lsecond(expr->args);
/*
* Looking for expressions like "EXPR OP CONST" or "CONST OP EXPR"
*
* XXX Currently only Var as expression is supported. Will be
* extended in future.
*/
if (IsA(right, Const))
{
if (!IsA(left, Var))
continue;
v = (Var *) left;
c = (Const *) right;
opno = expr->opno;
}
else if (IsA(left, Const))
{
/* reverse order (CONST OP VAR) */
if (!IsA(right, Var))
continue;
v = (Var *) right;
c = (Const *) left;
opno = get_commutator(expr->opno);
}
else
continue;
/* Not a btree family operator? */
if ((strategy = get_strategy(v->vartype, opno, BTREE_AM_OID)) == 0)
{
/*
* Maybe it's a gin family operator? (We only support
* jsonb 'exists' operator at the moment)
*/
if ((strategy = get_strategy(v->vartype, opno, GIN_AM_OID)) == 0
|| strategy != JsonbExistsStrategyNumber)
continue;
is_key = true;
}
}
else if (IsA(clause, Var))
{
/*
* Trivial expression containing only a single boolean Var. This
* also covers cases "BOOL_VAR = true"
*/
v = (Var *) clause;
strategy = BTEqualStrategyNumber;
c = (Const *) makeBoolConst(true, false);
}
else if (IsA(clause, BoolExpr))
{
/*
* Similar to previous case but for expressions like "!BOOL_VAR" or
* "BOOL_VAR = false"
*/
BoolExpr *boolExpr = (BoolExpr *) clause;
if (boolExpr->args && list_length(boolExpr->args) != 1)
continue;
if (!IsA(linitial(boolExpr->args), Var))
continue;
v = (Var *) linitial(boolExpr->args);
strategy = BTEqualStrategyNumber;
c = (Const *) makeBoolConst(false, false);
}
else
continue;
RowGroupFilter f
{
.attnum = v->varattno,
.is_key = is_key,
.value = c,
.strategy = strategy,
};
/* potentially inserting elements may throw exceptions */
bool error = false;
try {
filters.push_back(f);
} catch (std::exception &e) {
error = true;
}
if (error)
elog(ERROR, "extracting row filters failed");
}
}
static Const *
convert_const(Const *c, Oid dst_oid)
{
Oid funcid;
CoercionPathType ct;
ct = find_coercion_pathway(dst_oid, c->consttype,
COERCION_EXPLICIT, &funcid);
switch (ct)
{
case COERCION_PATH_FUNC:
{
FmgrInfo finfo;
Const *newc;
int16 typlen;
bool typbyval;
get_typlenbyval(dst_oid, &typlen, &typbyval);
newc = makeConst(dst_oid,
0,
c->constcollid,
typlen,
0,
c->constisnull,
typbyval);
fmgr_info(funcid, &finfo);
newc->constvalue = FunctionCall1(&finfo, c->constvalue);
return newc;
}
case COERCION_PATH_RELABELTYPE:
/* Cast is not needed */
break;
case COERCION_PATH_COERCEVIAIO:
{
/*
* In this type of cast we need to output the value to a string
* and then feed this string to the input function of the
* target type.
*/
Const *newc;
int16 typlen;
bool typbyval;
Oid input_fn, output_fn;
Oid input_param;
bool isvarlena;
char *str;
/* Construct a new Const node */
get_typlenbyval(dst_oid, &typlen, &typbyval);
newc = makeConst(dst_oid,
0,
c->constcollid,
typlen,
0,
c->constisnull,
typbyval);
/* Get IO functions */
getTypeOutputInfo(c->consttype, &output_fn, &isvarlena);
getTypeInputInfo(dst_oid, &input_fn, &input_param);
str = DatumGetCString(OidOutputFunctionCall(output_fn,
c->constvalue));
newc->constvalue = OidInputFunctionCall(input_fn, str,
input_param, 0);
return newc;
}
default:
elog(ERROR, "cast function to %s is not found",
format_type_be(dst_oid));
}
return c;
}
/*
* row_group_matches_filter
* Check if min/max values of the column of the row group match filter.
*/
static bool
row_group_matches_filter(parquet::Statistics *stats,
const arrow::DataType *arrow_type,
RowGroupFilter *filter)
{
FmgrInfo finfo;
Datum val;
int collid = filter->value->constcollid;
int strategy = filter->strategy;
if (arrow_type->id() == arrow::Type::MAP && filter->is_key)
{
/*
* Special case for jsonb `?` (exists) operator. As key is always
* of text type we need first convert it to the target type (if needed
* of course).
*/
/*
* Extract the key type (we don't check correctness here as we've
* already done this in `extract_rowgroups_list()`)
*/
auto strct = arrow_type->fields()[0];
auto key = strct->type()->fields()[0];
arrow_type = key->type().get();
/* Do conversion */
filter->value = convert_const(filter->value,
to_postgres_type(arrow_type->id()));
}
val = filter->value->constvalue;
find_cmp_func(&finfo,
filter->value->consttype,
to_postgres_type(arrow_type->id()));
switch (filter->strategy)
{
case BTLessStrategyNumber:
case BTLessEqualStrategyNumber:
{
Datum lower;
int cmpres;
bool satisfies;
std::string min = stats->EncodeMin();
lower = bytes_to_postgres_type(min.c_str(), min.length(),
arrow_type);
cmpres = FunctionCall2Coll(&finfo, collid, val, lower);
satisfies =
(strategy == BTLessStrategyNumber && cmpres > 0) ||
(strategy == BTLessEqualStrategyNumber && cmpres >= 0);
if (!satisfies)
return false;
break;
}
case BTGreaterStrategyNumber:
case BTGreaterEqualStrategyNumber:
{
Datum upper;
int cmpres;
bool satisfies;
std::string max = stats->EncodeMax();
upper = bytes_to_postgres_type(max.c_str(), max.length(),
arrow_type);
cmpres = FunctionCall2Coll(&finfo, collid, val, upper);
satisfies =
(strategy == BTGreaterStrategyNumber && cmpres < 0) ||
(strategy == BTGreaterEqualStrategyNumber && cmpres <= 0);
if (!satisfies)
return false;
break;
}
case BTEqualStrategyNumber:
case JsonbExistsStrategyNumber:
{
Datum lower,
upper;
std::string min = stats->EncodeMin();
std::string max = stats->EncodeMax();
lower = bytes_to_postgres_type(min.c_str(), min.length(),
arrow_type);
upper = bytes_to_postgres_type(max.c_str(), max.length(),
arrow_type);
int l = FunctionCall2Coll(&finfo, collid, val, lower);
int u = FunctionCall2Coll(&finfo, collid, val, upper);
if (l < 0 || u > 0)
return false;
break;
}
default:
/* should not happen */
Assert(false);
}
return true;
}
typedef enum
{
PS_START = 0,
PS_IDENT,
PS_QUOTE
} ParserState;
/*
* parse_filenames_list
* Parse space separated list of filenames.
*/
static List *
parse_filenames_list(const char *str)
{
char *cur = pstrdup(str);
char *f = cur;
ParserState state = PS_START;
List *filenames = NIL;
while (*cur)
{
switch (state)
{
case PS_START:
switch (*cur)
{
case ' ':
/* just skip */
break;
case '"':
f = cur + 1;
state = PS_QUOTE;
break;
default:
/* XXX we should check that *cur is a valid path symbol
* but let's skip it for now */
state = PS_IDENT;
f = cur;
break;
}
break;
case PS_IDENT:
switch (*cur)
{
case ' ':
*cur = '\0';
filenames = lappend(filenames, makeString(f));
state = PS_START;
break;
default:
break;
}
break;
case PS_QUOTE:
switch (*cur)
{
case '"':
*cur = '\0';
filenames = lappend(filenames, makeString(f));
state = PS_START;
break;
default:
break;
}
break;
default:
elog(ERROR, "parquet_fdw: unknown parse state");
}
cur++;
}
filenames = lappend(filenames, makeString(f));
return filenames;
}
/*
* extract_rowgroups_list
* Analyze query predicates and using min/max statistics determine which
* row groups satisfy clauses. Store resulting row group list to
* fdw_private.
*/
List *
extract_rowgroups_list(const char *filename,
TupleDesc tupleDesc,
std::list<RowGroupFilter> &filters,
uint64 *matched_rows,
uint64 *total_rows) noexcept
{
std::unique_ptr<parquet::arrow::FileReader> reader;
arrow::Status status;
List *rowgroups = NIL;
std::string error;
/* Open parquet file to read meta information */
try
{
status = parquet::arrow::FileReader::Make(
arrow::default_memory_pool(),
parquet::ParquetFileReader::OpenFile(filename, false),
&reader);
if (!status.ok())
throw Error("failed to open Parquet file: %s ('%s')",
status.message().c_str(), filename);
auto meta = reader->parquet_reader()->metadata();
parquet::ArrowReaderProperties props;
parquet::arrow::SchemaManifest manifest;
status = parquet::arrow::SchemaManifest::Make(meta->schema(), nullptr,
props, &manifest);
if (!status.ok())
throw Error("error creating arrow schema ('%s')", filename);
/* Check each row group whether it matches the filters */
for (int r = 0; r < reader->num_row_groups(); r++)
{
bool match = true;
auto rowgroup = meta->RowGroup(r);
/* Skip empty rowgroups */
if (!rowgroup->num_rows())
continue;
for (auto &filter : filters)
{
AttrNumber attnum;
char pg_colname[NAMEDATALEN];
attnum = filter.attnum - 1;
tolowercase(NameStr(TupleDescAttr(tupleDesc, attnum)->attname),
pg_colname);
/*
* Search for the column with the same name as filtered attribute
*/
for (auto &schema_field : manifest.schema_fields)
{
MemoryContext ccxt = CurrentMemoryContext;
bool error = false;
char errstr[ERROR_STR_LEN];
char arrow_colname[NAMEDATALEN];
auto &field = schema_field.field;
int column_index;
/* Skip complex objects (lists, structs except maps) */
if (schema_field.column_index == -1
&& field->type()->id() != arrow::Type::MAP)
continue;
if (field->name().length() > NAMEDATALEN)
throw Error("parquet column name '%s' is too long (max: %d)",
field->name().c_str(), NAMEDATALEN - 1);
tolowercase(field->name().c_str(), arrow_colname);
if (strcmp(pg_colname, arrow_colname) != 0)
continue;
if (field->type()->id() == arrow::Type::MAP)
{
/*
* Extract `key` column of the map.
* See `create_column_mapping()` for some details on
* map structure.
*/
Assert(schema_field.children.size() == 1);
auto &strct = schema_field.children[0];
Assert(strct.children.size() == 2);
auto &key = strct.children[0];
column_index = key.column_index;
}
else
column_index = schema_field.column_index;
/* Found it! */
std::shared_ptr<parquet::Statistics> stats;
auto column = rowgroup->ColumnChunk(column_index);
stats = column->statistics();
PG_TRY();
{
/*
* If at least one filter doesn't match rowgroup exclude
* the current row group and proceed with the next one.
*/
if (stats && !row_group_matches_filter(stats.get(),
field->type().get(),
&filter))
{
match = false;
elog(DEBUG1, "parquet_fdw: skip rowgroup %d", r + 1);
}
}
PG_CATCH();
{
ErrorData *errdata;
MemoryContextSwitchTo(ccxt);
error = true;
errdata = CopyErrorData();
FlushErrorState();
strncpy(errstr, errdata->message, ERROR_STR_LEN - 1);
FreeErrorData(errdata);
}
PG_END_TRY();
if (error)
throw Error("row group filter match failed: %s", errstr);
break;
} /* loop over columns */
if (!match)
break;
} /* loop over filters */
/* All the filters match this rowgroup */
if (match)
{
/* TODO: PG_TRY */
rowgroups = lappend_int(rowgroups, r);
*matched_rows += rowgroup->num_rows();
}
*total_rows += rowgroup->num_rows();
} /* loop over rowgroups */
}
catch(const std::exception& e) {
error = e.what();
}
if (!error.empty()) {
elog(ERROR,
"parquet_fdw: failed to extract row groups from Parquet file: %s ('%s')",
error.c_str(), filename);
}
return rowgroups;
}
struct FieldInfo
{
char name[NAMEDATALEN];
Oid oid;
};
/*
* extract_parquet_fields
* Read parquet file and return a list of its fields
*/
static List *
extract_parquet_fields(const char *path) noexcept
{
List *res = NIL;
std::string error;
try
{
std::unique_ptr<parquet::arrow::FileReader> reader;
parquet::ArrowReaderProperties props;
parquet::arrow::SchemaManifest manifest;
arrow::Status status;
FieldInfo *fields;
status = parquet::arrow::FileReader::Make(
arrow::default_memory_pool(),
parquet::ParquetFileReader::OpenFile(path, false),
&reader);
if (!status.ok())
throw Error("failed to open Parquet file %s ('%s')",
status.message().c_str(), path);
auto p_schema = reader->parquet_reader()->metadata()->schema();
if (!parquet::arrow::SchemaManifest::Make(p_schema, nullptr, props, &manifest).ok())
throw Error("error creating arrow schema ('%s')", path);
fields = (FieldInfo *) exc_palloc(
sizeof(FieldInfo) * manifest.schema_fields.size());
for (auto &schema_field : manifest.schema_fields)
{
auto &field = schema_field.field;
auto &type = field->type();
Oid pg_type;
switch (type->id())
{
case arrow::Type::LIST:
{
arrow::Type::type subtype_id;
Oid pg_subtype;
bool error = false;
if (type->num_fields() != 1)
throw Error("lists of structs are not supported ('%s')", path);
subtype_id = get_arrow_list_elem_type(type.get());
pg_subtype = to_postgres_type(subtype_id);
/* This sucks I know... */
PG_TRY();
{
pg_type = get_array_type(pg_subtype);
}
PG_CATCH();
{
error = true;
}
PG_END_TRY();
if (error)
throw Error("failed to get the type of array elements for %d",
pg_subtype);
break;
}
case arrow::Type::MAP:
pg_type = JSONBOID;
break;
default:
pg_type = to_postgres_type(type->id());
}
if (pg_type != InvalidOid)
{
if (field->name().length() > 63)
throw Error("field name '%s' in '%s' is too long",
field->name().c_str(), path);
memcpy(fields->name, field->name().c_str(), field->name().length() + 1);
fields->oid = pg_type;
res = lappend(res, fields++);
}
else
{
throw Error("cannot convert field '%s' of type '%s' in '%s'",
field->name().c_str(), type->name().c_str(), path);
}
}
}
catch (std::exception &e)
{
error = e.what();
}
if (!error.empty())
elog(ERROR, "parquet_fdw: %s", error.c_str());
return res;
}
/*
* create_foreign_table_query
* Produce a query text for creating a new foreign table.
*/
char *
create_foreign_table_query(const char *tablename,
const char *schemaname,
const char *servername,
char **paths, int npaths,
List *fields, List *options)
{
StringInfoData str;
ListCell *lc;
initStringInfo(&str);
appendStringInfo(&str, "CREATE FOREIGN TABLE ");
/* append table name */
if (schemaname)
appendStringInfo(&str, "%s.%s (",
quote_identifier(schemaname), quote_identifier(tablename));
else
appendStringInfo(&str, "%s (", quote_identifier(tablename));
/* append columns */
bool is_first = true;
foreach (lc, fields)
{
FieldInfo *field = (FieldInfo *) lfirst(lc);
char *name = field->name;
Oid pg_type = field->oid;
const char *type_name = format_type_be(pg_type);
if (!is_first)
appendStringInfo(&str, ", %s %s", quote_identifier(name), type_name);
else
{
appendStringInfo(&str, "%s %s", quote_identifier(name), type_name);
is_first = false;
}
}
appendStringInfo(&str, ") SERVER %s ", quote_identifier(servername));
appendStringInfo(&str, "OPTIONS (filename '");
/* list paths */
is_first = true;
for (int i = 0; i < npaths; ++i)
{
if (!is_first)
appendStringInfoChar(&str, ' ');
else
is_first = false;
appendStringInfoString(&str, paths[i]);
}
appendStringInfoChar(&str, '\'');
/* list options */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
appendStringInfo(&str, ", %s '%s'", def->defname, defGetString(def));
}
appendStringInfo(&str, ")");
return str.data;
}
static void
destroy_parquet_state(void *arg)
{
ParquetFdwExecutionState *festate = (ParquetFdwExecutionState *) arg;
if (festate)
delete festate;
}
/*
* C interface functions
*/
static List *
parse_attributes_list(char *start, Oid relid)
{
List *attrs = NIL;
char *token;
const char *delim = " ";
AttrNumber attnum;
while ((token = strtok(start, delim)) != NULL)
{
if ((attnum = get_attnum(relid, token)) == InvalidAttrNumber)
elog(ERROR, "paruqet_fdw: invalid attribute name '%s'", token);
attrs = lappend_int(attrs, attnum);
start = NULL;
}
return attrs;
}
/*
* OidFunctionCall1NullableArg
* Practically a copy-paste from FunctionCall1Coll with added capability
* of passing a NULL argument.
*/
static Datum
OidFunctionCall1NullableArg(Oid functionId, Datum arg, bool argisnull)
{
#if PG_VERSION_NUM < 120000
FunctionCallInfoData _fcinfo;
FunctionCallInfoData *fcinfo = &_fcinfo;
#else
LOCAL_FCINFO(fcinfo, 1);
#endif
FmgrInfo flinfo;
Datum result;
fmgr_info(functionId, &flinfo);
InitFunctionCallInfoData(*fcinfo, &flinfo, 1, InvalidOid, NULL, NULL);
#if PG_VERSION_NUM < 120000
fcinfo->arg[0] = arg;
fcinfo->argnull[0] = false;
#else
fcinfo->args[0].value = arg;
fcinfo->args[0].isnull = argisnull;
#endif
result = FunctionCallInvoke(fcinfo);
/* Check for null result, since caller is clearly not expecting one */
if (fcinfo->isnull)
elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
return result;
}
static List *
get_filenames_from_userfunc(const char *funcname, const char *funcarg)
{
Jsonb *j = NULL;
Oid funcid;
List *f = stringToQualifiedNameList(funcname);
Datum filenames;
Oid jsonboid = JSONBOID;
Datum *values;
bool *nulls;
int num;
List *res = NIL;
ArrayType *arr;
if (funcarg)
j = DatumGetJsonbP(DirectFunctionCall1(jsonb_in, CStringGetDatum(funcarg)));
funcid = LookupFuncName(f, 1, &jsonboid, false);
filenames = OidFunctionCall1NullableArg(funcid, (Datum) j, funcarg == NULL);
arr = DatumGetArrayTypeP(filenames);
if (ARR_ELEMTYPE(arr) != TEXTOID)
elog(ERROR, "function returned an array with non-TEXT element type");
deconstruct_array(arr, TEXTOID, -1, false, 'i', &values, &nulls, &num);
if (num == 0)
{
elog(WARNING,
"'%s' function returned an empty array; foreign table wasn't created",
get_func_name(funcid));
return NIL;
}
for (int i = 0; i < num; ++i)
{
if (nulls[i])
elog(ERROR, "user function returned an array containing NULL value(s)");
res = lappend(res, makeString(TextDatumGetCString(values[i])));
}
return res;
}
static void
get_table_options(Oid relid, ParquetFdwPlanState *fdw_private)
{
ForeignTable *table;
ListCell *lc;
char *funcname = NULL;
char *funcarg = NULL;
fdw_private->use_mmap = false;
fdw_private->use_threads = false;
fdw_private->max_open_files = 0;
fdw_private->files_in_order = false;
table = GetForeignTable(relid);
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "filename") == 0)
{