-
Notifications
You must be signed in to change notification settings - Fork 6
/
dynamodb_impl.cpp
1854 lines (1633 loc) · 55.2 KB
/
dynamodb_impl.cpp
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
/*-------------------------------------------------------------------------
*
* dynamodb_impl.cpp
* Implementation for dynamodb_fdw
*
* Portions Copyright (c) 2021, TOSHIBA CORPORATION
*
* IDENTIFICATION
* contrib/dynamodb_fdw/dynamodb_impl.cpp
*
*-------------------------------------------------------------------------
*/
#include "dynamodb_fdw.hpp"
#include "dynamodb_query.hpp"
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeValue.h>
#include <aws/dynamodb/model/ExecuteStatementRequest.h>
extern "C"
{
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_class.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/appendinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#if (PG_VERSION_NUM >= 130010 && PG_VERSION_NUM < 140000) || \
(PG_VERSION_NUM >= 140007 && PG_VERSION_NUM < 150000) || \
(PG_VERSION_NUM >= 150003)
#include "optimizer/inherit.h"
#endif
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/float.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
#include "nodes/print.h"
}
using namespace Aws::DynamoDB;
/* 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 DYNAMODB_ALLOCATION_TAG "DYNAMODB_ALLOCATION_TAG"
/*
* 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,
/* Integer list of attribute numbers retrieved by the SELECT */
FdwScanPrivateRetrievedAttrs
};
/*
* 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)
* 3) Boolean flag showing if the remote query has a RETURNING clause
* 4) Integer list of attribute numbers retrieved by RETURNING, if any
*/
enum FdwModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwModifyPrivateUpdateSql,
/* Integer list of target attribute numbers for INSERT/UPDATE */
FdwModifyPrivateTargetAttnums,
/* has-returning flag (as a Boolean node) */
FdwModifyPrivateHasReturning,
/* Integer list of attribute numbers retrieved by RETURNING */
FdwModifyPrivateRetrievedAttrs
};
/* Struct for extra information passed to estimate_path_cost_size() */
typedef struct
{
PathTarget *target;
double limit_tuples;
int64 count_est;
int64 offset_est;
} DynamoDBFdwPathExtraData;
/*
* Execution state of a foreign scan using dynamodb_fdw.
*/
typedef struct DynamoDBFdwScanState
{
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 */
Aws::DynamoDB::DynamoDBClient *conn; /* connection for the scan */
bool cursor_exists; /* have we created the cursor? */
/* for storing result tuples */
HeapTuple tuples; /* array of currently-retrieved tuples */
/* batch-level state, for optimizing rewinds and avoiding useless fetch */
bool eof_reached; /* true if last fetch reached EOF */
/* working memory contexts */
MemoryContext batch_cxt; /* context holding current batch of tuples */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
/* fetch more data */
char *next_token; /* next token for next request to retrieve more data */
bool next_fetch_ready; /* true if DynamoDB FDW ready for next fetch */
unsigned int row_index; /* the index of current processing item in the result set */
bool first_fetch; /* true if the first time data is fetched */
unsigned int num_rows; /* number of rows in data set */
std::shared_ptr<Aws::DynamoDB::Model::ExecuteStatementResult> result; /* contains the result of query */
} DynamoDBFdwScanState;
/*
* Execution state of a foreign insert/update/delete operation.
*/
typedef struct DynamoDBFdwModifyState
{
Relation rel; /* relcache entry for the foreign table */
/* for remote query execution */
Aws::DynamoDB::DynamoDBClient *conn; /* connection for the scan */
char *p_name; /* name of prepared statement, if created */
/* extracted fdw_private data */
char *query; /* text of INSERT/UPDATE/DELETE command */
List *target_attrs; /* list of target attribute numbers */
bool has_returning; /* is there a RETURNING clause? */
List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
/* working memory context */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
/* for update row movement if subplan result rel */
struct DynamoDBFdwModifyState *aux_fmstate; /* foreign-insert state, if
* created */
AttrNumber *junk_idx; /* indexes of key columns */
} DynamoDBFdwModifyState;
/*
* Helper functions
*/
static void dynamodb_estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *foreignrel,
List *param_join_conds,
List *pathkeys,
DynamoDBFdwPathExtraData *fpextra,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost);
static void create_cursor(ForeignScanState *node);
extern DynamoDBFdwModifyState *dynamodb_create_foreign_modify(EState *estate,
RangeTblEntry *rte,
ResultRelInfo *resultRelInfo,
CmdType operation,
Plan *subplan,
char *query,
List *target_attrs,
bool has_returning,
List *retrieved_attrs);
static void fetch_more_data(ForeignScanState *node);
static HeapTuple make_tuple_from_result_row(std::shared_ptr<Aws::DynamoDB::Model::ExecuteStatementResult> result,
unsigned int *row_index,
Relation rel,
List *retrieved_attrs,
ForeignScanState *fsstate,
MemoryContext temp_context);
static void dynamodb_store_returning_result(DynamoDBFdwModifyState *fmstate,
TupleTableSlot *slot,
std::shared_ptr<Aws::DynamoDB::Model::ExecuteStatementResult> result);
static List *dynamodb_get_key_names(TupleDesc tupdesc, Oid foreignTableId, char *partition_key,
char *sort_key);
/*
* dynamodbGetForeignRelSize
* 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.
*/
extern "C" void
dynamodbGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
DynamoDBFdwRelationInfo *fpinfo;
ListCell *lc;
/*
* We use DynamoDBFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo = (DynamoDBFdwRelationInfo *) palloc0(sizeof(DynamoDBFdwRelationInfo));
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);
/*
* Extract user-settable option values.
*/
fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST;
fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST;
fpinfo->shippable_extensions = NIL;
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
dynamodb_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 = lfirst_node(RestrictInfo, 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);
cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
/*
* Set # of retrieved rows and cached relation costs to some negative
* value, so that we can detect when they are set to some sensible values,
* during one (usually the first) of the calls to dynamodb_estimate_path_cost_size.
*/
fpinfo->retrieved_rows = -1;
fpinfo->rel_startup_cost = -1;
fpinfo->rel_total_cost = -1;
/*
* If the foreign table has never been ANALYZEd, it will have
* reltuples < 0, meaning "unknown". 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 (baserel->tuples < 0)
#else
if (baserel->pages == 0 && 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. */
dynamodb_estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost, &fpinfo->total_cost);
}
/*
* dynamodb_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 or an upper
* relation containing 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.
* fpextra specifies additional post-scan/join-processing steps such as the
* final sort and the LIMIT restriction.
*
* The function returns the cost and size estimates in p_rows, p_width,
* p_startup_cost and p_total_cost variables.
*/
static void
dynamodb_estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *foreignrel,
List *param_join_conds,
List *pathkeys,
DynamoDBFdwPathExtraData *fpextra,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost)
{
DynamoDBFdwRelationInfo *fpinfo = (DynamoDBFdwRelationInfo *) foreignrel->fdw_private;
double rows;
double retrieved_rows;
int width;
Cost startup_cost;
Cost total_cost;
Cost run_cost = 0;
/* Make sure the core code has set up the relation's reltarget */
Assert(foreignrel->reltarget);
/*
* We don't support join conditions in this mode (hence, no
* parameterized paths can be made).
*/
Assert(param_join_conds == NIL);
/*
* We will come here again and again with different set of pathkeys or
* additional post-scan/join-processing steps that caller wants to
* cost. We don't need to calculate the cost/size estimates for the
* underlying scan, join, or grouping each time. Instead, use those
* estimates if we have cached them already.
*/
if (fpinfo->rel_startup_cost >= 0 && fpinfo->rel_total_cost >= 0)
{
#if PG_VERSION_NUM >= 140000
Assert(fpinfo->retrieved_rows >= 0);
#else
Assert(fpinfo->retrieved_rows >= 1);
#endif
rows = fpinfo->rows;
retrieved_rows = fpinfo->retrieved_rows;
width = fpinfo->width;
startup_cost = fpinfo->rel_startup_cost;
run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
}
else
{
Cost cpu_per_tuple;
/* Use rows/width estimates made by set_baserel_size_estimates. */
rows = foreignrel->rows;
width = foreignrel->reltarget->width;
/*
* Back into an estimate of the number of retrieved rows. Just in
* case this is nuts, clamp to at most foreignrel->tuples.
*/
retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
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;
/* Add in tlist eval cost for each output row */
startup_cost += foreignrel->reltarget->cost.startup;
run_cost += foreignrel->reltarget->cost.per_tuple * rows;
}
/*
* 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 retrieved rows and cost estimates for scans, joins, or
* groupings without any parameterization, pathkeys, or additional
* post-scan/join-processing steps, before adding the costs for
* transferring data from the foreign server. These estimates are useful
* for costing remote joins involving this relation or costing other
* remote operations on this relation such as remote sorts and remote
* LIMIT restrictions, when the costs can not be obtained from the foreign
* server. This function will be called at least once for every foreign
* relation without any parameterization, pathkeys, or additional
* post-scan/join-processing steps.
*/
if (pathkeys == NIL && param_join_conds == NIL && fpextra == NULL)
{
fpinfo->retrieved_rows = retrieved_rows;
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;
}
/*
* dynamodbGetForeignPaths
* Create possible scan paths for a scan on the foreign table
*/
extern "C" void
dynamodbGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
DynamoDBFdwRelationInfo *fpinfo = (DynamoDBFdwRelationInfo *) 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.
*
* Although this path uses no join clauses, it could still have required
* parameterization due to LATERAL refs in its tlist.
*/
path = create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
fpinfo->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
baserel->lateral_relids,
NULL, /* no extra plan */
NIL); /* no fdw_private list */
add_path(baserel, (Path *) path);
}
/*
* dynamodbGetForeignPlan
* Create ForeignScan plan node which implements selected best path
*/
extern "C" ForeignScan *
dynamodbGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
DynamoDBFdwRelationInfo *fpinfo = (DynamoDBFdwRelationInfo *) foreignrel->fdw_private;
Index scan_relid;
List *fdw_private;
List *remote_exprs = NIL;
List *local_exprs = NIL;
List *fdw_scan_tlist = NIL;
List *fdw_recheck_quals = NIL;
List *retrieved_attrs = NIL;
StringInfoData sql;
bool tlist_has_json_arrow_op;
ListCell *lc;
/* DynamoDB FDW only support simple relation */
Assert(IS_SIMPLE_REL(foreignrel));
/* Decide to execute Json arrow operator support in the target list. */
tlist_has_json_arrow_op = dynamodb_tlist_has_json_arrow_op(root, foreignrel, tlist);
/*
* For base relations, set scan_relid as the relid of the relation.
*/
scan_relid = foreignrel->relid;
/*
* In a base-relation scan, we must apply the given scan_clauses.
*
* 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 found in fpinfo->remote_conds and fpinfo->local_conds.
*
* This code must match "extract_actual_clauses(scan_clauses, false)"
* except for the additional decision about remote versus local
* execution.
*/
foreach(lc, scan_clauses)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
/* Ignore any pseudoconstants, they're dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->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 (dynamodb_is_foreign_expr(root, foreignrel, rinfo->clause))
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;
/*
* Build the list of columns that contain Jsonb arrow operator
* to be fetched from the foreign server.
*/
if (tlist_has_json_arrow_op == true)
{
List *document_path_list = NIL;
if (tlist)
fdw_scan_tlist = list_copy(tlist);
else
fdw_scan_tlist = add_to_flat_tlist(fdw_scan_tlist, foreignrel->reltarget->exprs);
foreach(lc, local_exprs)
{
Node *node = (Node *)lfirst(lc);
fdw_scan_tlist = add_to_flat_tlist(fdw_scan_tlist,
pull_var_clause((Node *) node,
PVC_RECURSE_PLACEHOLDERS));
}
foreach(lc, remote_exprs)
{
Node *node = (Node *)lfirst(lc);
fdw_scan_tlist = add_to_flat_tlist(fdw_scan_tlist,
pull_var_clause((Node *) node,
PVC_RECURSE_PLACEHOLDERS));
}
/*
* DynamoDB does not support overlap document path.
* For example: SELECT friends.login.lastsignin, friends.login, friends.
* Therefore, do not push down arrow operators in that case.
*/
foreach(lc, fdw_scan_tlist)
{
StringInfoData document_path;
Expr *expr = ((TargetEntry *)lfirst(lc))->expr;
ListCell *attlc;
initStringInfo(&document_path);
dynamodb_get_document_path(&document_path, root, foreignrel, expr);
foreach(attlc, document_path_list)
{
char *target_name = strVal(lfirst(attlc));
if (strstr(target_name, document_path.data) != NULL ||
strstr(document_path.data, target_name) != NULL)
{
fdw_scan_tlist = NULL;
tlist_has_json_arrow_op = false;
break;
}
}
document_path_list = lappend(document_path_list, makeString(document_path.data));
}
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
dynamodb_deparse_select_stmt_for_rel(&sql, root, foreignrel, fdw_scan_tlist,
remote_exprs, best_path->path.pathkeys,
&retrieved_attrs);
/*
* 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_make2(makeString(sql.data),
retrieved_attrs);
/*
* 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,
NULL,
fdw_private,
fdw_scan_tlist,
fdw_recheck_quals,
outer_plan);
}
#if PG_VERSION_NUM >= 140000
/*
* Construct a tuple descriptor for the scan tuples handled by a foreign join.
*/
static TupleDesc
dynamodb_get_tupdesc_for_join_scan_tuples(ForeignScanState *node)
{
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
TupleDesc tupdesc;
/*
* The core code has already set up a scan tuple slot based on
* fsplan->fdw_scan_tlist, and this slot's tupdesc is mostly good enough,
* but there's one case where it isn't. If we have any whole-row row
* identifier Vars, they may have vartype RECORD, and we need to replace
* that with the associated table's actual composite type. This ensures
* that when we read those ROW() expression values from the remote server,
* we can convert them to a composite type the local server knows.
*/
tupdesc = CreateTupleDescCopy(node->ss.ss_ScanTupleSlot->tts_tupleDescriptor);
for (int i = 0; i < tupdesc->natts; i++)
{
Form_pg_attribute att = TupleDescAttr(tupdesc, i);
Var *var;
RangeTblEntry *rte;
Oid reltype;
/* Nothing to do if it's not a generic RECORD attribute */
if (att->atttypid != RECORDOID || att->atttypmod >= 0)
continue;
/*
* If we can't identify the referenced table, do nothing. This'll
* likely lead to failure later, but perhaps we can muddle through.
*/
var = (Var *) list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
i)->expr;
if (!IsA(var, Var) || var->varattno != 0)
continue;
rte = (RangeTblEntry *) list_nth(estate->es_range_table, var->varno - 1);
if (rte->rtekind != RTE_RELATION)
continue;
reltype = get_rel_type_id(rte->relid);
if (!OidIsValid(reltype))
continue;
att->atttypid = reltype;
/* shouldn't need to change anything else */
}
return tupdesc;
}
#endif
/*
* dynamodbBeginForeignScan
* Initiate an executor scan of a foreign DynamoDB table.
*/
extern "C" void
dynamodbBeginForeignScan(ForeignScanState *node, int eflags)
{
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
DynamoDBFdwScanState *fsstate;
RangeTblEntry *rte;
Oid userid;
ForeignTable *table;
UserMapping *user;
int rtindex;
/*
* 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 = (DynamoDBFdwScanState *) palloc0(sizeof(DynamoDBFdwScanState));
node->fdw_state = (void *) fsstate;
#if (PG_VERSION_NUM >= 160000)
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckPermissions() does.
*/
userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
if (fsplan->scan.scanrelid > 0)
rtindex = fsplan->scan.scanrelid;
else
rtindex = bms_next_member(fsplan->fs_base_relids, -1);
rte = exec_rt_fetch(rtindex, estate);
#else
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does. In case of a join or aggregate, 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 = exec_rt_fetch(rtindex, estate);
userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
#endif
/* 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->conn = dynamodb_get_connection(user);
/* Init data for cursor_exists as false */
fsstate->cursor_exists = false;
/* Get private info created by planner functions. */
fsstate->query = strVal(list_nth(fsplan->fdw_private,
FdwScanPrivateSelectSql));
fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
FdwScanPrivateRetrievedAttrs);
/* Create contexts for batches of tuples and per-tuple temp workspace. */
fsstate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt,
"dynamodb_fdw tuple data",
ALLOCSET_DEFAULT_SIZES);
fsstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
"dynamodb_fdw temporary data",
ALLOCSET_SMALL_SIZES);
/*
* 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;
#if (PG_VERSION_NUM >= 140000)
fsstate->tupdesc = dynamodb_get_tupdesc_for_join_scan_tuples(node);
#else
fsstate->tupdesc = node->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
#endif
}
}
/*
* dynamodbIterateForeignScan
* Retrieve next row from the result set, or clear tuple slot to indicate
* EOF.
*/
extern "C" TupleTableSlot *
dynamodbIterateForeignScan(ForeignScanState *node)
{
DynamoDBFdwScanState *fsstate = (DynamoDBFdwScanState *) node->fdw_state;
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
/*
* If this is the first call after Begin or ReScan, we need to create the
* cursor on the remote side.
*/
if (!fsstate->cursor_exists)
create_cursor(node);
fsstate->tuples = NULL;
/* No point in another fetch if we already detected EOF, though. */
if (!fsstate->eof_reached)
fetch_more_data(node);
/* If we didn't get any tuples, must be end of data. */
if (fsstate->tuples == NULL)
return ExecClearTuple(slot);
/*
* Return the next tuple.
*/
ExecStoreHeapTuple(fsstate->tuples, slot, false);
return slot;
}
/*
* dynamodbReScanForeignScan
* Restart the scan.
*/
extern "C" void
dynamodbReScanForeignScan(ForeignScanState *node)
{
DynamoDBFdwScanState *fsstate = (DynamoDBFdwScanState *) node->fdw_state;
/* If we haven't created the cursor yet, nothing to do. */
if (!fsstate->cursor_exists)
return;
/* Now force a fresh FETCH. */
fsstate->tuples = NULL;
fsstate->eof_reached = false;
fsstate->first_fetch = true;
fsstate->next_token = NULL;
fsstate->next_fetch_ready = true;
fsstate->row_index = 0;
}
/*
* dynamodbEndForeignScan
* Finish scanning foreign table and dispose objects used for this scan
*/
extern "C" void
dynamodbEndForeignScan(ForeignScanState *node)
{
DynamoDBFdwScanState *fsstate = (DynamoDBFdwScanState *) node->fdw_state;
/* if fsstate is NULL, we are in EXPLAIN; nothing to do */
if (fsstate == NULL)
return;
/* Release remote connection */
dynamodb_release_connection(fsstate->conn);
fsstate->conn = NULL;
/* MemoryContexts will be deleted automatically. */
}
extern "C" void
dynamodbAddForeignUpdateTargets(
#if (PG_VERSION_NUM >= 140000)
PlannerInfo *root,
Index rtindex,
#else
Query *parsetree,
#endif
RangeTblEntry *target_rte,
Relation target_relation)
{
Oid relid = RelationGetRelid(target_relation);
dynamodb_opt *opt;
opt = dynamodb_get_options(relid);
char *partition_key = opt->svr_partition_key;
char *sort_key = opt -> svr_sort_key;
TupleDesc tupdesc = target_relation->rd_att;
if (IS_KEY_EMPTY(partition_key))
elog(ERROR, "dynamodb_fdw: The partition_key option has not been set");
for (int i = 0; i < tupdesc->natts; ++i)
{
Form_pg_attribute att = TupleDescAttr(tupdesc, i);
Var *var;
char *attrname = NameStr(att->attname);
if (strcmp(partition_key, attrname) == 0 ||
(!IS_KEY_EMPTY(sort_key) && strcmp(sort_key, attrname) == 0))
{
#if PG_VERSION_NUM < 140000
Index rtindex = parsetree->resultRelation;
TargetEntry *tle;
#endif
/* Make a Var representing the desired value */
var = makeVar(rtindex,
att->attnum,
att->atttypid,
att->atttypmod,
att->attcollation,
0);
#if PG_VERSION_NUM >= 140000
/* Register it as a row-identity column needed by this target rel */
add_row_identity_var(root, var, rtindex, pstrdup(NameStr(att->attname)));
#else
tle = makeTargetEntry((Expr *) var,
list_length(parsetree->targetList) + 1,
pstrdup(NameStr(att->attname)), true);
/* ... and add it to the query's targetlist */
parsetree->targetList = lappend(parsetree->targetList, tle);
#endif
}
}
}
/*
* dynamodbPlanForeignModify
* Plan an insert/update/delete operation on a foreign table
*/
extern "C" List *
dynamodbPlanForeignModify(PlannerInfo *root, ModifyTable *plan, Index resultRelation, int subplan_index)
{
CmdType operation = plan->operation;
RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
Relation rel;
StringInfoData sql;
List *targetAttrs = NIL;
List *withCheckOptionList = NIL;
List *returningList = NIL;
List *retrieved_attrs = NIL;
bool trigger_update = false;
List *condAttr = NULL;
Oid foreignTableId;
TupleDesc tupdesc;
dynamodb_opt *opt;
char *partition_key;
char *sort_key;
initStringInfo(&sql);
/*
* Core code already has some lock on each rel being planned, so we can
* use NoLock here.
*/
rel = table_open(rte->relid, NoLock);
foreignTableId = RelationGetRelid(rel);
tupdesc = RelationGetDescr(rel);