forked from pgspider/influxdb_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
influxdb_fdw.c
3645 lines (3186 loc) · 105 KB
/
influxdb_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
/*-------------------------------------------------------------------------
*
* InfluxDB Foreign Data Wrapper for PostgreSQL
*
* Portions Copyright (c) 2018-2021, TOSHIBA CORPORATION
*
* IDENTIFICATION
* influxdb_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "influxdb_fdw.h"
#include <stdio.h>
#include "access/reloptions.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#if (PG_VERSION_NUM >= 140000)
#include "optimizer/appendinfo.h"
#endif
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/cost.h"
#include "optimizer/clauses.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/paths.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "funcapi.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/rel.h"
#include "utils/lsyscache.h"
#include "utils/array.h"
#include "utils/date.h"
#include "utils/hsearch.h"
#include "utils/timestamp.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_type.h"
#include "catalog/pg_proc.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#include "utils/typcache.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
extern PGDLLEXPORT void _PG_init(void);
bool influxdb_load_library(void);
static void influxdb_fdw_exit(int code, Datum arg);
PG_MODULE_MAGIC;
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_FDW_STARTUP_COST 100.0
/* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
#define DEFAULT_FDW_TUPLE_COST 0.01
/* If no remote estimates, assume a sort costs 20% extra */
#define DEFAULT_FDW_SORT_MULTIPLIER 1.2
#define IS_KEY_COLUMN(A) ((strcmp(A->defname, "key") == 0) && \
(strcmp(((Value *)(A->arg))->val.str, "true") == 0))
extern Datum influxdb_fdw_handler(PG_FUNCTION_ARGS);
extern Datum influxdb_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(influxdb_fdw_handler);
PG_FUNCTION_INFO_V1(influxdb_fdw_version);
static void influxdbGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void influxdbGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *influxdbGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan);
static void influxdbBeginForeignScan(ForeignScanState *node,
int eflags);
static TupleTableSlot *influxdbIterateForeignScan(ForeignScanState *node);
static void influxdbReScanForeignScan(ForeignScanState *node);
static void influxdbEndForeignScan(ForeignScanState *node);
static void influxdbAddForeignUpdateTargets(
#if (PG_VERSION_NUM < 140000)
Query *parsetree,
#else
PlannerInfo *root,
Index rtindex,
#endif
RangeTblEntry *target_rte,
Relation target_relation);
static List *influxdbPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void influxdbBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *influxdbExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
#if (PG_VERSION_NUM >= 140000)
static TupleTableSlot **influxdbExecForeignBatchInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot **slots,
TupleTableSlot **planSlots,
int *numSlots);
static int influxdbGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo);
#endif
static TupleTableSlot *influxdbExecForeignDelete(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void influxdbEndForeignModify(EState *estate,
ResultRelInfo *resultRelInfo);
#if (PG_VERSION_NUM >= 110000)
static void influxdbEndForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo);
static void influxdbBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo);
#endif
static bool influxdbPlanDirectModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void influxdbBeginDirectModify(ForeignScanState *node, int eflags);
static TupleTableSlot *influxdbIterateDirectModify(ForeignScanState *node);
static void influxdbEndDirectModify(ForeignScanState *node);
static void influxdbExplainForeignScan(ForeignScanState *node,
struct ExplainState *es);
static void influxdbExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
struct ExplainState *es);
static void influxdbExplainDirectModify(ForeignScanState *node,
struct ExplainState *es);
static bool influxdbAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static List *influxdbImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void influxdbGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel
#if (PG_VERSION_NUM >= 110000)
,void *extra
#endif
);
static void influxdb_to_pg_type(StringInfo str, char *typname);
static void prepare_query_params(PlanState *node,
List *fdw_exprs,
int numParams,
FmgrInfo **param_flinfo,
List **param_exprs,
const char ***param_values,
Oid **param_types,
InfluxDBType * *param_influxdb_types,
InfluxDBValue * *param_influxdb_values);
static void process_query_params(ExprContext *econtext,
FmgrInfo *param_flinfo,
List *param_exprs,
const char **param_values,
Oid *param_types,
InfluxDBType * param_influxdb_types,
InfluxDBValue * param_influxdb_values);
static void create_cursor(ForeignScanState *node);
static void execute_dml_stmt(ForeignScanState *node);
static TupleTableSlot **execute_foreign_insert_modify(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot **slots,
TupleTableSlot **planSlots,
int numSlots);
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel);
static void add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel);
static bool influxdb_contain_regex_star_functions_walker(Node *node, void *context);
static bool influxdb_contain_regex_star_functions(Node *clause);
#if (PG_VERSION_NUM >= 140000)
static int influxdb_get_batch_size_option(Relation rel);
#endif
/*
* This enum describes what's kept in the fdw_private list for a ForeignPath.
* We store:
*
* 1) Boolean flag showing if the remote query has the final sort
* 2) Boolean flag showing if the remote query has the LIMIT clause
*/
enum FdwPathPrivateIndex
{
/* has-final-sort flag (as an integer Value node) */
FdwPathPrivateHasFinalSort,
/* has-limit flag (as an integer Value node) */
FdwPathPrivateHasLimit
};
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ModifyTable node referencing a influxdb_fdw foreign table. We store:
*
* 1) DELETE statement text to be sent to the remote server
* 2) Integer list of target attribute numbers for INSERT (NIL for a DELETE)
*/
enum FdwModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwModifyPrivateUpdateSql,
/* Integer list of target attribute numbers */
FdwModifyPrivateTargetAttnums
};
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ForeignScan node that modifies a foreign table directly. We store:
*
* 1) UPDATE/DELETE statement text to be sent to the remote server
* 2) Boolean flag showing if the remote query has a RETURNING clause
* 3) Integer list of attribute numbers retrieved by RETURNING, if any
* 4) Boolean flag showing if we set the command es_processed
*/
enum FdwDirectModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwDirectModifyPrivateUpdateSql,
/* has-returning flag (as an integer Value node) */
FdwDirectModifyPrivateHasReturning,
/* Integer list of attribute numbers retrieved by RETURNING */
FdwDirectModifyPrivateRetrievedAttrs,
/* set-processed flag (as an integer Value node) */
FdwDirectModifyPrivateSetProcessed
};
/*
* Execution state of a foreign scan that modifies a foreign table directly.
*/
typedef struct InfluxDBFdwDirectModifyState
{
Relation rel; /* relcache entry for the foreign table */
AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
/* extracted fdw_private data */
char *query; /* text of UPDATE/DELETE command */
bool has_returning; /* is there a RETURNING clause? */
List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
bool set_processed; /* do we set the command es_processed? */
/* for remote query execution */
char **params;
int numParams; /* number of parameters passed to query */
FmgrInfo *param_flinfo; /* output conversion functions for them */
List *param_exprs; /* executable expressions for param values */
const char **param_values; /* textual values of query parameters */
Oid *param_types; /* type of query parameters */
InfluxDBType *param_influxdb_types; /* InfluxDB type of query parameters */
InfluxDBValue *param_influxdb_values; /* values for InfluxDB */
influxdb_opt *influxdbFdwOptions; /* InfluxDB FDW options */
/* for storing result tuples */
int num_tuples; /* # of result tuples */
int next_tuple; /* index of next one to return */
Relation resultRel; /* relcache entry for the target relation */
AttrNumber *attnoMap; /* array of attnums of input user columns */
AttrNumber ctidAttno; /* attnum of input ctid column */
AttrNumber oidAttno; /* attnum of input oid column */
bool hasSystemCols; /* are there system columns of resultRel? */
/* working memory context */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
} InfluxDBFdwDirectModifyState;
/*
* Library load-time initialization, sets on_proc_exit() callback for
* backend shutdown.
*/
void
_PG_init(void)
{
on_proc_exit(&influxdb_fdw_exit, PointerGetDatum(NULL));
}
/*
* influxdb_fdw_exit: Exit callback function.
*/
static void
influxdb_fdw_exit(int code, Datum arg)
{
}
Datum
influxdb_fdw_version(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(CODE_VERSION);
}
Datum
influxdb_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
elog(DEBUG1, "influxdb_fdw : %s", __func__);
fdwroutine->GetForeignRelSize = influxdbGetForeignRelSize;
fdwroutine->GetForeignPaths = influxdbGetForeignPaths;
fdwroutine->GetForeignPlan = influxdbGetForeignPlan;
fdwroutine->BeginForeignScan = influxdbBeginForeignScan;
fdwroutine->IterateForeignScan = influxdbIterateForeignScan;
fdwroutine->ReScanForeignScan = influxdbReScanForeignScan;
fdwroutine->EndForeignScan = influxdbEndForeignScan;
/* Functions for updating foreign tables */
fdwroutine->AddForeignUpdateTargets = influxdbAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = influxdbPlanForeignModify;
fdwroutine->BeginForeignModify = influxdbBeginForeignModify;
#if (PG_VERSION_NUM >= 140000)
fdwroutine->ExecForeignBatchInsert = influxdbExecForeignBatchInsert;
fdwroutine->GetForeignModifyBatchSize = influxdbGetForeignModifyBatchSize;
#endif
fdwroutine->ExecForeignInsert = influxdbExecForeignInsert;
fdwroutine->ExecForeignDelete = influxdbExecForeignDelete;
fdwroutine->EndForeignModify = influxdbEndForeignModify;
#if (PG_VERSION_NUM >= 110000)
fdwroutine->BeginForeignInsert = influxdbBeginForeignInsert;
fdwroutine->EndForeignInsert = influxdbEndForeignInsert;
#endif
fdwroutine->PlanDirectModify = influxdbPlanDirectModify;
fdwroutine->BeginDirectModify = influxdbBeginDirectModify;
fdwroutine->IterateDirectModify = influxdbIterateDirectModify;
fdwroutine->EndDirectModify = influxdbEndDirectModify;
/* support for EXPLAIN */
fdwroutine->ExplainForeignScan = influxdbExplainForeignScan;
fdwroutine->ExplainForeignModify = influxdbExplainForeignModify;
fdwroutine->ExplainDirectModify = influxdbExplainDirectModify;
/* support for ANALYSE */
fdwroutine->AnalyzeForeignTable = influxdbAnalyzeForeignTable;
/* support for IMPORT FOREIGN SCHEMA */
fdwroutine->ImportForeignSchema = influxdbImportForeignSchema;
/* Support functions for upper relation push-down */
fdwroutine->GetForeignUpperPaths = influxdbGetForeignUpperPaths;
PG_RETURN_POINTER(fdwroutine);
}
/*
* estimate_path_cost_size
* Get cost and size estimates for a foreign scan on given foreign relation
* either a base relation or a join between foreign relations.
*
* param_join_conds are the parameterization clauses with outer relations.
* pathkeys specify the expected sort order if any for given path being costed.
*
* The function returns the cost and size estimates in p_row, p_width,
* p_startup_cost and p_total_cost variables.
*/
static void
estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *foreignrel,
List *param_join_conds,
List *pathkeys,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost)
{
InfluxDBFdwRelationInfo *fpinfo = (InfluxDBFdwRelationInfo *) foreignrel->fdw_private;
double rows;
double retrieved_rows;
int width;
Cost startup_cost;
Cost total_cost;
Cost cpu_per_tuple;
/*
* If the table or the server is configured to use remote estimates,
* connect to the foreign server and execute EXPLAIN to estimate the
* number of rows selected by the restriction+join clauses. Otherwise,
* estimate rows using whatever statistics we have locally, in a way
* similar to ordinary tables.
*/
if (fpinfo->use_remote_estimate)
{
ereport(ERROR, (errmsg("Remote estimation is unsupported")));
}
else
{
Cost run_cost = 0;
/*
* We don't support join conditions in this mode (hence, no
* parameterized paths can be made).
*/
Assert(param_join_conds == NIL);
/*
* Use rows/width estimates made by set_baserel_size_estimates() for
* base foreign relations and set_joinrel_size_estimates() for join
* between foreign relations.
*/
rows = foreignrel->rows;
width = foreignrel->reltarget->width;
/* Back into an estimate of the number of retrieved rows. */
retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
/*
* We will come here again and again with different set of pathkeys
* that caller wants to cost. We don't need to calculate the cost of
* bare scan each time. Instead, use the costs if we have cached them
* already.
*/
if (fpinfo->rel_startup_cost > 0 && fpinfo->rel_total_cost > 0)
{
startup_cost = fpinfo->rel_startup_cost;
run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
}
else
{
Assert(foreignrel->reloptkind != RELOPT_JOINREL);
/* Clamp retrieved rows estimates to at most foreignrel->tuples. */
retrieved_rows = Min(retrieved_rows, foreignrel->tuples);
/*
* Cost as though this were a seqscan, which is pessimistic. We
* effectively imagine the local_conds are being evaluated
* remotely, too.
*/
startup_cost = 0;
run_cost = 0;
run_cost += seq_page_cost * foreignrel->pages;
startup_cost += foreignrel->baserestrictcost.startup;
cpu_per_tuple =
cpu_tuple_cost + foreignrel->baserestrictcost.per_tuple;
run_cost += cpu_per_tuple * foreignrel->tuples;
}
/*
* Without remote estimates, we have no real way to estimate the cost
* of generating sorted output. It could be free if the query plan
* the remote side would have chosen generates properly-sorted output
* anyway, but in most cases it will cost something. Estimate a value
* high enough that we won't pick the sorted path when the ordering
* isn't locally useful, but low enough that we'll err on the side of
* pushing down the ORDER BY clause when it's useful to do so.
*/
if (pathkeys != NIL)
{
startup_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
run_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
}
total_cost = startup_cost + run_cost;
}
/*
* Cache the costs for scans without any pathkeys or parameterization
* before adding the costs for transferring data from the foreign server.
* These costs are useful for costing the join between this relation and
* another foreign relation or to calculate the costs of paths with
* pathkeys for this relation, when the costs can not be obtained from the
* foreign server. This function will be called at least once for every
* foreign relation without pathkeys and parameterization.
*/
if (pathkeys == NIL && param_join_conds == NIL)
{
fpinfo->rel_startup_cost = startup_cost;
fpinfo->rel_total_cost = total_cost;
}
/*
* Add some additional cost factors to account for connection overhead
* (fdw_startup_cost), transferring data across the network
* (fdw_tuple_cost per retrieved row), and local manipulation of the data
* (cpu_tuple_cost per retrieved row).
*/
startup_cost += fpinfo->fdw_startup_cost;
total_cost += fpinfo->fdw_startup_cost;
total_cost += fpinfo->fdw_tuple_cost * retrieved_rows;
total_cost += cpu_tuple_cost * retrieved_rows;
/* Return results. */
*p_rows = rows;
*p_width = width;
*p_startup_cost = startup_cost;
*p_total_cost = total_cost;
}
/*
* influxdbGetForeignRelSize: Create a FdwPlan for a scan on the foreign table
*/
static void
influxdbGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
InfluxDBFdwRelationInfo *fpinfo;
ListCell *lc;
elog(DEBUG1, "influxdb_fdw : %s", __func__);
fpinfo = (InfluxDBFdwRelationInfo *) palloc0(sizeof(InfluxDBFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/* Base foreign tables need to be pushed down always. */
fpinfo->pushdown_safe = true;
/* Look up foreign-table catalog info. */
fpinfo->table = GetForeignTable(foreigntableid);
fpinfo->server = GetForeignServer(fpinfo->table->serverid);
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
foreach(lc, baserel->baserestrictinfo)
{
RestrictInfo *ri = (RestrictInfo *) lfirst(lc);
if (influxdb_is_foreign_expr(root, baserel, ri->clause, false))
fpinfo->remote_conds = lappend(fpinfo->remote_conds, ri);
else
fpinfo->local_conds = lappend(fpinfo->local_conds, ri);
}
/*
* Identify which attributes will need to be retrieved from the remote
* server.
*/
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid, &fpinfo->attrs_used);
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid, &fpinfo->attrs_used);
}
/*
* Compute the selectivity and cost of the local_conds, so we don't have
* to do it over again for each path. The best we can do for these
* conditions is to estimate selectivity on the basis of local statistics.
*/
fpinfo->local_conds_sel = clauselist_selectivity(root,
fpinfo->local_conds,
baserel->relid,
JOIN_INNER,
NULL);
/*
* Set cached relation costs to some negative value, so that we can detect
* when they are set to some sensible costs during one (usually the first)
* of the calls to estimate_path_cost_size().
*/
fpinfo->rel_startup_cost = -1;
fpinfo->rel_total_cost = -1;
/*
* If the table or the server is configured to use remote estimates,
* connect to the foreign server and execute EXPLAIN to estimate the
* number of rows selected by the restriction clauses, as well as the
* average row width. Otherwise, estimate using whatever statistics we
* have locally, in a way similar to ordinary tables.
*/
if (fpinfo->use_remote_estimate)
{
ereport(ERROR, (errmsg("Remote estimation is unsupported")));
}
else
{
/*
* We can't do much if we're not allowed to consult the remote server,
* but we can use a hack similar to plancat.c's treatment of empty
* relations: use a minimum size estimate of 10 pages, and divide by
* the column-datatype-based width estimate to get the corresponding
* number of tuples.
*/
#if (PG_VERSION_NUM < 140000)
/*
* If the foreign table has never been ANALYZEd, it will have relpages
* and reltuples equal to zero, which most likely has nothing to do
* with reality.
*/
if (baserel->pages == 0 && baserel->tuples == 0)
#else
/*
* If the foreign table has never been ANALYZEd, it will have
* reltuples < 0, meaning "unknown"
*/
if (baserel->tuples < 0)
#endif
{
baserel->pages = 10;
baserel->tuples =
(10 * BLCKSZ) / (baserel->reltarget->width +
MAXALIGN(SizeofHeapTupleHeader));
}
/* Estimate baserel size as best we can with local statistics. */
set_baserel_size_estimates(root, baserel);
/* Fill in basically-bogus cost estimates for use later. */
estimate_path_cost_size(root, baserel, NIL, NIL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost, &fpinfo->total_cost);
}
/*
* Set the name of relation in fpinfo, while we are constructing it here.
* It will be used to build the string describing the join relation in
* EXPLAIN output. We can't know whether VERBOSE option is specified or
* not, so always schema-qualify the foreign table name.
*/
fpinfo->relation_name = psprintf("%u", baserel->relid);
}
/*
* influxdbGetForeignPaths
* Create possible scan paths for a scan on the foreign table
*/
static void
influxdbGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
Cost startup_cost = 10;
Cost total_cost = baserel->rows + startup_cost;
elog(DEBUG1, "influxdb_fdw : %s", __func__);
/* Estimate costs */
total_cost = baserel->rows;
/* Create a ForeignPath node and add it as only possible path */
add_path(baserel, (Path *)
create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
baserel->rows,
startup_cost,
total_cost,
NIL, /* no pathkeys */
#if (PG_VERSION_NUM >= 120000)
baserel->lateral_relids,
#else
NULL, /* no outer rel either */
#endif
NULL, /* no extra plan */
NULL)); /* no fdw_private data */
}
/*
* influxdbGetForeignPlan: Get a foreign scan plan node
*/
static ForeignScan *
influxdbGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
InfluxDBFdwRelationInfo *fpinfo = (InfluxDBFdwRelationInfo *) baserel->fdw_private;
Index scan_relid = baserel->relid;
List *fdw_private = NULL;
List *local_exprs = NULL;
List *remote_exprs = NULL;
List *params_list = NULL;
List *fdw_scan_tlist = NIL;
List *remote_conds = NIL;
StringInfoData sql;
List *retrieved_attrs;
ListCell *lc;
List *fdw_recheck_quals = NIL;
int for_update;
bool has_limit = false;
elog(DEBUG1, "influxdb_fdw : %s", __func__);
/* Decide to execute function pushdown support in the target list. */
fpinfo->is_tlist_func_pushdown = influxdb_is_foreign_function_tlist(root, baserel, tlist);
/*
* Get FDW private data created by influxdbGetForeignUpperPaths(), if any.
*/
if (best_path->fdw_private)
{
has_limit = intVal(list_nth(best_path->fdw_private, FdwPathPrivateHasLimit));
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
/* Build the query */
initStringInfo(&sql);
/*
* Separate the scan_clauses into those that can be executed remotely and
* those that can't. baserestrictinfo clauses that were previously
* determined to be safe or unsafe by classifyConditions are shown in
* fpinfo->remote_conds and fpinfo->local_conds. Anything else in the
* scan_clauses list will be a join clause, which we have to check for
* remote-safety.
*
* Note: the join clauses we see here should be the exact same ones
* previously examined by influxdbGetForeignPaths. Possibly it'd be worth
* passing forward the classification work done then, rather than
* repeating it here.
*
* This code must match "extract_actual_clauses(scan_clauses, false)"
* except for the additional decision about remote versus local execution.
* Note however that we only strip the RestrictInfo nodes from the
* local_exprs list, since appendWhereClause expects a list of
* RestrictInfos.
*/
if ((baserel->reloptkind == RELOPT_BASEREL ||
baserel->reloptkind == RELOPT_OTHER_MEMBER_REL) &&
fpinfo->is_tlist_func_pushdown == false)
{
foreach(lc, scan_clauses)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
/* Ignore any pseudoconstants, they're dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->remote_conds, rinfo))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else if (list_member_ptr(fpinfo->local_conds, rinfo))
local_exprs = lappend(local_exprs, rinfo->clause);
else if (influxdb_is_foreign_expr(root, baserel, rinfo->clause, false))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
/*
* For a base-relation scan, we have to support EPQ recheck, which
* should recheck all the remote quals.
*/
fdw_recheck_quals = remote_exprs;
}
}
else
{
/*
* Join relation or upper relation - set scan_relid to 0.
*/
scan_relid = 0;
/*
* For a join rel, baserestrictinfo is NIL and we are not considering
* parameterization right now, so there should be no scan_clauses for
* a joinrel or an upper rel either.
*/
if (fpinfo->is_tlist_func_pushdown == false)
{
Assert(!scan_clauses);
}
/*
* Instead we get the conditions to apply from the fdw_private
* structure.
*/
remote_exprs = extract_actual_clauses(fpinfo->remote_conds, false);
local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
/*
* We leave fdw_recheck_quals empty in this case, since we never need
* to apply EPQ recheck clauses. In the case of a joinrel, EPQ
* recheck is handled elsewhere --- see influxdbGetForeignJoinPaths().
* If we're planning an upperrel (ie, remote grouping or aggregation)
* then there's no EPQ to do because SELECT FOR UPDATE wouldn't be
* allowed, and indeed we *can't* put the remote clauses into
* fdw_recheck_quals because the unaggregated Vars won't be available
* locally.
*/
/* Build the list of columns to be fetched from the foreign server. */
if (fpinfo->is_tlist_func_pushdown == true)
{
foreach(lc, tlist)
{
TargetEntry *tle = lfirst_node(TargetEntry, lc);
/*
* Pull out function from FieldSelect clause and add to
* fdw_scan_tlist to push down function portion only
*/
if (fpinfo->is_tlist_func_pushdown == true && IsA((Node *) tle->expr, FieldSelect))
{
fdw_scan_tlist = add_to_flat_tlist(fdw_scan_tlist,
influxdb_pull_func_clause((Node *) tle->expr));
}
else
{
fdw_scan_tlist = lappend(fdw_scan_tlist, tle);
}
}
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
fdw_scan_tlist = add_to_flat_tlist(fdw_scan_tlist,
pull_var_clause((Node *) rinfo->clause,
PVC_RECURSE_PLACEHOLDERS));
}
}
else
{
fdw_scan_tlist = influxdb_build_tlist_to_deparse(baserel);
}
/*
* Ensure that the outer plan produces a tuple whose descriptor
* matches our scan tuple slot. This is safe because all scans and
* joins support projection, so we never need to insert a Result node.
* Also, remove the local conditions from outer plan's quals, lest
* they will be evaluated twice, once by the local plan and once by
* the scan.
*/
if (outer_plan)
{
ListCell *lc;
/*
* Right now, we only consider grouping and aggregation beyond
* joins. Queries involving aggregates or grouping do not require
* EPQ mechanism, hence should not have an outer plan here.
*/
Assert(baserel->reloptkind != RELOPT_UPPER_REL);
outer_plan->targetlist = fdw_scan_tlist;
foreach(lc, local_exprs)
{
Join *join_plan = (Join *) outer_plan;
Node *qual = lfirst(lc);
outer_plan->qual = list_delete(outer_plan->qual, qual);
/*
* For an inner join the local conditions of foreign scan plan
* can be part of the joinquals as well.
*/
if (join_plan->jointype == JOIN_INNER)
join_plan->joinqual = list_delete(join_plan->joinqual,
qual);
}
}
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
influxdb_deparse_select_stmt_for_rel(&sql, root, baserel, fdw_scan_tlist,
remote_exprs, best_path->path.pathkeys,
false, &retrieved_attrs, ¶ms_list, has_limit);
/* Remember remote_exprs for possible use by influxdbPlanDirectModify */
fpinfo->final_remote_exprs = remote_exprs;
for_update = false;
if (baserel->relid == root->parse->resultRelation &&
(root->parse->commandType == CMD_UPDATE ||
root->parse->commandType == CMD_DELETE))
{
/* Relation is UPDATE/DELETE target, so use FOR UPDATE */
for_update = true;
}
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match enum FdwScanPrivateIndex, above.
*/
fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(for_update));
fdw_private = lappend(fdw_private, fdw_scan_tlist);
fdw_private = lappend(fdw_private, makeInteger(fpinfo->is_tlist_func_pushdown));
/*
* Create the ForeignScan node from target list, local filtering
* expressions, remote parameter expressions, and FDW private information.
*
* Note that the remote parameter expressions are stored in the fdw_exprs
* field of the finished plan node; we can't keep them in private state
* because then they wouldn't be subject to later planner processing.
*/
return make_foreignscan(tlist,
local_exprs,
scan_relid,
params_list,
fdw_private,
fdw_scan_tlist,
fdw_recheck_quals,
outer_plan);
}
/*
* influxdbBeginForeignScan: Initiate access to the database
*/
static void
influxdbBeginForeignScan(ForeignScanState *node, int eflags)
{
InfluxDBFdwExecState *festate = NULL;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
int numParams;
elog(DEBUG1, "influxdb_fdw : %s", __func__);
/*
* We'll save private state in node->fdw_state.
*/
festate = (InfluxDBFdwExecState *) palloc0(sizeof(InfluxDBFdwExecState));
node->fdw_state = (void *) festate;
festate->rowidx = 0;
/* Stash away the state info we have already */
festate->query = strVal(list_nth(fsplan->fdw_private, 0));
festate->retrieved_attrs = list_nth(fsplan->fdw_private, 1);
festate->for_update = intVal(list_nth(fsplan->fdw_private, 2)) ? true : false;
festate->tlist = (List *) list_nth(fsplan->fdw_private, 3);
festate->is_tlist_func_pushdown = intVal(list_nth(fsplan->fdw_private, 4)) ? true : false;
festate->cursor_exists = false;
/* Prepare for output conversion of parameters used in remote query. */
numParams = list_length(fsplan->fdw_exprs);
festate->numParams = numParams;
if (numParams > 0)
prepare_query_params((PlanState *) node,
fsplan->fdw_exprs,
numParams,
&festate->param_flinfo,
&festate->param_exprs,