-
Notifications
You must be signed in to change notification settings - Fork 6
/
deparse.cpp
2581 lines (2295 loc) · 66.4 KB
/
deparse.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
/*-------------------------------------------------------------------------
*
* deparse.cpp
* Query deparser for dynamodb_fdw
*
* This file includes functions that examine query WHERE clauses to see
* whether they're safe to send to the remote server for execution, as
* well as functions to construct the query text to be sent. The latter
* functionality is annoyingly duplicative of ruleutils.c, but there are
* enough special considerations that it seems best to keep this separate.
* One saving grace is that we only need deparse logic for node types that
* we consider safe to send.
*
* We assume that the remote session's search_path is exactly "pg_catalog",
* and thus we need schema-qualify all and only names outside pg_catalog.
*
* We do not consider that it is ever safe to send COLLATE expressions to
* the remote server: it might not have the same collation names we do.
* (Later we might consider it safe to send COLLATE "C", but even that would
* fail on old remote servers.) An expression is considered safe to send
* only if all operator/function input collations used in it are traceable to
* Var(s) of the foreign table. That implies that if the remote server gets
* a different answer than we do, the foreign table's columns are not marked
* with collations that match the remote table's columns, which we can
* consider to be user error.
*
* Portions Copyright (c) 2021, TOSHIBA CORPORATION
*
* IDENTIFICATION
* contrib/dynamodb_fdw/deparse.cpp
*
*-------------------------------------------------------------------------
*/
#include "dynamodb_fdw.hpp"
extern "C"
{
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_aggregate.h"
#if PG_VERSION_NUM >= 160000
#include "catalog/pg_authid.h"
#endif
#include "catalog/pg_collation.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_ts_config.h"
#include "catalog/pg_ts_dict.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "common/keywords.h"
#include "ctype.h"
#include "jansson.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/plannodes.h"
#include "nodes/bitmapset.h"
#include "optimizer/optimizer.h"
#include "optimizer/prep.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
}
/*
* Global context for foreign_expr_walker's search of an expression tree.
*/
typedef struct foreign_glob_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
Relids relids; /* relids of base relations in the underlying
* scan */
} foreign_glob_cxt;
/*
* Local (per-tree-level) context for foreign_expr_walker's search.
* This is concerned with identifying collations used in the expression.
*/
typedef enum
{
FDW_COLLATE_NONE, /* expression is of a noncollatable type, or
* it has default collation that is not
* traceable to a foreign Var */
FDW_COLLATE_SAFE, /* collation derives from a foreign Var */
FDW_COLLATE_UNSAFE /* collation is non-default and derives from
* something other than a foreign Var */
} FDWCollateState;
typedef struct foreign_loc_cxt
{
Oid collation; /* OID of current collation, if any */
FDWCollateState state; /* state of current collation choice */
} foreign_loc_cxt;
/*
* Context for deparseExpr
*/
typedef struct deparse_expr_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
RelOptInfo *scanrel; /* the underlying scan relation. Same as
* foreignrel, when that represents a join or
* a base relation. */
StringInfo buf; /* output buffer to append to */
bool has_arrow; /* True if expression contain arrow operators */
List **attrs_list; /* List of attributes */
} deparse_expr_cxt;
/*
* Struct to pull out attribute name
*/
typedef struct pull_attribute_name_context
{
StringInfo attribute_name; /* The target attribute name */
bool list_appended; /* True if both attribute name
and list number has been
appended into attribute_name*/
PlannerInfo *root; /* The information for planning */
int list_num; /* Number of nested list in the expression*/
} pull_attribute_name_context;
#define REL_ALIAS_PREFIX "r"
/* Handy macro to add relation name qualification */
#define ADD_REL_QUALIFIER(buf, varno) \
appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
#define SUBQUERY_REL_ALIAS_PREFIX "s"
#define SUBQUERY_COL_ALIAS_PREFIX "c"
static const char *compOpName[] =
{
/* Operator name */
"<", /* Less than */
">", /* Greater than */
"<=", /* Less than or equal */
">=", /* Greater than or equal */
"=", /* Equal */
"!=", /* Not equal */
"<>", /* Not equal */
NULL, /* NULL */
};
static const char *jsonOpName[] =
{
/* Operator name */
"->", /* json arrow operator */
"->>", /* json arrow operator */
NULL, /* NULL */
};
/*
* Functions to determine whether an expression can be evaluated safely on
* remote server.
*/
static bool dynamodb_foreign_expr_walker(Node *node,
foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt);
/*
* Functions to construct string representation of a node tree.
*/
static void dynamodb_deparse_target_list(StringInfo buf,
RangeTblEntry *rte,
Index rtindex,
Relation rel,
bool is_returning,
Bitmapset *attrs_used,
bool qualify_col,
List **retrieved_attrs);
static void dynamodb_deparse_column_ref(StringInfo buf, int varno,
int varattno, RangeTblEntry *rte,
List **retrieved_attrs,
bool need_store_attr);
static void dynamodb_deparse_relation(StringInfo buf, Relation rel);
static void dynamodb_deparse_expr(Expr *node, deparse_expr_cxt *context);
static void dynamodb_deparse_var(Var *node, deparse_expr_cxt *context);
static void dynamodb_deparse_const(Const *node, deparse_expr_cxt *context);
static void dynamodb_deparse_func_expr(FuncExpr *node, deparse_expr_cxt *context);
static void dynamodb_deparse_op_expr(OpExpr *node, deparse_expr_cxt *context);
static void dynamodb_deparse_operator_name(StringInfo buf, Form_pg_operator opform);
static void dynamodb_deparse_scalar_array_op_expr(ScalarArrayOpExpr *node,
deparse_expr_cxt *context);
static void dynamodb_deparse_array_expr(ArrayExpr *node, deparse_expr_cxt *context);
static void dynamodb_deparse_bool_expr(BoolExpr *node, deparse_expr_cxt *context);
static void dynamodb_deparse_null_test(NullTest *node, deparse_expr_cxt *context);
static void dynamodb_deparse_from_expr_for_rel(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel);
static void dynamodb_deparse_returning_list(StringInfo buf, RangeTblEntry *rte,
Index rtindex, Relation rel,
bool trig_after_row,
List *withCheckOptionList,
List *returningList,
List **retrieved_attrs,
bool is_delete);
static void dynamodb_deparse_from_expr(List *quals, deparse_expr_cxt *context);
static void dynamodb_deparse_select(List *tlist, List **retrieved_attrs, deparse_expr_cxt *context);
static void dynamodb_append_conditions(List *exprs, deparse_expr_cxt *context);
Form_pg_operator dynamodb_get_operator_expression(Oid oid);
static char *dynamodb_replace_operator(char *in);
DynamoDBOperatorsSupport dynamodb_validate_operator_name(Form_pg_operator opform);
static void dynamodb_store_attr_info(const char *col_name, int varno, List **retrieved_attr);
static void dynamodb_pull_attribute_name_walker(Node *node, pull_attribute_name_context *context);
static char *dynamodb_get_attribute_name(Node *node, PlannerInfo *root);
static char *dynamodb_get_column_name(Oid relid, int varattno);
void dynamodb_get_document_path(StringInfo buf, PlannerInfo *root, RelOptInfo *rel, Expr *expr);
/*
* dynamodb_classify_conditions
*
* Examine each qual clause in input_conds, and classify them into two groups,
* which are returned as two lists:
* - remote_conds contains expressions that can be evaluated remotely
* - local_conds contains expressions that can't be evaluated remotely
*/
void
dynamodb_classify_conditions(PlannerInfo *root,
RelOptInfo *baserel,
List *input_conds,
List **remote_conds,
List **local_conds)
{
ListCell *lc;
*remote_conds = NIL;
*local_conds = NIL;
foreach(lc, input_conds)
{
RestrictInfo *ri = lfirst_node(RestrictInfo, lc);
/*
* DynamoDB does not support condition with a boolean column only
* Example: WHERE c1;
*/
if (nodeTag(ri->clause) == T_Var)
{
*local_conds = lappend(*local_conds, ri);
continue;
}
if (dynamodb_is_foreign_expr(root, baserel, ri->clause))
*remote_conds = lappend(*remote_conds, ri);
else
*local_conds = lappend(*local_conds, ri);
}
}
/*
* dynamodb_quote_identifier
*
* Quote an identifier only if needed.
* When quotes are needed, we palloc the required space; slightly
* space-wasteful but well worth it for notational simplicity.
*/
const char *
dynamodb_quote_identifier(const char *ident)
{
/*
* Can avoid quoting if ident starts with a lowercase letter, a uppercase letter or underscore
* and contains only lowercase letters, uppercase letters, digits, and underscores, *and* is
* not any SQL keyword. Otherwise, supply quotes.
*/
int nquotes = 0;
bool safe;
const char *ptr;
char *result;
char *optr;
/*
* would like to use <ctype.h> macros here, but they might yield unwanted
* locale-specific results...
*/
safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_' || (ident[0] >= 'A' && ident[0] <= 'Z'));
for (ptr = ident; *ptr; ptr++)
{
char ch = *ptr;
if ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
(ch == '_'))
{
/* okay */
}
else
{
safe = false;
if (ch == '"')
nquotes++;
}
}
if (safe)
return ident; /* no change needed */
result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
optr = result;
*optr++ = '"';
for (ptr = ident; *ptr; ptr++)
{
char ch = *ptr;
if (ch == '"')
*optr++ = '"';
*optr++ = ch;
}
*optr++ = '"';
*optr = '\0';
return result;
}
/*
* dynamodb_is_foreign_expr
*
* Returns true if given expr is safe to evaluate on the foreign server.
*/
bool
dynamodb_is_foreign_expr(PlannerInfo *root,
RelOptInfo *baserel,
Expr *expr)
{
foreign_glob_cxt glob_cxt;
foreign_loc_cxt loc_cxt;
/*
* Check that the expression consists of nodes that are safe to execute
* remotely.
*/
glob_cxt.root = root;
glob_cxt.foreignrel = baserel;
/*
* For base relation, use its own relids.
*/
glob_cxt.relids = baserel->relids;
loc_cxt.collation = InvalidOid;
loc_cxt.state = FDW_COLLATE_NONE;
if (!dynamodb_foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt))
return false;
/*
* If the expression has a valid collation that does not arise from a
* foreign var, the expression can not be sent over.
*/
if (loc_cxt.state == FDW_COLLATE_UNSAFE)
return false;
/*
* An expression which includes any mutable functions can't be sent over
* because its result is not stable. For example, sending now() remote
* side could cause confusion from clock offsets. Future versions might
* be able to make this choice with more granularity. (We check this last
* because it requires a lot of expensive catalog lookups.)
*/
if (contain_mutable_functions((Node *) expr))
return false;
/* OK to evaluate on the remote server */
return true;
}
/*
* dynamodb_foreign_expr_walker
*
* Check if expression is safe to execute remotely, and return true if so.
*
* In addition, *outer_cxt is updated with collation information.
*
* We must check that the expression contains only node types we can deparse,
* that all types/functions/operators are safe to send (they are "shippable"),
* and that all collations used in the expression derive from Vars of the
* foreign table. Because of the latter, the logic is pretty close to
* assign_collations_walker() in parse_collate.c, though we can assume here
* that the given expression is valid. Note function mutability is not
* currently considered here.
*/
static bool
dynamodb_foreign_expr_walker(Node *node,
foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt)
{
bool check_type = true;
DynamoDBFdwRelationInfo *fpinfo;
foreign_loc_cxt inner_cxt;
Oid collation;
FDWCollateState state;
/* Need do nothing for empty subexpressions */
if (node == NULL)
return true;
/* May need server info from baserel's fdw_private struct */
fpinfo = (DynamoDBFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private);
/* Set up inner_cxt for possible recursion to child nodes */
inner_cxt.collation = InvalidOid;
inner_cxt.state = FDW_COLLATE_NONE;
switch (nodeTag(node))
{
case T_Var:
{
Var *var = (Var *) node;
/*
* If the Var is from the foreign table, we consider its
* collation (if any) safe to use. If it is from another
* table, we treat its collation the same way as we would a
* Param's collation, ie it's not safe for it to have a
* non-default collation.
*/
if (bms_is_member(var->varno, glob_cxt->relids) &&
var->varlevelsup == 0)
{
/* Var belongs to foreign table */
/*
* System columns other than ctid should not be sent to
* the remote, since we don't make any effort to ensure
* that local and remote values match (tableoid, in
* particular, almost certainly doesn't match).
*/
if (var->varattno < 0 &&
var->varattno != SelfItemPointerAttributeNumber)
return false;
/* Else check the collation */
collation = var->varcollid;
state = OidIsValid(collation) ? FDW_COLLATE_SAFE : FDW_COLLATE_NONE;
}
else
{
/* Parameter is unsupported */
return false;
}
}
break;
case T_Const:
{
Const *c = (Const *) node;
#if (PG_VERSION_NUM >= 160000)
/*
* Constants of regproc and related types can't be shipped
* unless the referenced object is shippable. But NULL's ok.
* (See also the related code in dependency.c.)
*/
if (!c->constisnull)
{
switch (c->consttype)
{
case REGPROCOID:
case REGPROCEDUREOID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
ProcedureRelationId, fpinfo))
return false;
break;
case REGOPEROID:
case REGOPERATOROID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
OperatorRelationId, fpinfo))
return false;
break;
case REGCLASSOID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
RelationRelationId, fpinfo))
return false;
break;
case REGTYPEOID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
TypeRelationId, fpinfo))
return false;
break;
case REGCOLLATIONOID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
CollationRelationId, fpinfo))
return false;
break;
case REGCONFIGOID:
/*
* For text search objects only, we weaken the
* normal shippability criterion to allow all OIDs
* below FirstNormalObjectId. Without this, none
* of the initdb-installed TS configurations would
* be shippable, which would be quite annoying.
*/
if (DatumGetObjectId(c->constvalue) >= FirstNormalObjectId &&
!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
TSConfigRelationId, fpinfo))
return false;
break;
case REGDICTIONARYOID:
if (DatumGetObjectId(c->constvalue) >= FirstNormalObjectId &&
!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
TSDictionaryRelationId, fpinfo))
return false;
break;
case REGNAMESPACEOID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
NamespaceRelationId, fpinfo))
return false;
break;
case REGROLEOID:
if (!dynamodb_is_shippable(DatumGetObjectId(c->constvalue),
AuthIdRelationId, fpinfo))
return false;
break;
}
}
#endif
/*
* If the constant has nondefault collation, either it's of a
* non-builtin type, or it reflects folding of a CollateExpr.
* It's unsafe to send to the remote unless it's used in a
* non-collation-sensitive context.
*/
collation = c->constcollid;
if (collation == InvalidOid ||
collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_FuncExpr:
{
FuncExpr *fe = (FuncExpr *) node;
char *opername = NULL;
/* get function name */
opername = get_func_name(fe->funcid);
/* check NULL for opername */
if (opername == NULL)
elog(ERROR, "dynamodb_fdw: cache lookup failed for function %u", fe->funcid);
if (strcmp(opername, "size") == 0)
{
Expr *arg = (Expr *) linitial(fe->args);
/* Do not push down if user does not input Var as argument */
if (nodeTag(arg) != T_Var)
return false;
}
else
return false;
/*
* Recurse to input subexpressions.
*/
if (!dynamodb_foreign_expr_walker((Node *) fe->args,
glob_cxt, &inner_cxt))
return false;
/*
* If function's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (fe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
fe->inputcollid != inner_cxt.collation)
return false;
/*
* Detect whether node is introducing a collation not derived
* from a foreign Var. (If so, we just mark it unsafe for now
* rather than immediately returning false, since the parent
* node might not care.)
*/
collation = fe->funccollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else if (collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_OpExpr:
{
OpExpr *oe = (OpExpr *) node;
Form_pg_operator form;
DynamoDBOperatorsSupport opkind;
char *opname;
/*
* Similarly, only shippable operators can be sent to remote.
* (If the operator is shippable, we assume its underlying
* function is too.)
*/
if (!dynamodb_is_shippable(oe->opno, OperatorRelationId, fpinfo))
return false;
form = dynamodb_get_operator_expression(oe->opno);
opname = form->oprname.data;
/*
* DynamoDB only support condition with the following syntax:
* Operand comparison_operator Operand
*/
if (!(form->oprkind == 'b' && list_length(oe->args) == 2))
return false;
opkind = dynamodb_validate_operator_name(form);
/* Return false if operator name is not supported */
if (opkind == OP_UNSUPPORT)
return false;
else if (opkind == OP_JSON)
{
/*
* The right operand must be a constant
*/
Expr *expr = (Expr *)lfirst(list_tail(oe->args));
if (!IsA(expr, Const))
return false;
else
{
/* Do not push down if the right operand is a negative number */
Const *c = (Const *) expr;
if (c->consttype == INT2OID ||
c->consttype == INT4OID ||
c->consttype == INT8OID)
{
int32 dat = DatumGetInt32(c->constvalue);
if (dat < 0)
return false;
}
}
}
else if (opkind == OP_CONDITIONAL)
{
Expr *left = (Expr *)lfirst(list_head(oe->args));
Expr *right = (Expr *)lfirst(list_tail(oe->args));
Expr *expr = NULL;
Const *c;
bool has_const = false;
if (nodeTag(left) == T_Const)
{
expr = left;
has_const = true;
}
else if (nodeTag(right) == T_Const)
{
expr = right;
has_const = true;
}
if (has_const)
{
c = (Const *) expr;
/* Do not push down when comparing with array */
if (c->consttype == INT2ARRAYOID ||
c->consttype == INT4ARRAYOID ||
c->consttype == INT8ARRAYOID ||
c->consttype == FLOAT4ARRAYOID ||
c->consttype == FLOAT8ARRAYOID ||
c->consttype == NUMERICARRAYOID ||
c->consttype == VARCHARARRAYOID ||
c->consttype == TEXTARRAYOID ||
c->consttype == BPCHARARRAYOID ||
c->consttype == NAMEARRAYOID)
return false;
/* Do not push down when comparing text using <, >, <=, >= */
if ((c->consttype == TEXTOID ||
c->consttype == VARCHAROID ||
c->consttype == BPCHAROID ||
c->consttype == NAMEOID ||
c->consttype == JSONBOID ||
c->consttype == JSONOID) &&
((strcmp(opname, "<") == 0 ||
strcmp(opname, "<=") == 0 ||
strcmp(opname, ">") == 0 ||
strcmp(opname, ">=") == 0)))
return false;
}
}
/*
* Recurse to input subexpressions.
*/
if (!dynamodb_foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
if (opkind != OP_JSON)
{
/*
* If operator's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (oe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
oe->inputcollid != inner_cxt.collation)
return false;
}
/* Result-collation handling is same as for functions */
collation = oe->opcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else if (collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_ScalarArrayOpExpr:
{
ScalarArrayOpExpr *oe = (ScalarArrayOpExpr *) node;
Form_pg_operator form;
char *opname = NULL;
Expr *arg1;
Expr *arg2;
/*
* Again, only shippable operators can be sent to remote.
*/
if (!dynamodb_is_shippable(oe->opno, OperatorRelationId, fpinfo))
return false;
form = dynamodb_get_operator_expression(oe->opno);
opname = form->oprname.data;
/* Only support push down equal or not-equal operator. */
if (!(strcmp(opname, "=") == 0 ||
strcmp(opname, "<>") == 0 ||
strcmp(opname, "!=") == 0))
return false;
arg1 = (Expr *) linitial(oe->args);
arg2 = (Expr *) lsecond(oe->args);
/*
* Do not push down when the first argument exist
* in the array because DynamoDB does not support it
* Example: c1 = ANY(ARRAY(c1, c2))
*/
if (nodeTag(arg2) == T_ArrayExpr)
{
ArrayExpr *a = (ArrayExpr *) arg2;
if (list_member(a->elements, arg1))
return false;
}
/*
* Recurse to input subexpressions.
*/
if (!dynamodb_foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
/*
* If operator's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (oe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
oe->inputcollid != inner_cxt.collation)
return false;
/* Output is always boolean and so noncollatable. */
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_BoolExpr:
{
BoolExpr *b = (BoolExpr *) node;
List *l = (List *) b->args;
ListCell *lc;
/*
* DynamoDB does not support the case only column as operand.
* Example: WHERE NOT c1; WHERE c1 OR condition
*/
foreach(lc, l)
{
if (nodeTag(lfirst(lc)) == T_Var)
return false;
}
/*
* Recurse to input subexpressions.
*/
if (!dynamodb_foreign_expr_walker((Node *) b->args,
glob_cxt, &inner_cxt))
return false;
/* Output is always boolean and so noncollatable. */
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_NullTest:
{
NullTest *nt = (NullTest *) node;
/*
* Recurse to input subexpressions.
*/
if (!dynamodb_foreign_expr_walker((Node *) nt->arg,
glob_cxt, &inner_cxt))
return false;
/* Output is always boolean and so noncollatable. */
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_List:
{
List *l = (List *) node;
ListCell *lc;
/*
* Recurse to component subexpressions.
*/
foreach(lc, l)
{
if (!dynamodb_foreign_expr_walker((Node *) lfirst(lc),
glob_cxt, &inner_cxt))
return false;
}
/*
* When processing a list, collation state just bubbles up
* from the list elements.
*/
collation = inner_cxt.collation;
state = inner_cxt.state;
/* Don't apply exprType() to the list. */
check_type = false;
}
break;
case T_ArrayExpr:
{
ArrayExpr *a = (ArrayExpr *) node;
/*
* Recurse to input subexpressions.
*/
if (!dynamodb_foreign_expr_walker((Node *) a->elements,
glob_cxt, &inner_cxt))
return false;
/*
* ArrayExpr must not introduce a collation not derived from
* an input foreign Var (same logic as for a function).
*/
collation = a->array_collid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else if (collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
default:
/*
* If it's anything else, assume it's unsafe. This list can be
* expanded later, but don't forget to add deparse support below.
*/
return false;
}
/*
* If result type of given expression is not shippable, it can't be sent
* to remote because it might have incompatible semantics on remote side.
*/
if (check_type && !dynamodb_is_shippable(exprType(node), TypeRelationId, fpinfo))
return false;
/*
* Now, merge my collation information into my parent's state.
*/
if (state > outer_cxt->state)
{
/* Override previous parent state */
outer_cxt->collation = collation;
outer_cxt->state = state;
}
else if (state == outer_cxt->state)
{
/* Merge, or detect error if there's a collation conflict */
switch (state)
{
case FDW_COLLATE_NONE:
/* Nothing + nothing is still nothing */
break;
case FDW_COLLATE_SAFE:
if (collation != outer_cxt->collation)
{
/*
* Non-default collation always beats default.
*/
if (outer_cxt->collation == DEFAULT_COLLATION_OID)
{
/* Override previous parent state */
outer_cxt->collation = collation;
}
else if (collation != DEFAULT_COLLATION_OID)
{
/*
* Conflict; show state as indeterminate. We don't
* want to "return false" right away, since parent
* node might not care about collation.
*/
outer_cxt->state = FDW_COLLATE_UNSAFE;
}
}
break;
case FDW_COLLATE_UNSAFE:
/* We're still conflicted ... */
break;
}
}
/* It looks OK */
return true;
}
/*
* dynamodb_deparse_select_stmt_for_rel
*
* Deparse SELECT statement for given relation into buf.
*
* tlist contains the list of desired columns to be fetched from foreign server.
* For a base relation fpinfo->attrs_used is used to construct SELECT clause,
* hence the tlist is ignored for a base relation.
*
* remote_conds is the list of conditions to be deparsed into the WHERE clause
* (or, in the case of upper relations, into the HAVING clause).
*
* pathkeys is the list of pathkeys to order the result by.
*
* is_subquery is the flag to indicate whether to deparse the specified
* relation as a subquery.
*
* List of columns selected is returned in retrieved_attrs.
*/
void
dynamodb_deparse_select_stmt_for_rel(StringInfo buf, PlannerInfo *root, RelOptInfo *rel,
List *tlist, List *remote_conds, List *pathkeys,
List **retrieved_attrs)
{
deparse_expr_cxt context;
List *quals;
/* Fill portions of context common to upper, join and base relation */
context.buf = buf;
context.root = root;
context.foreignrel = rel;
context.scanrel = rel;
context.has_arrow = false;
context.attrs_list = retrieved_attrs;
/* Construct SELECT clause */
dynamodb_deparse_select(tlist, retrieved_attrs, &context);
/*
* We can use the supplied list of remote conditions directly to build the WHERE clause.
*/
quals = remote_conds;
/* Construct FROM and WHERE clauses */
dynamodb_deparse_from_expr(quals, &context);
}
/*