-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsf_fdw.c
3497 lines (3073 loc) · 115 KB
/
tsf_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
/*-------------------------------------------------------------------------
*
* tsf_fdw.c
*
* Function definitions for TSF foreign data wrapper. These functions access
* data stored in TSF through the official C driver.
*
* Credit:
*
* This FDW heavily leaned on the mongo_fdw
* [https://github.com/citusdata/mongo_fdw] as an implementation
* guide. Thanks to Citus Data for making their FDW open source.
*
* The contrib/postgres_fdw also become vital as a reference for how to
* internalize join restrictions and sort orders to provide decent join
* performance between TSF foreign tables.
*
* Finally, the restriction parsing and evaluation is heavily modeled
* after the Python FDW module Multicorn libary by Kozea
* [https://github.com/Kozea/Multicorn/]
*
* Copyright (c) 2015 Golden Helix, Inc.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "tsf_fdw.h"
#include <sys/stat.h>
#include <limits.h>
#include <float.h>
#include "tsf.h"
#include "stringbuilder.h"
#include "query.h"
#include "util.h"
#include "access/reloptions.h"
#include "catalog/pg_type.h"
#include "catalog/pg_opfamily.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "nodes/makefuncs.h"
#include "optimizer/cost.h"
#include "optimizer/paths.h"
#include "optimizer/pathnode.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "storage/ipc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/rangetypes.h"
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
#if SIZEOF_DATUM != 8
#error "Only 64-bit machines supported. sizeof(void*) should be 8"
#endif
#ifndef USE_FLOAT8_BYVAL
#error "Only 64-bit machines supported. USE_FLOAT8_BYVAL must be set"
#endif
#ifndef NUMERICRANGEOID
#define NUMERICRANGEOID 3906
#endif
// #define REPORT_ITER_STATS 1
/* declarations for dynamic loading */
PG_MODULE_MAGIC;
/* Schema generation function for a single source */
PG_FUNCTION_INFO_V1(tsf_generate_schemas);
/* FDW handler and options validator functions */
PG_FUNCTION_INFO_V1(tsf_fdw_handler);
PG_FUNCTION_INFO_V1(tsf_fdw_validator);
/* Module load init */
void _PG_init(void);
typedef struct TsfFdwRelationInfo {
/* baserestrictinfo columns used */
List *columnList;
/* Estimated size and cost for a scan with baserestrictinfo quals. */
int width; /* length of columnList */
int row_count;
int rows_with_param_id;
bool is_matrix_source;
int rows_with_param_entity_id;
double rows_selected;
Cost startup_cost;
Cost total_cost;
} TsfFdwRelationInfo;
/*
* For each requested field, we have mapping to TSF source, field,
* mapping, iterator and Posgres type information.
*/
typedef struct ColumnMapping {
uint32 columnIndex;
Oid columnTypeId;
Oid columnArrayTypeId;
int sourceIdx;
int fieldIdx;
int mappingSourceIdx;
// mappingFieldIdx is always 0
tsf_iter *iter;
tsf_iter *mappingIter; // Not owned, borrowed from TsfSourceState
} ColumnMapping;
/* Restrictions that are internalized to the FDW */
typedef enum {
RestrictInt,
RestrictInt64,
RestrictDouble,
RestrictEnum,
RestrictBool,
RestrictString
} RestrictionType;
typedef struct RestrictionBase {
ColumnMapping *col;
RestrictionType type;
bool includeMissing; // Include missing values
bool inverted;
} RestrictionBase;
typedef struct IntRestriction {
RestrictionBase base;
int lowerBound;
int upperBound;
bool includeLowerBound;
bool includeUpperBound;
} IntRestriction;
typedef struct Int64Restriction {
RestrictionBase base;
int64_t lowerBound;
int64_t upperBound;
bool includeLowerBound;
bool includeUpperBound;
} Int64Restriction;
typedef struct DoubleRestriction {
RestrictionBase base;
double lowerBound;
double upperBound;
bool includeLowerBound;
bool includeUpperBound;
} DoubleRestriction;
typedef struct EnumRestriction {
RestrictionBase base;
int includeCount;
int *include; // Enum indexes to include
} EnumRestriction;
typedef struct BoolRestriction {
RestrictionBase base;
bool includeTrue;
bool includeFalse;
} BoolRestriction;
typedef struct StringRestriction {
RestrictionBase base;
int matchCount;
Size matchSize;
char *match; // Exact match
int (*strcmpfn)(const char*,const char*);
} StringRestriction;
typedef struct TsfSourceState {
int sourceId;
const char *fileName;
tsf_file *tsf; // Not owned, borrowed pointer from tsfHandleCache;
tsf_iter *mappingIter; // Owned, used if this is a mapping source
} TsfSourceState;
/*
* TsfFdwExecState keeps foreign data wrapper specific execution state
* that we create and hold onto when executing the query.
*/
typedef struct TsfFdwExecState {
// column index here and in columnmapping means index into the tuple
// representing full width of the FDW table. By convention _id is 0,
// _entity_id is 1, but technically you can define a FDW table with
// these fields in any order.
int idColumnIndex;
int entityIdColumnIndex;
int columnCount;
struct ColumnMapping *columnMapping;
int restrictionCount;
struct RestrictionBase **columnRestrictions;
tsf_field_type fieldType;
TsfSourceState *sources;
int sourceCount;
tsf_iter *iter; // Primary iterator (no fields)
// Parsed out of qualList is restriciton info
List *qualList;
bool paramsChanged; //re-eval on next iter
// iter to be driven by a specific set of IDs
int idListIdx;
int *idList;
int idListCount;
// Used to set up matrix field query
int *entityIdList;
int entityIdListCount;
} TsfFdwExecState;
/* FDW Handler Functions */
static void TsfGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreignTableId);
static void TsfGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreignTableId);
static ForeignScan *TsfGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreignTableId,
ForeignPath *bestPath, List *targetList,
List *restrictionClauses
#if PG_VERSION_NUM >= 90500
,Plan *outer_plan
#endif
);
static void TsfExplainForeignScan(ForeignScanState *scanState, ExplainState *explainState);
static void TsfBeginForeignScan(ForeignScanState *scanState, int executorFlags);
static TupleTableSlot *TsfIterateForeignScan(ForeignScanState *scanState);
static void TsfEndForeignScan(ForeignScanState *scanState);
static void TsfReScanForeignScan(ForeignScanState *scanState);
/* Table introspection helpders */
static TsfFdwOptions *getTsfFdwOptions(Oid foreignTableId);
static List *columnList(RelOptInfo *baserel);
static char *strJoin(const char *left, const char *right, char joiner);
static void buildColumnMapping(Oid foreignTableId, List *columnList, TsfFdwOptions *tsfFdwOptions,
TsfFdwExecState *executionState);
/* Plan builder helpers */
static bool isIdRestriction(Oid foreignTableId, MulticornBaseQual *qual);
static bool isInternableRestriction(Oid foreignTableId, MulticornBaseQual *qual);
static bool isEntityIdRestriction(Oid foreignTableId, MulticornBaseQual *qual);
static bool isParamatizable(Oid foreignTableId, RelOptInfo *baserel, Expr *expr,
bool *outIsEntityIdRestriction);
/* Scan iteration helpers */
static void executeQualList(ForeignScanState *scanState, bool dontUpdateConst, bool *entityIdsChanged);
static void initQuery(TsfFdwExecState *state);
static void resetQuery(TsfFdwExecState *state);
static bool iterateWithRestrictions(TsfFdwExecState *state);
static void fillTupleSlot(TsfFdwExecState *state, Datum *columnValues, bool *columnNulls);
/* case insenstive string comapre */
static int stricmp(char const *a, char const *b)
{
for (;; a++, b++) {
int d = tolower(*a) - tolower(*b);
if (d != 0 || !*a)
return d;
}
return -1; // should never be reached
}
#define NEXT_CHAR(c, clen) ((c)++, (clen)--)
#define COMPARE_CHAR(a, b) (ci ? tolower(a) == tolower(b) : a == b)
static int like_match(const char *t, int tlen, const char *p, int plen, bool ci)
{
/* This was adapted from like_match.c which is used for ILIKE/LIKE evaluation
* by postgres */
/* Fast path for match-everything pattern */
if (plen == 1 && *p == '%')
return 1;
/* Since this function recurses, it could be driven to stack overflow */
check_stack_depth();
/*
* In this loop, we advance by char when matching wildcards (and thus on
* recursive entry to this function we are properly char-synced). On other
* occasions it is safe to advance by byte, as the text and pattern will
* be in lockstep. This allows us to perform all comparisons between the
* text and pattern on a byte by byte basis, even for multi-byte
* encodings.
*/
while (tlen > 0 && plen > 0) {
if (*p == '\\') {
/* Next pattern byte must match literally, whatever it is */
NEXT_CHAR(p, plen);
/* ... and there had better be one, per SQL standard */
if (plen <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
errmsg("LIKE pattern must not end with escape character")));
if (!COMPARE_CHAR(*p, *t))
return 0;
} else if (*p == '%') {
char firstpat;
/*
* % processing is essentially a search for a text position at
* which the remainder of the text matches the remainder of the
* pattern, using a recursive call to check each potential match.
*
* If there are wildcards immediately following the %, we can skip
* over them first, using the idea that any sequence of N _'s and
* one or more %'s is equivalent to N _'s and one % (ie, it will
* match any sequence of at least N text characters). In this way
* we will always run the recursive search loop using a pattern
* fragment that begins with a literal character-to-match, thereby
* not recursing more than we have to.
*/
NEXT_CHAR(p, plen);
while (plen > 0) {
if (*p == '%')
NEXT_CHAR(p, plen);
else if (*p == '_') {
/* If not enough text left to match the pattern, ABORT */
if (tlen <= 0)
return -1;
NEXT_CHAR(t, tlen);
NEXT_CHAR(p, plen);
} else
break; /* Reached a non-wildcard pattern char */
}
/*
* If we're at end of pattern, match: we have a trailing % which
* matches any remaining text string.
*/
if (plen <= 0)
return 1;
/*
* Otherwise, scan for a text position at which we can match the
* rest of the pattern. The first remaining pattern char is known
* to be a regular or escaped literal character, so we can compare
* the first pattern byte to each text byte to avoid recursing
* more than we have to. This fact also guarantees that we don't
* have to consider a match to the zero-length substring at the
* end of the text.
*/
if (*p == '\\') {
if (plen < 2)
ereport(ERROR,
(errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
errmsg("LIKE pattern must not end with escape character")));
firstpat = p[1];
} else
firstpat = *p;
while (tlen > 0) {
if (COMPARE_CHAR(*t, firstpat)) {
int matched = like_match(t, tlen, p, plen, ci);
if (matched != 0)
return matched; /* TRUE or ABORT */
}
NEXT_CHAR(t, tlen);
}
/*
* End of text with no match, so no point in trying later places
* to start matching this pattern.
*/
return -1;
} else if (*p == '_') {
/* _ matches any single character, and we know there is one */
NEXT_CHAR(t, tlen);
NEXT_CHAR(p, plen);
continue;
} else if (!COMPARE_CHAR(*p, *t)) {
/* non-wildcard pattern char fails to match text char */
return 0;
}
/*
* Pattern and text match, so advance.
*
*/
NEXT_CHAR(t, tlen);
NEXT_CHAR(p, plen);
}
if (tlen > 0)
return 0; /* end of pattern, but not of text */
/*
* End of text, but perhaps not of pattern. Match iff the remaining
* pattern can match a zero-length string, ie, it's zero or more %'s.
*/
while (plen > 0 && *p == '%')
NEXT_CHAR(p, plen);
if (plen <= 0)
return 1;
/*
* End of text with no match, so no point in trying later places to start
* matching this pattern.
*/
return -1;
}
/* case sensitive patern match */
static int strlike(char const *a, char const *b)
{
return (like_match(a, strlen(a), b, strlen(b), false) != 1);
}
/* case insensitive patern match */
static int strilike(char const *a, char const *b)
{
return (like_match(a, strlen(a), b, strlen(b), true) != 1);
}
/* inverted case sensitive patern match */
static int notstrlike(char const *a, char const *b)
{
return (like_match(a, strlen(a), b, strlen(b), false) == 1);
}
/* inverted case insensitive patern match */
static int notstrilike(char const *a, char const *b)
{
return (like_match(a, strlen(a), b, strlen(b), true) == 1);
}
/*
* Convert a tsf_value_type to appropriate Postgres type
*/
static const char *psqlTypeForTsfType(tsf_value_type type)
{
switch (type) {
case TypeInt32:
return "integer";
case TypeInt64:
return "bigint";
case TypeFloat32:
return "real";
case TypeFloat64:
return "double precision";
case TypeBool:
return "boolean";
case TypeString:
return "text";
case TypeEnum:
return "text";
case TypeInt32Array:
return "integer[]";
case TypeFloat32Array:
return "real[]";
case TypeFloat64Array:
return "double precision[]";
case TypeBoolArray:
return "boolean[]";
case TypeStringArray:
return "text[]";
case TypeEnumArray:
return "text[]";
case TypeUnkown:
default:
return "";
}
}
static const char *fieldTypeLetter(tsf_field_type fieldType)
{
switch (fieldType) {
case FieldLocusAttribute:
return "l";
case FieldEntityAttribute:
return "e";
case FieldMatrix:
return "m";
default:
return "";
}
}
static void createTableSchema(stringbuilder *str, const char *prefix, const char *fileName,
int sourceId, tsf_source *s, tsf_field_type fieldType,
const char *tableSuffix)
{
char *buf = 0;
// Locus attr field table
bool foundOne = false;
for (int i = 0; i < s->field_count; i++) {
if (s->fields[i].field_type == fieldType) {
if (!foundOne) {
foundOne = true;
if (str->pos > 0) // Add double space between consecutive statements
sb_append_str(str, "\n");
asprintf(&buf, "CREATE FOREIGN TABLE %s_%d%s (\n _id integer", prefix, sourceId,
tableSuffix);
sb_append_str(str, buf);
free(buf);
if (fieldType == FieldMatrix)
sb_append_str(str, ",\n _entity_id integer");
}
asprintf(&buf, ",\n \"%s\" %s", s->fields[i].symbol,
psqlTypeForTsfType(s->fields[i].value_type));
sb_append_str(str, buf);
free(buf);
}
}
if (foundOne) {
sb_append_str(str, "\n )\n SERVER tsf_server\n");
const char *fieldTypeStr = fieldTypeLetter(fieldType);
asprintf(&buf, " OPTIONS (filename '%s', sourceid '%d', fieldtype '%s');\n", fileName,
sourceId, fieldTypeStr);
sb_append_str(str, buf);
free(buf);
}
}
// Helpers
#define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
#define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
/*
* tsf_generate_schemas is a user-facing helper function to generate
* CREATE FOREIGN TABLE schemas for all sources in a TSF.
*/
Datum tsf_generate_schemas(PG_FUNCTION_ARGS)
{
text *prefixText = PG_GETARG_TEXT_P(0);
text *fileNameText = PG_GETARG_TEXT_P(1);
const char *prefix = GET_STR(prefixText);
const char *fileName = GET_STR(fileNameText);
int sourceId = PG_GETARG_INT32(2);
tsf_file *tsf = tsf_open_file(fileName);
if (tsf->errmsg != NULL) {
ereport(ERROR,
(errmsg("could not open to %s", fileName),
errhint("TSF driver connection error: %s", tsf->errmsg)));
}
stringbuilder *str = sb_new();
for (int id = sourceId <= 0 ? 1 : sourceId;
id < (sourceId <= 0 ? tsf->source_count + 1 : sourceId + 1);
id++) {
tsf_source *s = &tsf->sources[id - 1];
createTableSchema(str, prefix, fileName, id, s, FieldLocusAttribute, "");
createTableSchema(str, prefix, fileName, id, s, FieldMatrix, "_matrix");
createTableSchema(str, prefix, fileName, id, s, FieldEntityAttribute, "_entity");
}
text *ret = GET_TEXT(sb_cstring(str));
sb_destroy(str, true);
tsf_close_file(tsf);
PG_RETURN_TEXT_P(ret);
}
// Backed process cache that outlives individual queries and holds open
// TSF files by their name.
typedef struct TsfHandleCache {
tsf_file **tsfs;
char **tsfFileNames;
int count;
} TsfHandleCache;
TsfHandleCache *tsfHandleCache;
/*
* Find an existing open TSF file, or open it and add it to our
* tsfHandleCache
*/
static tsf_file *tsfCacheOpen(const char *tsfFileName)
{
for (int i = 0; i < tsfHandleCache->count; i++) {
if (strcmp(tsfFileName, tsfHandleCache->tsfFileNames[i]) == 0) {
return tsfHandleCache->tsfs[i];
}
}
// Open new TSF file
tsf_file *tsf = tsf_open_file(tsfFileName);
if (tsf->errmsg != NULL) {
ereport(ERROR,
(errmsg("could not open %s", tsfFileName),
errhint("TSF driver connection error: %s", tsf->errmsg)));
}
// Expand our lists to include new TSF file
MemoryContext oldctx = MemoryContextSwitchTo(CacheMemoryContext);
TsfHandleCache prev = *tsfHandleCache;
tsfHandleCache->tsfs = palloc0(sizeof(tsf_file *) * (tsfHandleCache->count + 1));
tsfHandleCache->tsfFileNames = palloc0(sizeof(tsf_file *) * (tsfHandleCache->count + 1));
if (tsfHandleCache->count > 0) {
memcpy(tsfHandleCache->tsfs, prev.tsfs, sizeof(tsf_file *) * tsfHandleCache->count);
memcpy(tsfHandleCache->tsfFileNames, prev.tsfFileNames,
sizeof(const char *) * tsfHandleCache->count);
pfree(prev.tsfs);
pfree(prev.tsfFileNames);
}
int idx = tsfHandleCache->count;
tsfHandleCache->count++;
tsfHandleCache->tsfs[idx] = tsf;
// Clone file name as its passed by ref
tsfHandleCache->tsfFileNames[idx] = palloc0(strlen(tsfFileName) + 1);
memcpy(tsfHandleCache->tsfFileNames[idx], tsfFileName, strlen(tsfFileName));
MemoryContextSwitchTo(oldctx);
return tsf;
}
/**
* Find a matching TsfSourceState, or add one in executionState
*/
static int getTsfSource(const char *tsfFileName, int sourceId, TsfFdwExecState *executionState)
{
for (int i = 0; i < executionState->sourceCount; i++) {
if (strcmp(tsfFileName, executionState->sources[i].fileName) == 0) {
if (sourceId == executionState->sources[i].sourceId)
return i;
}
}
Assert(sourceId <= tsf->source_count);
TsfSourceState *prev = executionState->sources;
executionState->sources = palloc0(sizeof(TsfSourceState) * (executionState->sourceCount + 1));
if (executionState->sourceCount > 0) {
memcpy(executionState->sources, prev, sizeof(TsfSourceState) * executionState->sourceCount);
pfree(prev);
}
int sourceIdx = executionState->sourceCount;
executionState->sourceCount++;
TsfSourceState *s = &executionState->sources[sourceIdx];
s->fileName = tsfFileName;
s->sourceId = sourceId;
s->tsf = tsfCacheOpen(tsfFileName);
return sourceIdx;
}
/*
* Exit callbakc function to clean up our tsfHandleCache, closing all
* open file handles etc
*/
static void tsfFdwExit(int code, Datum arg)
{
if (!tsfHandleCache)
return;
for (int i = 0; i < tsfHandleCache->count; i++) {
tsf_close_file(tsfHandleCache->tsfs[i]);
pfree(tsfHandleCache->tsfFileNames[i]);
}
pfree(tsfHandleCache);
tsfHandleCache = NULL;
}
/*
* Library load-time initialization, sets on_proc_exit() callback for
* backend shutdown.
*/
void _PG_init(void)
{
MemoryContext oldctx = MemoryContextSwitchTo(CacheMemoryContext);
tsfHandleCache = palloc0(sizeof(TsfHandleCache));
MemoryContextSwitchTo(oldctx);
on_proc_exit(&tsfFdwExit, PointerGetDatum(NULL));
}
/*
* tsf_fdw_handler creates and returns a struct with pointers to foreign table
* callback functions.
*/
Datum tsf_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwRoutine = makeNode(FdwRoutine);
fdwRoutine->GetForeignRelSize = TsfGetForeignRelSize;
fdwRoutine->GetForeignPaths = TsfGetForeignPaths;
fdwRoutine->GetForeignPlan = TsfGetForeignPlan;
fdwRoutine->ExplainForeignScan = TsfExplainForeignScan;
fdwRoutine->BeginForeignScan = TsfBeginForeignScan;
fdwRoutine->IterateForeignScan = TsfIterateForeignScan;
fdwRoutine->ReScanForeignScan = TsfReScanForeignScan;
fdwRoutine->EndForeignScan = TsfEndForeignScan;
// fdwRoutine->AnalyzeForeignTable = TsfAnalyzeForeignTable;
PG_RETURN_POINTER(fdwRoutine);
}
/*
* buildOptionNamesString finds all options that are valid for the current context,
* and concatenates these option names in a comma separated string.
*/
static StringInfo buildOptionNamesString(Oid currentContextId)
{
StringInfo optionNamesString = makeStringInfo();
bool firstOptionPrinted = false;
int32 optionIndex = 0;
for (optionIndex = 0; optionIndex < ValidOptionCount; optionIndex++) {
const TsfValidOption *validOption = &(ValidOptionArray[optionIndex]);
/* if option belongs to current context, append option name */
if (currentContextId == validOption->optionContextId) {
if (firstOptionPrinted) {
appendStringInfoString(optionNamesString, ", ");
}
appendStringInfoString(optionNamesString, validOption->optionName);
firstOptionPrinted = true;
}
}
return optionNamesString;
}
/*
* tsf_fdw_validator validates options given to one of the following commands:
* foreign data wrapper, server, user mapping, or foreign table. This function
* errors out if the given option name or its value is considered invalid.
*/
Datum tsf_fdw_validator(PG_FUNCTION_ARGS)
{
int32 sourceId = -1;
Datum optionArray = PG_GETARG_DATUM(0);
Oid optionContextId = PG_GETARG_OID(1);
List *optionList = untransformRelOptions(optionArray);
ListCell *optionCell = NULL;
foreach (optionCell, optionList) {
DefElem *optionDef = (DefElem *)lfirst(optionCell);
char *optionName = optionDef->defname;
bool optionValid = false;
int32 optionIndex = 0;
for (optionIndex = 0; optionIndex < ValidOptionCount; optionIndex++) {
const TsfValidOption *validOption = &(ValidOptionArray[optionIndex]);
if ((optionContextId == validOption->optionContextId) &&
(strncmp(optionName, validOption->optionName, NAMEDATALEN) == 0)) {
optionValid = true;
break;
}
}
/* if invalid option, display an informative error message */
if (!optionValid) {
StringInfo optionNamesString = buildOptionNamesString(optionContextId);
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", optionName),
errhint("Valid options in this context are: %s", optionNamesString->data)));
}
if (strncmp(optionName, OPTION_NAME_SOURCEID, NAMEDATALEN) == 0) {
char *optionValue = defGetString(optionDef);
sourceId = pg_atoi(optionValue, sizeof(int32), 0);
(void)sourceId; // remove warning
}
if (strncmp(optionName, OPTION_NAME_FIELDTYPE, NAMEDATALEN) == 0) {
char *optionValue = defGetString(optionDef);
if ((strncmp(optionValue, "m", NAMEDATALEN) != 0) &&
(strncmp(optionValue, "l", NAMEDATALEN) != 0) &&
(strncmp(optionValue, "e", NAMEDATALEN) != 0)) {
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid value for \"%s\"", optionName),
errhint("Valid values are 'm' or matrix, 'l' for locus attribute or 'e' "
"for entity attribute.")));
}
}
}
PG_RETURN_VOID();
}
/*
* TsfGetForeignRelSize obtains relation size estimates for tsf foreign table.
*/
static void TsfGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreignTableId)
{
TsfFdwOptions *tsfFdwOptions = getTsfFdwOptions(foreignTableId);
const char *tsfFileName = strJoin(tsfFdwOptions->path, tsfFdwOptions->filename, '\0');
tsf_file *tsf = tsfCacheOpen(tsfFileName);
if (tsfFdwOptions->sourceId < 1 || tsfFdwOptions->sourceId > tsf->source_count) {
ereport(ERROR,
(errmsg("Invalid source id %s:%d", tsfFdwOptions->filename, tsfFdwOptions->sourceId),
errhint("There are %d sources in the TSF", tsf->source_count)));
}
tsf_source *tsfSource = &tsf->sources[tsfFdwOptions->sourceId - 1];
/*
* We use PgFdwRelationInfo to pass various information to subsequent
* functions.
*/
TsfFdwRelationInfo *fpinfo = (TsfFdwRelationInfo *)palloc0(sizeof(TsfFdwRelationInfo));
baserel->fdw_private = (void *)fpinfo;
fpinfo->columnList = columnList(baserel); // Extract used fields only
fpinfo->width = list_length(fpinfo->columnList);
// matrix should be entity_count * locus_count
switch (tsfFdwOptions->fieldType) {
case FieldEntityAttribute:
fpinfo->row_count = tsfSource->entity_count;
fpinfo->rows_with_param_id = fpinfo->row_count;
break;
case FieldLocusAttribute:
fpinfo->row_count = tsfSource->locus_count;
fpinfo->rows_with_param_id = fpinfo->row_count;
break;
case FieldMatrix:
fpinfo->row_count = tsfSource->locus_count * tsfSource->entity_count;
fpinfo->rows_with_param_id = tsfSource->entity_count;
fpinfo->is_matrix_source = true;
fpinfo->rows_with_param_entity_id = tsfSource->locus_count;
break;
default: {
ereport(
ERROR,
(errmsg("Invalid field type specified %s:%d", tsfFdwOptions->filename,
tsfFdwOptions->sourceId),
errhint("The fieldtype option to the tsf_fdw tables must be set to 'l', 'm', or 'e'")));
}
}
List *rowClauseList = baserel->baserestrictinfo;
double rowSelectivity = clauselist_selectivity(root, rowClauseList, 0, JOIN_INNER, NULL);
fpinfo->rows_selected = clamp_row_est(fpinfo->row_count * rowSelectivity);
baserel->rows = fpinfo->rows_selected;
// elog(INFO, "%s[%d][%d], rowCount %d, rowSelectivity: %f, clamped: %f", __func__,
// tsfFdwOptions->sourceId, tsfFdwOptions->fieldType, fpinfo->row_count, rowSelectivity,
// fpinfo->rows_selected);
}
static bool exprVarNameMatch(Expr *expr, Oid foreignTableId, PlannerInfo *root, const char *name)
{
if (nodeTag(expr) == T_Var) {
Var *var = (Var *)expr;
if (var->varlevelsup == 0) {
RangeTblEntry *rte = planner_rt_fetch(var->varno, root);
if (rte->relid == foreignTableId) {
char *columnName = get_attname(rte->relid, var->varattno);
if (columnName && stricmp(columnName, name) == 0)
return true;
}
}
}
return false;
}
/*
* TsfGetForeignPaths creates possible access paths for a scan on the foreign
* table.
*
* There is always a "default" full scan path, but given path_keys (ORDER
* BY), filters and joins there may be other paths we can directly
* internalize.
*/
static void TsfGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreignTableId)
{
TsfFdwRelationInfo *fpinfo = (TsfFdwRelationInfo *)baserel->fdw_private;
/*
* We skip reading columns that are not in query. Here we assume that all
* columns in relation have the same width.
*/
Cost startupCost = 10;
Cost totalCost = (fpinfo->rows_selected * fpinfo->width) + startupCost;
/*
* Create simplest ForeignScan path node and add it to baserel. This
* path corresponds to SeqScan path of the table. We already did all
* the work to estimate cost and size of this path in
* TsfGetForeignRelSize.
*/
ForeignPath *path;
path = create_foreignscan_path(root, baserel, baserel->rows, startupCost, totalCost,
NIL, /* no pathkeys */
NULL, /* no outer rel */
#if PG_VERSION_NUM >= 90500
NULL, /* no extra plan */
#endif
NIL); /* no fdw_private */
add_path(baserel, (Path *)path);
/*
* Look for pathkeys that match the natural sort order of TSF tables
*/
List *usable_pathkeys = NIL;
ListCell *lc;
foreach (lc, root->query_pathkeys) {
PathKey *pathkey = (PathKey *)lfirst(lc);
EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
Expr *em_expr;
/*
* Extract the expression and allow only the following pathkeys
* _id ASC
* (_id ASC, _entity_id ASC)
*/
if (!pathkey_ec->ec_has_volatile && (em_expr = find_em_expr_for_rel(pathkey_ec, baserel)) &&
pathkey->pk_strategy == BTLessStrategyNumber &&
(exprVarNameMatch(em_expr, foreignTableId, root, "_id") ||
(list_length(usable_pathkeys) == 1 &&
exprVarNameMatch(em_expr, foreignTableId, root, "_entity_id"))))
usable_pathkeys = lappend(usable_pathkeys, pathkey);
else {
/*
* Any other pathkeys are not internalizable, so reset.
*/
// elog(INFO, "[%f] Found NON usable pathkeys %s [%s]", baserel->rows,
// nodeToString(pathkey_ec), nodeToString(usable_pathkeys));
list_free(usable_pathkeys);
usable_pathkeys = NIL;
break;
}
}
/* Create a path with useful pathkeys, if we found one. */
if (usable_pathkeys != NULL) {
// No different cost for including these pathkeys, since we are
// inherently sorted by _id, _entity_id
// elog(INFO, "[%f] Found %d usable pathkeys", baserel->rows, list_length(usable_pathkeys));
add_path(baserel, (Path *)create_foreignscan_path(root, baserel, baserel->rows, startupCost,
totalCost, usable_pathkeys,
NULL,
#if PG_VERSION_NUM >= 90500
NULL,
#endif
NIL));
}
/*
* Thumb through all join clauses for the rel to identify which outer
* relations could supply one or more safe-to-handle join clauses.
* We'll build a parameterized path for each such outer relation.
*
* It's convenient to manage this by representing each candidate outer
* relation by the ParamPathInfo node for it. We can then use the
* ppi_clauses list in the ParamPathInfo node directly as a list of the
* interesting join clauses for that rel. This takes care of the
* possibility that there are multiple safe join clauses for such a rel,
* and also ensures that we account for unsafe join clauses that we'll
* still have to enforce locally (since the parameterized-path machinery
* insists that we handle all movable clauses).
*/
List *ppi_list = NIL;
foreach (lc, baserel->joininfo) {
RestrictInfo *rinfo = (RestrictInfo *)lfirst(lc);
Relids required_outer;
ParamPathInfo *param_info;
/* Check if clause can be moved to this rel */
if (!join_clause_is_movable_to(rinfo, baserel))
continue;