-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathocgeo_fdw.c
1615 lines (1376 loc) · 54.5 KB
/
ocgeo_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
/*-------------------------------------------------------------------------
*
* ocgeo_fdw.c
* PostgreSQL-related functions for OpenCageData foreign data wrapper.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <curl/curl.h>
#include "fmgr.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "access/xact.h"
#include "catalog/indexing.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "mb/pg_wchar.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pg_list.h"
#if PG_VERSION_NUM < 120000
#include "nodes/relation.h"
#include "optimizer/var.h"
#else
#include "optimizer/optimizer.h"
#include "nodes/pathnodes.h"
#endif
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parsetree.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/jsonb.h"
#if PG_VERSION_NUM < 130000
#include "utils/jsonapi.h"
#else
#include "utils/jsonfuncs.h"
#endif
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#endif
#include "ocgeo_api.h"
#include "cJSON.h"
PG_MODULE_MAGIC;
/*
* Describes the valid options for objects that use this wrapper.
*/
struct OCGeoFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
bool optrequired;
};
#define URI_OPTION "uri"
#define API_KEY_OPTION "api_key"
#define MAX_REQS_SEC_OPTION "max_reqs_sec"
#define MAX_REQS_DAY_OPTION "max_reqs_day"
#define QUERY_ATT_NAME "q"
#define MAX_RESULTS_REQUESTED 50
/*
* Valid options for ocgeo_fdw.
*/
static struct OCGeoFdwOption valid_options[] = {
{URI_OPTION, ForeignServerRelationId, true},
{API_KEY_OPTION, UserMappingRelationId, true},
{MAX_REQS_SEC_OPTION, UserMappingRelationId, false},
{MAX_REQS_DAY_OPTION, UserMappingRelationId, false}
};
#define option_count (sizeof(valid_options)/sizeof(struct OCGeoFdwOption))
typedef struct ocgeo_fdw_options
{
char* uri;
char* api_key;
int max_reqs_sec;
int max_reqs_day;
} ocgeo_fdw_options;
extern PGDLLEXPORT void _PG_init (void);
/*
* SQL functions
*/
extern PGDLLEXPORT Datum ocgeo_fdw_handler(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum ocgeo_fdw_validator(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum ocgeo_stats(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(ocgeo_fdw_handler);
PG_FUNCTION_INFO_V1(ocgeo_fdw_validator);
PG_FUNCTION_INFO_V1 (ocgeo_stats);
/*
* FDW callback routines
*/
static void ocgeoGetForeignRelSize (PlannerInfo * root, RelOptInfo * baserel, Oid foreigntableid);
static ForeignScan *ocgeoGetForeignPlan (PlannerInfo * root, RelOptInfo * foreignrel, Oid foreigntableid, ForeignPath * best_path, List * tlist, List * scan_clauses , Plan * outer_plan);
static void ocgeoBeginForeignScan (ForeignScanState * node, int eflags);
static TupleTableSlot *ocgeoIterateForeignScan (ForeignScanState * node);
static void ocgeoEndForeignScan (ForeignScanState * node);
static void ocgeoGetForeignPaths (PlannerInfo * root, RelOptInfo * baserel, Oid foreigntableid);
static void ocgeoReScanForeignScan (ForeignScanState * node);
static void ocgeoExplainForeignScan (ForeignScanState * node, ExplainState * es);
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to callback routines.
*/
PGDLLEXPORT Datum
ocgeo_fdw_handler (PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode (FdwRoutine);
fdwroutine->GetForeignRelSize = ocgeoGetForeignRelSize;
fdwroutine->BeginForeignScan = ocgeoBeginForeignScan;
fdwroutine->IterateForeignScan = ocgeoIterateForeignScan;
fdwroutine->EndForeignScan = ocgeoEndForeignScan;
fdwroutine->GetForeignPlan = ocgeoGetForeignPlan;
fdwroutine->GetForeignPaths = ocgeoGetForeignPaths;
fdwroutine->ExplainForeignScan = ocgeoExplainForeignScan;
fdwroutine->ReScanForeignScan = ocgeoReScanForeignScan;
PG_RETURN_POINTER (fdwroutine);
}
/*
* ocgeo_fdw_validator
* Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
* USER MAPPING or FOREIGN TABLE that uses ocgeo_fdw.
*
* Raise an ERROR if the option or its value are considered invalid
* or a required option is missing.
*/
PGDLLEXPORT Datum
ocgeo_fdw_validator (PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions (PG_GETARG_DATUM (0));
Oid catalog = PG_GETARG_OID (1);
ListCell *cell;
bool option_given[option_count] = { false };
int i;
/*
* Check that only options supported by ocgeo_fdw, and allowed for the
* current object type, are given.
*/
foreach (cell, options_list) {
DefElem *def = lfirst_node (DefElem, cell);
bool opt_found = false;
/* search for the option in the list of valid options */
for (i = 0; i < option_count; ++i) {
if (catalog == valid_options[i].optcontext && strcmp (valid_options[i].optname, def->defname) == 0) {
opt_found = true;
option_given[i] = true;
break;
}
}
/* option not found, generate error message */
if (!opt_found) {
/* generate list of options */
StringInfoData buf;
initStringInfo (&buf);
for (i = 0; i < option_count; ++i) {
if (catalog == valid_options[i].optcontext)
appendStringInfo (&buf, "%s%s", (buf.len > 0) ? ", " : "", valid_options[i].optname);
}
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg ("invalid option \"%s\"", def->defname),
errhint ("Valid options in this context are: %s", buf.data)));
}
/* check valid values for "max_reqs_sec" or "max_reqs_day", they should be numbers */
if (strcmp (def->defname, MAX_REQS_SEC_OPTION) == 0
|| strcmp (def->defname, MAX_REQS_DAY_OPTION) == 0) {
char *val = ((Value *) (def->arg))->val.str;
char *endptr;
unsigned long numVal = strtol (val, &endptr, 0);
if (val[0] == '\0' || *endptr != '\0' || numVal < 0)
ereport (ERROR,
(errcode (ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg ("invalid value for option \"%s\"", def->defname),
errhint ("Valid values in this context are positive integers.")));
}
}
/* check that all required options have been given */
for (i = 0; i < option_count; ++i) {
if (catalog == valid_options[i].optcontext
&& valid_options[i].optrequired && !option_given[i]) {
ereport(ERROR,
(errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
errmsg ("missing required option \"%s\"", valid_options[i].optname)));
}
}
PG_RETURN_VOID ();
}
static void
exitHook (int code, Datum arg)
{
curl_global_cleanup();
}
/*
* _PG_init
* Library load-time initalization.
* Sets exitHook() callback for backend shutdown.
*/
void _PG_init (void)
{
elog(DEBUG2,"function %s, before curl global init",__func__);
// register an exit hook
on_proc_exit (&exitHook, PointerGetDatum (NULL));
curl_global_init(CURL_GLOBAL_ALL);
elog(DEBUG2,"function %s, after curl global init",__func__);
}
/*
* Hashtable key that defines the identity of a hashtable entry. We only
* keep the user oid
*/
typedef Oid ocgeoHashKey;
// See https://github.com/postgres/postgres/blob/REL_12_3/contrib/pg_stat_statements/pg_stat_statements.c
/*
* The actual stats counters kept within pgssEntry.
*/
typedef struct Counters
{
int32 calls; /* # of times executed */
int32 success_calls; /* # of times executed successfully */
double total_time; /* total execution time, in msec */
ocgeo_rate_info_t rate_info; /* rate info, got from the most recent API call */
/* Rate limit information for implementing rate limiting using the "leaky bucket"
algorithm (https://en.wikipedia.org/wiki/Leaky_bucket) */
struct timeval ts; /* the (unix epoch) timestamp of the most recent API request */
int tokens; /* how many requests are allowed to be made, recorded
when the most recent API request was sent. */
} Counters;
/*
* Statistics per user
*
*/
typedef struct ocgeoHashEntry
{
ocgeoHashKey key; /* hash key of entry - MUST BE FIRST */
Counters counters; /* the statistics for this query */
} ocgeoHashEntry;
typedef struct ocgeoTableOptions
{
Oid server_id;
Oid user_id;
char* uri;
char* api_key;
int max_reqs_sec;
int max_reqs_day;
} ocgeoTableOptions;
/*
* the hash table keeping the Counters per user Oid
*/
static HTAB *ocgeo_hash = NULL;
static List * ColumnList(RelOptInfo *baserel);
/*
* Helper functions
*/
static void ocgeoGetOptions(Oid foreigntableid, ocgeoTableOptions *options);
static Counters * ocgeoGetCounters(ocgeoTableOptions *table_options);
static bool isAttrInRestrictInfo(Index relid, AttrNumber attno, RestrictInfo *restrictinfo);
static List *clausesInvolvingAttr(Index relid, AttrNumber attnum, EquivalenceClass *eq_class);
static List * findPaths(PlannerInfo *root, RelOptInfo *baserel, List *possiblePaths, int startupCost);
extern Value* colnameFromVar(Var *var, PlannerInfo *root);
extern void extractRestrictions(Relids base_relids, Expr *node, List **quals);
static char* colnameFromTupleVar(Var *var, TupleDesc desc);
Datum
ocgeo_stats(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
int call_cntr;
int max_calls;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
HTAB *ht = ocgeo_hash;
HASH_SEQ_STATUS *hash_seq = NULL;
/* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_INIT();
/* switch to memory context appropriate for multiple function calls */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* total number of tuples to be returned */
funcctx->max_calls = ht != NULL ? hash_get_num_entries(ht) : 0;
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
/*
* generate attribute metadata needed later to produce tuples from raw
* C strings
*/
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
if (ht != NULL) {
hash_seq = palloc0(sizeof(*hash_seq));
hash_seq_init(hash_seq, ht);
funcctx->user_fctx = hash_seq;
}
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
call_cntr = funcctx->call_cntr;
max_calls = funcctx->max_calls;
attinmeta = funcctx->attinmeta;
hash_seq = funcctx->user_fctx;
ocgeoHashEntry* hentry = hash_seq != NULL ? hash_seq_search(hash_seq) : NULL;
if (hentry != NULL) /* do when there is more left to send */
{
char **values;
HeapTuple tuple;
Datum result;
int32 total_calls;
int32 failed_calls;
double total_time_ms;
double total_time;
total_calls = hentry->counters.calls;
failed_calls = total_calls - hentry->counters.success_calls;
total_time_ms = hentry->counters.total_time;
total_time = total_time_ms / 1000.0;
/*
* Prepare a values array for building the returned tuple.
* This should be an array of C strings which will
* be processed later by the type input functions.
*/
values = (char **) palloc(6 * sizeof(char *));
values[0] = (char *) palloc(16 * sizeof(char));
values[1] = (char *) palloc(16 * sizeof(char));
values[2] = (char *) palloc(20 * sizeof(char));
values[3] = (char *) palloc(16 * sizeof(char));
values[4] = (char *) palloc(16 * sizeof(char));
snprintf(values[0], 16, "%d", total_calls);
snprintf(values[1], 16, "%d", failed_calls);
snprintf(values[2], 20, "%.2lf", total_time);
snprintf(values[3], 16, "%d", hentry->counters.rate_info.limit);
snprintf(values[4], 16, "%d", hentry->counters.rate_info.remaining);
if (hentry->counters.rate_info.reset > 0) {
struct pg_tm *reset_timestamp;
/* Convert the UNIX timestamp in the rate_info reset field to
tm UTC time. Postgres defines a pg_time_t type as an alias
to 'int64' (see pgtime.h) to make sure it covers a wider date
range. Too bad that cJSON parses any integral value to 'int'
and therefore casting to pg_time_t does not yield any benefit,
but maybe in the future? */
reset_timestamp = pg_gmtime((pg_time_t*) &hentry->counters.rate_info.reset);
values[5] = (char *) palloc(30 * sizeof(char));
snprintf(values[5], 30, "%04d-%02d-%02d %02d:%02d:%0dZ",
reset_timestamp->tm_year+1900, reset_timestamp->tm_mon, reset_timestamp->tm_mday,
reset_timestamp->tm_hour, reset_timestamp->tm_min, reset_timestamp->tm_sec);
}
else
/* there's no reset infomation, so return NULL */
values[5] = NULL;
/* build a tuple */
tuple = BuildTupleFromCStrings(attinmeta, values);
/* make the tuple into a datum */
result = HeapTupleGetDatum(tuple);
/* clean up (this is not really necessary) */
pfree(values[0]);
pfree(values[1]);
pfree(values[2]);
pfree(values[3]);
pfree(values[4]);
pfree(values[5]);
pfree(values);
SRF_RETURN_NEXT(funcctx, result);
}
else /* do when there is no more left */
{
if (hash_seq != NULL)
pfree(hash_seq);
SRF_RETURN_DONE(funcctx);
}
}
static void
ocgeoGetOptions(Oid foreigntableid, ocgeoTableOptions *table_options)
{
ForeignTable *table;
ForeignServer *server;
UserMapping *mapping;
List *options;
ListCell *lc;
table = GetForeignTable(foreigntableid);
server = GetForeignServer(table->serverid);
mapping = GetUserMapping(GetUserId(), table->serverid);
table_options->user_id = mapping->userid;
table_options->server_id = server->serverid;
/* Default values: Free plan */
table_options->max_reqs_day = 2500;
table_options->max_reqs_sec = 1;
options = NIL;
options = list_concat(options, table->options);
options = list_concat(options, server->options);
options = list_concat(options, mapping->options);
/* Loop through the options, and get the uri, apikey, etc. */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, URI_OPTION) == 0)
table_options->uri = defGetString(def);
if (strcmp(def->defname, API_KEY_OPTION) == 0)
table_options->api_key = defGetString(def);
if (strcmp(def->defname, MAX_REQS_SEC_OPTION) == 0)
table_options->max_reqs_sec = atoi(defGetString(def));
if (strcmp(def->defname, MAX_REQS_DAY_OPTION) == 0)
table_options->max_reqs_day = atoi(defGetString(def));
}
}
char* colnameFromTupleVar(Var* var, TupleDesc tupdesc)
{
Index varattno = var->varattno;
char* name = NameStr(TupleDescAttr(tupdesc, varattno - 1)->attname);
return name;
}
Counters * ocgeoGetCounters(struct ocgeoTableOptions *table_options) {
bool found;
ocgeoHashEntry* entry;
ocgeoHashKey key;
/* First time through, initialize connection cache hashtable */
if (ocgeo_hash == NULL)
{
HASHCTL ctl;
MemSet(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(ocgeoHashKey);
ctl.entrysize = sizeof(ocgeoHashEntry);
ctl.hash = tag_hash;
/* allocate ocgeo_hash in the cache context */
ctl.hcxt = CacheMemoryContext;
ocgeo_hash = hash_create("ocgeo_fdw connections", 8,
&ctl,
HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
}
/* Create hash key for the entry */
key = table_options->user_id;
/*
* Find or create cached entry for requested connection.
*/
entry = hash_search(ocgeo_hash, &key, HASH_ENTER, &found);
if (!found) {
/* initialize new hashtable entry (key is already filled in) */
entry->counters = (Counters) {0};
entry->counters.tokens = table_options->max_reqs_sec;
gettimeofday(&entry->counters.ts, NULL);
}
return &entry->counters;
}
#if PG_VERSION_NUM < 110000
#define GET_RELID_ATTNAME(foreignTableId, columnId) get_relid_attribute_name(foreignTableId, columnId)
#else
#define GET_RELID_ATTNAME(foreignTableId, columnId) get_attname(foreignTableId, columnId, false)
#endif
typedef struct ocgeoFdwPlanState {
ForeignTable* table;
ForeignServer* server;
Oid user_id;
AttInMetadata *attinmeta;
/* baserestrictinfo clauses, broken down into safe and unsafe subsets. */
List *remote_conds;
List *local_conds;
/* Bitmap of attr numbers we need to fetch from the remote server. */
Bitmapset *attrs_used;
/* Estimated size and cost for a scan with baserestrictinfo quals. */
double rows;
int width;
Cost startup_cost;
Cost total_cost;
} ocgeoFdwPlanState;
/*
* ColumnList
* Takes in the planner's information about this foreign table. The
* function then finds all columns needed for query execution, including
* those used in projections, joins, and filter clauses, de-duplicates
* these columns, and returns them in a new list.
*/
List *
ColumnList(RelOptInfo *baserel)
{
List *columnList = NIL;
List *neededColumnList;
AttrNumber columnIndex;
AttrNumber columnCount = baserel->max_attr;
List *targetColumnList = baserel->reltarget->exprs;
List *restrictInfoList = baserel->baserestrictinfo;
ListCell *restrictInfoCell;
/* First add the columns used in joins and projections */
neededColumnList = list_copy(targetColumnList);
/* Then walk over all restriction clauses, and pull up any used columns */
foreach(restrictInfoCell, restrictInfoList)
{
RestrictInfo *restrictInfo = (RestrictInfo *) lfirst(restrictInfoCell);
Node *restrictClause = (Node *) restrictInfo->clause;
List *clauseColumnList = NIL;
/* Recursively pull up any columns used in the restriction clause */
clauseColumnList = pull_var_clause(restrictClause,
PVC_RECURSE_PLACEHOLDERS);
neededColumnList = list_union(neededColumnList, clauseColumnList);
}
/* Walk over all column definitions, and de-duplicate column list */
for (columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
ListCell *neededColumnCell;
Var *column = NULL;
/* Look for this column in the needed column list */
foreach(neededColumnCell, neededColumnList) {
Var *neededColumn = lfirst_node(Var, neededColumnCell);
if (neededColumn->varattno == columnIndex) {
column = neededColumn;
break;
}
}
if (column != NULL)
columnList = lappend(columnList, column);
}
return columnList;
}
static void classifyConditions(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId, List *input_conds, List **remote_conds, List **local_conds);
/*
* Obtain relation size estimates for a foreign table. This is called at
* the beginning of planning for a query that scans a foreign table. root
* is the planner's global information about the query; baserel is the
* planner's information about this table; and foreigntableid is the
* pg_class OID of the foreign table. (foreigntableid could be obtained
* from the planner data structures, but it's passed explicitly to save
* effort.)
*
* This function should update baserel->rows to be the expected number of
* rows returned by the table scan, after accounting for the filtering
* done by the restriction quals. The initial value of baserel->rows is
* just a constant default estimate, which should be replaced if at all
* possible. The function may also choose to update baserel->width if it
* can compute a better estimate of the average result row width.
*/
static void
ocgeoGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
elog(DEBUG2,"entering function %s",__func__);
ocgeoFdwPlanState *fplanstate;
ocgeoTableOptions table_options;
fplanstate = palloc0(sizeof(*fplanstate));
baserel->fdw_private = fplanstate;
/* Look up foreign-table catalog info. */
fplanstate->table = GetForeignTable(foreigntableid);
fplanstate->server = GetForeignServer(fplanstate->table->serverid);
fplanstate->user_id = baserel->userid;
/* Get attribute descriptions for the foreign table: */
Relation rel = RelationIdGetRelation(fplanstate->table->relid);
TupleDesc desc = RelationGetDescr(rel);
fplanstate->attinmeta = TupleDescGetAttInMetadata(desc);
RelationClose(rel);
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
classifyConditions(root, baserel, foreigntableid, baserel->baserestrictinfo,
&fplanstate->remote_conds, &fplanstate->local_conds);
elog(DEBUG1, "%s: remote conds: %d, local conds: %d", __func__, list_length(fplanstate->remote_conds),
list_length(fplanstate->local_conds));
fplanstate->attrs_used = NULL;
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid, &fplanstate->attrs_used);
ListCell* lc;
foreach(lc, fplanstate->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid,
&fplanstate->attrs_used);
}
ocgeoGetOptions(foreigntableid, &table_options);
baserel->tuples = 1e10; /* number of tuples in relation (not considering restrictions) */
baserel->rows = MAX_RESULTS_REQUESTED; /* estimated number of tuples in the relation after restriction
clauses have been applied (ie, output rows of a plan for it) */
fplanstate->startup_cost = 25;
fplanstate->total_cost = fplanstate->startup_cost + baserel->rows;
}
/*
* Create possible access paths for a scan on a foreign table. This is
* called during query planning. The parameters are the same as for
* GetForeignRelSize, which has already been called.
*
* This function must generate at least one access path (ForeignPath node)
* for a scan on the foreign table and must call add_path to add each such
* path to baserel->pathlist. It's recommended to use
* create_foreignscan_path to build the ForeignPath nodes. The function
* can generate multiple access paths, e.g., a path which has valid
* pathkeys to represent a pre-sorted result. Each access path must
* contain cost estimates, and can contain any FDW-private information
* that is needed to identify the specific scan method intended.
*/
static void
ocgeoGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
elog(DEBUG2,"entering function %s",__func__);
ocgeoFdwPlanState *planstate = baserel->fdw_private;
/* Try to find parameterized paths */
List* possiblePaths = NIL;
List* paths = findPaths(root, baserel, possiblePaths, planstate->startup_cost);
elog(DEBUG1, "%s: param paths %d", __func__, list_length(paths));
/* if there are parameterized paths (because of joins etc) do not add
* a default path, to force a nested loop */
if (list_length(planstate->remote_conds) > 0 && list_length(paths) == 0) {
/* Add a simple default path */
paths = lappend(paths, create_foreignscan_path(root, baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif
baserel->rows,
planstate->startup_cost,
#if PG_VERSION_NUM >= 90600
baserel->rows * baserel->reltarget->width,
#else
baserel->rows * baserel->width,
#endif
NIL, /* no pathkeys */
NULL,
#if PG_VERSION_NUM >= 90500
NULL,
#endif
NULL));
}
/* Add each ForeignPath previously found */
ListCell* lc;
foreach(lc, paths)
{
ForeignPath *path = (ForeignPath *) lfirst(lc);
/* Add the path without modification */
add_path(baserel, (Path *) path);
}
elog(DEBUG2,"exiting function %s",__func__);
}
static void printRestrictInfoList(List* l, Oid relid)
{
if (l == NIL)
return;
ListCell* lc;
StringInfoData d;
initStringInfo(&d);
foreach(lc, l) {
/* See https://doxygen.postgresql.org/pathnodes_8h_source.html#l01981 */
RestrictInfo* r = lfirst_node(RestrictInfo, lc);
if (!IsA(r->clause, OpExpr)) continue;
OpExpr* e = IsA(r->clause, OpExpr) ? castNode(OpExpr, r->clause) : NULL;
int n = list_length(e->args);
if (n<1) continue;
Var* var = linitial_node(Var, e->args);
Const* con = lsecond_node(Const, e->args);
appendStringInfo(&d, "(%s %s ", GET_RELID_ATTNAME(relid, var->varattno), get_opname(e->opno));
switch(var->vartype) {
case TEXTOID:
case VARCHAROID:
appendStringInfo(&d, "'%s')", TextDatumGetCString(con->constvalue));
break;
case INT4OID:
case INT2OID:
appendStringInfo(&d, "%d)", DatumGetInt32(con->constvalue));
break;
default:
appendStringInfo(&d, "..{%d})", var->vartype);
break;
}
if (lc != list_tail(l))
appendStringInfo(&d, " AND ");
}
elog(DEBUG1, "%s: %s", __func__, d.data);
pfree(d.data);
}
/*
* Examine each qual clause in input_conds, and classify them into two groups,
* which are returned as two lists:
* - remote_conds contains expressions that can be evaluated remotely
* - local_conds contains expressions that can't be evaluated remotely
*/
void
classifyConditions(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreignTableId,
List *input_conds,
List **remote_conds,
List **local_conds)
{
ListCell *lc;
*remote_conds = NIL;
*local_conds = NIL;
Relids relids = baserel->relids;
/*
if (IS_UPPER_REL(baserel))
relids = fpinfo->outerrel->relids;
else
relids = baserel->relids;
*/
foreach(lc, input_conds)
{
RestrictInfo *ri = lfirst_node(RestrictInfo, lc);
Expr* clause = ri->clause;
if (nodeTag(clause) != T_OpExpr)
goto add_local;
OpExpr* opExpr = castNode(OpExpr, clause);
if (list_length(opExpr->args) != 2)
goto add_local;
if (nodeTag(linitial(opExpr->args)) != T_Var && nodeTag(lsecond(opExpr->args)) != T_Const)
goto add_local;
Var* var = linitial_node(Var, opExpr->args);
char* opName = get_opname(opExpr->opno);
if (!bms_is_member(var->varno, relids) /* && var->varlevelsup == 0*/) /* attribute belongs to foreign table ? */
goto add_local;
/* We can deal with restrictions of the form:
* q=<string>
* confidence >= <int>
*/
char* attName = GET_RELID_ATTNAME(foreignTableId, var->varattno);
if ((strcmp(opName, "=") == 0 && strcmp(attName, QUERY_ATT_NAME)==0) ||
(strcmp(opName, ">=") == 0 && strcmp(attName, "confidence")==0)) {
*remote_conds = lappend(*remote_conds, ri);
continue;
}
add_local:
*local_conds = lappend(*local_conds, ri);
}
}
/*
* Create a ForeignScan plan node from the selected foreign access path.
* This is called at the end of query planning. The parameters are as for
* GetForeignRelSize, plus the selected ForeignPath (previously produced
* by GetForeignPaths), the target list to be emitted by the plan node,
* and the restriction clauses to be enforced by the plan node.
*
* This function must create and return a ForeignScan plan node; it's
* recommended to use make_foreignscan to build the ForeignScan node.
*
*/
static ForeignScan *
ocgeoGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
Index scan_relid = baserel->relid;
List *colList;
elog(DEBUG2,"entering function %s, %d restrictions",__func__, list_length(baserel->baserestrictinfo));
printRestrictInfoList(baserel->baserestrictinfo, foreigntableid);
colList = ColumnList(baserel);
/*
* We push down applicable restriction clauses to the API (notably the "query"
* restriction and the "min_confidence"), but for simplicity
* we currently put all the restrictionClauses into the plan node's qual
* list for the executor to re-check. So all we have to do here is strip
* RestrictInfo nodes from the clauses and ignore pseudoconstants (which
* will be handled elsewhere).
*/
scan_clauses = extract_actual_clauses(scan_clauses, false);
elog(DEBUG1,"%s, %d column list, %d scan clauses",__func__, list_length(colList), list_length(scan_clauses));
/* Create the ForeignScan node */
return make_foreignscan(tlist,
scan_clauses,
scan_relid,
scan_clauses, /* expressions to evaluate */
colList, /* private state: the column list */
NIL, /* no custom tlist */
NIL,
outer_plan);
elog(DEBUG2,"exiting function %s",__func__);
}
/*
* ColumnMapping reprents a hash table entry that maps a column name to column
* related information. We construct these hash table entries to speed up the
* conversion from JSON documents to PostgreSQL tuples; and each hash entry
* maps the column name to the column's tuple index and its type-related
* information.
*/
typedef struct ColumnMapping
{
char columnName[NAMEDATALEN];
uint32 columnIndex;
Oid columnTypeId;
int32 columnTypeMod;
Oid columnArrayTypeId;
} ColumnMapping;
/*
* ColumnMappingHash
* Creates a hash table that maps column names to column index and types.
*
* This table helps us quickly translate OpenCageData JSON data fields to the
* corresponding PostgreSQL columns.
*/
static HTAB *
ColumnMappingHash(Oid foreignTableId, List *columnList)
{
ListCell *columnCell;
const long hashTableSize = 2048;
HTAB *columnMappingHash;
/* Create hash table */
HASHCTL hashInfo;
memset(&hashInfo, 0, sizeof(hashInfo));
hashInfo.keysize = NAMEDATALEN;
hashInfo.entrysize = sizeof(ColumnMapping);
hashInfo.hash = string_hash;
hashInfo.hcxt = CurrentMemoryContext;
columnMappingHash = hash_create("Column Mapping Hash", hashTableSize,
&hashInfo,
(HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT));
Assert(columnMappingHash != NULL);
foreach(columnCell, columnList)
{
Var *column = (Var *) lfirst(columnCell);
AttrNumber columnId = column->varattno;
ColumnMapping *columnMapping;
char *columnName = NULL;
bool handleFound = false;
columnName = GET_RELID_ATTNAME (foreignTableId, columnId);
columnMapping = (ColumnMapping *) hash_search(columnMappingHash,
columnName,
HASH_ENTER,