-
Notifications
You must be signed in to change notification settings - Fork 37
/
hdfs_deparse.c
2424 lines (2118 loc) · 63.5 KB
/
hdfs_deparse.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* hdfs_deparse.c
* Query deparser for hdfs_fdw.
*
* Portions Copyright (c) 2012-2019, PostgreSQL Global Development Group
* Portions Copyright (c) 2004-2024, EnterpriseDB Corporation.
*
* IDENTIFICATION
* hdfs_deparse.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "hdfs_fdw.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
/*
* Global context for hdfs_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 */
/*
* For join pushdown, only a limited set of operators are allowed to be
* pushed. This flag helps us identify if we are walking through the list
* of join conditions. Also true for aggregate relations to restrict
* aggregates for specified list.
*/
bool is_remote_cond; /* true for join or aggregate relations */
Relids relids; /* relids of base relations in the underlying
* scan */
} foreign_glob_cxt;
/*
* Local (per-tree-level) context for hdfs_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 */
FDW_COLLATE_SAFE, /* collation derives from a foreign Var */
FDW_COLLATE_UNSAFE /* collation derives from something else */
} 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 hdfs_deparse_expr
*/
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 */
List **params_list; /* exprs that will become remote Params */
bool is_limit_node; /* the expression represents a LIMIT node */
} deparse_expr_cxt;
#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"
/*
* Functions to determine whether an expression can be evaluated safely on
* remote server.
*/
static bool hdfs_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 hdfs_deparse_target_list(StringInfo buf,
PlannerInfo *root,
Index rtindex,
Relation rel,
Bitmapset *attrs_used,
List **retrieved_attrs);
static char *hdfs_quote_identifier(const char *str, char quotechar);
static void hdfs_deparse_column_ref(StringInfo buf, int varno, int varattno,
PlannerInfo *root, bool qualify_col);
static void hdfs_deparse_relation(StringInfo buf, Relation rel);
static void hdfs_deparse_expr(Expr *expr, deparse_expr_cxt *context);
static void hdfs_deparse_var(Var *node, deparse_expr_cxt *context);
static void hdfs_deparse_const(Const *node, deparse_expr_cxt *context);
static void hdfs_deparse_param(Param *node, deparse_expr_cxt *context);
static void hdfs_deparse_subscripting_ref(SubscriptingRef *node,
deparse_expr_cxt *context);
static void hdfs_deparse_func_expr(FuncExpr *node, deparse_expr_cxt *context);
static void hdfs_deparse_op_expr(OpExpr *node, deparse_expr_cxt *context);
static void hdfs_deparse_operator_name(StringInfo buf,
Form_pg_operator opform);
static void hdfs_deparse_distinct_expr(DistinctExpr *node,
deparse_expr_cxt *context);
static void hdfs_deparse_scalar_array_op_expr(ScalarArrayOpExpr *node,
deparse_expr_cxt *context);
static void hdfs_deparse_relabel_type(RelabelType *node,
deparse_expr_cxt *context);
static void hdfs_deparse_bool_expr(BoolExpr *node, deparse_expr_cxt *context);
static void hdfs_deparse_null_test(NullTest *node, deparse_expr_cxt *context);
static void hdfs_deparse_array_expr(ArrayExpr *node,
deparse_expr_cxt *context);
static void hdfs_deparse_string_literal(StringInfo buf, const char *val);
static void hdfs_print_remote_param(deparse_expr_cxt *context);
static void hdfs_print_remote_placeholder(deparse_expr_cxt *context);
static void hdfs_append_conditions(List *exprs, deparse_expr_cxt *context);
static void hdfs_deparse_select_sql(List *tlist, bool is_subquery,
List **retrieved_attrs,
deparse_expr_cxt *context);
static void hdfs_deparse_from_expr_for_rel(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel,
bool use_alias, List **params_list);
static void hdfs_deparse_from_expr(List *quals, deparse_expr_cxt *context,
bool use_alias);
static void hdfs_deparse_rangeTblRef(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel, bool make_subquery,
List **params_list);
static void hdfs_deparse_explicit_target_list(List *tlist,
List **retrieved_attrs,
deparse_expr_cxt *context);
static void hdfs_deparse_subquery_target_list(deparse_expr_cxt *context);
static void hdfs_append_function_name(Oid funcid, deparse_expr_cxt *context);
static void hdfs_deparse_aggref(Aggref *node, deparse_expr_cxt *context);
static void hdfs_append_groupby_clause(List *tlist, deparse_expr_cxt *context);
static Node *hdfs_deparse_sort_group_clause(Index ref, List *tlist,
deparse_expr_cxt *context);
static void hdfs_append_orderby_clause(List *pathkeys, bool has_final_sort,
deparse_expr_cxt *context);
static void hdfs_append_orderby_suffix(const char *sortby_dir, Oid sortcoltype,
bool nulls_first,
deparse_expr_cxt *context);
static void hdfs_append_limit_clause(deparse_expr_cxt *context,
CLIENT_TYPE client_type);
/*
* Helper functions
*/
static bool hdfs_is_subquery_var(Var *node, RelOptInfo *foreignrel,
int *relno, int *colno,
deparse_expr_cxt *context);
static void hdfs_get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
int *relno, int *colno,
deparse_expr_cxt *context);
/*
* 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
hdfs_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 = (RestrictInfo *) lfirst(lc);
if (hdfs_is_foreign_expr(root, baserel, ri->clause, false))
*remote_conds = lappend(*remote_conds, ri);
else
*local_conds = lappend(*local_conds, ri);
}
}
/*
* Returns true if given expr is safe to evaluate on the foreign server.
*/
bool
hdfs_is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr,
bool is_remote_cond)
{
foreign_glob_cxt glob_cxt;
foreign_loc_cxt loc_cxt;
HDFSFdwRelationInfo *fpinfo = (HDFSFdwRelationInfo *) (baserel->fdw_private);
/*
* Check that the expression consists of nodes that are safe to execute
* remotely.
*/
glob_cxt.root = root;
glob_cxt.foreignrel = baserel;
glob_cxt.is_remote_cond = is_remote_cond;
/*
* For an upper relation, use relids from its underneath scan relation,
* because the upperrel's own relids currently aren't set to anything
* meaningful by the core code. For other relation, use their own relids.
*/
if (IS_UPPER_REL(baserel))
glob_cxt.relids = fpinfo->outerrel->relids;
else
glob_cxt.relids = baserel->relids;
loc_cxt.collation = InvalidOid;
loc_cxt.state = FDW_COLLATE_NONE;
if (!hdfs_foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt))
return false;
/* Expressions examined here should be boolean, i.e. noncollatable */
Assert(loc_cxt.collation == InvalidOid);
Assert(loc_cxt.state == FDW_COLLATE_NONE);
/*
* 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;
}
/*
* 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 (which we approximate
* as being built-in), 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.
*/
static bool
hdfs_foreign_expr_walker(Node *node,
foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt)
{
bool check_type = true;
foreign_loc_cxt inner_cxt;
/* Need do nothing for empty subexpressions */
if (node == NULL)
return true;
/* 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 (bms_is_member(var->varno, glob_cxt->relids) &&
var->varlevelsup == 0)
{
/* Var belongs to foreign table */
if (var->varattno < 0 &&
var->varattno != SelfItemPointerAttributeNumber)
return false;
}
}
break;
case T_Const:
case T_Param:
break;
case T_SubscriptingRef:
{
SubscriptingRef *sbref = (SubscriptingRef *) node;;
/* Should not be in the join clauses of the Join-pushdown */
if (glob_cxt->is_remote_cond)
return false;
/* Assignment should not be in restrictions. */
if (sbref->refassgnexpr != NULL)
return false;
/*
* Recurse to remaining subexpressions. Since the array
* subscripts must yield (noncollatable) integers, they won't
* affect the inner_cxt state.
*/
if (!hdfs_foreign_expr_walker((Node *) sbref->refupperindexpr,
glob_cxt, &inner_cxt))
return false;
if (!hdfs_foreign_expr_walker((Node *) sbref->reflowerindexpr,
glob_cxt, &inner_cxt))
return false;
if (!hdfs_foreign_expr_walker((Node *) sbref->refexpr,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_FuncExpr:
{
FuncExpr *fe = (FuncExpr *) node;
/* Should not be in the join clauses of the Join-pushdown */
if (glob_cxt->is_remote_cond)
return false;
/*
* If function used by the expression is not built-in, it
* can't be sent to remote because it might have incompatible
* semantics on remote side.
*/
if (!hdfs_is_builtin(fe->funcid))
return false;
/*
* Recurse to input subexpressions.
*/
if (!hdfs_foreign_expr_walker((Node *) fe->args,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_OpExpr:
case T_DistinctExpr: /* struct-equivalent to OpExpr */
{
OpExpr *oe = (OpExpr *) node;
const char *operatorName = get_opname(oe->opno);
/*
* Join-pushdown allows only a few operators to be pushed
* down.
*/
if (glob_cxt->is_remote_cond &&
(!(strcmp(operatorName, "<") == 0 ||
strcmp(operatorName, ">") == 0 ||
strcmp(operatorName, "<=") == 0 ||
strcmp(operatorName, ">=") == 0 ||
strcmp(operatorName, "<>") == 0 ||
strcmp(operatorName, "=") == 0 ||
strcmp(operatorName, "+") == 0 ||
strcmp(operatorName, "-") == 0 ||
strcmp(operatorName, "*") == 0 ||
strcmp(operatorName, "%") == 0 ||
strcmp(operatorName, "/") == 0)))
return false;
/*
* Similarly, only built-in operators can be sent to remote.
* (If the operator is, surely its underlying function is
* too.)
*/
if (!hdfs_is_builtin(oe->opno))
return false;
/*
* Recurse to input subexpressions.
*/
if (!hdfs_foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_ScalarArrayOpExpr:
{
ScalarArrayOpExpr *oe = (ScalarArrayOpExpr *) node;
/* Should not be in the join clauses of the Join-pushdown */
if (glob_cxt->is_remote_cond)
return false;
/*
* Again, only built-in operators can be sent to remote.
*/
if (!hdfs_is_builtin(oe->opno))
return false;
/*
* Recurse to input subexpressions.
*/
if (!hdfs_foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_RelabelType:
{
RelabelType *r = (RelabelType *) node;
/*
* Recurse to input subexpression.
*/
if (!hdfs_foreign_expr_walker((Node *) r->arg,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_BoolExpr:
{
BoolExpr *b = (BoolExpr *) node;
/*
* Recurse to input subexpressions.
*/
if (!hdfs_foreign_expr_walker((Node *) b->args,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_NullTest:
{
NullTest *nt = (NullTest *) node;
/*
* Recurse to input subexpressions.
*/
if (!hdfs_foreign_expr_walker((Node *) nt->arg,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_ArrayExpr:
{
ArrayExpr *a = (ArrayExpr *) node;
/* Should not be in the join clauses of the Join-pushdown */
if (glob_cxt->is_remote_cond)
return false;
/*
* Recurse to input subexpressions.
*/
if (!hdfs_foreign_expr_walker((Node *) a->elements,
glob_cxt, &inner_cxt))
return false;
}
break;
case T_List:
{
List *l = (List *) node;
ListCell *lc;
/*
* Recurse to component subexpressions.
*/
foreach(lc, l)
{
if (!hdfs_foreign_expr_walker((Node *) lfirst(lc),
glob_cxt, &inner_cxt))
return false;
}
/* Don't apply exprType() to the list. */
check_type = false;
}
break;
case T_Aggref:
{
Aggref *agg = (Aggref *) node;
ListCell *lc;
const char *func_name;
/* Not safe to pushdown when not in grouping context */
if (!IS_UPPER_REL(glob_cxt->foreignrel))
return false;
/* Only non-split aggregates are pushable. */
if (agg->aggsplit != AGGSPLIT_SIMPLE)
return false;
/* Aggregates with order are not supported on hive/spark. */
if (agg->aggorder)
return false;
/* FILTER clause is not supported on hive/spark. */
if (agg->aggfilter)
return false;
/* VARIADIC not supported on hive/spark. */
if (agg->aggvariadic)
return false;
/* As usual, it must be shippable. */
if (!hdfs_is_builtin(agg->aggfnoid))
return false;
func_name = get_func_name(agg->aggfnoid);
if (!(strcmp(func_name, "min") == 0 ||
strcmp(func_name, "max") == 0 ||
strcmp(func_name, "sum") == 0 ||
strcmp(func_name, "avg") == 0 ||
strcmp(func_name, "count") == 0))
return false;
/*
* Recurse to input args. aggdirectargs, aggorder and
* aggdistinct are all present in args, so no need to check
* their shippability explicitly.
*/
foreach(lc, agg->args)
{
Node *n = (Node *) lfirst(lc);
/* If TargetEntry, extract the expression from it */
if (IsA(n, TargetEntry))
{
TargetEntry *tle = (TargetEntry *) n;
n = (Node *) tle->expr;
}
if (!hdfs_foreign_expr_walker(n, glob_cxt, &inner_cxt))
return false;
}
}
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 built-in, it can't be sent to
* remote because it might have incompatible semantics on remote side.
*/
if (check_type && !hdfs_is_builtin(exprType(node)))
return false;
/* It looks OK */
return true;
}
/*
* Return true if given object is one of PostgreSQL's built-in objects.
*
* We use FirstBootstrapObjectId as the cutoff, so that we only consider
* objects with hand-assigned OIDs to be "built in", not for instance any
* function or type defined in the information_schema.
*
* Our constraints for dealing with types are tighter than they are for
* functions or operators: we want to accept only types that are in pg_catalog,
* else format_type might incorrectly fail to schema-qualify their names.
* (This could be fixed with some changes to format_type, but for now there's
* no need.) Thus we must exclude information_schema types.
*
* XXX there is a problem with this, which is that the set of built-in
* objects expands over time. Something that is built-in to us might not
* be known to the remote server, if it's of an older version. But keeping
* track of that would be a huge exercise.
*/
bool
hdfs_is_builtin(Oid oid)
{
return (oid < FirstGenbkiObjectId);
}
void
hdfs_deparse_explain(hdfs_opt *opt, StringInfo buf)
{
appendStringInfo(buf, "EXPLAIN SELECT * FROM ");
appendStringInfo(buf, "%s.%s", hdfs_quote_identifier(opt->dbname, '`'),
hdfs_quote_identifier(opt->table_name, '`'));
/*
* For accurate row counts we should append where clauses with the
* statement, but if where clause is parameterized we should handle it the
* way postgres fdw does.
* TODO:
* if (fpinfo->remote_conds)
* hdfs_append_where_clause(opt, buf, root, baserel,
* fpinfo->remote_conds, true,
* ¶ms_list);
*/
}
void
hdfs_deparse_describe(StringInfo buf, Relation rel)
{
appendStringInfo(buf, "DESCRIBE FORMATTED ");
hdfs_deparse_relation(buf, rel);
}
void
hdfs_deparse_analyze(StringInfo buf, Relation rel)
{
appendStringInfo(buf, "ANALYZE TABLE ");
hdfs_deparse_relation(buf, rel);
appendStringInfo(buf, " COMPUTE STATISTICS");
}
/*
* hdfs_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.
*
* pathkeys is the list of pathkeys to order the result by.
*
* If params_list is not NULL, it receives a list of Params and other-relation
* Vars used in the clauses; these values must be transmitted to the remote
* server as parameter values.
*
* 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
hdfs_deparse_select_stmt_for_rel(StringInfo buf, PlannerInfo *root,
RelOptInfo *rel, List *tlist,
List *remote_conds, bool is_subquery,
List *pathkeys,
bool has_final_sort, bool has_limit,
List **retrieved_attrs,
List **params_list)
{
deparse_expr_cxt context;
List *quals;
HDFSFdwRelationInfo *fpinfo = (HDFSFdwRelationInfo *) rel->fdw_private;
/*
* We handle relations for foreign tables and joins between those and
* upper relations
*/
Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
/* Fill portions of context common to base relation */
context.buf = buf;
context.root = root;
context.foreignrel = rel;
context.params_list = params_list;
context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
context.is_limit_node = false;
/* Construct SELECT clause */
hdfs_deparse_select_sql(tlist, is_subquery, retrieved_attrs, &context);
/*
* For upper relations, the WHERE clause is built from the remote
* conditions of the underlying scan relation; otherwise, we can use the
* supplied list of remote conditions directly.
*/
if (IS_UPPER_REL(rel))
{
HDFSFdwRelationInfo *ofpinfo;
ofpinfo = (HDFSFdwRelationInfo *) fpinfo->outerrel->fdw_private;
quals = ofpinfo->remote_conds;
}
else
quals = remote_conds;
/* Construct FROM and WHERE clauses */
hdfs_deparse_from_expr(quals, &context, is_subquery);
if (IS_UPPER_REL(rel))
{
/* Append GROUP BY clause */
hdfs_append_groupby_clause(fpinfo->grouped_tlist, &context);
/* Append HAVING clause */
if (remote_conds)
{
appendStringInfoString(buf, " HAVING ");
hdfs_append_conditions(remote_conds, &context);
}
}
/* Add ORDER BY clause if we found any useful pathkeys */
if (pathkeys)
hdfs_append_orderby_clause(pathkeys, has_final_sort, &context);
/* Add LIMIT clause if necessary */
if (has_limit)
hdfs_append_limit_clause(&context, fpinfo->client_type);
}
/*
* hdfs_deparse_select_sql
* Construct a simple SELECT statement that retrieves desired columns
* of the specified foreign table, and append it to "buf". The output
* contains just "SELECT ...".
*
* We also create an integer List of the columns being retrieved, which is
* returned to *retrieved_attrs, unless we deparse the specified relation
* as a subquery.
*
* tlist is the list of desired columns. is_subquery is the flag to
* indicate whether to deparse the specified relation as a subquery.
* Read prologue of deparseSelectStmtForRel() for details.
*/
static void
hdfs_deparse_select_sql(List *tlist, bool is_subquery, List **retrieved_attrs,
deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
RelOptInfo *foreignrel = context->foreignrel;
PlannerInfo *root = context->root;
appendStringInfoString(buf, "SELECT ");
if (is_subquery)
{
/*
* For a relation that is deparsed as a subquery, emit expressions
* specified in the relation's reltarget. Note that since this is for
* the subquery, no need to care about *retrieved_attrs.
*/
hdfs_deparse_subquery_target_list(context);
}
else if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
{
/*
* For a join or upper relation the input tlist gives the list of
* columns required to be fetched from the foreign server.
*/
hdfs_deparse_explicit_target_list(tlist, retrieved_attrs, context);
}
else
{
HDFSFdwRelationInfo *fpinfo = (HDFSFdwRelationInfo *) foreignrel->fdw_private;
RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
Relation rel;
/*
* Core code already has some lock on each rel being planned, so we
* can use NoLock here.
*/
#if PG_VERSION_NUM < 130000
rel = heap_open(rte->relid, NoLock);
#else
rel = table_open(rte->relid, NoLock);
#endif
/* Construct target list */
hdfs_deparse_target_list(buf, root, foreignrel->relid, rel,
fpinfo->attrs_used, retrieved_attrs);
#if PG_VERSION_NUM < 130000
heap_close(rel, NoLock);
#else
table_close(rel, NoLock);
#endif
}
}
/*
* hdfs_deparse_from_expr
* Construct a FROM clause and, if needed, a WHERE clause, and
* append those to "buf".
*
* quals is the list of clauses to be included in the WHERE clause.
*/
static void
hdfs_deparse_from_expr(List *quals, deparse_expr_cxt *context, bool use_alias)
{
StringInfo buf = context->buf;
RelOptInfo *scanrel = context->scanrel;
Assert(!IS_UPPER_REL(context->foreignrel) ||
IS_JOIN_REL(scanrel) || IS_SIMPLE_REL(scanrel));
use_alias |= (bms_membership(scanrel->relids) == BMS_MULTIPLE);
/* Construct FROM clause */
appendStringInfoString(buf, " FROM ");
hdfs_deparse_from_expr_for_rel(buf, context->root, scanrel,
use_alias, context->params_list);
/* Construct WHERE clause */
if (quals != NIL)
{
appendStringInfoString(buf, " WHERE ");
hdfs_append_conditions(quals, context);
}
}
/*
* hdfs_deparse_explicit_target_list
* Deparse given targetlist and append it to context->buf.
*
* retrieved_attrs is the list of continuously increasing integers starting
* from 1. It has same number of entries as tlist.
*/
static void
hdfs_deparse_explicit_target_list(List *tlist, List **retrieved_attrs,
deparse_expr_cxt *context)
{
ListCell *lc;
StringInfo buf = context->buf;
int i = 0;
*retrieved_attrs = NIL;
foreach(lc, tlist)
{
if (i > 0)
appendStringInfoString(buf, ", ");
hdfs_deparse_expr((Expr *) lfirst(lc), context);
*retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
i++;
}
if (i == 0)
appendStringInfoString(buf, "NULL");
}
/*
* hdfs_deparse_subquery_target_list
*
* Emit expressions specified in the given relation's reltarget.
*
* This is used for deparsing the given relation as a subquery.
*/
static void
hdfs_deparse_subquery_target_list(deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
RelOptInfo *foreignrel = context->foreignrel;
bool first;
ListCell *lc;
int i;
List *scan_var_list = NIL;
List *whole_row_lists = NIL;
/* Should only be called in these cases. */
Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
scan_var_list = pull_var_clause((Node *) foreignrel->reltarget->exprs,
PVC_RECURSE_PLACEHOLDERS);
scan_var_list = hdfs_adjust_whole_row_ref(context->root, scan_var_list,
&whole_row_lists,
foreignrel->relids);
first = true;
i = 1;
foreach(lc, scan_var_list)
{
Node *node = (Node *) lfirst(lc);
if (!first)
appendStringInfo(buf, " %s%d, ", SUBQUERY_COL_ALIAS_PREFIX, i++);
first = false;
hdfs_deparse_expr((Expr *) node, context);
}
/* Don't generate bad syntax if no expressions */
if (first)
appendStringInfoString(buf, "NULL");
else
{
/* Append the column alias for the last expression */
appendStringInfo(buf, " %s%d", SUBQUERY_COL_ALIAS_PREFIX, i++);
}
}
/*
* hdfs_append_conditions
* Deparse conditions from the provided list and append them to buf.
*
* The conditions in the list are assumed to be ANDed. This function is used
* to deparse WHERE clauses, JOIN .. ON clauses and HAVING clauses.
*
* Depending on the caller, the list elements might be either RestrictInfos
* or bare clauses.
*/
static void
hdfs_append_conditions(List *exprs, deparse_expr_cxt *context)
{
ListCell *lc;
bool is_first = true;
StringInfo buf = context->buf;
foreach(lc, exprs)
{
Expr *expr = (Expr *) lfirst(lc);
/*
* Extract clause from RestrictInfo, if required. See comments in
* declaration of HDFSFdwRelationInfo for details.
*/
if (IsA(expr, RestrictInfo))
{
RestrictInfo *ri = (RestrictInfo *) expr;
expr = ri->clause;
}
/* Connect expressions with "AND" and parenthesize each condition. */
if (!is_first)
appendStringInfoString(buf, " AND ");
appendStringInfoChar(buf, '(');
hdfs_deparse_expr(expr, context);
appendStringInfoChar(buf, ')');
is_first = false;
}
}
/*
* Emit a target list that retrieves the columns specified in attrs_used.
*
* The target list text is appended to buf, and we also create an integer
* list of the columns being retrieved, which is returned to *retrieved_attrs.
*/
static void
hdfs_deparse_target_list(StringInfo buf,
PlannerInfo *root,
Index rtindex,
Relation rel,
Bitmapset *attrs_used,
List **retrieved_attrs)
{
TupleDesc tupdesc = RelationGetDescr(rel);
int i;
bool first = true;
bool have_wholerow = false;
*retrieved_attrs = NIL;
/*
* If whole-row reference is used or all the columns in the table are
* referenced, instead of sending all the column's list, send 'SELECT *'
* query to avoid the Map-reduce job.
*/
if (attrs_used != NULL &&
(bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, attrs_used) ||
tupdesc->natts == bms_num_members(attrs_used)))
{
have_wholerow = true;
appendStringInfoChar(buf, '*');
}
for (i = 1; i <= tupdesc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
/* Ignore dropped attributes. */
if (attr->attisdropped)
continue;
if (have_wholerow ||
bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
{
if (!have_wholerow)
{
if (!first)
appendStringInfoString(buf, ", ");
first = false;
hdfs_deparse_column_ref(buf, rtindex, i, root, false);
}