Repository navigation
Expand file tree
/
Copy pathgriddb_fdw.c
More file actions
3303 lines (2808 loc) · 90 KB
/
Copy pathgriddb_fdw.c
File metadata and controls
3303 lines (2808 loc) · 90 KB
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) 2018, 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 "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"
#include "optimizer/cost.h"
#include "optimizer/paths.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "storage/ipc.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/datum.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"
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,
};
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ModifyTable node referencing a postgres_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
};
typedef struct GridDBFdwFieldInfo
{
size_t column_count; /* column count */
GSChar **column_names; /* column name */
GSType *column_types; /* column type */
} GridDBFdwFieldInfo;
/* This structure is used for passing data from the scan to the modify */
typedef struct GridDBFdwScanModifyRelay
{
GSRowSet *row_set; /* result set */
GSRow *row; /* row for the update */
GridDBFdwFieldInfo field_info; /* column information */
Datum rowkey_val; /* rowkey the cursor is pointing */
} GridDBFdwScanModifyRelay;
/*
* 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 */
/* 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 */
/* for storing result tuples */
int32_t num_tuples; /* # of tuples in array */
unsigned int cursor; /* result set cursor pointing current index */
} 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 */
Datum **target_values; /* update or delete target row information */
uint64_t num_target; /* # of stored modified row */
uint64_t max_target; /* # of storable modified row */
CmdType operation; /* INSERT, UPDATE, or DELETE */
} GridDBFdwModifyState;
/*
* 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.
*/
static
#ifdef WIN32
__declspec(thread)
#else
__thread
#endif
GridDBFdwScanModifyRelay griddb_sm_share;
/*
* SQL functions
*/
extern Datum griddb_fdw_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(griddb_fdw_handler);
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);
static void griddbAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
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);
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);
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);
/*
* 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,
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 GSTimestamp griddb_convert_pg2gs_timestamp(Timestamp dt);
static Datum griddb_make_datum_from_row(GSRow * row, int32_t attid,
GSType gs_type, Oid pg_type);
static void griddb_execute_and_fetch(ForeignScanState *node);
static void griddb_find_junk_attno(GridDBFdwModifyState * fmstate, List *targetlist);
static int (*griddb_get_comparator(GSType gs_type)) (const void *, const void *);
static void griddb_modify_target_init(GridDBFdwModifyState * fmstate);
static void griddb_modify_target_expand(GridDBFdwModifyState * fmstate);
static void griddb_modify_target_fini(GridDBFdwModifyState * fmstate);
static void griddb_modify_target_insert(GridDBFdwModifyState * fmstate,
TupleTableSlot *slot, TupleTableSlot *planSlot,
GridDBFdwFieldInfo * field_info);
static void griddb_modify_target_sort(GridDBFdwModifyState * fmstate,
GridDBFdwFieldInfo * field_info);
static void griddb_judge_bulk_mode(GridDBFdwModifyState * fmstate, TupleTableSlot *planSlot);
static void griddb_modify_targets_apply(GridDBFdwModifyState * fmstate, GridDBFdwFieldInfo * field_info);
static void griddb_set_row_field(GSRow * row, Datum value, GSType gs_type, int pindex);
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);
void
_PG_init()
{
on_proc_exit(&griddb_fdw_exit, PointerGetDatum(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_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;
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;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = griddbImportForeignSchema;
/* Not support functions for join push-down */
routine->GetForeignJoinPaths = NULL;
PG_RETURN_POINTER(routine);
}
/*
* 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;
/*
* We use PgFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo =
(GriddbFdwRelationInfo *) palloc0(sizeof(GriddbFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/* 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;
/*
* 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;
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
{
/*
* 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 (baserel->pages == 0 && baserel->tuples == 0)
{
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);
}
}
/*
* 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;
/*
* 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,
NULL, /* default pathtarget */
fpinfo->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NULL, /* no extra plan */
NIL); /* no fdw_private list */
add_path(baserel, (Path *) path);
/*
* 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")));
}
/*
* 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 *retrieved_attrs;
StringInfoData sql;
ListCell *lc;
int for_update = 0;
/*
* 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.
*/
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 (is_foreign_expr(root, foreignrel, rinfo->clause))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
griddb_deparse_select(&sql, root, foreignrel, remote_conds,
best_path->path.pathkeys,
&retrieved_attrs, ¶ms_list);
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));
/*
* Create the ForeignScan node for the given relation.
*
* 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,
NULL,
remote_exprs,
outer_plan);
}
/*
* BeginForeignScan
* called during executor startup. perform any initialization
* needed, but not start the actual scan.
*/
static void
griddbBeginForeignScan(ForeignScanState *node, int eflags)
{
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
GridDBFdwScanState *fsstate = NULL;
RangeTblEntry *rte;
Oid userid;
ForeignTable *table;
UserMapping *user;
int rtindex;
int for_update;
/*
* Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
*/
if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
return;
/*
* We'll save private state in node->fdw_state.
*/
fsstate = (GridDBFdwScanState *) palloc0(sizeof(GridDBFdwScanState));
node->fdw_state = (void *) fsstate;
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does. In case of a join, use the lowest-numbered
* member RTE as a representative; we would get the same result from any.
*/
if (fsplan->scan.scanrelid > 0)
rtindex = fsplan->scan.scanrelid;
else
rtindex = bms_next_member(fsplan->fs_relids, -1);
rte = rt_fetch(rtindex, estate->es_range_table);
userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
/* Get info about foreign table. */
table = GetForeignTable(rte->relid);
user = GetUserMapping(userid, table->serverid);
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
fsstate->store = griddb_get_connection(user, false,
RelationGetRelid(node->ss.ss_currentRelation));
fsstate->cont_name = get_rel_name(rte->relid);
fsstate->cont = griddb_get_container(user, rte->relid, fsstate->store);
fsstate->query = strVal(list_nth(fsplan->fdw_private,
FdwScanPrivateSelectSql));
fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
FdwScanPrivateRetrievedAttrs);
for_update = intVal(list_nth(fsplan->fdw_private,
FdwScanPrivateForUpdate));
fsstate->for_update = for_update ? GS_TRUE : GS_FALSE;
fsstate->row_set = NULL;
fsstate->row = NULL;
fsstate->num_tuples = 0;
fsstate->cursor = 0;
/*
* Get info we'll need for converting data fetched from the foreign server
* into local representation and error reporting during that process.
*/
if (fsplan->scan.scanrelid > 0)
{
fsstate->rel = node->ss.ss_currentRelation;
fsstate->tupdesc = RelationGetDescr(fsstate->rel);
}
else
{
fsstate->rel = NULL;
fsstate->tupdesc = node->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
}
griddb_execute_and_fetch(node);
}
/*
* IterateForeignScan
* Retrieve next row from the result set, or clear tuple slot to indicate
* EOF.
* Fetch one row from the foreign source, returning it in a tuple table slot
* (the node's ScanTupleSlot should be used for this purpose).
* Return NULL if no more rows are available.
*/
static TupleTableSlot *
griddbIterateForeignScan(ForeignScanState *node)
{
GridDBFdwScanState *fsstate = (GridDBFdwScanState *) node->fdw_state;
TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
memset(tupleSlot->tts_values, 0, sizeof(Datum) * tupleDescriptor->natts);
memset(tupleSlot->tts_isnull, true, sizeof(bool) * tupleDescriptor->natts);
ExecClearTuple(tupleSlot);
/*
* Return the next tuple.
*/
if (fsstate->cursor < fsstate->num_tuples)
{
GSResult ret = GS_RESULT_OK;
ListCell *lc = NULL;
GSType *column_types = fsstate->field_info.column_types;
Assert(gsHasNextRow(fsstate->row_set) == GS_TRUE);
ret = gsGetNextRow(fsstate->row_set, fsstate->row);
if (!GS_SUCCEEDED(ret))
griddb_REPORT_ERROR(ERROR, ret, fsstate->row_set);
/* Construct tuple slot */
foreach(lc, fsstate->retrieved_attrs)
{
int attnum = lfirst_int(lc);
if (attnum > 0)
{
Oid pgtype;
Relation rel = fsstate->rel;
TupleDesc tupdesc;
if (rel)
tupdesc = RelationGetDescr(rel);
else
tupdesc = fsstate->tupdesc;
pgtype = tupdesc->attrs[attnum - 1]->atttypid;
tupleSlot->tts_values[attnum - 1] =
griddb_make_datum_from_row(fsstate->row, attnum - 1,
column_types[attnum - 1],
pgtype);
}
tupleSlot->tts_isnull[attnum - 1] = false;
}
ExecStoreVirtualTuple(tupleSlot);
fsstate->cursor++;
}
/* Memorize rowkey value which the cursor is pointing. */
if (fsstate->for_update)
griddb_sm_share.rowkey_val = tupleSlot->tts_values[ROWKEY_ATTNO - 1];
return tupleSlot;
}
/*
* ReScanForeignScan
* Restart the scan from the beginning
*/
static void
griddbReScanForeignScan(ForeignScanState *node)
{
GridDBFdwScanState *fsstate = (GridDBFdwScanState *) node->fdw_state;
/* If we haven't fetched the result set yet, nothing to do. */
if (fsstate->row_set == NULL)
return;
fsstate->cursor = 0;
griddb_free_column_info(&fsstate->field_info);
gsCloseRow(&fsstate->row);
gsCloseRowSet(&fsstate->row_set);
/* Execute TQL again */
griddb_execute_and_fetch(node);
}
/*
* EndForeignScan
* End the scan and release resources.
*/
static void
griddbEndForeignScan(ForeignScanState *node)
{
GridDBFdwScanState *fsstate = (GridDBFdwScanState *) node->fdw_state;
/* if fsstate is NULL, we are in EXPLAIN; nothing to do */
if (fsstate == NULL)
return;
Assert(fsstate->cursor == fsstate->num_tuples);
gsCloseRow(&fsstate->row);
gsCloseRowSet(&fsstate->row_set);
griddb_free_column_info(&fsstate->field_info);
if (fsstate->for_update)
{
griddb_free_column_info(&griddb_sm_share.field_info);
memset(&griddb_sm_share, 0, sizeof(GridDBFdwScanModifyRelay));
}
/* Release remote connection */
griddb_release_connection(fsstate->store);
fsstate->store = NULL;
/* MemoryContexts will be deleted automatically. */
}
/*
* AddForeignUpdateTargets
* Add resjunk column(s) needed for update/delete on a foreign table
* We add first column forcibly. So we are adding that into target list.
*/
static void
griddbAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation)
{
Var *var = NULL;
const char *attrname = NULL;
TargetEntry *tle = NULL;
/*
* What we need is the rowkey which is the first column
*/
Form_pg_attribute attr =
RelationGetDescr(target_relation)->attrs[ROWKEY_ATTNO - 1];
/* Make a Var representing the desired value */
var = makeVar(parsetree->resultRelation,
ROWKEY_ATTNO,
attr->atttypid,
attr->atttypmod,
attr->attcollation,
0);
/* Wrap it in a TLE with the right name ... */
attrname = NameStr(attr->attname);
tle = makeTargetEntry((Expr *) var,
list_length(parsetree->targetList) + 1,
pstrdup(attrname),
true);
/* ... and add it to the query's targetlist */
parsetree->targetList = lappend(parsetree->targetList, tle);
}
/*
* postgresPlanForeignModify
* Plan an insert/update/delete operation on a foreign table
*/
static List *
griddbPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index)
{
CmdType operation = plan->operation;
RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
Relation rel;
List *targetAttrs = NIL;
/*
* Core code already has some lock on each rel being planned, so we can
* use NoLock here.
*/
rel = heap_open(rte->relid, NoLock);
/*
* In an INSERT, we transmit all columns that are defined in the foreign
* table.
*/
if (operation == CMD_INSERT)
{
TupleDesc tupdesc = RelationGetDescr(rel);
int attnum;
for (attnum = 1; attnum <= tupdesc->natts; attnum++)
{
Form_pg_attribute attr = tupdesc->attrs[attnum - 1];
if (!attr->attisdropped)
targetAttrs = lappend_int(targetAttrs, attnum);
}
}
/*
* In an UPDATE, we transmit only columns that were explicitly targets of
* the UPDATE, so as to avoid unnecessary data transmission. (We can't do
* that for INSERT since we would miss sending default values for columns
* not listed in the source statement.)
*/
else if (operation == CMD_UPDATE)
{
int col;
col = -1;
while ((col = bms_next_member(rte->updatedCols, col)) >= 0)
{
/* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
if (attno <= InvalidAttrNumber) /* shouldn't happen */
elog(ERROR, "system-column update is not supported");
if (attno == ROWKEY_ATTNO)
elog(ERROR, "rowkey-column update is not supported");
targetAttrs = lappend_int(targetAttrs, attno);
}
}
if (operation == CMD_UPDATE || operation == CMD_DELETE)
{
List *options;
ListCell *lc;
bool hasRowKey = false;
/*
* Check rowkey option is set. This option is required to modify
* table. 1st column is rowkey column because of GridDB's
* specification.
*/
options = GetForeignColumnOptions(rte->relid, ROWKEY_ATTNO);
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if ((strcmp(def->defname, OPTION_ROWKEY) == 0) && (defGetBoolean(def) == true))
hasRowKey = true;
}
if (!hasRowKey)
elog(ERROR, "Cannot modify a table if rowkey is not assigned to the 1st column.");
}