forked from pgspider/griddb_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
griddb_fdw.c
5422 lines (4706 loc) · 153 KB
/
griddb_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
/*
* GridDB Foreign Data Wrapper
*
* Portions Copyright (c) 2021, TOSHIBA CORPORATION
*
* IDENTIFICATION
* griddb_fdw.c
*
*/
#include "postgres.h"
#include "griddb_fdw.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "nodes/pg_list.h"
#include "nodes/makefuncs.h"
#include "catalog/pg_type.h"
#include "catalog/pg_proc.h"
#include "commands/explain.h"
#include "commands/defrem.h"
#include "executor/spi.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "miscadmin.h"
#if (PG_VERSION_NUM >= 140000)
#include "optimizer/appendinfo.h"
#endif
#include "optimizer/cost.h"
#include "optimizer/paths.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "storage/ipc.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/datum.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/elog.h"
#include "utils/timestamp.h"
#if (PG_VERSION_NUM < 100000)
#include "utils/bytea.h"
#endif
PG_MODULE_MAGIC;
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* These items are indexed with the enum FdwScanPrivateIndex, so an item
* can be fetched with list_nth(). For example, to get the SELECT statement:
* sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
*/
enum FdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwScanPrivateSelectSql,
/* List of restriction clauses that can be executed remotely */
FdwScanPrivateRemoteConds,
/* Integer list of attribute numbers retrieved by the SELECT */
FdwScanPrivateRetrievedAttrs,
/* Integer representing UPDATE/DELETE target */
FdwScanPrivateForUpdate,
/* Scan tlist */
FdwScanTlist,
/* RTE */
FDWScanRTE,
/* Integer representing aggregate function name */
FdwScanPrivateAggRefName,
/* Integer representing aggregate function */
FdwScanPrivateAggRefColumn,
};
/* Callback argument for ec_member_matches_foreign */
typedef struct ec_member_foreign_arg
{
Expr *current; /* current expr, or NULL if not yet found */
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ModifyTable node referencing a griddb_fdw foreign table. We store:
*
* 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server
* 2) Integer list of target attribute numbers for INSERT/UPDATE
* (NIL for a DELETE)
*/
enum FdwModifyPrivateIndex
{
/* Integer list of target attribute numbers for INSERT/UPDATE */
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
};
/*
* 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
};
/*
* The following structures are used for sharing data between scaning
* functions and modification functions.
* In griddb_fdw, the data modification (UPDATE/DELETE) is done via rowset
* which is created by ForeignScan. So rowset must be passed from ForeignScan
* to ForeignModify.
*/
typedef Oid GridDBFdwSMRelayKey; /* foreigntableid */
typedef struct GridDBFdwSMRelay
{
GridDBFdwSMRelayKey key; /* hash key (must be first) */
GSRowSet *row_set; /* result set */
GSRow *row; /* row for the update */
GridDBFdwFieldInfo field_info; /* column information */
Datum rowkey_val; /* rowkey the cursor is pointing */
} GridDBFdwSMRelay;
static HTAB *griddb_sm_share = NULL;
static bool griddb_enable_partial_execution = false;
/*
* Execution state of a foreign scan using griddb_fdw.
*/
typedef struct GridDBFdwScanState
{
Relation rel; /* relcache entry for the foreign table. NULL
* for a foreign join scan. */
TupleDesc tupdesc; /* tuple descriptor of scan */
/* extracted fdw_private data */
char *query; /* text of SELECT command */
List *retrieved_attrs; /* list of retrieved attribute numbers */
List *fdw_scan_tlist; /* optional tlist describing scan tuple */
/* for remote query execution */
GSGridStore *store; /* connection for the scan */
GSChar *cont_name; /* container name */
GSContainer *cont; /* container to be selected */
GSBool for_update; /* GS_TRUE if UPDATE/DELETE target */
GridDBFdwFieldInfo field_info; /* field information */
GSRowSet *row_set; /* result set */
GSRow *row; /* row for the update */
GridDBAggref *aggref; /* aggregate function information */
/* for storing result tuples */
unsigned int cursor; /* result set cursor pointing current index */
/* for sharing data with ForeignModify */
GridDBFdwSMRelay *smrelay; /* cache of the relay */
} GridDBFdwScanState;
/*
* Execution state of a foreign insert/update/delete operation.
*/
typedef struct GridDBFdwModifyState
{
Relation rel; /* relcache entry for the foreign table */
/* for remote query execution */
GSGridStore *store; /* connection for the scan */
GSChar *cont_name; /* container name */
GSContainer *cont; /* container to be modified */
/* extracted fdw_private data */
List *target_attrs; /* list of target attribute numbers */
bool bulk_mode; /* true if UPDATE/DELETE targets are pointing
* different rows from result set cursor */
AttrNumber junk_att_no; /* rowkey attribute number */
HTAB *modified_rowkeys; /* rowkey hash */
GridDBFdwModifiedRows modified_rows;
CmdType operation; /* INSERT, UPDATE, or DELETE */
/* for sharing data with ForeignScan */
GridDBFdwSMRelay *smrelay; /* cache of the relay */
int batch_size; /* value of FDW option "batch_size" */
struct GridDBFdwModifyState *aux_fmstate; /* foreign-insert state, if
* created */
} GridDBFdwModifyState;
/*
* SQL functions
*/
extern Datum griddb_fdw_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(griddb_fdw_handler);
PG_FUNCTION_INFO_V1(griddb_fdw_version);
void _PG_init(void);
void _PG_fini(void);
/*
* FDW callback routines
*/
static void griddbGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void griddbGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *griddbGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan);
static void griddbBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *griddbIterateForeignScan(ForeignScanState *node);
static void griddbReScanForeignScan(ForeignScanState *node);
static void griddbEndForeignScan(ForeignScanState *node);
#if PG_VERSION_NUM < 140000
static void griddbAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
#else
static void griddbAddForeignUpdateTargets(PlannerInfo *root,
Index rtindex,
RangeTblEntry *target_rte,
Relation target_relation);
#endif
static List *griddbPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void griddbBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *griddbExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
#if PG_VERSION_NUM >= 140000
static TupleTableSlot **griddbExecForeignBatchInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot **slots,
TupleTableSlot **planSlots,
int *numSlots);
static int griddbGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo);
#endif
static TupleTableSlot *griddbExecForeignUpdate(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *griddbExecForeignDelete(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void griddbEndForeignModify(EState *estate,
ResultRelInfo *resultRelInfo);
#if (PG_VERSION_NUM >= 110000)
static void griddbEndForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo);
static void griddbBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo);
#endif
static int griddbIsForeignRelUpdatable(Relation rel);
static bool griddbPlanDirectModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void griddbExplainForeignScan(ForeignScanState *node,
ExplainState *es);
static void griddbExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es);
static bool griddbAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static List *griddbImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void griddbGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel
#if (PG_VERSION_NUM >= 110000)
,void *extra
#endif
);
static void griddb_get_datatype_for_conversion(Oid pg_type, regproc *typeinput,
int *typemod);
static bool griddb_foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel);
static void griddb_add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel
#if (PG_VERSION_NUM >= 110000)
,GroupPathExtraData *extra
#endif
);
/*
* Helper functions
*/
static void griddb_fdw_exit(int code, Datum arg);
static void estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *baserel,
List *join_conds,
List *pathkeys,
GriddbFdwPathExtraData * fpextra,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost);
static void griddb_make_column_info(GSContainerInfo * cont_info,
GridDBFdwFieldInfo * field_info);
static void griddb_free_column_info(GridDBFdwFieldInfo * field_info);
static Oid griddb_pgtyp_from_gstyp(GSType gs_type, const char **name);
static Timestamp griddb_convert_gs2pg_timestamp(GSTimestamp ts);
static char *griddb_convert_gs2pg_timestamp_to_string(GSTimestamp ts);
static GSTimestamp griddb_convert_pg2gs_timestamp(Timestamp dt);
static void griddb_execute_and_fetch(ForeignScanState *node);
static void griddb_find_junk_attno(GridDBFdwModifyState * fmstate, List *targetlist);
static void griddb_judge_bulk_mode(GridDBFdwModifyState * fmstate, TupleTableSlot *planSlot);
static void griddb_bind_for_putrow(GridDBFdwModifyState * fmstate,
TupleTableSlot *slot,
GSRow * row, Relation rel,
GridDBFdwFieldInfo * field_info);
static void griddb_add_column_name_and_type(StringInfoData *buf,
GSContainerInfo * info);
static GSChar * *grifddb_name_list_dup(const GSChar * const *src,
size_t cont_size);
static void grifddb_name_list_free(GSChar * *p, size_t cont_size);
static void griddb_execute_commands(List *cmd_list);
int griddb_set_transmission_modes();
void griddb_reset_transmission_modes(int nestlevel);
static void griddb_check_rowkey_update(GridDBFdwModifyState * fmstate, TupleTableSlot *new_slot);
static Oid griddb_get_agg_type(GridDBFdwFieldInfo field_info, GridDBAggref * aggref);
static Datum griddb_make_datum_record(StringInfoData *values, TupleDesc tupdesc, GSType * column_types,
GSRow * row, regproc typeinput, int typemod);
static List *griddb_get_useful_pathkeys_for_relation(PlannerInfo *root,
RelOptInfo *rel);
static List *griddb_get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel);
static void griddb_add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
Path *epq_path);
static void griddb_add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel,
RelOptInfo *final_rel
#if (PG_VERSION_NUM >= 120000)
,FinalPathExtraData *extra
#endif
);
#if (PG_VERSION_NUM >= 140000)
static int get_batch_size_option(Relation rel);
#endif
void
_PG_init()
{
on_proc_exit(&griddb_fdw_exit, PointerGetDatum(NULL));
DefineCustomBoolVariable("griddbfdw.enable_partial_execution",
"enable partial execution",
NULL,
&griddb_enable_partial_execution,
false,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
}
/*
* griddb_fdw_exit: Exit callback function.
*/
static void
griddb_fdw_exit(int code, Datum arg)
{
griddb_cleanup_connection();
}
void
_PG_fini()
{
}
Datum
griddb_fdw_version(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(CODE_VERSION);
}
Datum
griddb_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *routine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
routine->GetForeignRelSize = griddbGetForeignRelSize;
routine->GetForeignPaths = griddbGetForeignPaths;
routine->GetForeignPlan = griddbGetForeignPlan;
routine->BeginForeignScan = griddbBeginForeignScan;
routine->IterateForeignScan = griddbIterateForeignScan;
routine->ReScanForeignScan = griddbReScanForeignScan;
routine->EndForeignScan = griddbEndForeignScan;
/* Functions for updating foreign tables */
routine->AddForeignUpdateTargets = griddbAddForeignUpdateTargets;
routine->PlanForeignModify = griddbPlanForeignModify;
routine->BeginForeignModify = griddbBeginForeignModify;
routine->ExecForeignInsert = griddbExecForeignInsert;
routine->ExecForeignUpdate = griddbExecForeignUpdate;
routine->ExecForeignDelete = griddbExecForeignDelete;
routine->EndForeignModify = griddbEndForeignModify;
routine->IsForeignRelUpdatable = griddbIsForeignRelUpdatable;
#if (PG_VERSION_NUM >= 110000)
routine->BeginForeignInsert = griddbBeginForeignInsert;
routine->EndForeignInsert = griddbEndForeignInsert;
#endif
routine->PlanDirectModify = griddbPlanDirectModify;
routine->BeginDirectModify = NULL;
routine->IterateDirectModify = NULL;
routine->EndDirectModify = NULL;
/* Function for EvalPlanQual rechecks */
routine->RecheckForeignScan = NULL;
/* Support functions for EXPLAIN */
routine->ExplainForeignScan = griddbExplainForeignScan;
routine->ExplainForeignModify = griddbExplainForeignModify;
routine->ExplainDirectModify = NULL;
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = griddbAnalyzeForeignTable;
#if (PG_VERSION_NUM >= 140000)
/* Support function for Batch Insert */
routine->ExecForeignBatchInsert = griddbExecForeignBatchInsert;
routine->GetForeignModifyBatchSize = griddbGetForeignModifyBatchSize;
/* Curently gridDB does not support asynchronous execution */
routine->IsForeignPathAsyncCapable = NULL;
routine->ForeignAsyncRequest = NULL;
routine->ForeignAsyncConfigureWait = NULL;
routine->ForeignAsyncNotify = NULL;
#endif
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = griddbImportForeignSchema;
/* Not support functions for join push-down */
routine->GetForeignJoinPaths = NULL;
/* Support functions for upper relation push-down */
routine->GetForeignUpperPaths = griddbGetForeignUpperPaths;
PG_RETURN_POINTER(routine);
}
/*
* Get a hash entry of GridDBFdwScanModifyRelay corresponding to
* the foreign table oid from a global hash variable.
*/
static GridDBFdwSMRelay *
griddb_get_smrelay(Oid foreigntableid)
{
bool found;
GridDBFdwSMRelay *entry;
GridDBFdwSMRelayKey key;
/* First time through, initialize connection cache hashtable */
if (griddb_sm_share == NULL)
{
HASHCTL ctl;
MemSet(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(GridDBFdwSMRelayKey);
ctl.entrysize = sizeof(GridDBFdwSMRelay);
/* allocate ConnectionHash in the cache context */
ctl.hcxt = CacheMemoryContext;
griddb_sm_share = hash_create("griddb_fdw scan modify relay", 8,
&ctl,
#if PG_VERSION_NUM >= 140000
HASH_ELEM | HASH_BLOBS);
#else
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
#endif
}
/* Create hash key for the entry. Assume no pad bytes in key struct */
key = foreigntableid;
/*
* Find or create cached entry for requested connection.
*/
entry = (GridDBFdwSMRelay *) hash_search(griddb_sm_share, &key, HASH_ENTER,
&found);
if (!found)
{
/* initialize new hashtable entry (key is already filled in) */
entry->row_set = NULL;
entry->row = NULL;
memset(&entry->field_info, 0, sizeof(GridDBFdwFieldInfo));
entry->rowkey_val = 0;
}
return entry;
}
static void
griddb_close_smrelay(Oid foreigntableid)
{
GridDBFdwSMRelayKey key = foreigntableid;
Assert(griddb_sm_share);
hash_search(griddb_sm_share, &key, HASH_REMOVE, NULL);
}
/*
* griddbGetForeignRelSize
* Estimate # of rows and width of the result of the scan
*
* We should consider the effect of all baserestrictinfo clauses here, but
* not any join clauses.
*/
static void
griddbGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
GriddbFdwRelationInfo *fpinfo;
ListCell *lc;
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
griddb_opt *options = NULL;
elog(DEBUG1, "griddb_fdw: %s", __func__);
/*
* We use GriddbFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo =
(GriddbFdwRelationInfo *) palloc0(sizeof(GriddbFdwRelationInfo));
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);
/* Fetch options */
options = griddb_get_options(foreigntableid);
/*
* Extract user-settable option values. Note that per-table setting of
* use_remote_estimate overrides per-server setting.
*/
fpinfo->use_remote_estimate = options->use_remote_estimate;
fpinfo->fdw_startup_cost = options->fdw_startup_cost;
fpinfo->fdw_tuple_cost = options->fdw_tuple_cost;
fpinfo->shippable_extensions = NIL;
fpinfo->fetch_size = 100;
/*
* If the table or the server is configured to use remote estimates,
* identify which user to do remote access as during planning. This
* should match what ExecCheckRTEPerms() does. If we fail due to lack of
* permissions, the query would have failed at runtime anyway.
*/
if (fpinfo->use_remote_estimate)
{
Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid);
}
else
fpinfo->user = NULL;
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
griddb_classify_conditions(root, baserel, baserel->baserestrictinfo,
&fpinfo->remote_conds, &fpinfo->local_conds);
/*
* Identify which attributes will need to be retrieved from the remote
* server. These include all attrs needed for joins or final output, plus
* all attrs used in the local_conds. (Note: if we end up using a
* parameterized scan, it's possible that some of the join clauses will be
* sent to the remote and thus we wouldn't really need to retrieve the
* columns used in them. Doesn't seem worth detecting that case though.)
*/
fpinfo->attrs_used = NULL;
#if PG_VERSION_NUM >= 90600
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
&fpinfo->attrs_used);
#else
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid, &fpinfo->attrs_used);
#endif
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
{
/*
* 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. We can't do a whole lot about that 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 (baserel->pages == 0 && baserel->tuples == 0)
#else
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, NULL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost, &fpinfo->total_cost);
}
}
/*
* GetForeignPaths
* create access path for a scan on the foreign table
*/
static void
griddbGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
GriddbFdwRelationInfo *fpinfo =
(GriddbFdwRelationInfo *) baserel->fdw_private;
ForeignPath *path;
elog(DEBUG1, "griddb_fdw: %s", __func__);
/*
* Create simplest ForeignScan path node and add it to baserel. This path
* corresponds to SeqScan path of regular tables (though depending on what
* baserestrict conditions we were able to send to remote, there might
* actually be an indexscan happening there). We already did all the work
* to estimate cost and size of this path.
*/
path = create_foreignscan_path(root, baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif
fpinfo->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
#if (PG_VERSION_NUM >= 120000)
baserel->lateral_relids,
#else
NULL, /* no outer rel either */
#endif
NULL, /* no extra plan */
NIL); /* no fdw_private list */
add_path(baserel, (Path *) path);
/* Add paths with pathkeys */
griddb_add_paths_with_pathkeys_for_rel(root, baserel, NULL);
/*
* If we're not using remote estimates, stop here. We have no way to
* estimate whether any join clauses would be worth sending across, so
* don't bother building parameterized paths.
*/
if (!fpinfo->use_remote_estimate)
return;
ereport(ERROR, (errmsg("Remote estimation is unsupported")));
}
/*
* Force assorted GUC parameters to settings that ensure that we'll output
* data values in a form that is unambiguous to the remote server.
*
* This is rather expensive and annoying to do once per row, but there's
* little choice if we want to be sure values are transmitted accurately;
* we can't leave the settings in place between rows for fear of affecting
* user-visible computations.
*
* We use the equivalent of a function SET option to allow the settings to
* persist only until the caller calls griddb_reset_transmission_modes(). If an
* error is thrown in between, guc.c will take care of undoing the settings.
*
* The return value is the nestlevel that must be passed to
* griddb_reset_transmission_modes() to undo things.
*/
int
griddb_set_transmission_modes(void)
{
int nestlevel = NewGUCNestLevel();
/*
* The values set here should match what pg_dump does. See also
* configure_remote_session in connection.c.
*/
if (DateStyle != USE_ISO_DATES)
(void) set_config_option("datestyle", "ISO",
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_SAVE, true, 0, false);
if (IntervalStyle != INTSTYLE_POSTGRES)
(void) set_config_option("intervalstyle", "postgres",
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_SAVE, true, 0, false);
if (extra_float_digits < 3)
(void) set_config_option("extra_float_digits", "3",
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_SAVE, true, 0, false);
return nestlevel;
}
/*
* Undo the effects of griddb_set_transmission_modes().
*/
void
griddb_reset_transmission_modes(int nestlevel)
{
AtEOXact_GUC(true, nestlevel);
}
/*
* GetForeignPlan
* Create ForeignScan plan node which implements selected best path
*/
static ForeignScan *
griddbGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
GriddbFdwRelationInfo *fpinfo = (GriddbFdwRelationInfo *) foreignrel->fdw_private;
Index scan_relid = foreignrel->relid;
List *fdw_private;
List *remote_conds = NIL;
List *remote_exprs = NIL;
List *local_exprs = NIL;
List *params_list = NIL;
List *fdw_scan_tlist = NIL;
List *retrieved_attrs;
StringInfoData sql;
ListCell *lc;
int for_update = 0;
int guc_level = 0;
bool has_limit = false;
RangeTblEntry *rte;
elog(DEBUG1, "griddb_fdw: %s", __func__);
/* Decide to execute function pushdown support in the target list. */
fpinfo->is_tlist_func_pushdown = griddb_is_foreign_function_tlist(root, foreignrel, tlist);
/*
* Get FDW private data created by griddbGetForeignUpperPaths(), if any.
*/
if (best_path->fdw_private)
{
has_limit = intVal(list_nth(best_path->fdw_private, FdwPathPrivateHasLimit));
}
/*
* 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 postgresGetForeignPaths. 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 don't strip the RestrictInfo nodes from the
* remote_conds list, since appendWhereClause expects a list of
* RestrictInfos.
*/
if ((foreignrel->reloptkind == RELOPT_BASEREL ||
foreignrel->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 (griddb_is_foreign_expr(root, foreignrel, rinfo->clause, false))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
}
else
{
/*
* 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)
{
scan_relid = 0;
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);
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,
griddb_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 = griddb_build_tlist_to_deparse(foreignrel);
}
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
/* Deparse timestamp as ISO style */
guc_level = griddb_set_transmission_modes();
griddb_deparse_select(&sql, root, foreignrel, remote_conds,
best_path->path.pathkeys,
&retrieved_attrs, ¶ms_list, fdw_scan_tlist, has_limit);
griddb_reset_transmission_modes(guc_level);
griddb_deparse_locking_clause(root, foreignrel, &for_update);
if (foreignrel->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 = 1;
}
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match order in enum FdwScanPrivateIndex.
*/
fdw_private = list_make4(makeString(sql.data),
remote_conds,
retrieved_attrs,
makeInteger(for_update));
fdw_private = lappend(fdw_private, fdw_scan_tlist);
if IS_UPPER_REL
(foreignrel)
{
rte = planner_rt_fetch(((GriddbFdwRelationInfo *) ((RelOptInfo *) foreignrel)->fdw_private)->outerrel->relid, root);
}
else
{
rte = planner_rt_fetch(foreignrel->relid, root);
}
fdw_private = lappend(fdw_private, rte);