Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * deparse.c
4 : * Query deparser for postgres_fdw
5 : *
6 : * This file includes functions that examine query WHERE clauses to see
7 : * whether they're safe to send to the remote server for execution, as
8 : * well as functions to construct the query text to be sent. The latter
9 : * functionality is annoyingly duplicative of ruleutils.c, but there are
10 : * enough special considerations that it seems best to keep this separate.
11 : * One saving grace is that we only need deparse logic for node types that
12 : * we consider safe to send.
13 : *
14 : * We assume that the remote session's search_path is exactly "pg_catalog",
15 : * and thus we need schema-qualify all and only names outside pg_catalog.
16 : *
17 : * We do not consider that it is ever safe to send COLLATE expressions to
18 : * the remote server: it might not have the same collation names we do.
19 : * (Later we might consider it safe to send COLLATE "C", but even that would
20 : * fail on old remote servers.) An expression is considered safe to send
21 : * only if all operator/function input collations used in it are traceable to
22 : * Var(s) of the foreign table. That implies that if the remote server gets
23 : * a different answer than we do, the foreign table's columns are not marked
24 : * with collations that match the remote table's columns, which we can
25 : * consider to be user error.
26 : *
27 : * Portions Copyright (c) 2012-2024, PostgreSQL Global Development Group
28 : *
29 : * IDENTIFICATION
30 : * contrib/postgres_fdw/deparse.c
31 : *
32 : *-------------------------------------------------------------------------
33 : */
34 : #include "postgres.h"
35 :
36 : #include "access/htup_details.h"
37 : #include "access/sysattr.h"
38 : #include "access/table.h"
39 : #include "catalog/pg_aggregate.h"
40 : #include "catalog/pg_authid.h"
41 : #include "catalog/pg_collation.h"
42 : #include "catalog/pg_namespace.h"
43 : #include "catalog/pg_operator.h"
44 : #include "catalog/pg_opfamily.h"
45 : #include "catalog/pg_proc.h"
46 : #include "catalog/pg_ts_config.h"
47 : #include "catalog/pg_ts_dict.h"
48 : #include "catalog/pg_type.h"
49 : #include "commands/defrem.h"
50 : #include "commands/tablecmds.h"
51 : #include "nodes/makefuncs.h"
52 : #include "nodes/nodeFuncs.h"
53 : #include "nodes/plannodes.h"
54 : #include "optimizer/optimizer.h"
55 : #include "optimizer/prep.h"
56 : #include "optimizer/tlist.h"
57 : #include "parser/parsetree.h"
58 : #include "postgres_fdw.h"
59 : #include "utils/builtins.h"
60 : #include "utils/lsyscache.h"
61 : #include "utils/rel.h"
62 : #include "utils/syscache.h"
63 : #include "utils/typcache.h"
64 :
65 : /*
66 : * Global context for foreign_expr_walker's search of an expression tree.
67 : */
68 : typedef struct foreign_glob_cxt
69 : {
70 : PlannerInfo *root; /* global planner state */
71 : RelOptInfo *foreignrel; /* the foreign relation we are planning for */
72 : Relids relids; /* relids of base relations in the underlying
73 : * scan */
74 : } foreign_glob_cxt;
75 :
76 : /*
77 : * Local (per-tree-level) context for foreign_expr_walker's search.
78 : * This is concerned with identifying collations used in the expression.
79 : */
80 : typedef enum
81 : {
82 : FDW_COLLATE_NONE, /* expression is of a noncollatable type, or
83 : * it has default collation that is not
84 : * traceable to a foreign Var */
85 : FDW_COLLATE_SAFE, /* collation derives from a foreign Var */
86 : FDW_COLLATE_UNSAFE, /* collation is non-default and derives from
87 : * something other than a foreign Var */
88 : } FDWCollateState;
89 :
90 : typedef struct foreign_loc_cxt
91 : {
92 : Oid collation; /* OID of current collation, if any */
93 : FDWCollateState state; /* state of current collation choice */
94 : } foreign_loc_cxt;
95 :
96 : /*
97 : * Context for deparseExpr
98 : */
99 : typedef struct deparse_expr_cxt
100 : {
101 : PlannerInfo *root; /* global planner state */
102 : RelOptInfo *foreignrel; /* the foreign relation we are planning for */
103 : RelOptInfo *scanrel; /* the underlying scan relation. Same as
104 : * foreignrel, when that represents a join or
105 : * a base relation. */
106 : StringInfo buf; /* output buffer to append to */
107 : List **params_list; /* exprs that will become remote Params */
108 : } deparse_expr_cxt;
109 :
110 : #define REL_ALIAS_PREFIX "r"
111 : /* Handy macro to add relation name qualification */
112 : #define ADD_REL_QUALIFIER(buf, varno) \
113 : appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
114 : #define SUBQUERY_REL_ALIAS_PREFIX "s"
115 : #define SUBQUERY_COL_ALIAS_PREFIX "c"
116 :
117 : /*
118 : * Functions to determine whether an expression can be evaluated safely on
119 : * remote server.
120 : */
121 : static bool foreign_expr_walker(Node *node,
122 : foreign_glob_cxt *glob_cxt,
123 : foreign_loc_cxt *outer_cxt,
124 : foreign_loc_cxt *case_arg_cxt);
125 : static char *deparse_type_name(Oid type_oid, int32 typemod);
126 :
127 : /*
128 : * Functions to construct string representation of a node tree.
129 : */
130 : static void deparseTargetList(StringInfo buf,
131 : RangeTblEntry *rte,
132 : Index rtindex,
133 : Relation rel,
134 : bool is_returning,
135 : Bitmapset *attrs_used,
136 : bool qualify_col,
137 : List **retrieved_attrs);
138 : static void deparseExplicitTargetList(List *tlist,
139 : bool is_returning,
140 : List **retrieved_attrs,
141 : deparse_expr_cxt *context);
142 : static void deparseSubqueryTargetList(deparse_expr_cxt *context);
143 : static void deparseReturningList(StringInfo buf, RangeTblEntry *rte,
144 : Index rtindex, Relation rel,
145 : bool trig_after_row,
146 : List *withCheckOptionList,
147 : List *returningList,
148 : List **retrieved_attrs);
149 : static void deparseColumnRef(StringInfo buf, int varno, int varattno,
150 : RangeTblEntry *rte, bool qualify_col);
151 : static void deparseRelation(StringInfo buf, Relation rel);
152 : static void deparseExpr(Expr *node, deparse_expr_cxt *context);
153 : static void deparseVar(Var *node, deparse_expr_cxt *context);
154 : static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype);
155 : static void deparseParam(Param *node, deparse_expr_cxt *context);
156 : static void deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context);
157 : static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context);
158 : static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context);
159 : static bool isPlainForeignVar(Expr *node, deparse_expr_cxt *context);
160 : static void deparseOperatorName(StringInfo buf, Form_pg_operator opform);
161 : static void deparseDistinctExpr(DistinctExpr *node, deparse_expr_cxt *context);
162 : static void deparseScalarArrayOpExpr(ScalarArrayOpExpr *node,
163 : deparse_expr_cxt *context);
164 : static void deparseRelabelType(RelabelType *node, deparse_expr_cxt *context);
165 : static void deparseBoolExpr(BoolExpr *node, deparse_expr_cxt *context);
166 : static void deparseNullTest(NullTest *node, deparse_expr_cxt *context);
167 : static void deparseCaseExpr(CaseExpr *node, deparse_expr_cxt *context);
168 : static void deparseArrayExpr(ArrayExpr *node, deparse_expr_cxt *context);
169 : static void printRemoteParam(int paramindex, Oid paramtype, int32 paramtypmod,
170 : deparse_expr_cxt *context);
171 : static void printRemotePlaceholder(Oid paramtype, int32 paramtypmod,
172 : deparse_expr_cxt *context);
173 : static void deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs,
174 : deparse_expr_cxt *context);
175 : static void deparseLockingClause(deparse_expr_cxt *context);
176 : static void appendOrderByClause(List *pathkeys, bool has_final_sort,
177 : deparse_expr_cxt *context);
178 : static void appendLimitClause(deparse_expr_cxt *context);
179 : static void appendConditions(List *exprs, deparse_expr_cxt *context);
180 : static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root,
181 : RelOptInfo *foreignrel, bool use_alias,
182 : Index ignore_rel, List **ignore_conds,
183 : List **additional_conds,
184 : List **params_list);
185 : static void appendWhereClause(List *exprs, List *additional_conds,
186 : deparse_expr_cxt *context);
187 : static void deparseFromExpr(List *quals, deparse_expr_cxt *context);
188 : static void deparseRangeTblRef(StringInfo buf, PlannerInfo *root,
189 : RelOptInfo *foreignrel, bool make_subquery,
190 : Index ignore_rel, List **ignore_conds,
191 : List **additional_conds, List **params_list);
192 : static void deparseAggref(Aggref *node, deparse_expr_cxt *context);
193 : static void appendGroupByClause(List *tlist, deparse_expr_cxt *context);
194 : static void appendOrderBySuffix(Oid sortop, Oid sortcoltype, bool nulls_first,
195 : deparse_expr_cxt *context);
196 : static void appendAggOrderBy(List *orderList, List *targetList,
197 : deparse_expr_cxt *context);
198 : static void appendFunctionName(Oid funcid, deparse_expr_cxt *context);
199 : static Node *deparseSortGroupClause(Index ref, List *tlist, bool force_colno,
200 : deparse_expr_cxt *context);
201 :
202 : /*
203 : * Helper functions
204 : */
205 : static bool is_subquery_var(Var *node, RelOptInfo *foreignrel,
206 : int *relno, int *colno);
207 : static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
208 : int *relno, int *colno);
209 :
210 :
211 : /*
212 : * Examine each qual clause in input_conds, and classify them into two groups,
213 : * which are returned as two lists:
214 : * - remote_conds contains expressions that can be evaluated remotely
215 : * - local_conds contains expressions that can't be evaluated remotely
216 : */
217 : void
218 4758 : classifyConditions(PlannerInfo *root,
219 : RelOptInfo *baserel,
220 : List *input_conds,
221 : List **remote_conds,
222 : List **local_conds)
223 : {
224 : ListCell *lc;
225 :
226 4758 : *remote_conds = NIL;
227 4758 : *local_conds = NIL;
228 :
229 6192 : foreach(lc, input_conds)
230 : {
231 1434 : RestrictInfo *ri = lfirst_node(RestrictInfo, lc);
232 :
233 1434 : if (is_foreign_expr(root, baserel, ri->clause))
234 1268 : *remote_conds = lappend(*remote_conds, ri);
235 : else
236 166 : *local_conds = lappend(*local_conds, ri);
237 : }
238 4758 : }
239 :
240 : /*
241 : * Returns true if given expr is safe to evaluate on the foreign server.
242 : */
243 : bool
244 7278 : is_foreign_expr(PlannerInfo *root,
245 : RelOptInfo *baserel,
246 : Expr *expr)
247 : {
248 : foreign_glob_cxt glob_cxt;
249 : foreign_loc_cxt loc_cxt;
250 7278 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
251 :
252 : /*
253 : * Check that the expression consists of nodes that are safe to execute
254 : * remotely.
255 : */
256 7278 : glob_cxt.root = root;
257 7278 : glob_cxt.foreignrel = baserel;
258 :
259 : /*
260 : * For an upper relation, use relids from its underneath scan relation,
261 : * because the upperrel's own relids currently aren't set to anything
262 : * meaningful by the core code. For other relation, use their own relids.
263 : */
264 7278 : if (IS_UPPER_REL(baserel))
265 896 : glob_cxt.relids = fpinfo->outerrel->relids;
266 : else
267 6382 : glob_cxt.relids = baserel->relids;
268 7278 : loc_cxt.collation = InvalidOid;
269 7278 : loc_cxt.state = FDW_COLLATE_NONE;
270 7278 : if (!foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt, NULL))
271 300 : return false;
272 :
273 : /*
274 : * If the expression has a valid collation that does not arise from a
275 : * foreign var, the expression can not be sent over.
276 : */
277 6978 : if (loc_cxt.state == FDW_COLLATE_UNSAFE)
278 4 : return false;
279 :
280 : /*
281 : * An expression which includes any mutable functions can't be sent over
282 : * because its result is not stable. For example, sending now() remote
283 : * side could cause confusion from clock offsets. Future versions might
284 : * be able to make this choice with more granularity. (We check this last
285 : * because it requires a lot of expensive catalog lookups.)
286 : */
287 6974 : if (contain_mutable_functions((Node *) expr))
288 48 : return false;
289 :
290 : /* OK to evaluate on the remote server */
291 6926 : return true;
292 : }
293 :
294 : /*
295 : * Check if expression is safe to execute remotely, and return true if so.
296 : *
297 : * In addition, *outer_cxt is updated with collation information.
298 : *
299 : * case_arg_cxt is NULL if this subexpression is not inside a CASE-with-arg.
300 : * Otherwise, it points to the collation info derived from the arg expression,
301 : * which must be consulted by any CaseTestExpr.
302 : *
303 : * We must check that the expression contains only node types we can deparse,
304 : * that all types/functions/operators are safe to send (they are "shippable"),
305 : * and that all collations used in the expression derive from Vars of the
306 : * foreign table. Because of the latter, the logic is pretty close to
307 : * assign_collations_walker() in parse_collate.c, though we can assume here
308 : * that the given expression is valid. Note function mutability is not
309 : * currently considered here.
310 : */
311 : static bool
312 18096 : foreign_expr_walker(Node *node,
313 : foreign_glob_cxt *glob_cxt,
314 : foreign_loc_cxt *outer_cxt,
315 : foreign_loc_cxt *case_arg_cxt)
316 : {
317 18096 : bool check_type = true;
318 : PgFdwRelationInfo *fpinfo;
319 : foreign_loc_cxt inner_cxt;
320 : Oid collation;
321 : FDWCollateState state;
322 :
323 : /* Need do nothing for empty subexpressions */
324 18096 : if (node == NULL)
325 644 : return true;
326 :
327 : /* May need server info from baserel's fdw_private struct */
328 17452 : fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private);
329 :
330 : /* Set up inner_cxt for possible recursion to child nodes */
331 17452 : inner_cxt.collation = InvalidOid;
332 17452 : inner_cxt.state = FDW_COLLATE_NONE;
333 :
334 17452 : switch (nodeTag(node))
335 : {
336 8052 : case T_Var:
337 : {
338 8052 : Var *var = (Var *) node;
339 :
340 : /*
341 : * If the Var is from the foreign table, we consider its
342 : * collation (if any) safe to use. If it is from another
343 : * table, we treat its collation the same way as we would a
344 : * Param's collation, ie it's not safe for it to have a
345 : * non-default collation.
346 : */
347 8052 : if (bms_is_member(var->varno, glob_cxt->relids) &&
348 7206 : var->varlevelsup == 0)
349 : {
350 : /* Var belongs to foreign table */
351 :
352 : /*
353 : * System columns other than ctid should not be sent to
354 : * the remote, since we don't make any effort to ensure
355 : * that local and remote values match (tableoid, in
356 : * particular, almost certainly doesn't match).
357 : */
358 7206 : if (var->varattno < 0 &&
359 20 : var->varattno != SelfItemPointerAttributeNumber)
360 16 : return false;
361 :
362 : /* Else check the collation */
363 7190 : collation = var->varcollid;
364 7190 : state = OidIsValid(collation) ? FDW_COLLATE_SAFE : FDW_COLLATE_NONE;
365 : }
366 : else
367 : {
368 : /* Var belongs to some other table */
369 846 : collation = var->varcollid;
370 846 : if (collation == InvalidOid ||
371 : collation == DEFAULT_COLLATION_OID)
372 : {
373 : /*
374 : * It's noncollatable, or it's safe to combine with a
375 : * collatable foreign Var, so set state to NONE.
376 : */
377 846 : state = FDW_COLLATE_NONE;
378 : }
379 : else
380 : {
381 : /*
382 : * Do not fail right away, since the Var might appear
383 : * in a collation-insensitive context.
384 : */
385 0 : state = FDW_COLLATE_UNSAFE;
386 : }
387 : }
388 : }
389 8036 : break;
390 1798 : case T_Const:
391 : {
392 1798 : Const *c = (Const *) node;
393 :
394 : /*
395 : * Constants of regproc and related types can't be shipped
396 : * unless the referenced object is shippable. But NULL's ok.
397 : * (See also the related code in dependency.c.)
398 : */
399 1798 : if (!c->constisnull)
400 : {
401 1780 : switch (c->consttype)
402 : {
403 0 : case REGPROCOID:
404 : case REGPROCEDUREOID:
405 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
406 : ProcedureRelationId, fpinfo))
407 0 : return false;
408 0 : break;
409 0 : case REGOPEROID:
410 : case REGOPERATOROID:
411 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
412 : OperatorRelationId, fpinfo))
413 0 : return false;
414 0 : break;
415 0 : case REGCLASSOID:
416 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
417 : RelationRelationId, fpinfo))
418 0 : return false;
419 0 : break;
420 0 : case REGTYPEOID:
421 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
422 : TypeRelationId, fpinfo))
423 0 : return false;
424 0 : break;
425 0 : case REGCOLLATIONOID:
426 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
427 : CollationRelationId, fpinfo))
428 0 : return false;
429 0 : break;
430 8 : case REGCONFIGOID:
431 :
432 : /*
433 : * For text search objects only, we weaken the
434 : * normal shippability criterion to allow all OIDs
435 : * below FirstNormalObjectId. Without this, none
436 : * of the initdb-installed TS configurations would
437 : * be shippable, which would be quite annoying.
438 : */
439 8 : if (DatumGetObjectId(c->constvalue) >= FirstNormalObjectId &&
440 8 : !is_shippable(DatumGetObjectId(c->constvalue),
441 : TSConfigRelationId, fpinfo))
442 4 : return false;
443 4 : break;
444 0 : case REGDICTIONARYOID:
445 0 : if (DatumGetObjectId(c->constvalue) >= FirstNormalObjectId &&
446 0 : !is_shippable(DatumGetObjectId(c->constvalue),
447 : TSDictionaryRelationId, fpinfo))
448 0 : return false;
449 0 : break;
450 0 : case REGNAMESPACEOID:
451 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
452 : NamespaceRelationId, fpinfo))
453 0 : return false;
454 0 : break;
455 0 : case REGROLEOID:
456 0 : if (!is_shippable(DatumGetObjectId(c->constvalue),
457 : AuthIdRelationId, fpinfo))
458 0 : return false;
459 0 : break;
460 : }
461 18 : }
462 :
463 : /*
464 : * If the constant has nondefault collation, either it's of a
465 : * non-builtin type, or it reflects folding of a CollateExpr.
466 : * It's unsafe to send to the remote unless it's used in a
467 : * non-collation-sensitive context.
468 : */
469 1794 : collation = c->constcollid;
470 1794 : if (collation == InvalidOid ||
471 : collation == DEFAULT_COLLATION_OID)
472 1790 : state = FDW_COLLATE_NONE;
473 : else
474 4 : state = FDW_COLLATE_UNSAFE;
475 : }
476 1794 : break;
477 50 : case T_Param:
478 : {
479 50 : Param *p = (Param *) node;
480 :
481 : /*
482 : * If it's a MULTIEXPR Param, punt. We can't tell from here
483 : * whether the referenced sublink/subplan contains any remote
484 : * Vars; if it does, handling that is too complicated to
485 : * consider supporting at present. Fortunately, MULTIEXPR
486 : * Params are not reduced to plain PARAM_EXEC until the end of
487 : * planning, so we can easily detect this case. (Normal
488 : * PARAM_EXEC Params are safe to ship because their values
489 : * come from somewhere else in the plan tree; but a MULTIEXPR
490 : * references a sub-select elsewhere in the same targetlist,
491 : * so we'd be on the hook to evaluate it somehow if we wanted
492 : * to handle such cases as direct foreign updates.)
493 : */
494 50 : if (p->paramkind == PARAM_MULTIEXPR)
495 6 : return false;
496 :
497 : /*
498 : * Collation rule is same as for Consts and non-foreign Vars.
499 : */
500 44 : collation = p->paramcollid;
501 44 : if (collation == InvalidOid ||
502 : collation == DEFAULT_COLLATION_OID)
503 44 : state = FDW_COLLATE_NONE;
504 : else
505 0 : state = FDW_COLLATE_UNSAFE;
506 : }
507 44 : break;
508 2 : case T_SubscriptingRef:
509 : {
510 2 : SubscriptingRef *sr = (SubscriptingRef *) node;
511 :
512 : /* Assignment should not be in restrictions. */
513 2 : if (sr->refassgnexpr != NULL)
514 0 : return false;
515 :
516 : /*
517 : * Recurse into the remaining subexpressions. The container
518 : * subscripts will not affect collation of the SubscriptingRef
519 : * result, so do those first and reset inner_cxt afterwards.
520 : */
521 2 : if (!foreign_expr_walker((Node *) sr->refupperindexpr,
522 : glob_cxt, &inner_cxt, case_arg_cxt))
523 0 : return false;
524 2 : inner_cxt.collation = InvalidOid;
525 2 : inner_cxt.state = FDW_COLLATE_NONE;
526 2 : if (!foreign_expr_walker((Node *) sr->reflowerindexpr,
527 : glob_cxt, &inner_cxt, case_arg_cxt))
528 0 : return false;
529 2 : inner_cxt.collation = InvalidOid;
530 2 : inner_cxt.state = FDW_COLLATE_NONE;
531 2 : if (!foreign_expr_walker((Node *) sr->refexpr,
532 : glob_cxt, &inner_cxt, case_arg_cxt))
533 0 : return false;
534 :
535 : /*
536 : * Container subscripting typically yields same collation as
537 : * refexpr's, but in case it doesn't, use same logic as for
538 : * function nodes.
539 : */
540 2 : collation = sr->refcollid;
541 2 : if (collation == InvalidOid)
542 2 : state = FDW_COLLATE_NONE;
543 0 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
544 0 : collation == inner_cxt.collation)
545 0 : state = FDW_COLLATE_SAFE;
546 0 : else if (collation == DEFAULT_COLLATION_OID)
547 0 : state = FDW_COLLATE_NONE;
548 : else
549 0 : state = FDW_COLLATE_UNSAFE;
550 : }
551 2 : break;
552 268 : case T_FuncExpr:
553 : {
554 268 : FuncExpr *fe = (FuncExpr *) node;
555 :
556 : /*
557 : * If function used by the expression is not shippable, it
558 : * can't be sent to remote because it might have incompatible
559 : * semantics on remote side.
560 : */
561 268 : if (!is_shippable(fe->funcid, ProcedureRelationId, fpinfo))
562 16 : return false;
563 :
564 : /*
565 : * Recurse to input subexpressions.
566 : */
567 252 : if (!foreign_expr_walker((Node *) fe->args,
568 : glob_cxt, &inner_cxt, case_arg_cxt))
569 26 : return false;
570 :
571 : /*
572 : * If function's input collation is not derived from a foreign
573 : * Var, it can't be sent to remote.
574 : */
575 226 : if (fe->inputcollid == InvalidOid)
576 : /* OK, inputs are all noncollatable */ ;
577 66 : else if (inner_cxt.state != FDW_COLLATE_SAFE ||
578 40 : fe->inputcollid != inner_cxt.collation)
579 26 : return false;
580 :
581 : /*
582 : * Detect whether node is introducing a collation not derived
583 : * from a foreign Var. (If so, we just mark it unsafe for now
584 : * rather than immediately returning false, since the parent
585 : * node might not care.)
586 : */
587 200 : collation = fe->funccollid;
588 200 : if (collation == InvalidOid)
589 162 : state = FDW_COLLATE_NONE;
590 38 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
591 36 : collation == inner_cxt.collation)
592 36 : state = FDW_COLLATE_SAFE;
593 2 : else if (collation == DEFAULT_COLLATION_OID)
594 0 : state = FDW_COLLATE_NONE;
595 : else
596 2 : state = FDW_COLLATE_UNSAFE;
597 : }
598 200 : break;
599 3052 : case T_OpExpr:
600 : case T_DistinctExpr: /* struct-equivalent to OpExpr */
601 : {
602 3052 : OpExpr *oe = (OpExpr *) node;
603 :
604 : /*
605 : * Similarly, only shippable operators can be sent to remote.
606 : * (If the operator is shippable, we assume its underlying
607 : * function is too.)
608 : */
609 3052 : if (!is_shippable(oe->opno, OperatorRelationId, fpinfo))
610 94 : return false;
611 :
612 : /*
613 : * Recurse to input subexpressions.
614 : */
615 2958 : if (!foreign_expr_walker((Node *) oe->args,
616 : glob_cxt, &inner_cxt, case_arg_cxt))
617 126 : return false;
618 :
619 : /*
620 : * If operator's input collation is not derived from a foreign
621 : * Var, it can't be sent to remote.
622 : */
623 2832 : if (oe->inputcollid == InvalidOid)
624 : /* OK, inputs are all noncollatable */ ;
625 138 : else if (inner_cxt.state != FDW_COLLATE_SAFE ||
626 126 : oe->inputcollid != inner_cxt.collation)
627 12 : return false;
628 :
629 : /* Result-collation handling is same as for functions */
630 2820 : collation = oe->opcollid;
631 2820 : if (collation == InvalidOid)
632 2792 : state = FDW_COLLATE_NONE;
633 28 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
634 28 : collation == inner_cxt.collation)
635 28 : state = FDW_COLLATE_SAFE;
636 0 : else if (collation == DEFAULT_COLLATION_OID)
637 0 : state = FDW_COLLATE_NONE;
638 : else
639 0 : state = FDW_COLLATE_UNSAFE;
640 : }
641 2820 : break;
642 6 : case T_ScalarArrayOpExpr:
643 : {
644 6 : ScalarArrayOpExpr *oe = (ScalarArrayOpExpr *) node;
645 :
646 : /*
647 : * Again, only shippable operators can be sent to remote.
648 : */
649 6 : if (!is_shippable(oe->opno, OperatorRelationId, fpinfo))
650 0 : return false;
651 :
652 : /*
653 : * Recurse to input subexpressions.
654 : */
655 6 : if (!foreign_expr_walker((Node *) oe->args,
656 : glob_cxt, &inner_cxt, case_arg_cxt))
657 0 : return false;
658 :
659 : /*
660 : * If operator's input collation is not derived from a foreign
661 : * Var, it can't be sent to remote.
662 : */
663 6 : if (oe->inputcollid == InvalidOid)
664 : /* OK, inputs are all noncollatable */ ;
665 0 : else if (inner_cxt.state != FDW_COLLATE_SAFE ||
666 0 : oe->inputcollid != inner_cxt.collation)
667 0 : return false;
668 :
669 : /* Output is always boolean and so noncollatable. */
670 6 : collation = InvalidOid;
671 6 : state = FDW_COLLATE_NONE;
672 : }
673 6 : break;
674 136 : case T_RelabelType:
675 : {
676 136 : RelabelType *r = (RelabelType *) node;
677 :
678 : /*
679 : * Recurse to input subexpression.
680 : */
681 136 : if (!foreign_expr_walker((Node *) r->arg,
682 : glob_cxt, &inner_cxt, case_arg_cxt))
683 0 : return false;
684 :
685 : /*
686 : * RelabelType must not introduce a collation not derived from
687 : * an input foreign Var (same logic as for a real function).
688 : */
689 136 : collation = r->resultcollid;
690 136 : if (collation == InvalidOid)
691 0 : state = FDW_COLLATE_NONE;
692 136 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
693 128 : collation == inner_cxt.collation)
694 116 : state = FDW_COLLATE_SAFE;
695 20 : else if (collation == DEFAULT_COLLATION_OID)
696 6 : state = FDW_COLLATE_NONE;
697 : else
698 14 : state = FDW_COLLATE_UNSAFE;
699 : }
700 136 : break;
701 72 : case T_BoolExpr:
702 : {
703 72 : BoolExpr *b = (BoolExpr *) node;
704 :
705 : /*
706 : * Recurse to input subexpressions.
707 : */
708 72 : if (!foreign_expr_walker((Node *) b->args,
709 : glob_cxt, &inner_cxt, case_arg_cxt))
710 0 : return false;
711 :
712 : /* Output is always boolean and so noncollatable. */
713 72 : collation = InvalidOid;
714 72 : state = FDW_COLLATE_NONE;
715 : }
716 72 : break;
717 54 : case T_NullTest:
718 : {
719 54 : NullTest *nt = (NullTest *) node;
720 :
721 : /*
722 : * Recurse to input subexpressions.
723 : */
724 54 : if (!foreign_expr_walker((Node *) nt->arg,
725 : glob_cxt, &inner_cxt, case_arg_cxt))
726 0 : return false;
727 :
728 : /* Output is always boolean and so noncollatable. */
729 54 : collation = InvalidOid;
730 54 : state = FDW_COLLATE_NONE;
731 : }
732 54 : break;
733 26 : case T_CaseExpr:
734 : {
735 26 : CaseExpr *ce = (CaseExpr *) node;
736 : foreign_loc_cxt arg_cxt;
737 : foreign_loc_cxt tmp_cxt;
738 : ListCell *lc;
739 :
740 : /*
741 : * Recurse to CASE's arg expression, if any. Its collation
742 : * has to be saved aside for use while examining CaseTestExprs
743 : * within the WHEN expressions.
744 : */
745 26 : arg_cxt.collation = InvalidOid;
746 26 : arg_cxt.state = FDW_COLLATE_NONE;
747 26 : if (ce->arg)
748 : {
749 14 : if (!foreign_expr_walker((Node *) ce->arg,
750 : glob_cxt, &arg_cxt, case_arg_cxt))
751 2 : return false;
752 : }
753 :
754 : /* Examine the CaseWhen subexpressions. */
755 58 : foreach(lc, ce->args)
756 : {
757 34 : CaseWhen *cw = lfirst_node(CaseWhen, lc);
758 :
759 34 : if (ce->arg)
760 : {
761 : /*
762 : * In a CASE-with-arg, the parser should have produced
763 : * WHEN clauses of the form "CaseTestExpr = RHS",
764 : * possibly with an implicit coercion inserted above
765 : * the CaseTestExpr. However in an expression that's
766 : * been through the optimizer, the WHEN clause could
767 : * be almost anything (since the equality operator
768 : * could have been expanded into an inline function).
769 : * In such cases forbid pushdown, because
770 : * deparseCaseExpr can't handle it.
771 : */
772 22 : Node *whenExpr = (Node *) cw->expr;
773 : List *opArgs;
774 :
775 22 : if (!IsA(whenExpr, OpExpr))
776 2 : return false;
777 :
778 22 : opArgs = ((OpExpr *) whenExpr)->args;
779 22 : if (list_length(opArgs) != 2 ||
780 22 : !IsA(strip_implicit_coercions(linitial(opArgs)),
781 : CaseTestExpr))
782 0 : return false;
783 : }
784 :
785 : /*
786 : * Recurse to WHEN expression, passing down the arg info.
787 : * Its collation doesn't affect the result (really, it
788 : * should be boolean and thus not have a collation).
789 : */
790 34 : tmp_cxt.collation = InvalidOid;
791 34 : tmp_cxt.state = FDW_COLLATE_NONE;
792 34 : if (!foreign_expr_walker((Node *) cw->expr,
793 : glob_cxt, &tmp_cxt, &arg_cxt))
794 2 : return false;
795 :
796 : /* Recurse to THEN expression. */
797 32 : if (!foreign_expr_walker((Node *) cw->result,
798 : glob_cxt, &inner_cxt, case_arg_cxt))
799 0 : return false;
800 : }
801 :
802 : /* Recurse to ELSE expression. */
803 24 : if (!foreign_expr_walker((Node *) ce->defresult,
804 : glob_cxt, &inner_cxt, case_arg_cxt))
805 0 : return false;
806 :
807 : /*
808 : * Detect whether node is introducing a collation not derived
809 : * from a foreign Var. (If so, we just mark it unsafe for now
810 : * rather than immediately returning false, since the parent
811 : * node might not care.) This is the same as for function
812 : * nodes, except that the input collation is derived from only
813 : * the THEN and ELSE subexpressions.
814 : */
815 24 : collation = ce->casecollid;
816 24 : if (collation == InvalidOid)
817 24 : state = FDW_COLLATE_NONE;
818 0 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
819 0 : collation == inner_cxt.collation)
820 0 : state = FDW_COLLATE_SAFE;
821 0 : else if (collation == DEFAULT_COLLATION_OID)
822 0 : state = FDW_COLLATE_NONE;
823 : else
824 0 : state = FDW_COLLATE_UNSAFE;
825 : }
826 24 : break;
827 22 : case T_CaseTestExpr:
828 : {
829 22 : CaseTestExpr *c = (CaseTestExpr *) node;
830 :
831 : /* Punt if we seem not to be inside a CASE arg WHEN. */
832 22 : if (!case_arg_cxt)
833 0 : return false;
834 :
835 : /*
836 : * Otherwise, any nondefault collation attached to the
837 : * CaseTestExpr node must be derived from foreign Var(s) in
838 : * the CASE arg.
839 : */
840 22 : collation = c->collation;
841 22 : if (collation == InvalidOid)
842 16 : state = FDW_COLLATE_NONE;
843 6 : else if (case_arg_cxt->state == FDW_COLLATE_SAFE &&
844 4 : collation == case_arg_cxt->collation)
845 4 : state = FDW_COLLATE_SAFE;
846 2 : else if (collation == DEFAULT_COLLATION_OID)
847 0 : state = FDW_COLLATE_NONE;
848 : else
849 2 : state = FDW_COLLATE_UNSAFE;
850 : }
851 22 : break;
852 8 : case T_ArrayExpr:
853 : {
854 8 : ArrayExpr *a = (ArrayExpr *) node;
855 :
856 : /*
857 : * Recurse to input subexpressions.
858 : */
859 8 : if (!foreign_expr_walker((Node *) a->elements,
860 : glob_cxt, &inner_cxt, case_arg_cxt))
861 0 : return false;
862 :
863 : /*
864 : * ArrayExpr must not introduce a collation not derived from
865 : * an input foreign Var (same logic as for a function).
866 : */
867 8 : collation = a->array_collid;
868 8 : if (collation == InvalidOid)
869 8 : state = FDW_COLLATE_NONE;
870 0 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
871 0 : collation == inner_cxt.collation)
872 0 : state = FDW_COLLATE_SAFE;
873 0 : else if (collation == DEFAULT_COLLATION_OID)
874 0 : state = FDW_COLLATE_NONE;
875 : else
876 0 : state = FDW_COLLATE_UNSAFE;
877 : }
878 8 : break;
879 3296 : case T_List:
880 : {
881 3296 : List *l = (List *) node;
882 : ListCell *lc;
883 :
884 : /*
885 : * Recurse to component subexpressions.
886 : */
887 9368 : foreach(lc, l)
888 : {
889 6250 : if (!foreign_expr_walker((Node *) lfirst(lc),
890 : glob_cxt, &inner_cxt, case_arg_cxt))
891 178 : return false;
892 : }
893 :
894 : /*
895 : * When processing a list, collation state just bubbles up
896 : * from the list elements.
897 : */
898 3118 : collation = inner_cxt.collation;
899 3118 : state = inner_cxt.state;
900 :
901 : /* Don't apply exprType() to the list. */
902 3118 : check_type = false;
903 : }
904 3118 : break;
905 550 : case T_Aggref:
906 : {
907 550 : Aggref *agg = (Aggref *) node;
908 : ListCell *lc;
909 :
910 : /* Not safe to pushdown when not in grouping context */
911 550 : if (!IS_UPPER_REL(glob_cxt->foreignrel))
912 0 : return false;
913 :
914 : /* Only non-split aggregates are pushable. */
915 550 : if (agg->aggsplit != AGGSPLIT_SIMPLE)
916 0 : return false;
917 :
918 : /* As usual, it must be shippable. */
919 550 : if (!is_shippable(agg->aggfnoid, ProcedureRelationId, fpinfo))
920 8 : return false;
921 :
922 : /*
923 : * Recurse to input args. aggdirectargs, aggorder and
924 : * aggdistinct are all present in args, so no need to check
925 : * their shippability explicitly.
926 : */
927 980 : foreach(lc, agg->args)
928 : {
929 462 : Node *n = (Node *) lfirst(lc);
930 :
931 : /* If TargetEntry, extract the expression from it */
932 462 : if (IsA(n, TargetEntry))
933 : {
934 462 : TargetEntry *tle = (TargetEntry *) n;
935 :
936 462 : n = (Node *) tle->expr;
937 : }
938 :
939 462 : if (!foreign_expr_walker(n,
940 : glob_cxt, &inner_cxt, case_arg_cxt))
941 24 : return false;
942 : }
943 :
944 : /*
945 : * For aggorder elements, check whether the sort operator, if
946 : * specified, is shippable or not.
947 : */
948 518 : if (agg->aggorder)
949 : {
950 140 : foreach(lc, agg->aggorder)
951 : {
952 76 : SortGroupClause *srt = (SortGroupClause *) lfirst(lc);
953 : Oid sortcoltype;
954 : TypeCacheEntry *typentry;
955 : TargetEntry *tle;
956 :
957 76 : tle = get_sortgroupref_tle(srt->tleSortGroupRef,
958 : agg->args);
959 76 : sortcoltype = exprType((Node *) tle->expr);
960 76 : typentry = lookup_type_cache(sortcoltype,
961 : TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
962 : /* Check shippability of non-default sort operator. */
963 76 : if (srt->sortop != typentry->lt_opr &&
964 28 : srt->sortop != typentry->gt_opr &&
965 12 : !is_shippable(srt->sortop, OperatorRelationId,
966 : fpinfo))
967 8 : return false;
968 : }
969 : }
970 :
971 : /* Check aggregate filter */
972 510 : if (!foreign_expr_walker((Node *) agg->aggfilter,
973 : glob_cxt, &inner_cxt, case_arg_cxt))
974 4 : return false;
975 :
976 : /*
977 : * If aggregate's input collation is not derived from a
978 : * foreign Var, it can't be sent to remote.
979 : */
980 506 : if (agg->inputcollid == InvalidOid)
981 : /* OK, inputs are all noncollatable */ ;
982 44 : else if (inner_cxt.state != FDW_COLLATE_SAFE ||
983 44 : agg->inputcollid != inner_cxt.collation)
984 0 : return false;
985 :
986 : /*
987 : * Detect whether node is introducing a collation not derived
988 : * from a foreign Var. (If so, we just mark it unsafe for now
989 : * rather than immediately returning false, since the parent
990 : * node might not care.)
991 : */
992 506 : collation = agg->aggcollid;
993 506 : if (collation == InvalidOid)
994 504 : state = FDW_COLLATE_NONE;
995 2 : else if (inner_cxt.state == FDW_COLLATE_SAFE &&
996 2 : collation == inner_cxt.collation)
997 2 : state = FDW_COLLATE_SAFE;
998 0 : else if (collation == DEFAULT_COLLATION_OID)
999 0 : state = FDW_COLLATE_NONE;
1000 : else
1001 0 : state = FDW_COLLATE_UNSAFE;
1002 : }
1003 506 : break;
1004 60 : default:
1005 :
1006 : /*
1007 : * If it's anything else, assume it's unsafe. This list can be
1008 : * expanded later, but don't forget to add deparse support below.
1009 : */
1010 60 : return false;
1011 : }
1012 :
1013 : /*
1014 : * If result type of given expression is not shippable, it can't be sent
1015 : * to remote because it might have incompatible semantics on remote side.
1016 : */
1017 16842 : if (check_type && !is_shippable(exprType(node), TypeRelationId, fpinfo))
1018 50 : return false;
1019 :
1020 : /*
1021 : * Now, merge my collation information into my parent's state.
1022 : */
1023 16792 : if (state > outer_cxt->state)
1024 : {
1025 : /* Override previous parent state */
1026 960 : outer_cxt->collation = collation;
1027 960 : outer_cxt->state = state;
1028 : }
1029 15832 : else if (state == outer_cxt->state)
1030 : {
1031 : /* Merge, or detect error if there's a collation conflict */
1032 15730 : switch (state)
1033 : {
1034 15706 : case FDW_COLLATE_NONE:
1035 : /* Nothing + nothing is still nothing */
1036 15706 : break;
1037 22 : case FDW_COLLATE_SAFE:
1038 22 : if (collation != outer_cxt->collation)
1039 : {
1040 : /*
1041 : * Non-default collation always beats default.
1042 : */
1043 0 : if (outer_cxt->collation == DEFAULT_COLLATION_OID)
1044 : {
1045 : /* Override previous parent state */
1046 0 : outer_cxt->collation = collation;
1047 : }
1048 0 : else if (collation != DEFAULT_COLLATION_OID)
1049 : {
1050 : /*
1051 : * Conflict; show state as indeterminate. We don't
1052 : * want to "return false" right away, since parent
1053 : * node might not care about collation.
1054 : */
1055 0 : outer_cxt->state = FDW_COLLATE_UNSAFE;
1056 : }
1057 : }
1058 22 : break;
1059 2 : case FDW_COLLATE_UNSAFE:
1060 : /* We're still conflicted ... */
1061 2 : break;
1062 : }
1063 102 : }
1064 :
1065 : /* It looks OK */
1066 16792 : return true;
1067 : }
1068 :
1069 : /*
1070 : * Returns true if given expr is something we'd have to send the value of
1071 : * to the foreign server.
1072 : *
1073 : * This should return true when the expression is a shippable node that
1074 : * deparseExpr would add to context->params_list. Note that we don't care
1075 : * if the expression *contains* such a node, only whether one appears at top
1076 : * level. We need this to detect cases where setrefs.c would recognize a
1077 : * false match between an fdw_exprs item (which came from the params_list)
1078 : * and an entry in fdw_scan_tlist (which we're considering putting the given
1079 : * expression into).
1080 : */
1081 : bool
1082 542 : is_foreign_param(PlannerInfo *root,
1083 : RelOptInfo *baserel,
1084 : Expr *expr)
1085 : {
1086 542 : if (expr == NULL)
1087 0 : return false;
1088 :
1089 542 : switch (nodeTag(expr))
1090 : {
1091 152 : case T_Var:
1092 : {
1093 : /* It would have to be sent unless it's a foreign Var */
1094 152 : Var *var = (Var *) expr;
1095 152 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
1096 : Relids relids;
1097 :
1098 152 : if (IS_UPPER_REL(baserel))
1099 152 : relids = fpinfo->outerrel->relids;
1100 : else
1101 0 : relids = baserel->relids;
1102 :
1103 152 : if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
1104 152 : return false; /* foreign Var, so not a param */
1105 : else
1106 0 : return true; /* it'd have to be a param */
1107 : break;
1108 : }
1109 8 : case T_Param:
1110 : /* Params always have to be sent to the foreign server */
1111 8 : return true;
1112 382 : default:
1113 382 : break;
1114 : }
1115 382 : return false;
1116 : }
1117 :
1118 : /*
1119 : * Returns true if it's safe to push down the sort expression described by
1120 : * 'pathkey' to the foreign server.
1121 : */
1122 : bool
1123 1518 : is_foreign_pathkey(PlannerInfo *root,
1124 : RelOptInfo *baserel,
1125 : PathKey *pathkey)
1126 : {
1127 1518 : EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
1128 1518 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
1129 :
1130 : /*
1131 : * is_foreign_expr would detect volatile expressions as well, but checking
1132 : * ec_has_volatile here saves some cycles.
1133 : */
1134 1518 : if (pathkey_ec->ec_has_volatile)
1135 8 : return false;
1136 :
1137 : /* can't push down the sort if the pathkey's opfamily is not shippable */
1138 1510 : if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId, fpinfo))
1139 6 : return false;
1140 :
1141 : /* can push if a suitable EC member exists */
1142 1504 : return (find_em_for_rel(root, pathkey_ec, baserel) != NULL);
1143 : }
1144 :
1145 : /*
1146 : * Convert type OID + typmod info into a type name we can ship to the remote
1147 : * server. Someplace else had better have verified that this type name is
1148 : * expected to be known on the remote end.
1149 : *
1150 : * This is almost just format_type_with_typemod(), except that if left to its
1151 : * own devices, that function will make schema-qualification decisions based
1152 : * on the local search_path, which is wrong. We must schema-qualify all
1153 : * type names that are not in pg_catalog. We assume here that built-in types
1154 : * are all in pg_catalog and need not be qualified; otherwise, qualify.
1155 : */
1156 : static char *
1157 1054 : deparse_type_name(Oid type_oid, int32 typemod)
1158 : {
1159 1054 : bits16 flags = FORMAT_TYPE_TYPEMOD_GIVEN;
1160 :
1161 1054 : if (!is_builtin(type_oid))
1162 0 : flags |= FORMAT_TYPE_FORCE_QUALIFY;
1163 :
1164 1054 : return format_type_extended(type_oid, typemod, flags);
1165 : }
1166 :
1167 : /*
1168 : * Build the targetlist for given relation to be deparsed as SELECT clause.
1169 : *
1170 : * The output targetlist contains the columns that need to be fetched from the
1171 : * foreign server for the given relation. If foreignrel is an upper relation,
1172 : * then the output targetlist can also contain expressions to be evaluated on
1173 : * foreign server.
1174 : */
1175 : List *
1176 1548 : build_tlist_to_deparse(RelOptInfo *foreignrel)
1177 : {
1178 1548 : List *tlist = NIL;
1179 1548 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1180 : ListCell *lc;
1181 :
1182 : /*
1183 : * For an upper relation, we have already built the target list while
1184 : * checking shippability, so just return that.
1185 : */
1186 1548 : if (IS_UPPER_REL(foreignrel))
1187 322 : return fpinfo->grouped_tlist;
1188 :
1189 : /*
1190 : * We require columns specified in foreignrel->reltarget->exprs and those
1191 : * required for evaluating the local conditions.
1192 : */
1193 1226 : tlist = add_to_flat_tlist(tlist,
1194 1226 : pull_var_clause((Node *) foreignrel->reltarget->exprs,
1195 : PVC_RECURSE_PLACEHOLDERS));
1196 1274 : foreach(lc, fpinfo->local_conds)
1197 : {
1198 48 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1199 :
1200 48 : tlist = add_to_flat_tlist(tlist,
1201 48 : pull_var_clause((Node *) rinfo->clause,
1202 : PVC_RECURSE_PLACEHOLDERS));
1203 : }
1204 :
1205 1226 : return tlist;
1206 : }
1207 :
1208 : /*
1209 : * Deparse SELECT statement for given relation into buf.
1210 : *
1211 : * tlist contains the list of desired columns to be fetched from foreign server.
1212 : * For a base relation fpinfo->attrs_used is used to construct SELECT clause,
1213 : * hence the tlist is ignored for a base relation.
1214 : *
1215 : * remote_conds is the list of conditions to be deparsed into the WHERE clause
1216 : * (or, in the case of upper relations, into the HAVING clause).
1217 : *
1218 : * If params_list is not NULL, it receives a list of Params and other-relation
1219 : * Vars used in the clauses; these values must be transmitted to the remote
1220 : * server as parameter values.
1221 : *
1222 : * If params_list is NULL, we're generating the query for EXPLAIN purposes,
1223 : * so Params and other-relation Vars should be replaced by dummy values.
1224 : *
1225 : * pathkeys is the list of pathkeys to order the result by.
1226 : *
1227 : * is_subquery is the flag to indicate whether to deparse the specified
1228 : * relation as a subquery.
1229 : *
1230 : * List of columns selected is returned in retrieved_attrs.
1231 : */
1232 : void
1233 4460 : deparseSelectStmtForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *rel,
1234 : List *tlist, List *remote_conds, List *pathkeys,
1235 : bool has_final_sort, bool has_limit, bool is_subquery,
1236 : List **retrieved_attrs, List **params_list)
1237 : {
1238 : deparse_expr_cxt context;
1239 4460 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1240 : List *quals;
1241 :
1242 : /*
1243 : * We handle relations for foreign tables, joins between those and upper
1244 : * relations.
1245 : */
1246 : Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
1247 :
1248 : /* Fill portions of context common to upper, join and base relation */
1249 4460 : context.buf = buf;
1250 4460 : context.root = root;
1251 4460 : context.foreignrel = rel;
1252 4460 : context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
1253 4460 : context.params_list = params_list;
1254 :
1255 : /* Construct SELECT clause */
1256 4460 : deparseSelectSql(tlist, is_subquery, retrieved_attrs, &context);
1257 :
1258 : /*
1259 : * For upper relations, the WHERE clause is built from the remote
1260 : * conditions of the underlying scan relation; otherwise, we can use the
1261 : * supplied list of remote conditions directly.
1262 : */
1263 4460 : if (IS_UPPER_REL(rel))
1264 322 : {
1265 : PgFdwRelationInfo *ofpinfo;
1266 :
1267 322 : ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
1268 322 : quals = ofpinfo->remote_conds;
1269 : }
1270 : else
1271 4138 : quals = remote_conds;
1272 :
1273 : /* Construct FROM and WHERE clauses */
1274 4460 : deparseFromExpr(quals, &context);
1275 :
1276 4460 : if (IS_UPPER_REL(rel))
1277 : {
1278 : /* Append GROUP BY clause */
1279 322 : appendGroupByClause(tlist, &context);
1280 :
1281 : /* Append HAVING clause */
1282 322 : if (remote_conds)
1283 : {
1284 36 : appendStringInfoString(buf, " HAVING ");
1285 36 : appendConditions(remote_conds, &context);
1286 : }
1287 : }
1288 :
1289 : /* Add ORDER BY clause if we found any useful pathkeys */
1290 4460 : if (pathkeys)
1291 1426 : appendOrderByClause(pathkeys, has_final_sort, &context);
1292 :
1293 : /* Add LIMIT clause if necessary */
1294 4460 : if (has_limit)
1295 282 : appendLimitClause(&context);
1296 :
1297 : /* Add any necessary FOR UPDATE/SHARE. */
1298 4460 : deparseLockingClause(&context);
1299 4460 : }
1300 :
1301 : /*
1302 : * Construct a simple SELECT statement that retrieves desired columns
1303 : * of the specified foreign table, and append it to "buf". The output
1304 : * contains just "SELECT ... ".
1305 : *
1306 : * We also create an integer List of the columns being retrieved, which is
1307 : * returned to *retrieved_attrs, unless we deparse the specified relation
1308 : * as a subquery.
1309 : *
1310 : * tlist is the list of desired columns. is_subquery is the flag to
1311 : * indicate whether to deparse the specified relation as a subquery.
1312 : * Read prologue of deparseSelectStmtForRel() for details.
1313 : */
1314 : static void
1315 4460 : deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs,
1316 : deparse_expr_cxt *context)
1317 : {
1318 4460 : StringInfo buf = context->buf;
1319 4460 : RelOptInfo *foreignrel = context->foreignrel;
1320 4460 : PlannerInfo *root = context->root;
1321 4460 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1322 :
1323 : /*
1324 : * Construct SELECT list
1325 : */
1326 4460 : appendStringInfoString(buf, "SELECT ");
1327 :
1328 4460 : if (is_subquery)
1329 : {
1330 : /*
1331 : * For a relation that is deparsed as a subquery, emit expressions
1332 : * specified in the relation's reltarget. Note that since this is for
1333 : * the subquery, no need to care about *retrieved_attrs.
1334 : */
1335 72 : deparseSubqueryTargetList(context);
1336 : }
1337 4388 : else if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
1338 : {
1339 : /*
1340 : * For a join or upper relation the input tlist gives the list of
1341 : * columns required to be fetched from the foreign server.
1342 : */
1343 1548 : deparseExplicitTargetList(tlist, false, retrieved_attrs, context);
1344 : }
1345 : else
1346 : {
1347 : /*
1348 : * For a base relation fpinfo->attrs_used gives the list of columns
1349 : * required to be fetched from the foreign server.
1350 : */
1351 2840 : RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
1352 :
1353 : /*
1354 : * Core code already has some lock on each rel being planned, so we
1355 : * can use NoLock here.
1356 : */
1357 2840 : Relation rel = table_open(rte->relid, NoLock);
1358 :
1359 2840 : deparseTargetList(buf, rte, foreignrel->relid, rel, false,
1360 : fpinfo->attrs_used, false, retrieved_attrs);
1361 2840 : table_close(rel, NoLock);
1362 : }
1363 4460 : }
1364 :
1365 : /*
1366 : * Construct a FROM clause and, if needed, a WHERE clause, and append those to
1367 : * "buf".
1368 : *
1369 : * quals is the list of clauses to be included in the WHERE clause.
1370 : * (These may or may not include RestrictInfo decoration.)
1371 : */
1372 : static void
1373 4460 : deparseFromExpr(List *quals, deparse_expr_cxt *context)
1374 : {
1375 4460 : StringInfo buf = context->buf;
1376 4460 : RelOptInfo *scanrel = context->scanrel;
1377 4460 : List *additional_conds = NIL;
1378 :
1379 : /* For upper relations, scanrel must be either a joinrel or a baserel */
1380 : Assert(!IS_UPPER_REL(context->foreignrel) ||
1381 : IS_JOIN_REL(scanrel) || IS_SIMPLE_REL(scanrel));
1382 :
1383 : /* Construct FROM clause */
1384 4460 : appendStringInfoString(buf, " FROM ");
1385 4460 : deparseFromExprForRel(buf, context->root, scanrel,
1386 4460 : (bms_membership(scanrel->relids) == BMS_MULTIPLE),
1387 : (Index) 0, NULL, &additional_conds,
1388 : context->params_list);
1389 4460 : appendWhereClause(quals, additional_conds, context);
1390 4460 : if (additional_conds != NIL)
1391 256 : list_free_deep(additional_conds);
1392 4460 : }
1393 :
1394 : /*
1395 : * Emit a target list that retrieves the columns specified in attrs_used.
1396 : * This is used for both SELECT and RETURNING targetlists; the is_returning
1397 : * parameter is true only for a RETURNING targetlist.
1398 : *
1399 : * The tlist text is appended to buf, and we also create an integer List
1400 : * of the columns being retrieved, which is returned to *retrieved_attrs.
1401 : *
1402 : * If qualify_col is true, add relation alias before the column name.
1403 : */
1404 : static void
1405 3524 : deparseTargetList(StringInfo buf,
1406 : RangeTblEntry *rte,
1407 : Index rtindex,
1408 : Relation rel,
1409 : bool is_returning,
1410 : Bitmapset *attrs_used,
1411 : bool qualify_col,
1412 : List **retrieved_attrs)
1413 : {
1414 3524 : TupleDesc tupdesc = RelationGetDescr(rel);
1415 : bool have_wholerow;
1416 : bool first;
1417 : int i;
1418 :
1419 3524 : *retrieved_attrs = NIL;
1420 :
1421 : /* If there's a whole-row reference, we'll need all the columns. */
1422 3524 : have_wholerow = bms_is_member(0 - FirstLowInvalidHeapAttributeNumber,
1423 : attrs_used);
1424 :
1425 3524 : first = true;
1426 25318 : for (i = 1; i <= tupdesc->natts; i++)
1427 : {
1428 21794 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
1429 :
1430 : /* Ignore dropped attributes. */
1431 21794 : if (attr->attisdropped)
1432 1962 : continue;
1433 :
1434 33564 : if (have_wholerow ||
1435 13732 : bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
1436 : attrs_used))
1437 : {
1438 12258 : if (!first)
1439 8970 : appendStringInfoString(buf, ", ");
1440 3288 : else if (is_returning)
1441 208 : appendStringInfoString(buf, " RETURNING ");
1442 12258 : first = false;
1443 :
1444 12258 : deparseColumnRef(buf, rtindex, i, rte, qualify_col);
1445 :
1446 12258 : *retrieved_attrs = lappend_int(*retrieved_attrs, i);
1447 : }
1448 : }
1449 :
1450 : /*
1451 : * Add ctid if needed. We currently don't support retrieving any other
1452 : * system columns.
1453 : */
1454 3524 : if (bms_is_member(SelfItemPointerAttributeNumber - FirstLowInvalidHeapAttributeNumber,
1455 : attrs_used))
1456 : {
1457 560 : if (!first)
1458 424 : appendStringInfoString(buf, ", ");
1459 136 : else if (is_returning)
1460 0 : appendStringInfoString(buf, " RETURNING ");
1461 560 : first = false;
1462 :
1463 560 : if (qualify_col)
1464 0 : ADD_REL_QUALIFIER(buf, rtindex);
1465 560 : appendStringInfoString(buf, "ctid");
1466 :
1467 560 : *retrieved_attrs = lappend_int(*retrieved_attrs,
1468 : SelfItemPointerAttributeNumber);
1469 : }
1470 :
1471 : /* Don't generate bad syntax if no undropped columns */
1472 3524 : if (first && !is_returning)
1473 88 : appendStringInfoString(buf, "NULL");
1474 3524 : }
1475 :
1476 : /*
1477 : * Deparse the appropriate locking clause (FOR UPDATE or FOR SHARE) for a
1478 : * given relation (context->scanrel).
1479 : */
1480 : static void
1481 4460 : deparseLockingClause(deparse_expr_cxt *context)
1482 : {
1483 4460 : StringInfo buf = context->buf;
1484 4460 : PlannerInfo *root = context->root;
1485 4460 : RelOptInfo *rel = context->scanrel;
1486 4460 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1487 4460 : int relid = -1;
1488 :
1489 11162 : while ((relid = bms_next_member(rel->relids, relid)) >= 0)
1490 : {
1491 : /*
1492 : * Ignore relation if it appears in a lower subquery. Locking clause
1493 : * for such a relation is included in the subquery if necessary.
1494 : */
1495 6702 : if (bms_is_member(relid, fpinfo->lower_subquery_rels))
1496 104 : continue;
1497 :
1498 : /*
1499 : * Add FOR UPDATE/SHARE if appropriate. We apply locking during the
1500 : * initial row fetch, rather than later on as is done for local
1501 : * tables. The extra roundtrips involved in trying to duplicate the
1502 : * local semantics exactly don't seem worthwhile (see also comments
1503 : * for RowMarkType).
1504 : *
1505 : * Note: because we actually run the query as a cursor, this assumes
1506 : * that DECLARE CURSOR ... FOR UPDATE is supported, which it isn't
1507 : * before 8.3.
1508 : */
1509 6598 : if (bms_is_member(relid, root->all_result_relids) &&
1510 554 : (root->parse->commandType == CMD_UPDATE ||
1511 240 : root->parse->commandType == CMD_DELETE))
1512 : {
1513 : /* Relation is UPDATE/DELETE target, so use FOR UPDATE */
1514 550 : appendStringInfoString(buf, " FOR UPDATE");
1515 :
1516 : /* Add the relation alias if we are here for a join relation */
1517 550 : if (IS_JOIN_REL(rel))
1518 84 : appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
1519 : }
1520 : else
1521 : {
1522 6048 : PlanRowMark *rc = get_plan_rowmark(root->rowMarks, relid);
1523 :
1524 6048 : if (rc)
1525 : {
1526 : /*
1527 : * Relation is specified as a FOR UPDATE/SHARE target, so
1528 : * handle that. (But we could also see LCS_NONE, meaning this
1529 : * isn't a target relation after all.)
1530 : *
1531 : * For now, just ignore any [NO] KEY specification, since (a)
1532 : * it's not clear what that means for a remote table that we
1533 : * don't have complete information about, and (b) it wouldn't
1534 : * work anyway on older remote servers. Likewise, we don't
1535 : * worry about NOWAIT.
1536 : */
1537 656 : switch (rc->strength)
1538 : {
1539 352 : case LCS_NONE:
1540 : /* No locking needed */
1541 352 : break;
1542 76 : case LCS_FORKEYSHARE:
1543 : case LCS_FORSHARE:
1544 76 : appendStringInfoString(buf, " FOR SHARE");
1545 76 : break;
1546 228 : case LCS_FORNOKEYUPDATE:
1547 : case LCS_FORUPDATE:
1548 228 : appendStringInfoString(buf, " FOR UPDATE");
1549 228 : break;
1550 : }
1551 :
1552 : /* Add the relation alias if we are here for a join relation */
1553 656 : if (bms_membership(rel->relids) == BMS_MULTIPLE &&
1554 380 : rc->strength != LCS_NONE)
1555 208 : appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
1556 : }
1557 : }
1558 : }
1559 4460 : }
1560 :
1561 : /*
1562 : * Deparse conditions from the provided list and append them to buf.
1563 : *
1564 : * The conditions in the list are assumed to be ANDed. This function is used to
1565 : * deparse WHERE clauses, JOIN .. ON clauses and HAVING clauses.
1566 : *
1567 : * Depending on the caller, the list elements might be either RestrictInfos
1568 : * or bare clauses.
1569 : */
1570 : static void
1571 3520 : appendConditions(List *exprs, deparse_expr_cxt *context)
1572 : {
1573 : int nestlevel;
1574 : ListCell *lc;
1575 3520 : bool is_first = true;
1576 3520 : StringInfo buf = context->buf;
1577 :
1578 : /* Make sure any constants in the exprs are printed portably */
1579 3520 : nestlevel = set_transmission_modes();
1580 :
1581 8090 : foreach(lc, exprs)
1582 : {
1583 4570 : Expr *expr = (Expr *) lfirst(lc);
1584 :
1585 : /* Extract clause from RestrictInfo, if required */
1586 4570 : if (IsA(expr, RestrictInfo))
1587 3888 : expr = ((RestrictInfo *) expr)->clause;
1588 :
1589 : /* Connect expressions with "AND" and parenthesize each condition. */
1590 4570 : if (!is_first)
1591 1050 : appendStringInfoString(buf, " AND ");
1592 :
1593 4570 : appendStringInfoChar(buf, '(');
1594 4570 : deparseExpr(expr, context);
1595 4570 : appendStringInfoChar(buf, ')');
1596 :
1597 4570 : is_first = false;
1598 : }
1599 :
1600 3520 : reset_transmission_modes(nestlevel);
1601 3520 : }
1602 :
1603 : /*
1604 : * Append WHERE clause, containing conditions from exprs and additional_conds,
1605 : * to context->buf.
1606 : */
1607 : static void
1608 4988 : appendWhereClause(List *exprs, List *additional_conds, deparse_expr_cxt *context)
1609 : {
1610 4988 : StringInfo buf = context->buf;
1611 4988 : bool need_and = false;
1612 : ListCell *lc;
1613 :
1614 4988 : if (exprs != NIL || additional_conds != NIL)
1615 2278 : appendStringInfoString(buf, " WHERE ");
1616 :
1617 : /*
1618 : * If there are some filters, append them.
1619 : */
1620 4988 : if (exprs != NIL)
1621 : {
1622 2072 : appendConditions(exprs, context);
1623 2072 : need_and = true;
1624 : }
1625 :
1626 : /*
1627 : * If there are some EXISTS conditions, coming from SEMI-JOINS, append
1628 : * them.
1629 : */
1630 5308 : foreach(lc, additional_conds)
1631 : {
1632 320 : if (need_and)
1633 114 : appendStringInfoString(buf, " AND ");
1634 320 : appendStringInfoString(buf, (char *) lfirst(lc));
1635 320 : need_and = true;
1636 : }
1637 4988 : }
1638 :
1639 : /* Output join name for given join type */
1640 : const char *
1641 2114 : get_jointype_name(JoinType jointype)
1642 : {
1643 2114 : switch (jointype)
1644 : {
1645 1422 : case JOIN_INNER:
1646 1422 : return "INNER";
1647 :
1648 400 : case JOIN_LEFT:
1649 400 : return "LEFT";
1650 :
1651 0 : case JOIN_RIGHT:
1652 0 : return "RIGHT";
1653 :
1654 216 : case JOIN_FULL:
1655 216 : return "FULL";
1656 :
1657 76 : case JOIN_SEMI:
1658 76 : return "SEMI";
1659 :
1660 0 : default:
1661 : /* Shouldn't come here, but protect from buggy code. */
1662 0 : elog(ERROR, "unsupported join type %d", jointype);
1663 : }
1664 :
1665 : /* Keep compiler happy */
1666 : return NULL;
1667 : }
1668 :
1669 : /*
1670 : * Deparse given targetlist and append it to context->buf.
1671 : *
1672 : * tlist is list of TargetEntry's which in turn contain Var nodes.
1673 : *
1674 : * retrieved_attrs is the list of continuously increasing integers starting
1675 : * from 1. It has same number of entries as tlist.
1676 : *
1677 : * This is used for both SELECT and RETURNING targetlists; the is_returning
1678 : * parameter is true only for a RETURNING targetlist.
1679 : */
1680 : static void
1681 1564 : deparseExplicitTargetList(List *tlist,
1682 : bool is_returning,
1683 : List **retrieved_attrs,
1684 : deparse_expr_cxt *context)
1685 : {
1686 : ListCell *lc;
1687 1564 : StringInfo buf = context->buf;
1688 1564 : int i = 0;
1689 :
1690 1564 : *retrieved_attrs = NIL;
1691 :
1692 9226 : foreach(lc, tlist)
1693 : {
1694 7662 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
1695 :
1696 7662 : if (i > 0)
1697 6140 : appendStringInfoString(buf, ", ");
1698 1522 : else if (is_returning)
1699 4 : appendStringInfoString(buf, " RETURNING ");
1700 :
1701 7662 : deparseExpr((Expr *) tle->expr, context);
1702 :
1703 7662 : *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
1704 7662 : i++;
1705 : }
1706 :
1707 1564 : if (i == 0 && !is_returning)
1708 30 : appendStringInfoString(buf, "NULL");
1709 1564 : }
1710 :
1711 : /*
1712 : * Emit expressions specified in the given relation's reltarget.
1713 : *
1714 : * This is used for deparsing the given relation as a subquery.
1715 : */
1716 : static void
1717 72 : deparseSubqueryTargetList(deparse_expr_cxt *context)
1718 : {
1719 72 : StringInfo buf = context->buf;
1720 72 : RelOptInfo *foreignrel = context->foreignrel;
1721 : bool first;
1722 : ListCell *lc;
1723 :
1724 : /* Should only be called in these cases. */
1725 : Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
1726 :
1727 72 : first = true;
1728 184 : foreach(lc, foreignrel->reltarget->exprs)
1729 : {
1730 112 : Node *node = (Node *) lfirst(lc);
1731 :
1732 112 : if (!first)
1733 48 : appendStringInfoString(buf, ", ");
1734 112 : first = false;
1735 :
1736 112 : deparseExpr((Expr *) node, context);
1737 : }
1738 :
1739 : /* Don't generate bad syntax if no expressions */
1740 72 : if (first)
1741 8 : appendStringInfoString(buf, "NULL");
1742 72 : }
1743 :
1744 : /*
1745 : * Construct FROM clause for given relation
1746 : *
1747 : * The function constructs ... JOIN ... ON ... for join relation. For a base
1748 : * relation it just returns schema-qualified tablename, with the appropriate
1749 : * alias if so requested.
1750 : *
1751 : * 'ignore_rel' is either zero or the RT index of a target relation. In the
1752 : * latter case the function constructs FROM clause of UPDATE or USING clause
1753 : * of DELETE; it deparses the join relation as if the relation never contained
1754 : * the target relation, and creates a List of conditions to be deparsed into
1755 : * the top-level WHERE clause, which is returned to *ignore_conds.
1756 : *
1757 : * 'additional_conds' is a pointer to a list of strings to be appended to
1758 : * the WHERE clause, coming from lower-level SEMI-JOINs.
1759 : */
1760 : static void
1761 8056 : deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel,
1762 : bool use_alias, Index ignore_rel, List **ignore_conds,
1763 : List **additional_conds, List **params_list)
1764 : {
1765 8056 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1766 :
1767 8056 : if (IS_JOIN_REL(foreignrel))
1768 1818 : {
1769 : StringInfoData join_sql_o;
1770 : StringInfoData join_sql_i;
1771 1834 : RelOptInfo *outerrel = fpinfo->outerrel;
1772 1834 : RelOptInfo *innerrel = fpinfo->innerrel;
1773 1834 : bool outerrel_is_target = false;
1774 1834 : bool innerrel_is_target = false;
1775 1834 : List *additional_conds_i = NIL;
1776 1834 : List *additional_conds_o = NIL;
1777 :
1778 1834 : if (ignore_rel > 0 && bms_is_member(ignore_rel, foreignrel->relids))
1779 : {
1780 : /*
1781 : * If this is an inner join, add joinclauses to *ignore_conds and
1782 : * set it to empty so that those can be deparsed into the WHERE
1783 : * clause. Note that since the target relation can never be
1784 : * within the nullable side of an outer join, those could safely
1785 : * be pulled up into the WHERE clause (see foreign_join_ok()).
1786 : * Note also that since the target relation is only inner-joined
1787 : * to any other relation in the query, all conditions in the join
1788 : * tree mentioning the target relation could be deparsed into the
1789 : * WHERE clause by doing this recursively.
1790 : */
1791 24 : if (fpinfo->jointype == JOIN_INNER)
1792 : {
1793 40 : *ignore_conds = list_concat(*ignore_conds,
1794 20 : fpinfo->joinclauses);
1795 20 : fpinfo->joinclauses = NIL;
1796 : }
1797 :
1798 : /*
1799 : * Check if either of the input relations is the target relation.
1800 : */
1801 24 : if (outerrel->relid == ignore_rel)
1802 16 : outerrel_is_target = true;
1803 8 : else if (innerrel->relid == ignore_rel)
1804 0 : innerrel_is_target = true;
1805 : }
1806 :
1807 : /* Deparse outer relation if not the target relation. */
1808 1834 : if (!outerrel_is_target)
1809 : {
1810 1818 : initStringInfo(&join_sql_o);
1811 1818 : deparseRangeTblRef(&join_sql_o, root, outerrel,
1812 1818 : fpinfo->make_outerrel_subquery,
1813 : ignore_rel, ignore_conds, &additional_conds_o,
1814 : params_list);
1815 :
1816 : /*
1817 : * If inner relation is the target relation, skip deparsing it.
1818 : * Note that since the join of the target relation with any other
1819 : * relation in the query is an inner join and can never be within
1820 : * the nullable side of an outer join, the join could be
1821 : * interchanged with higher-level joins (cf. identity 1 on outer
1822 : * join reordering shown in src/backend/optimizer/README), which
1823 : * means it's safe to skip the target-relation deparsing here.
1824 : */
1825 1818 : if (innerrel_is_target)
1826 : {
1827 : Assert(fpinfo->jointype == JOIN_INNER);
1828 : Assert(fpinfo->joinclauses == NIL);
1829 0 : appendBinaryStringInfo(buf, join_sql_o.data, join_sql_o.len);
1830 : /* Pass EXISTS conditions to upper level */
1831 0 : if (additional_conds_o != NIL)
1832 : {
1833 : Assert(*additional_conds == NIL);
1834 0 : *additional_conds = additional_conds_o;
1835 : }
1836 16 : return;
1837 : }
1838 : }
1839 :
1840 : /* Deparse inner relation if not the target relation. */
1841 1834 : if (!innerrel_is_target)
1842 : {
1843 1834 : initStringInfo(&join_sql_i);
1844 1834 : deparseRangeTblRef(&join_sql_i, root, innerrel,
1845 1834 : fpinfo->make_innerrel_subquery,
1846 : ignore_rel, ignore_conds, &additional_conds_i,
1847 : params_list);
1848 :
1849 : /*
1850 : * SEMI-JOIN is deparsed as the EXISTS subquery. It references
1851 : * outer and inner relations, so it should be evaluated as the
1852 : * condition in the upper-level WHERE clause. We deparse the
1853 : * condition and pass it to upper level callers as an
1854 : * additional_conds list. Upper level callers are responsible for
1855 : * inserting conditions from the list where appropriate.
1856 : */
1857 1834 : if (fpinfo->jointype == JOIN_SEMI)
1858 : {
1859 : deparse_expr_cxt context;
1860 : StringInfoData str;
1861 :
1862 : /* Construct deparsed condition from this SEMI-JOIN */
1863 320 : initStringInfo(&str);
1864 320 : appendStringInfo(&str, "EXISTS (SELECT NULL FROM %s",
1865 : join_sql_i.data);
1866 :
1867 320 : context.buf = &str;
1868 320 : context.foreignrel = foreignrel;
1869 320 : context.scanrel = foreignrel;
1870 320 : context.root = root;
1871 320 : context.params_list = params_list;
1872 :
1873 : /*
1874 : * Append SEMI-JOIN clauses and EXISTS conditions from lower
1875 : * levels to the current EXISTS subquery
1876 : */
1877 320 : appendWhereClause(fpinfo->joinclauses, additional_conds_i, &context);
1878 :
1879 : /*
1880 : * EXISTS conditions, coming from lower join levels, have just
1881 : * been processed.
1882 : */
1883 320 : if (additional_conds_i != NIL)
1884 : {
1885 32 : list_free_deep(additional_conds_i);
1886 32 : additional_conds_i = NIL;
1887 : }
1888 :
1889 : /* Close parentheses for EXISTS subquery */
1890 320 : appendStringInfoChar(&str, ')');
1891 :
1892 320 : *additional_conds = lappend(*additional_conds, str.data);
1893 : }
1894 :
1895 : /*
1896 : * If outer relation is the target relation, skip deparsing it.
1897 : * See the above note about safety.
1898 : */
1899 1834 : if (outerrel_is_target)
1900 : {
1901 : Assert(fpinfo->jointype == JOIN_INNER);
1902 : Assert(fpinfo->joinclauses == NIL);
1903 16 : appendBinaryStringInfo(buf, join_sql_i.data, join_sql_i.len);
1904 : /* Pass EXISTS conditions to the upper call */
1905 16 : if (additional_conds_i != NIL)
1906 : {
1907 : Assert(*additional_conds == NIL);
1908 0 : *additional_conds = additional_conds_i;
1909 : }
1910 16 : return;
1911 : }
1912 : }
1913 :
1914 : /* Neither of the relations is the target relation. */
1915 : Assert(!outerrel_is_target && !innerrel_is_target);
1916 :
1917 : /*
1918 : * For semijoin FROM clause is deparsed as an outer relation. An inner
1919 : * relation and join clauses are converted to EXISTS condition and
1920 : * passed to the upper level.
1921 : */
1922 1818 : if (fpinfo->jointype == JOIN_SEMI)
1923 : {
1924 320 : appendBinaryStringInfo(buf, join_sql_o.data, join_sql_o.len);
1925 : }
1926 : else
1927 : {
1928 : /*
1929 : * For a join relation FROM clause, entry is deparsed as
1930 : *
1931 : * ((outer relation) <join type> (inner relation) ON
1932 : * (joinclauses))
1933 : */
1934 1498 : appendStringInfo(buf, "(%s %s JOIN %s ON ", join_sql_o.data,
1935 : get_jointype_name(fpinfo->jointype), join_sql_i.data);
1936 :
1937 : /* Append join clause; (TRUE) if no join clause */
1938 1498 : if (fpinfo->joinclauses)
1939 : {
1940 : deparse_expr_cxt context;
1941 :
1942 1412 : context.buf = buf;
1943 1412 : context.foreignrel = foreignrel;
1944 1412 : context.scanrel = foreignrel;
1945 1412 : context.root = root;
1946 1412 : context.params_list = params_list;
1947 :
1948 1412 : appendStringInfoChar(buf, '(');
1949 1412 : appendConditions(fpinfo->joinclauses, &context);
1950 1412 : appendStringInfoChar(buf, ')');
1951 : }
1952 : else
1953 86 : appendStringInfoString(buf, "(TRUE)");
1954 :
1955 : /* End the FROM clause entry. */
1956 1498 : appendStringInfoChar(buf, ')');
1957 : }
1958 :
1959 : /*
1960 : * Construct additional_conds to be passed to the upper caller from
1961 : * current level additional_conds and additional_conds, coming from
1962 : * inner and outer rels.
1963 : */
1964 1818 : if (additional_conds_o != NIL)
1965 : {
1966 96 : *additional_conds = list_concat(*additional_conds,
1967 : additional_conds_o);
1968 96 : list_free(additional_conds_o);
1969 : }
1970 :
1971 1818 : if (additional_conds_i != NIL)
1972 : {
1973 0 : *additional_conds = list_concat(*additional_conds,
1974 : additional_conds_i);
1975 0 : list_free(additional_conds_i);
1976 : }
1977 : }
1978 : else
1979 : {
1980 6222 : RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
1981 :
1982 : /*
1983 : * Core code already has some lock on each rel being planned, so we
1984 : * can use NoLock here.
1985 : */
1986 6222 : Relation rel = table_open(rte->relid, NoLock);
1987 :
1988 6222 : deparseRelation(buf, rel);
1989 :
1990 : /*
1991 : * Add a unique alias to avoid any conflict in relation names due to
1992 : * pulled up subqueries in the query being built for a pushed down
1993 : * join.
1994 : */
1995 6222 : if (use_alias)
1996 3048 : appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid);
1997 :
1998 6222 : table_close(rel, NoLock);
1999 : }
2000 : }
2001 :
2002 : /*
2003 : * Append FROM clause entry for the given relation into buf.
2004 : * Conditions from lower-level SEMI-JOINs are appended to additional_conds
2005 : * and should be added to upper level WHERE clause.
2006 : */
2007 : static void
2008 3652 : deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel,
2009 : bool make_subquery, Index ignore_rel, List **ignore_conds,
2010 : List **additional_conds, List **params_list)
2011 : {
2012 3652 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
2013 :
2014 : /* Should only be called in these cases. */
2015 : Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
2016 :
2017 : Assert(fpinfo->local_conds == NIL);
2018 :
2019 : /* If make_subquery is true, deparse the relation as a subquery. */
2020 3652 : if (make_subquery)
2021 : {
2022 : List *retrieved_attrs;
2023 : int ncols;
2024 :
2025 : /*
2026 : * The given relation shouldn't contain the target relation, because
2027 : * this should only happen for input relations for a full join, and
2028 : * such relations can never contain an UPDATE/DELETE target.
2029 : */
2030 : Assert(ignore_rel == 0 ||
2031 : !bms_is_member(ignore_rel, foreignrel->relids));
2032 :
2033 : /* Deparse the subquery representing the relation. */
2034 72 : appendStringInfoChar(buf, '(');
2035 72 : deparseSelectStmtForRel(buf, root, foreignrel, NIL,
2036 : fpinfo->remote_conds, NIL,
2037 : false, false, true,
2038 : &retrieved_attrs, params_list);
2039 72 : appendStringInfoChar(buf, ')');
2040 :
2041 : /* Append the relation alias. */
2042 72 : appendStringInfo(buf, " %s%d", SUBQUERY_REL_ALIAS_PREFIX,
2043 : fpinfo->relation_index);
2044 :
2045 : /*
2046 : * Append the column aliases if needed. Note that the subquery emits
2047 : * expressions specified in the relation's reltarget (see
2048 : * deparseSubqueryTargetList).
2049 : */
2050 72 : ncols = list_length(foreignrel->reltarget->exprs);
2051 72 : if (ncols > 0)
2052 : {
2053 : int i;
2054 :
2055 64 : appendStringInfoChar(buf, '(');
2056 176 : for (i = 1; i <= ncols; i++)
2057 : {
2058 112 : if (i > 1)
2059 48 : appendStringInfoString(buf, ", ");
2060 :
2061 112 : appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i);
2062 : }
2063 64 : appendStringInfoChar(buf, ')');
2064 : }
2065 : }
2066 : else
2067 3580 : deparseFromExprForRel(buf, root, foreignrel, true, ignore_rel,
2068 : ignore_conds, additional_conds,
2069 : params_list);
2070 3652 : }
2071 :
2072 : /*
2073 : * deparse remote INSERT statement
2074 : *
2075 : * The statement text is appended to buf, and we also create an integer List
2076 : * of the columns being retrieved by WITH CHECK OPTION or RETURNING (if any),
2077 : * which is returned to *retrieved_attrs.
2078 : *
2079 : * This also stores end position of the VALUES clause, so that we can rebuild
2080 : * an INSERT for a batch of rows later.
2081 : */
2082 : void
2083 282 : deparseInsertSql(StringInfo buf, RangeTblEntry *rte,
2084 : Index rtindex, Relation rel,
2085 : List *targetAttrs, bool doNothing,
2086 : List *withCheckOptionList, List *returningList,
2087 : List **retrieved_attrs, int *values_end_len)
2088 : {
2089 282 : TupleDesc tupdesc = RelationGetDescr(rel);
2090 : AttrNumber pindex;
2091 : bool first;
2092 : ListCell *lc;
2093 :
2094 282 : appendStringInfoString(buf, "INSERT INTO ");
2095 282 : deparseRelation(buf, rel);
2096 :
2097 282 : if (targetAttrs)
2098 : {
2099 280 : appendStringInfoChar(buf, '(');
2100 :
2101 280 : first = true;
2102 1040 : foreach(lc, targetAttrs)
2103 : {
2104 760 : int attnum = lfirst_int(lc);
2105 :
2106 760 : if (!first)
2107 480 : appendStringInfoString(buf, ", ");
2108 760 : first = false;
2109 :
2110 760 : deparseColumnRef(buf, rtindex, attnum, rte, false);
2111 : }
2112 :
2113 280 : appendStringInfoString(buf, ") VALUES (");
2114 :
2115 280 : pindex = 1;
2116 280 : first = true;
2117 1040 : foreach(lc, targetAttrs)
2118 : {
2119 760 : int attnum = lfirst_int(lc);
2120 760 : Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2121 :
2122 760 : if (!first)
2123 480 : appendStringInfoString(buf, ", ");
2124 760 : first = false;
2125 :
2126 760 : if (attr->attgenerated)
2127 10 : appendStringInfoString(buf, "DEFAULT");
2128 : else
2129 : {
2130 750 : appendStringInfo(buf, "$%d", pindex);
2131 750 : pindex++;
2132 : }
2133 : }
2134 :
2135 280 : appendStringInfoChar(buf, ')');
2136 : }
2137 : else
2138 2 : appendStringInfoString(buf, " DEFAULT VALUES");
2139 282 : *values_end_len = buf->len;
2140 :
2141 282 : if (doNothing)
2142 6 : appendStringInfoString(buf, " ON CONFLICT DO NOTHING");
2143 :
2144 282 : deparseReturningList(buf, rte, rtindex, rel,
2145 282 : rel->trigdesc && rel->trigdesc->trig_insert_after_row,
2146 : withCheckOptionList, returningList, retrieved_attrs);
2147 282 : }
2148 :
2149 : /*
2150 : * rebuild remote INSERT statement
2151 : *
2152 : * Provided a number of rows in a batch, builds INSERT statement with the
2153 : * right number of parameters.
2154 : */
2155 : void
2156 52 : rebuildInsertSql(StringInfo buf, Relation rel,
2157 : char *orig_query, List *target_attrs,
2158 : int values_end_len, int num_params,
2159 : int num_rows)
2160 : {
2161 52 : TupleDesc tupdesc = RelationGetDescr(rel);
2162 : int i;
2163 : int pindex;
2164 : bool first;
2165 : ListCell *lc;
2166 :
2167 : /* Make sure the values_end_len is sensible */
2168 : Assert((values_end_len > 0) && (values_end_len <= strlen(orig_query)));
2169 :
2170 : /* Copy up to the end of the first record from the original query */
2171 52 : appendBinaryStringInfo(buf, orig_query, values_end_len);
2172 :
2173 : /*
2174 : * Add records to VALUES clause (we already have parameters for the first
2175 : * row, so start at the right offset).
2176 : */
2177 52 : pindex = num_params + 1;
2178 206 : for (i = 0; i < num_rows; i++)
2179 : {
2180 154 : appendStringInfoString(buf, ", (");
2181 :
2182 154 : first = true;
2183 450 : foreach(lc, target_attrs)
2184 : {
2185 296 : int attnum = lfirst_int(lc);
2186 296 : Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2187 :
2188 296 : if (!first)
2189 142 : appendStringInfoString(buf, ", ");
2190 296 : first = false;
2191 :
2192 296 : if (attr->attgenerated)
2193 2 : appendStringInfoString(buf, "DEFAULT");
2194 : else
2195 : {
2196 294 : appendStringInfo(buf, "$%d", pindex);
2197 294 : pindex++;
2198 : }
2199 : }
2200 :
2201 154 : appendStringInfoChar(buf, ')');
2202 : }
2203 :
2204 : /* Copy stuff after VALUES clause from the original query */
2205 52 : appendStringInfoString(buf, orig_query + values_end_len);
2206 52 : }
2207 :
2208 : /*
2209 : * deparse remote UPDATE statement
2210 : *
2211 : * The statement text is appended to buf, and we also create an integer List
2212 : * of the columns being retrieved by WITH CHECK OPTION or RETURNING (if any),
2213 : * which is returned to *retrieved_attrs.
2214 : */
2215 : void
2216 100 : deparseUpdateSql(StringInfo buf, RangeTblEntry *rte,
2217 : Index rtindex, Relation rel,
2218 : List *targetAttrs,
2219 : List *withCheckOptionList, List *returningList,
2220 : List **retrieved_attrs)
2221 : {
2222 100 : TupleDesc tupdesc = RelationGetDescr(rel);
2223 : AttrNumber pindex;
2224 : bool first;
2225 : ListCell *lc;
2226 :
2227 100 : appendStringInfoString(buf, "UPDATE ");
2228 100 : deparseRelation(buf, rel);
2229 100 : appendStringInfoString(buf, " SET ");
2230 :
2231 100 : pindex = 2; /* ctid is always the first param */
2232 100 : first = true;
2233 246 : foreach(lc, targetAttrs)
2234 : {
2235 146 : int attnum = lfirst_int(lc);
2236 146 : Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2237 :
2238 146 : if (!first)
2239 46 : appendStringInfoString(buf, ", ");
2240 146 : first = false;
2241 :
2242 146 : deparseColumnRef(buf, rtindex, attnum, rte, false);
2243 146 : if (attr->attgenerated)
2244 4 : appendStringInfoString(buf, " = DEFAULT");
2245 : else
2246 : {
2247 142 : appendStringInfo(buf, " = $%d", pindex);
2248 142 : pindex++;
2249 : }
2250 : }
2251 100 : appendStringInfoString(buf, " WHERE ctid = $1");
2252 :
2253 100 : deparseReturningList(buf, rte, rtindex, rel,
2254 100 : rel->trigdesc && rel->trigdesc->trig_update_after_row,
2255 : withCheckOptionList, returningList, retrieved_attrs);
2256 100 : }
2257 :
2258 : /*
2259 : * deparse remote UPDATE statement
2260 : *
2261 : * 'buf' is the output buffer to append the statement to
2262 : * 'rtindex' is the RT index of the associated target relation
2263 : * 'rel' is the relation descriptor for the target relation
2264 : * 'foreignrel' is the RelOptInfo for the target relation or the join relation
2265 : * containing all base relations in the query
2266 : * 'targetlist' is the tlist of the underlying foreign-scan plan node
2267 : * (note that this only contains new-value expressions and junk attrs)
2268 : * 'targetAttrs' is the target columns of the UPDATE
2269 : * 'remote_conds' is the qual clauses that must be evaluated remotely
2270 : * '*params_list' is an output list of exprs that will become remote Params
2271 : * 'returningList' is the RETURNING targetlist
2272 : * '*retrieved_attrs' is an output list of integers of columns being retrieved
2273 : * by RETURNING (if any)
2274 : */
2275 : void
2276 90 : deparseDirectUpdateSql(StringInfo buf, PlannerInfo *root,
2277 : Index rtindex, Relation rel,
2278 : RelOptInfo *foreignrel,
2279 : List *targetlist,
2280 : List *targetAttrs,
2281 : List *remote_conds,
2282 : List **params_list,
2283 : List *returningList,
2284 : List **retrieved_attrs)
2285 : {
2286 : deparse_expr_cxt context;
2287 : int nestlevel;
2288 : bool first;
2289 90 : RangeTblEntry *rte = planner_rt_fetch(rtindex, root);
2290 : ListCell *lc,
2291 : *lc2;
2292 90 : List *additional_conds = NIL;
2293 :
2294 : /* Set up context struct for recursion */
2295 90 : context.root = root;
2296 90 : context.foreignrel = foreignrel;
2297 90 : context.scanrel = foreignrel;
2298 90 : context.buf = buf;
2299 90 : context.params_list = params_list;
2300 :
2301 90 : appendStringInfoString(buf, "UPDATE ");
2302 90 : deparseRelation(buf, rel);
2303 90 : if (foreignrel->reloptkind == RELOPT_JOINREL)
2304 8 : appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2305 90 : appendStringInfoString(buf, " SET ");
2306 :
2307 : /* Make sure any constants in the exprs are printed portably */
2308 90 : nestlevel = set_transmission_modes();
2309 :
2310 90 : first = true;
2311 196 : forboth(lc, targetlist, lc2, targetAttrs)
2312 : {
2313 106 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
2314 106 : int attnum = lfirst_int(lc2);
2315 :
2316 : /* update's new-value expressions shouldn't be resjunk */
2317 : Assert(!tle->resjunk);
2318 :
2319 106 : if (!first)
2320 16 : appendStringInfoString(buf, ", ");
2321 106 : first = false;
2322 :
2323 106 : deparseColumnRef(buf, rtindex, attnum, rte, false);
2324 106 : appendStringInfoString(buf, " = ");
2325 106 : deparseExpr((Expr *) tle->expr, &context);
2326 : }
2327 :
2328 90 : reset_transmission_modes(nestlevel);
2329 :
2330 90 : if (foreignrel->reloptkind == RELOPT_JOINREL)
2331 : {
2332 8 : List *ignore_conds = NIL;
2333 :
2334 :
2335 8 : appendStringInfoString(buf, " FROM ");
2336 8 : deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2337 : &ignore_conds, &additional_conds, params_list);
2338 8 : remote_conds = list_concat(remote_conds, ignore_conds);
2339 : }
2340 :
2341 90 : appendWhereClause(remote_conds, additional_conds, &context);
2342 :
2343 90 : if (additional_conds != NIL)
2344 0 : list_free_deep(additional_conds);
2345 :
2346 90 : if (foreignrel->reloptkind == RELOPT_JOINREL)
2347 8 : deparseExplicitTargetList(returningList, true, retrieved_attrs,
2348 : &context);
2349 : else
2350 82 : deparseReturningList(buf, rte, rtindex, rel, false,
2351 : NIL, returningList, retrieved_attrs);
2352 90 : }
2353 :
2354 : /*
2355 : * deparse remote DELETE statement
2356 : *
2357 : * The statement text is appended to buf, and we also create an integer List
2358 : * of the columns being retrieved by RETURNING (if any), which is returned
2359 : * to *retrieved_attrs.
2360 : */
2361 : void
2362 32 : deparseDeleteSql(StringInfo buf, RangeTblEntry *rte,
2363 : Index rtindex, Relation rel,
2364 : List *returningList,
2365 : List **retrieved_attrs)
2366 : {
2367 32 : appendStringInfoString(buf, "DELETE FROM ");
2368 32 : deparseRelation(buf, rel);
2369 32 : appendStringInfoString(buf, " WHERE ctid = $1");
2370 :
2371 32 : deparseReturningList(buf, rte, rtindex, rel,
2372 32 : rel->trigdesc && rel->trigdesc->trig_delete_after_row,
2373 : NIL, returningList, retrieved_attrs);
2374 32 : }
2375 :
2376 : /*
2377 : * deparse remote DELETE statement
2378 : *
2379 : * 'buf' is the output buffer to append the statement to
2380 : * 'rtindex' is the RT index of the associated target relation
2381 : * 'rel' is the relation descriptor for the target relation
2382 : * 'foreignrel' is the RelOptInfo for the target relation or the join relation
2383 : * containing all base relations in the query
2384 : * 'remote_conds' is the qual clauses that must be evaluated remotely
2385 : * '*params_list' is an output list of exprs that will become remote Params
2386 : * 'returningList' is the RETURNING targetlist
2387 : * '*retrieved_attrs' is an output list of integers of columns being retrieved
2388 : * by RETURNING (if any)
2389 : */
2390 : void
2391 118 : deparseDirectDeleteSql(StringInfo buf, PlannerInfo *root,
2392 : Index rtindex, Relation rel,
2393 : RelOptInfo *foreignrel,
2394 : List *remote_conds,
2395 : List **params_list,
2396 : List *returningList,
2397 : List **retrieved_attrs)
2398 : {
2399 : deparse_expr_cxt context;
2400 118 : List *additional_conds = NIL;
2401 :
2402 : /* Set up context struct for recursion */
2403 118 : context.root = root;
2404 118 : context.foreignrel = foreignrel;
2405 118 : context.scanrel = foreignrel;
2406 118 : context.buf = buf;
2407 118 : context.params_list = params_list;
2408 :
2409 118 : appendStringInfoString(buf, "DELETE FROM ");
2410 118 : deparseRelation(buf, rel);
2411 118 : if (foreignrel->reloptkind == RELOPT_JOINREL)
2412 8 : appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2413 :
2414 118 : if (foreignrel->reloptkind == RELOPT_JOINREL)
2415 : {
2416 8 : List *ignore_conds = NIL;
2417 :
2418 8 : appendStringInfoString(buf, " USING ");
2419 8 : deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2420 : &ignore_conds, &additional_conds, params_list);
2421 8 : remote_conds = list_concat(remote_conds, ignore_conds);
2422 : }
2423 :
2424 118 : appendWhereClause(remote_conds, additional_conds, &context);
2425 :
2426 118 : if (additional_conds != NIL)
2427 0 : list_free_deep(additional_conds);
2428 :
2429 118 : if (foreignrel->reloptkind == RELOPT_JOINREL)
2430 8 : deparseExplicitTargetList(returningList, true, retrieved_attrs,
2431 : &context);
2432 : else
2433 110 : deparseReturningList(buf, planner_rt_fetch(rtindex, root),
2434 : rtindex, rel, false,
2435 : NIL, returningList, retrieved_attrs);
2436 118 : }
2437 :
2438 : /*
2439 : * Add a RETURNING clause, if needed, to an INSERT/UPDATE/DELETE.
2440 : */
2441 : static void
2442 606 : deparseReturningList(StringInfo buf, RangeTblEntry *rte,
2443 : Index rtindex, Relation rel,
2444 : bool trig_after_row,
2445 : List *withCheckOptionList,
2446 : List *returningList,
2447 : List **retrieved_attrs)
2448 : {
2449 606 : Bitmapset *attrs_used = NULL;
2450 :
2451 606 : if (trig_after_row)
2452 : {
2453 : /* whole-row reference acquires all non-system columns */
2454 48 : attrs_used =
2455 48 : bms_make_singleton(0 - FirstLowInvalidHeapAttributeNumber);
2456 : }
2457 :
2458 606 : if (withCheckOptionList != NIL)
2459 : {
2460 : /*
2461 : * We need the attrs, non-system and system, mentioned in the local
2462 : * query's WITH CHECK OPTION list.
2463 : *
2464 : * Note: we do this to ensure that WCO constraints will be evaluated
2465 : * on the data actually inserted/updated on the remote side, which
2466 : * might differ from the data supplied by the core code, for example
2467 : * as a result of remote triggers.
2468 : */
2469 38 : pull_varattnos((Node *) withCheckOptionList, rtindex,
2470 : &attrs_used);
2471 : }
2472 :
2473 606 : if (returningList != NIL)
2474 : {
2475 : /*
2476 : * We need the attrs, non-system and system, mentioned in the local
2477 : * query's RETURNING list.
2478 : */
2479 136 : pull_varattnos((Node *) returningList, rtindex,
2480 : &attrs_used);
2481 : }
2482 :
2483 606 : if (attrs_used != NULL)
2484 220 : deparseTargetList(buf, rte, rtindex, rel, true, attrs_used, false,
2485 : retrieved_attrs);
2486 : else
2487 386 : *retrieved_attrs = NIL;
2488 606 : }
2489 :
2490 : /*
2491 : * Construct SELECT statement to acquire size in blocks of given relation.
2492 : *
2493 : * Note: we use local definition of block size, not remote definition.
2494 : * This is perhaps debatable.
2495 : *
2496 : * Note: pg_relation_size() exists in 8.1 and later.
2497 : */
2498 : void
2499 80 : deparseAnalyzeSizeSql(StringInfo buf, Relation rel)
2500 : {
2501 : StringInfoData relname;
2502 :
2503 : /* We'll need the remote relation name as a literal. */
2504 80 : initStringInfo(&relname);
2505 80 : deparseRelation(&relname, rel);
2506 :
2507 80 : appendStringInfoString(buf, "SELECT pg_catalog.pg_relation_size(");
2508 80 : deparseStringLiteral(buf, relname.data);
2509 80 : appendStringInfo(buf, "::pg_catalog.regclass) / %d", BLCKSZ);
2510 80 : }
2511 :
2512 : /*
2513 : * Construct SELECT statement to acquire the number of rows and the relkind of
2514 : * a relation.
2515 : *
2516 : * Note: we just return the remote server's reltuples value, which might
2517 : * be off a good deal, but it doesn't seem worth working harder. See
2518 : * comments in postgresAcquireSampleRowsFunc.
2519 : */
2520 : void
2521 80 : deparseAnalyzeInfoSql(StringInfo buf, Relation rel)
2522 : {
2523 : StringInfoData relname;
2524 :
2525 : /* We'll need the remote relation name as a literal. */
2526 80 : initStringInfo(&relname);
2527 80 : deparseRelation(&relname, rel);
2528 :
2529 80 : appendStringInfoString(buf, "SELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
2530 80 : deparseStringLiteral(buf, relname.data);
2531 80 : appendStringInfoString(buf, "::pg_catalog.regclass");
2532 80 : }
2533 :
2534 : /*
2535 : * Construct SELECT statement to acquire sample rows of given relation.
2536 : *
2537 : * SELECT command is appended to buf, and list of columns retrieved
2538 : * is returned to *retrieved_attrs.
2539 : *
2540 : * We only support sampling methods we can decide based on server version.
2541 : * Allowing custom TSM modules (like tsm_system_rows) might be useful, but it
2542 : * would require detecting which extensions are installed, to allow automatic
2543 : * fall-back. Moreover, the methods may use different parameters like number
2544 : * of rows (and not sampling rate). So we leave this for future improvements.
2545 : *
2546 : * Using random() to sample rows on the remote server has the advantage that
2547 : * this works on all PostgreSQL versions (unlike TABLESAMPLE), and that it
2548 : * does the sampling on the remote side (without transferring everything and
2549 : * then discarding most rows).
2550 : *
2551 : * The disadvantage is that we still have to read all rows and evaluate the
2552 : * random(), while TABLESAMPLE (at least with the "system" method) may skip.
2553 : * It's not that different from the "bernoulli" method, though.
2554 : *
2555 : * We could also do "ORDER BY random() LIMIT x", which would always pick
2556 : * the expected number of rows, but it requires sorting so it may be much
2557 : * more expensive (particularly on large tables, which is what the
2558 : * remote sampling is meant to improve).
2559 : */
2560 : void
2561 80 : deparseAnalyzeSql(StringInfo buf, Relation rel,
2562 : PgFdwSamplingMethod sample_method, double sample_frac,
2563 : List **retrieved_attrs)
2564 : {
2565 80 : Oid relid = RelationGetRelid(rel);
2566 80 : TupleDesc tupdesc = RelationGetDescr(rel);
2567 : int i;
2568 : char *colname;
2569 : List *options;
2570 : ListCell *lc;
2571 80 : bool first = true;
2572 :
2573 80 : *retrieved_attrs = NIL;
2574 :
2575 80 : appendStringInfoString(buf, "SELECT ");
2576 350 : for (i = 0; i < tupdesc->natts; i++)
2577 : {
2578 : /* Ignore dropped columns. */
2579 270 : if (TupleDescAttr(tupdesc, i)->attisdropped)
2580 6 : continue;
2581 :
2582 264 : if (!first)
2583 184 : appendStringInfoString(buf, ", ");
2584 264 : first = false;
2585 :
2586 : /* Use attribute name or column_name option. */
2587 264 : colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
2588 264 : options = GetForeignColumnOptions(relid, i + 1);
2589 :
2590 264 : foreach(lc, options)
2591 : {
2592 6 : DefElem *def = (DefElem *) lfirst(lc);
2593 :
2594 6 : if (strcmp(def->defname, "column_name") == 0)
2595 : {
2596 6 : colname = defGetString(def);
2597 6 : break;
2598 : }
2599 : }
2600 :
2601 264 : appendStringInfoString(buf, quote_identifier(colname));
2602 :
2603 264 : *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
2604 : }
2605 :
2606 : /* Don't generate bad syntax for zero-column relation. */
2607 80 : if (first)
2608 0 : appendStringInfoString(buf, "NULL");
2609 :
2610 : /*
2611 : * Construct FROM clause, and perhaps WHERE clause too, depending on the
2612 : * selected sampling method.
2613 : */
2614 80 : appendStringInfoString(buf, " FROM ");
2615 80 : deparseRelation(buf, rel);
2616 :
2617 80 : switch (sample_method)
2618 : {
2619 80 : case ANALYZE_SAMPLE_OFF:
2620 : /* nothing to do here */
2621 80 : break;
2622 :
2623 0 : case ANALYZE_SAMPLE_RANDOM:
2624 0 : appendStringInfo(buf, " WHERE pg_catalog.random() < %f", sample_frac);
2625 0 : break;
2626 :
2627 0 : case ANALYZE_SAMPLE_SYSTEM:
2628 0 : appendStringInfo(buf, " TABLESAMPLE SYSTEM(%f)", (100.0 * sample_frac));
2629 0 : break;
2630 :
2631 0 : case ANALYZE_SAMPLE_BERNOULLI:
2632 0 : appendStringInfo(buf, " TABLESAMPLE BERNOULLI(%f)", (100.0 * sample_frac));
2633 0 : break;
2634 :
2635 0 : case ANALYZE_SAMPLE_AUTO:
2636 : /* should have been resolved into actual method */
2637 0 : elog(ERROR, "unexpected sampling method");
2638 : break;
2639 : }
2640 80 : }
2641 :
2642 : /*
2643 : * Construct a simple "TRUNCATE rel" statement
2644 : */
2645 : void
2646 24 : deparseTruncateSql(StringInfo buf,
2647 : List *rels,
2648 : DropBehavior behavior,
2649 : bool restart_seqs)
2650 : {
2651 : ListCell *cell;
2652 :
2653 24 : appendStringInfoString(buf, "TRUNCATE ");
2654 :
2655 52 : foreach(cell, rels)
2656 : {
2657 28 : Relation rel = lfirst(cell);
2658 :
2659 28 : if (cell != list_head(rels))
2660 4 : appendStringInfoString(buf, ", ");
2661 :
2662 28 : deparseRelation(buf, rel);
2663 : }
2664 :
2665 24 : appendStringInfo(buf, " %s IDENTITY",
2666 : restart_seqs ? "RESTART" : "CONTINUE");
2667 :
2668 24 : if (behavior == DROP_RESTRICT)
2669 20 : appendStringInfoString(buf, " RESTRICT");
2670 4 : else if (behavior == DROP_CASCADE)
2671 4 : appendStringInfoString(buf, " CASCADE");
2672 24 : }
2673 :
2674 : /*
2675 : * Construct name to use for given column, and emit it into buf.
2676 : * If it has a column_name FDW option, use that instead of attribute name.
2677 : *
2678 : * If qualify_col is true, qualify column name with the alias of relation.
2679 : */
2680 : static void
2681 28994 : deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte,
2682 : bool qualify_col)
2683 : {
2684 : /* We support fetching the remote side's CTID and OID. */
2685 28994 : if (varattno == SelfItemPointerAttributeNumber)
2686 : {
2687 96 : if (qualify_col)
2688 92 : ADD_REL_QUALIFIER(buf, varno);
2689 96 : appendStringInfoString(buf, "ctid");
2690 : }
2691 28898 : else if (varattno < 0)
2692 : {
2693 : /*
2694 : * All other system attributes are fetched as 0, except for table OID,
2695 : * which is fetched as the local table OID. However, we must be
2696 : * careful; the table could be beneath an outer join, in which case it
2697 : * must go to NULL whenever the rest of the row does.
2698 : */
2699 0 : Oid fetchval = 0;
2700 :
2701 0 : if (varattno == TableOidAttributeNumber)
2702 0 : fetchval = rte->relid;
2703 :
2704 0 : if (qualify_col)
2705 : {
2706 0 : appendStringInfoString(buf, "CASE WHEN (");
2707 0 : ADD_REL_QUALIFIER(buf, varno);
2708 0 : appendStringInfo(buf, "*)::text IS NOT NULL THEN %u END", fetchval);
2709 : }
2710 : else
2711 0 : appendStringInfo(buf, "%u", fetchval);
2712 : }
2713 28898 : else if (varattno == 0)
2714 : {
2715 : /* Whole row reference */
2716 : Relation rel;
2717 : Bitmapset *attrs_used;
2718 :
2719 : /* Required only to be passed down to deparseTargetList(). */
2720 : List *retrieved_attrs;
2721 :
2722 : /*
2723 : * The lock on the relation will be held by upper callers, so it's
2724 : * fine to open it with no lock here.
2725 : */
2726 464 : rel = table_open(rte->relid, NoLock);
2727 :
2728 : /*
2729 : * The local name of the foreign table can not be recognized by the
2730 : * foreign server and the table it references on foreign server might
2731 : * have different column ordering or different columns than those
2732 : * declared locally. Hence we have to deparse whole-row reference as
2733 : * ROW(columns referenced locally). Construct this by deparsing a
2734 : * "whole row" attribute.
2735 : */
2736 464 : attrs_used = bms_add_member(NULL,
2737 : 0 - FirstLowInvalidHeapAttributeNumber);
2738 :
2739 : /*
2740 : * In case the whole-row reference is under an outer join then it has
2741 : * to go NULL whenever the rest of the row goes NULL. Deparsing a join
2742 : * query would always involve multiple relations, thus qualify_col
2743 : * would be true.
2744 : */
2745 464 : if (qualify_col)
2746 : {
2747 456 : appendStringInfoString(buf, "CASE WHEN (");
2748 456 : ADD_REL_QUALIFIER(buf, varno);
2749 456 : appendStringInfoString(buf, "*)::text IS NOT NULL THEN ");
2750 : }
2751 :
2752 464 : appendStringInfoString(buf, "ROW(");
2753 464 : deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col,
2754 : &retrieved_attrs);
2755 464 : appendStringInfoChar(buf, ')');
2756 :
2757 : /* Complete the CASE WHEN statement started above. */
2758 464 : if (qualify_col)
2759 456 : appendStringInfoString(buf, " END");
2760 :
2761 464 : table_close(rel, NoLock);
2762 464 : bms_free(attrs_used);
2763 : }
2764 : else
2765 : {
2766 28434 : char *colname = NULL;
2767 : List *options;
2768 : ListCell *lc;
2769 :
2770 : /* varno must not be any of OUTER_VAR, INNER_VAR and INDEX_VAR. */
2771 : Assert(!IS_SPECIAL_VARNO(varno));
2772 :
2773 : /*
2774 : * If it's a column of a foreign table, and it has the column_name FDW
2775 : * option, use that value.
2776 : */
2777 28434 : options = GetForeignColumnOptions(rte->relid, varattno);
2778 28434 : foreach(lc, options)
2779 : {
2780 6562 : DefElem *def = (DefElem *) lfirst(lc);
2781 :
2782 6562 : if (strcmp(def->defname, "column_name") == 0)
2783 : {
2784 6562 : colname = defGetString(def);
2785 6562 : break;
2786 : }
2787 : }
2788 :
2789 : /*
2790 : * If it's a column of a regular table or it doesn't have column_name
2791 : * FDW option, use attribute name.
2792 : */
2793 28434 : if (colname == NULL)
2794 21872 : colname = get_attname(rte->relid, varattno, false);
2795 :
2796 28434 : if (qualify_col)
2797 14572 : ADD_REL_QUALIFIER(buf, varno);
2798 :
2799 28434 : appendStringInfoString(buf, quote_identifier(colname));
2800 : }
2801 28994 : }
2802 :
2803 : /*
2804 : * Append remote name of specified foreign table to buf.
2805 : * Use value of table_name FDW option (if any) instead of relation's name.
2806 : * Similarly, schema_name FDW option overrides schema name.
2807 : */
2808 : static void
2809 7112 : deparseRelation(StringInfo buf, Relation rel)
2810 : {
2811 : ForeignTable *table;
2812 7112 : const char *nspname = NULL;
2813 7112 : const char *relname = NULL;
2814 : ListCell *lc;
2815 :
2816 : /* obtain additional catalog information. */
2817 7112 : table = GetForeignTable(RelationGetRelid(rel));
2818 :
2819 : /*
2820 : * Use value of FDW options if any, instead of the name of object itself.
2821 : */
2822 23264 : foreach(lc, table->options)
2823 : {
2824 16152 : DefElem *def = (DefElem *) lfirst(lc);
2825 :
2826 16152 : if (strcmp(def->defname, "schema_name") == 0)
2827 4912 : nspname = defGetString(def);
2828 11240 : else if (strcmp(def->defname, "table_name") == 0)
2829 7112 : relname = defGetString(def);
2830 : }
2831 :
2832 : /*
2833 : * Note: we could skip printing the schema name if it's pg_catalog, but
2834 : * that doesn't seem worth the trouble.
2835 : */
2836 7112 : if (nspname == NULL)
2837 2200 : nspname = get_namespace_name(RelationGetNamespace(rel));
2838 7112 : if (relname == NULL)
2839 0 : relname = RelationGetRelationName(rel);
2840 :
2841 7112 : appendStringInfo(buf, "%s.%s",
2842 : quote_identifier(nspname), quote_identifier(relname));
2843 7112 : }
2844 :
2845 : /*
2846 : * Append a SQL string literal representing "val" to buf.
2847 : */
2848 : void
2849 644 : deparseStringLiteral(StringInfo buf, const char *val)
2850 : {
2851 : const char *valptr;
2852 :
2853 : /*
2854 : * Rather than making assumptions about the remote server's value of
2855 : * standard_conforming_strings, always use E'foo' syntax if there are any
2856 : * backslashes. This will fail on remote servers before 8.1, but those
2857 : * are long out of support.
2858 : */
2859 644 : if (strchr(val, '\\') != NULL)
2860 2 : appendStringInfoChar(buf, ESCAPE_STRING_SYNTAX);
2861 644 : appendStringInfoChar(buf, '\'');
2862 5852 : for (valptr = val; *valptr; valptr++)
2863 : {
2864 5208 : char ch = *valptr;
2865 :
2866 5208 : if (SQL_STR_DOUBLE(ch, true))
2867 4 : appendStringInfoChar(buf, ch);
2868 5208 : appendStringInfoChar(buf, ch);
2869 : }
2870 644 : appendStringInfoChar(buf, '\'');
2871 644 : }
2872 :
2873 : /*
2874 : * Deparse given expression into context->buf.
2875 : *
2876 : * This function must support all the same node types that foreign_expr_walker
2877 : * accepts.
2878 : *
2879 : * Note: unlike ruleutils.c, we just use a simple hard-wired parenthesization
2880 : * scheme: anything more complex than a Var, Const, function call or cast
2881 : * should be self-parenthesized.
2882 : */
2883 : static void
2884 23648 : deparseExpr(Expr *node, deparse_expr_cxt *context)
2885 : {
2886 23648 : if (node == NULL)
2887 0 : return;
2888 :
2889 23648 : switch (nodeTag(node))
2890 : {
2891 16366 : case T_Var:
2892 16366 : deparseVar((Var *) node, context);
2893 16366 : break;
2894 1140 : case T_Const:
2895 1140 : deparseConst((Const *) node, context, 0);
2896 1140 : break;
2897 56 : case T_Param:
2898 56 : deparseParam((Param *) node, context);
2899 56 : break;
2900 2 : case T_SubscriptingRef:
2901 2 : deparseSubscriptingRef((SubscriptingRef *) node, context);
2902 2 : break;
2903 116 : case T_FuncExpr:
2904 116 : deparseFuncExpr((FuncExpr *) node, context);
2905 116 : break;
2906 5194 : case T_OpExpr:
2907 5194 : deparseOpExpr((OpExpr *) node, context);
2908 5194 : break;
2909 2 : case T_DistinctExpr:
2910 2 : deparseDistinctExpr((DistinctExpr *) node, context);
2911 2 : break;
2912 8 : case T_ScalarArrayOpExpr:
2913 8 : deparseScalarArrayOpExpr((ScalarArrayOpExpr *) node, context);
2914 8 : break;
2915 66 : case T_RelabelType:
2916 66 : deparseRelabelType((RelabelType *) node, context);
2917 66 : break;
2918 76 : case T_BoolExpr:
2919 76 : deparseBoolExpr((BoolExpr *) node, context);
2920 76 : break;
2921 56 : case T_NullTest:
2922 56 : deparseNullTest((NullTest *) node, context);
2923 56 : break;
2924 42 : case T_CaseExpr:
2925 42 : deparseCaseExpr((CaseExpr *) node, context);
2926 42 : break;
2927 8 : case T_ArrayExpr:
2928 8 : deparseArrayExpr((ArrayExpr *) node, context);
2929 8 : break;
2930 516 : case T_Aggref:
2931 516 : deparseAggref((Aggref *) node, context);
2932 516 : break;
2933 0 : default:
2934 0 : elog(ERROR, "unsupported expression type for deparse: %d",
2935 : (int) nodeTag(node));
2936 : break;
2937 : }
2938 : }
2939 :
2940 : /*
2941 : * Deparse given Var node into context->buf.
2942 : *
2943 : * If the Var belongs to the foreign relation, just print its remote name.
2944 : * Otherwise, it's effectively a Param (and will in fact be a Param at
2945 : * run time). Handle it the same way we handle plain Params --- see
2946 : * deparseParam for comments.
2947 : */
2948 : static void
2949 16366 : deparseVar(Var *node, deparse_expr_cxt *context)
2950 : {
2951 16366 : Relids relids = context->scanrel->relids;
2952 : int relno;
2953 : int colno;
2954 :
2955 : /* Qualify columns when multiple relations are involved. */
2956 16366 : bool qualify_col = (bms_membership(relids) == BMS_MULTIPLE);
2957 :
2958 : /*
2959 : * If the Var belongs to the foreign relation that is deparsed as a
2960 : * subquery, use the relation and column alias to the Var provided by the
2961 : * subquery, instead of the remote name.
2962 : */
2963 16366 : if (is_subquery_var(node, context->scanrel, &relno, &colno))
2964 : {
2965 232 : appendStringInfo(context->buf, "%s%d.%s%d",
2966 : SUBQUERY_REL_ALIAS_PREFIX, relno,
2967 : SUBQUERY_COL_ALIAS_PREFIX, colno);
2968 232 : return;
2969 : }
2970 :
2971 16134 : if (bms_is_member(node->varno, relids) && node->varlevelsup == 0)
2972 15724 : deparseColumnRef(context->buf, node->varno, node->varattno,
2973 15724 : planner_rt_fetch(node->varno, context->root),
2974 : qualify_col);
2975 : else
2976 : {
2977 : /* Treat like a Param */
2978 410 : if (context->params_list)
2979 : {
2980 22 : int pindex = 0;
2981 : ListCell *lc;
2982 :
2983 : /* find its index in params_list */
2984 22 : foreach(lc, *context->params_list)
2985 : {
2986 0 : pindex++;
2987 0 : if (equal(node, (Node *) lfirst(lc)))
2988 0 : break;
2989 : }
2990 22 : if (lc == NULL)
2991 : {
2992 : /* not in list, so add it */
2993 22 : pindex++;
2994 22 : *context->params_list = lappend(*context->params_list, node);
2995 : }
2996 :
2997 22 : printRemoteParam(pindex, node->vartype, node->vartypmod, context);
2998 : }
2999 : else
3000 : {
3001 388 : printRemotePlaceholder(node->vartype, node->vartypmod, context);
3002 : }
3003 : }
3004 : }
3005 :
3006 : /*
3007 : * Deparse given constant value into context->buf.
3008 : *
3009 : * This function has to be kept in sync with ruleutils.c's get_const_expr.
3010 : *
3011 : * As in that function, showtype can be -1 to never show "::typename"
3012 : * decoration, +1 to always show it, or 0 to show it only if the constant
3013 : * wouldn't be assumed to be the right type by default.
3014 : *
3015 : * In addition, this code allows showtype to be -2 to indicate that we should
3016 : * not show "::typename" decoration if the constant is printed as an untyped
3017 : * literal or NULL (while in other cases, behaving as for showtype == 0).
3018 : */
3019 : static void
3020 3520 : deparseConst(Const *node, deparse_expr_cxt *context, int showtype)
3021 : {
3022 3520 : StringInfo buf = context->buf;
3023 : Oid typoutput;
3024 : bool typIsVarlena;
3025 : char *extval;
3026 3520 : bool isfloat = false;
3027 3520 : bool isstring = false;
3028 : bool needlabel;
3029 :
3030 3520 : if (node->constisnull)
3031 : {
3032 38 : appendStringInfoString(buf, "NULL");
3033 38 : if (showtype >= 0)
3034 38 : appendStringInfo(buf, "::%s",
3035 : deparse_type_name(node->consttype,
3036 : node->consttypmod));
3037 38 : return;
3038 : }
3039 :
3040 3482 : getTypeOutputInfo(node->consttype,
3041 : &typoutput, &typIsVarlena);
3042 3482 : extval = OidOutputFunctionCall(typoutput, node->constvalue);
3043 :
3044 3482 : switch (node->consttype)
3045 : {
3046 3316 : case INT2OID:
3047 : case INT4OID:
3048 : case INT8OID:
3049 : case OIDOID:
3050 : case FLOAT4OID:
3051 : case FLOAT8OID:
3052 : case NUMERICOID:
3053 : {
3054 : /*
3055 : * No need to quote unless it's a special value such as 'NaN'.
3056 : * See comments in get_const_expr().
3057 : */
3058 3316 : if (strspn(extval, "0123456789+-eE.") == strlen(extval))
3059 : {
3060 3316 : if (extval[0] == '+' || extval[0] == '-')
3061 2 : appendStringInfo(buf, "(%s)", extval);
3062 : else
3063 3314 : appendStringInfoString(buf, extval);
3064 3316 : if (strcspn(extval, "eE.") != strlen(extval))
3065 4 : isfloat = true; /* it looks like a float */
3066 : }
3067 : else
3068 0 : appendStringInfo(buf, "'%s'", extval);
3069 : }
3070 3316 : break;
3071 0 : case BITOID:
3072 : case VARBITOID:
3073 0 : appendStringInfo(buf, "B'%s'", extval);
3074 0 : break;
3075 4 : case BOOLOID:
3076 4 : if (strcmp(extval, "t") == 0)
3077 4 : appendStringInfoString(buf, "true");
3078 : else
3079 0 : appendStringInfoString(buf, "false");
3080 4 : break;
3081 162 : default:
3082 162 : deparseStringLiteral(buf, extval);
3083 162 : isstring = true;
3084 162 : break;
3085 : }
3086 :
3087 3482 : pfree(extval);
3088 :
3089 3482 : if (showtype == -1)
3090 0 : return; /* never print type label */
3091 :
3092 : /*
3093 : * For showtype == 0, append ::typename unless the constant will be
3094 : * implicitly typed as the right type when it is read in.
3095 : *
3096 : * XXX this code has to be kept in sync with the behavior of the parser,
3097 : * especially make_const.
3098 : */
3099 3482 : switch (node->consttype)
3100 : {
3101 2842 : case BOOLOID:
3102 : case INT4OID:
3103 : case UNKNOWNOID:
3104 2842 : needlabel = false;
3105 2842 : break;
3106 42 : case NUMERICOID:
3107 42 : needlabel = !isfloat || (node->consttypmod >= 0);
3108 42 : break;
3109 598 : default:
3110 598 : if (showtype == -2)
3111 : {
3112 : /* label unless we printed it as an untyped string */
3113 86 : needlabel = !isstring;
3114 : }
3115 : else
3116 512 : needlabel = true;
3117 598 : break;
3118 : }
3119 3482 : if (needlabel || showtype > 0)
3120 550 : appendStringInfo(buf, "::%s",
3121 : deparse_type_name(node->consttype,
3122 : node->consttypmod));
3123 : }
3124 :
3125 : /*
3126 : * Deparse given Param node.
3127 : *
3128 : * If we're generating the query "for real", add the Param to
3129 : * context->params_list if it's not already present, and then use its index
3130 : * in that list as the remote parameter number. During EXPLAIN, there's
3131 : * no need to identify a parameter number.
3132 : */
3133 : static void
3134 56 : deparseParam(Param *node, deparse_expr_cxt *context)
3135 : {
3136 56 : if (context->params_list)
3137 : {
3138 36 : int pindex = 0;
3139 : ListCell *lc;
3140 :
3141 : /* find its index in params_list */
3142 40 : foreach(lc, *context->params_list)
3143 : {
3144 4 : pindex++;
3145 4 : if (equal(node, (Node *) lfirst(lc)))
3146 0 : break;
3147 : }
3148 36 : if (lc == NULL)
3149 : {
3150 : /* not in list, so add it */
3151 36 : pindex++;
3152 36 : *context->params_list = lappend(*context->params_list, node);
3153 : }
3154 :
3155 36 : printRemoteParam(pindex, node->paramtype, node->paramtypmod, context);
3156 : }
3157 : else
3158 : {
3159 20 : printRemotePlaceholder(node->paramtype, node->paramtypmod, context);
3160 : }
3161 56 : }
3162 :
3163 : /*
3164 : * Deparse a container subscript expression.
3165 : */
3166 : static void
3167 2 : deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context)
3168 : {
3169 2 : StringInfo buf = context->buf;
3170 : ListCell *lowlist_item;
3171 : ListCell *uplist_item;
3172 :
3173 : /* Always parenthesize the expression. */
3174 2 : appendStringInfoChar(buf, '(');
3175 :
3176 : /*
3177 : * Deparse referenced array expression first. If that expression includes
3178 : * a cast, we have to parenthesize to prevent the array subscript from
3179 : * being taken as typename decoration. We can avoid that in the typical
3180 : * case of subscripting a Var, but otherwise do it.
3181 : */
3182 2 : if (IsA(node->refexpr, Var))
3183 0 : deparseExpr(node->refexpr, context);
3184 : else
3185 : {
3186 2 : appendStringInfoChar(buf, '(');
3187 2 : deparseExpr(node->refexpr, context);
3188 2 : appendStringInfoChar(buf, ')');
3189 : }
3190 :
3191 : /* Deparse subscript expressions. */
3192 2 : lowlist_item = list_head(node->reflowerindexpr); /* could be NULL */
3193 4 : foreach(uplist_item, node->refupperindexpr)
3194 : {
3195 2 : appendStringInfoChar(buf, '[');
3196 2 : if (lowlist_item)
3197 : {
3198 0 : deparseExpr(lfirst(lowlist_item), context);
3199 0 : appendStringInfoChar(buf, ':');
3200 0 : lowlist_item = lnext(node->reflowerindexpr, lowlist_item);
3201 : }
3202 2 : deparseExpr(lfirst(uplist_item), context);
3203 2 : appendStringInfoChar(buf, ']');
3204 : }
3205 :
3206 2 : appendStringInfoChar(buf, ')');
3207 2 : }
3208 :
3209 : /*
3210 : * Deparse a function call.
3211 : */
3212 : static void
3213 116 : deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context)
3214 : {
3215 116 : StringInfo buf = context->buf;
3216 : bool use_variadic;
3217 : bool first;
3218 : ListCell *arg;
3219 :
3220 : /*
3221 : * If the function call came from an implicit coercion, then just show the
3222 : * first argument.
3223 : */
3224 116 : if (node->funcformat == COERCE_IMPLICIT_CAST)
3225 : {
3226 42 : deparseExpr((Expr *) linitial(node->args), context);
3227 42 : return;
3228 : }
3229 :
3230 : /*
3231 : * If the function call came from a cast, then show the first argument
3232 : * plus an explicit cast operation.
3233 : */
3234 74 : if (node->funcformat == COERCE_EXPLICIT_CAST)
3235 : {
3236 0 : Oid rettype = node->funcresulttype;
3237 : int32 coercedTypmod;
3238 :
3239 : /* Get the typmod if this is a length-coercion function */
3240 0 : (void) exprIsLengthCoercion((Node *) node, &coercedTypmod);
3241 :
3242 0 : deparseExpr((Expr *) linitial(node->args), context);
3243 0 : appendStringInfo(buf, "::%s",
3244 : deparse_type_name(rettype, coercedTypmod));
3245 0 : return;
3246 : }
3247 :
3248 : /* Check if need to print VARIADIC (cf. ruleutils.c) */
3249 74 : use_variadic = node->funcvariadic;
3250 :
3251 : /*
3252 : * Normal function: display as proname(args).
3253 : */
3254 74 : appendFunctionName(node->funcid, context);
3255 74 : appendStringInfoChar(buf, '(');
3256 :
3257 : /* ... and all the arguments */
3258 74 : first = true;
3259 156 : foreach(arg, node->args)
3260 : {
3261 82 : if (!first)
3262 8 : appendStringInfoString(buf, ", ");
3263 82 : if (use_variadic && lnext(node->args, arg) == NULL)
3264 0 : appendStringInfoString(buf, "VARIADIC ");
3265 82 : deparseExpr((Expr *) lfirst(arg), context);
3266 82 : first = false;
3267 : }
3268 74 : appendStringInfoChar(buf, ')');
3269 : }
3270 :
3271 : /*
3272 : * Deparse given operator expression. To avoid problems around
3273 : * priority of operations, we always parenthesize the arguments.
3274 : */
3275 : static void
3276 5194 : deparseOpExpr(OpExpr *node, deparse_expr_cxt *context)
3277 : {
3278 5194 : StringInfo buf = context->buf;
3279 : HeapTuple tuple;
3280 : Form_pg_operator form;
3281 : Expr *right;
3282 5194 : bool canSuppressRightConstCast = false;
3283 : char oprkind;
3284 :
3285 : /* Retrieve information about the operator from system catalog. */
3286 5194 : tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
3287 5194 : if (!HeapTupleIsValid(tuple))
3288 0 : elog(ERROR, "cache lookup failed for operator %u", node->opno);
3289 5194 : form = (Form_pg_operator) GETSTRUCT(tuple);
3290 5194 : oprkind = form->oprkind;
3291 :
3292 : /* Sanity check. */
3293 : Assert((oprkind == 'l' && list_length(node->args) == 1) ||
3294 : (oprkind == 'b' && list_length(node->args) == 2));
3295 :
3296 5194 : right = llast(node->args);
3297 :
3298 : /* Always parenthesize the expression. */
3299 5194 : appendStringInfoChar(buf, '(');
3300 :
3301 : /* Deparse left operand, if any. */
3302 5194 : if (oprkind == 'b')
3303 : {
3304 5188 : Expr *left = linitial(node->args);
3305 5188 : Oid leftType = exprType((Node *) left);
3306 5188 : Oid rightType = exprType((Node *) right);
3307 5188 : bool canSuppressLeftConstCast = false;
3308 :
3309 : /*
3310 : * When considering a binary operator, if one operand is a Const that
3311 : * can be printed as a bare string literal or NULL (i.e., it will look
3312 : * like type UNKNOWN to the remote parser), the Const normally
3313 : * receives an explicit cast to the operator's input type. However,
3314 : * in Const-to-Var comparisons where both operands are of the same
3315 : * type, we prefer to suppress the explicit cast, leaving the Const's
3316 : * type resolution up to the remote parser. The remote's resolution
3317 : * heuristic will assume that an unknown input type being compared to
3318 : * a known input type is of that known type as well.
3319 : *
3320 : * This hack allows some cases to succeed where a remote column is
3321 : * declared with a different type in the local (foreign) table. By
3322 : * emitting "foreigncol = 'foo'" not "foreigncol = 'foo'::text" or the
3323 : * like, we allow the remote parser to pick an "=" operator that's
3324 : * compatible with whatever type the remote column really is, such as
3325 : * an enum.
3326 : *
3327 : * We allow cast suppression to happen only when the other operand is
3328 : * a plain foreign Var. Although the remote's unknown-type heuristic
3329 : * would apply to other cases just as well, we would be taking a
3330 : * bigger risk that the inferred type is something unexpected. With
3331 : * this restriction, if anything goes wrong it's the user's fault for
3332 : * not declaring the local column with the same type as the remote
3333 : * column.
3334 : */
3335 5188 : if (leftType == rightType)
3336 : {
3337 5156 : if (IsA(left, Const))
3338 6 : canSuppressLeftConstCast = isPlainForeignVar(right, context);
3339 5150 : else if (IsA(right, Const))
3340 2874 : canSuppressRightConstCast = isPlainForeignVar(left, context);
3341 : }
3342 :
3343 5188 : if (canSuppressLeftConstCast)
3344 4 : deparseConst((Const *) left, context, -2);
3345 : else
3346 5184 : deparseExpr(left, context);
3347 :
3348 5188 : appendStringInfoChar(buf, ' ');
3349 : }
3350 :
3351 : /* Deparse operator name. */
3352 5194 : deparseOperatorName(buf, form);
3353 :
3354 : /* Deparse right operand. */
3355 5194 : appendStringInfoChar(buf, ' ');
3356 :
3357 5194 : if (canSuppressRightConstCast)
3358 2376 : deparseConst((Const *) right, context, -2);
3359 : else
3360 2818 : deparseExpr(right, context);
3361 :
3362 5194 : appendStringInfoChar(buf, ')');
3363 :
3364 5194 : ReleaseSysCache(tuple);
3365 5194 : }
3366 :
3367 : /*
3368 : * Will "node" deparse as a plain foreign Var?
3369 : */
3370 : static bool
3371 2880 : isPlainForeignVar(Expr *node, deparse_expr_cxt *context)
3372 : {
3373 : /*
3374 : * We allow the foreign Var to have an implicit RelabelType, mainly so
3375 : * that this'll work with varchar columns. Note that deparseRelabelType
3376 : * will not print such a cast, so we're not breaking the restriction that
3377 : * the expression print as a plain Var. We won't risk it for an implicit
3378 : * cast that requires a function, nor for non-implicit RelabelType; such
3379 : * cases seem too likely to involve semantics changes compared to what
3380 : * would happen on the remote side.
3381 : */
3382 2880 : if (IsA(node, RelabelType) &&
3383 10 : ((RelabelType *) node)->relabelformat == COERCE_IMPLICIT_CAST)
3384 10 : node = ((RelabelType *) node)->arg;
3385 :
3386 2880 : if (IsA(node, Var))
3387 : {
3388 : /*
3389 : * The Var must be one that'll deparse as a foreign column reference
3390 : * (cf. deparseVar).
3391 : */
3392 2380 : Var *var = (Var *) node;
3393 2380 : Relids relids = context->scanrel->relids;
3394 :
3395 2380 : if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
3396 2380 : return true;
3397 : }
3398 :
3399 500 : return false;
3400 : }
3401 :
3402 : /*
3403 : * Print the name of an operator.
3404 : */
3405 : static void
3406 5218 : deparseOperatorName(StringInfo buf, Form_pg_operator opform)
3407 : {
3408 : char *opname;
3409 :
3410 : /* opname is not a SQL identifier, so we should not quote it. */
3411 5218 : opname = NameStr(opform->oprname);
3412 :
3413 : /* Print schema name only if it's not pg_catalog */
3414 5218 : if (opform->oprnamespace != PG_CATALOG_NAMESPACE)
3415 : {
3416 : const char *opnspname;
3417 :
3418 26 : opnspname = get_namespace_name(opform->oprnamespace);
3419 : /* Print fully qualified operator name. */
3420 26 : appendStringInfo(buf, "OPERATOR(%s.%s)",
3421 : quote_identifier(opnspname), opname);
3422 : }
3423 : else
3424 : {
3425 : /* Just print operator name. */
3426 5192 : appendStringInfoString(buf, opname);
3427 : }
3428 5218 : }
3429 :
3430 : /*
3431 : * Deparse IS DISTINCT FROM.
3432 : */
3433 : static void
3434 2 : deparseDistinctExpr(DistinctExpr *node, deparse_expr_cxt *context)
3435 : {
3436 2 : StringInfo buf = context->buf;
3437 :
3438 : Assert(list_length(node->args) == 2);
3439 :
3440 2 : appendStringInfoChar(buf, '(');
3441 2 : deparseExpr(linitial(node->args), context);
3442 2 : appendStringInfoString(buf, " IS DISTINCT FROM ");
3443 2 : deparseExpr(lsecond(node->args), context);
3444 2 : appendStringInfoChar(buf, ')');
3445 2 : }
3446 :
3447 : /*
3448 : * Deparse given ScalarArrayOpExpr expression. To avoid problems
3449 : * around priority of operations, we always parenthesize the arguments.
3450 : */
3451 : static void
3452 8 : deparseScalarArrayOpExpr(ScalarArrayOpExpr *node, deparse_expr_cxt *context)
3453 : {
3454 8 : StringInfo buf = context->buf;
3455 : HeapTuple tuple;
3456 : Form_pg_operator form;
3457 : Expr *arg1;
3458 : Expr *arg2;
3459 :
3460 : /* Retrieve information about the operator from system catalog. */
3461 8 : tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
3462 8 : if (!HeapTupleIsValid(tuple))
3463 0 : elog(ERROR, "cache lookup failed for operator %u", node->opno);
3464 8 : form = (Form_pg_operator) GETSTRUCT(tuple);
3465 :
3466 : /* Sanity check. */
3467 : Assert(list_length(node->args) == 2);
3468 :
3469 : /* Always parenthesize the expression. */
3470 8 : appendStringInfoChar(buf, '(');
3471 :
3472 : /* Deparse left operand. */
3473 8 : arg1 = linitial(node->args);
3474 8 : deparseExpr(arg1, context);
3475 8 : appendStringInfoChar(buf, ' ');
3476 :
3477 : /* Deparse operator name plus decoration. */
3478 8 : deparseOperatorName(buf, form);
3479 8 : appendStringInfo(buf, " %s (", node->useOr ? "ANY" : "ALL");
3480 :
3481 : /* Deparse right operand. */
3482 8 : arg2 = lsecond(node->args);
3483 8 : deparseExpr(arg2, context);
3484 :
3485 8 : appendStringInfoChar(buf, ')');
3486 :
3487 : /* Always parenthesize the expression. */
3488 8 : appendStringInfoChar(buf, ')');
3489 :
3490 8 : ReleaseSysCache(tuple);
3491 8 : }
3492 :
3493 : /*
3494 : * Deparse a RelabelType (binary-compatible cast) node.
3495 : */
3496 : static void
3497 66 : deparseRelabelType(RelabelType *node, deparse_expr_cxt *context)
3498 : {
3499 66 : deparseExpr(node->arg, context);
3500 66 : if (node->relabelformat != COERCE_IMPLICIT_CAST)
3501 0 : appendStringInfo(context->buf, "::%s",
3502 : deparse_type_name(node->resulttype,
3503 : node->resulttypmod));
3504 66 : }
3505 :
3506 : /*
3507 : * Deparse a BoolExpr node.
3508 : */
3509 : static void
3510 76 : deparseBoolExpr(BoolExpr *node, deparse_expr_cxt *context)
3511 : {
3512 76 : StringInfo buf = context->buf;
3513 76 : const char *op = NULL; /* keep compiler quiet */
3514 : bool first;
3515 : ListCell *lc;
3516 :
3517 76 : switch (node->boolop)
3518 : {
3519 36 : case AND_EXPR:
3520 36 : op = "AND";
3521 36 : break;
3522 40 : case OR_EXPR:
3523 40 : op = "OR";
3524 40 : break;
3525 0 : case NOT_EXPR:
3526 0 : appendStringInfoString(buf, "(NOT ");
3527 0 : deparseExpr(linitial(node->args), context);
3528 0 : appendStringInfoChar(buf, ')');
3529 0 : return;
3530 : }
3531 :
3532 76 : appendStringInfoChar(buf, '(');
3533 76 : first = true;
3534 228 : foreach(lc, node->args)
3535 : {
3536 152 : if (!first)
3537 76 : appendStringInfo(buf, " %s ", op);
3538 152 : deparseExpr((Expr *) lfirst(lc), context);
3539 152 : first = false;
3540 : }
3541 76 : appendStringInfoChar(buf, ')');
3542 : }
3543 :
3544 : /*
3545 : * Deparse IS [NOT] NULL expression.
3546 : */
3547 : static void
3548 56 : deparseNullTest(NullTest *node, deparse_expr_cxt *context)
3549 : {
3550 56 : StringInfo buf = context->buf;
3551 :
3552 56 : appendStringInfoChar(buf, '(');
3553 56 : deparseExpr(node->arg, context);
3554 :
3555 : /*
3556 : * For scalar inputs, we prefer to print as IS [NOT] NULL, which is
3557 : * shorter and traditional. If it's a rowtype input but we're applying a
3558 : * scalar test, must print IS [NOT] DISTINCT FROM NULL to be semantically
3559 : * correct.
3560 : */
3561 56 : if (node->argisrow || !type_is_rowtype(exprType((Node *) node->arg)))
3562 : {
3563 56 : if (node->nulltesttype == IS_NULL)
3564 38 : appendStringInfoString(buf, " IS NULL)");
3565 : else
3566 18 : appendStringInfoString(buf, " IS NOT NULL)");
3567 : }
3568 : else
3569 : {
3570 0 : if (node->nulltesttype == IS_NULL)
3571 0 : appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL)");
3572 : else
3573 0 : appendStringInfoString(buf, " IS DISTINCT FROM NULL)");
3574 : }
3575 56 : }
3576 :
3577 : /*
3578 : * Deparse CASE expression
3579 : */
3580 : static void
3581 42 : deparseCaseExpr(CaseExpr *node, deparse_expr_cxt *context)
3582 : {
3583 42 : StringInfo buf = context->buf;
3584 : ListCell *lc;
3585 :
3586 42 : appendStringInfoString(buf, "(CASE");
3587 :
3588 : /* If this is a CASE arg WHEN then emit the arg expression */
3589 42 : if (node->arg != NULL)
3590 : {
3591 18 : appendStringInfoChar(buf, ' ');
3592 18 : deparseExpr(node->arg, context);
3593 : }
3594 :
3595 : /* Add each condition/result of the CASE clause */
3596 98 : foreach(lc, node->args)
3597 : {
3598 56 : CaseWhen *whenclause = (CaseWhen *) lfirst(lc);
3599 :
3600 : /* WHEN */
3601 56 : appendStringInfoString(buf, " WHEN ");
3602 56 : if (node->arg == NULL) /* CASE WHEN */
3603 24 : deparseExpr(whenclause->expr, context);
3604 : else /* CASE arg WHEN */
3605 : {
3606 : /* Ignore the CaseTestExpr and equality operator. */
3607 32 : deparseExpr(lsecond(castNode(OpExpr, whenclause->expr)->args),
3608 : context);
3609 : }
3610 :
3611 : /* THEN */
3612 56 : appendStringInfoString(buf, " THEN ");
3613 56 : deparseExpr(whenclause->result, context);
3614 : }
3615 :
3616 : /* add ELSE if present */
3617 42 : if (node->defresult != NULL)
3618 : {
3619 42 : appendStringInfoString(buf, " ELSE ");
3620 42 : deparseExpr(node->defresult, context);
3621 : }
3622 :
3623 : /* append END */
3624 42 : appendStringInfoString(buf, " END)");
3625 42 : }
3626 :
3627 : /*
3628 : * Deparse ARRAY[...] construct.
3629 : */
3630 : static void
3631 8 : deparseArrayExpr(ArrayExpr *node, deparse_expr_cxt *context)
3632 : {
3633 8 : StringInfo buf = context->buf;
3634 8 : bool first = true;
3635 : ListCell *lc;
3636 :
3637 8 : appendStringInfoString(buf, "ARRAY[");
3638 24 : foreach(lc, node->elements)
3639 : {
3640 16 : if (!first)
3641 8 : appendStringInfoString(buf, ", ");
3642 16 : deparseExpr(lfirst(lc), context);
3643 16 : first = false;
3644 : }
3645 8 : appendStringInfoChar(buf, ']');
3646 :
3647 : /* If the array is empty, we need an explicit cast to the array type. */
3648 8 : if (node->elements == NIL)
3649 0 : appendStringInfo(buf, "::%s",
3650 : deparse_type_name(node->array_typeid, -1));
3651 8 : }
3652 :
3653 : /*
3654 : * Deparse an Aggref node.
3655 : */
3656 : static void
3657 516 : deparseAggref(Aggref *node, deparse_expr_cxt *context)
3658 : {
3659 516 : StringInfo buf = context->buf;
3660 : bool use_variadic;
3661 :
3662 : /* Only basic, non-split aggregation accepted. */
3663 : Assert(node->aggsplit == AGGSPLIT_SIMPLE);
3664 :
3665 : /* Check if need to print VARIADIC (cf. ruleutils.c) */
3666 516 : use_variadic = node->aggvariadic;
3667 :
3668 : /* Find aggregate name from aggfnoid which is a pg_proc entry */
3669 516 : appendFunctionName(node->aggfnoid, context);
3670 516 : appendStringInfoChar(buf, '(');
3671 :
3672 : /* Add DISTINCT */
3673 516 : appendStringInfoString(buf, (node->aggdistinct != NIL) ? "DISTINCT " : "");
3674 :
3675 516 : if (AGGKIND_IS_ORDERED_SET(node->aggkind))
3676 : {
3677 : /* Add WITHIN GROUP (ORDER BY ..) */
3678 : ListCell *arg;
3679 16 : bool first = true;
3680 :
3681 : Assert(!node->aggvariadic);
3682 : Assert(node->aggorder != NIL);
3683 :
3684 36 : foreach(arg, node->aggdirectargs)
3685 : {
3686 20 : if (!first)
3687 4 : appendStringInfoString(buf, ", ");
3688 20 : first = false;
3689 :
3690 20 : deparseExpr((Expr *) lfirst(arg), context);
3691 : }
3692 :
3693 16 : appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
3694 16 : appendAggOrderBy(node->aggorder, node->args, context);
3695 : }
3696 : else
3697 : {
3698 : /* aggstar can be set only in zero-argument aggregates */
3699 500 : if (node->aggstar)
3700 134 : appendStringInfoChar(buf, '*');
3701 : else
3702 : {
3703 : ListCell *arg;
3704 366 : bool first = true;
3705 :
3706 : /* Add all the arguments */
3707 740 : foreach(arg, node->args)
3708 : {
3709 374 : TargetEntry *tle = (TargetEntry *) lfirst(arg);
3710 374 : Node *n = (Node *) tle->expr;
3711 :
3712 374 : if (tle->resjunk)
3713 8 : continue;
3714 :
3715 366 : if (!first)
3716 0 : appendStringInfoString(buf, ", ");
3717 366 : first = false;
3718 :
3719 : /* Add VARIADIC */
3720 366 : if (use_variadic && lnext(node->args, arg) == NULL)
3721 4 : appendStringInfoString(buf, "VARIADIC ");
3722 :
3723 366 : deparseExpr((Expr *) n, context);
3724 : }
3725 : }
3726 :
3727 : /* Add ORDER BY */
3728 500 : if (node->aggorder != NIL)
3729 : {
3730 44 : appendStringInfoString(buf, " ORDER BY ");
3731 44 : appendAggOrderBy(node->aggorder, node->args, context);
3732 : }
3733 : }
3734 :
3735 : /* Add FILTER (WHERE ..) */
3736 516 : if (node->aggfilter != NULL)
3737 : {
3738 24 : appendStringInfoString(buf, ") FILTER (WHERE ");
3739 24 : deparseExpr((Expr *) node->aggfilter, context);
3740 : }
3741 :
3742 516 : appendStringInfoChar(buf, ')');
3743 516 : }
3744 :
3745 : /*
3746 : * Append ORDER BY within aggregate function.
3747 : */
3748 : static void
3749 60 : appendAggOrderBy(List *orderList, List *targetList, deparse_expr_cxt *context)
3750 : {
3751 60 : StringInfo buf = context->buf;
3752 : ListCell *lc;
3753 60 : bool first = true;
3754 :
3755 124 : foreach(lc, orderList)
3756 : {
3757 64 : SortGroupClause *srt = (SortGroupClause *) lfirst(lc);
3758 : Node *sortexpr;
3759 :
3760 64 : if (!first)
3761 4 : appendStringInfoString(buf, ", ");
3762 64 : first = false;
3763 :
3764 : /* Deparse the sort expression proper. */
3765 64 : sortexpr = deparseSortGroupClause(srt->tleSortGroupRef, targetList,
3766 : false, context);
3767 : /* Add decoration as needed. */
3768 64 : appendOrderBySuffix(srt->sortop, exprType(sortexpr), srt->nulls_first,
3769 : context);
3770 : }
3771 60 : }
3772 :
3773 : /*
3774 : * Append the ASC, DESC, USING <OPERATOR> and NULLS FIRST / NULLS LAST parts
3775 : * of an ORDER BY clause.
3776 : */
3777 : static void
3778 1744 : appendOrderBySuffix(Oid sortop, Oid sortcoltype, bool nulls_first,
3779 : deparse_expr_cxt *context)
3780 : {
3781 1744 : StringInfo buf = context->buf;
3782 : TypeCacheEntry *typentry;
3783 :
3784 : /* See whether operator is default < or > for sort expr's datatype. */
3785 1744 : typentry = lookup_type_cache(sortcoltype,
3786 : TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
3787 :
3788 1744 : if (sortop == typentry->lt_opr)
3789 1698 : appendStringInfoString(buf, " ASC");
3790 46 : else if (sortop == typentry->gt_opr)
3791 30 : appendStringInfoString(buf, " DESC");
3792 : else
3793 : {
3794 : HeapTuple opertup;
3795 : Form_pg_operator operform;
3796 :
3797 16 : appendStringInfoString(buf, " USING ");
3798 :
3799 : /* Append operator name. */
3800 16 : opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(sortop));
3801 16 : if (!HeapTupleIsValid(opertup))
3802 0 : elog(ERROR, "cache lookup failed for operator %u", sortop);
3803 16 : operform = (Form_pg_operator) GETSTRUCT(opertup);
3804 16 : deparseOperatorName(buf, operform);
3805 16 : ReleaseSysCache(opertup);
3806 : }
3807 :
3808 1744 : if (nulls_first)
3809 22 : appendStringInfoString(buf, " NULLS FIRST");
3810 : else
3811 1722 : appendStringInfoString(buf, " NULLS LAST");
3812 1744 : }
3813 :
3814 : /*
3815 : * Print the representation of a parameter to be sent to the remote side.
3816 : *
3817 : * Note: we always label the Param's type explicitly rather than relying on
3818 : * transmitting a numeric type OID in PQsendQueryParams(). This allows us to
3819 : * avoid assuming that types have the same OIDs on the remote side as they
3820 : * do locally --- they need only have the same names.
3821 : */
3822 : static void
3823 58 : printRemoteParam(int paramindex, Oid paramtype, int32 paramtypmod,
3824 : deparse_expr_cxt *context)
3825 : {
3826 58 : StringInfo buf = context->buf;
3827 58 : char *ptypename = deparse_type_name(paramtype, paramtypmod);
3828 :
3829 58 : appendStringInfo(buf, "$%d::%s", paramindex, ptypename);
3830 58 : }
3831 :
3832 : /*
3833 : * Print the representation of a placeholder for a parameter that will be
3834 : * sent to the remote side at execution time.
3835 : *
3836 : * This is used when we're just trying to EXPLAIN the remote query.
3837 : * We don't have the actual value of the runtime parameter yet, and we don't
3838 : * want the remote planner to generate a plan that depends on such a value
3839 : * anyway. Thus, we can't do something simple like "$1::paramtype".
3840 : * Instead, we emit "((SELECT null::paramtype)::paramtype)".
3841 : * In all extant versions of Postgres, the planner will see that as an unknown
3842 : * constant value, which is what we want. This might need adjustment if we
3843 : * ever make the planner flatten scalar subqueries. Note: the reason for the
3844 : * apparently useless outer cast is to ensure that the representation as a
3845 : * whole will be parsed as an a_expr and not a select_with_parens; the latter
3846 : * would do the wrong thing in the context "x = ANY(...)".
3847 : */
3848 : static void
3849 408 : printRemotePlaceholder(Oid paramtype, int32 paramtypmod,
3850 : deparse_expr_cxt *context)
3851 : {
3852 408 : StringInfo buf = context->buf;
3853 408 : char *ptypename = deparse_type_name(paramtype, paramtypmod);
3854 :
3855 408 : appendStringInfo(buf, "((SELECT null::%s)::%s)", ptypename, ptypename);
3856 408 : }
3857 :
3858 : /*
3859 : * Deparse GROUP BY clause.
3860 : */
3861 : static void
3862 322 : appendGroupByClause(List *tlist, deparse_expr_cxt *context)
3863 : {
3864 322 : StringInfo buf = context->buf;
3865 322 : Query *query = context->root->parse;
3866 : ListCell *lc;
3867 322 : bool first = true;
3868 :
3869 : /* Nothing to be done, if there's no GROUP BY clause in the query. */
3870 322 : if (!query->groupClause)
3871 120 : return;
3872 :
3873 202 : appendStringInfoString(buf, " GROUP BY ");
3874 :
3875 : /*
3876 : * Queries with grouping sets are not pushed down, so we don't expect
3877 : * grouping sets here.
3878 : */
3879 : Assert(!query->groupingSets);
3880 :
3881 : /*
3882 : * We intentionally print query->groupClause not processed_groupClause,
3883 : * leaving it to the remote planner to get rid of any redundant GROUP BY
3884 : * items again. This is necessary in case processed_groupClause reduced
3885 : * to empty, and in any case the redundancy situation on the remote might
3886 : * be different than what we think here.
3887 : */
3888 428 : foreach(lc, query->groupClause)
3889 : {
3890 226 : SortGroupClause *grp = (SortGroupClause *) lfirst(lc);
3891 :
3892 226 : if (!first)
3893 24 : appendStringInfoString(buf, ", ");
3894 226 : first = false;
3895 :
3896 226 : deparseSortGroupClause(grp->tleSortGroupRef, tlist, true, context);
3897 : }
3898 : }
3899 :
3900 : /*
3901 : * Deparse ORDER BY clause defined by the given pathkeys.
3902 : *
3903 : * The clause should use Vars from context->scanrel if !has_final_sort,
3904 : * or from context->foreignrel's targetlist if has_final_sort.
3905 : *
3906 : * We find a suitable pathkey expression (some earlier step
3907 : * should have verified that there is one) and deparse it.
3908 : */
3909 : static void
3910 1426 : appendOrderByClause(List *pathkeys, bool has_final_sort,
3911 : deparse_expr_cxt *context)
3912 : {
3913 : ListCell *lcell;
3914 : int nestlevel;
3915 1426 : StringInfo buf = context->buf;
3916 1426 : bool gotone = false;
3917 :
3918 : /* Make sure any constants in the exprs are printed portably */
3919 1426 : nestlevel = set_transmission_modes();
3920 :
3921 3118 : foreach(lcell, pathkeys)
3922 : {
3923 1692 : PathKey *pathkey = lfirst(lcell);
3924 : EquivalenceMember *em;
3925 : Expr *em_expr;
3926 : Oid oprid;
3927 :
3928 1692 : if (has_final_sort)
3929 : {
3930 : /*
3931 : * By construction, context->foreignrel is the input relation to
3932 : * the final sort.
3933 : */
3934 406 : em = find_em_for_rel_target(context->root,
3935 : pathkey->pk_eclass,
3936 : context->foreignrel);
3937 : }
3938 : else
3939 1286 : em = find_em_for_rel(context->root,
3940 : pathkey->pk_eclass,
3941 : context->scanrel);
3942 :
3943 : /*
3944 : * We don't expect any error here; it would mean that shippability
3945 : * wasn't verified earlier. For the same reason, we don't recheck
3946 : * shippability of the sort operator.
3947 : */
3948 1692 : if (em == NULL)
3949 0 : elog(ERROR, "could not find pathkey item to sort");
3950 :
3951 1692 : em_expr = em->em_expr;
3952 :
3953 : /*
3954 : * If the member is a Const expression then we needn't add it to the
3955 : * ORDER BY clause. This can happen in UNION ALL queries where the
3956 : * union child targetlist has a Const. Adding these would be
3957 : * wasteful, but also, for INT columns, an integer literal would be
3958 : * seen as an ordinal column position rather than a value to sort by.
3959 : * deparseConst() does have code to handle this, but it seems less
3960 : * effort on all accounts just to skip these for ORDER BY clauses.
3961 : */
3962 1692 : if (IsA(em_expr, Const))
3963 12 : continue;
3964 :
3965 1680 : if (!gotone)
3966 : {
3967 1420 : appendStringInfoString(buf, " ORDER BY ");
3968 1420 : gotone = true;
3969 : }
3970 : else
3971 260 : appendStringInfoString(buf, ", ");
3972 :
3973 : /*
3974 : * Lookup the operator corresponding to the strategy in the opclass.
3975 : * The datatype used by the opfamily is not necessarily the same as
3976 : * the expression type (for array types for example).
3977 : */
3978 1680 : oprid = get_opfamily_member(pathkey->pk_opfamily,
3979 : em->em_datatype,
3980 : em->em_datatype,
3981 1680 : pathkey->pk_strategy);
3982 1680 : if (!OidIsValid(oprid))
3983 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3984 : pathkey->pk_strategy, em->em_datatype, em->em_datatype,
3985 : pathkey->pk_opfamily);
3986 :
3987 1680 : deparseExpr(em_expr, context);
3988 :
3989 : /*
3990 : * Here we need to use the expression's actual type to discover
3991 : * whether the desired operator will be the default or not.
3992 : */
3993 1680 : appendOrderBySuffix(oprid, exprType((Node *) em_expr),
3994 1680 : pathkey->pk_nulls_first, context);
3995 :
3996 : }
3997 1426 : reset_transmission_modes(nestlevel);
3998 1426 : }
3999 :
4000 : /*
4001 : * Deparse LIMIT/OFFSET clause.
4002 : */
4003 : static void
4004 282 : appendLimitClause(deparse_expr_cxt *context)
4005 : {
4006 282 : PlannerInfo *root = context->root;
4007 282 : StringInfo buf = context->buf;
4008 : int nestlevel;
4009 :
4010 : /* Make sure any constants in the exprs are printed portably */
4011 282 : nestlevel = set_transmission_modes();
4012 :
4013 282 : if (root->parse->limitCount)
4014 : {
4015 282 : appendStringInfoString(buf, " LIMIT ");
4016 282 : deparseExpr((Expr *) root->parse->limitCount, context);
4017 : }
4018 282 : if (root->parse->limitOffset)
4019 : {
4020 150 : appendStringInfoString(buf, " OFFSET ");
4021 150 : deparseExpr((Expr *) root->parse->limitOffset, context);
4022 : }
4023 :
4024 282 : reset_transmission_modes(nestlevel);
4025 282 : }
4026 :
4027 : /*
4028 : * appendFunctionName
4029 : * Deparses function name from given function oid.
4030 : */
4031 : static void
4032 590 : appendFunctionName(Oid funcid, deparse_expr_cxt *context)
4033 : {
4034 590 : StringInfo buf = context->buf;
4035 : HeapTuple proctup;
4036 : Form_pg_proc procform;
4037 : const char *proname;
4038 :
4039 590 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4040 590 : if (!HeapTupleIsValid(proctup))
4041 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
4042 590 : procform = (Form_pg_proc) GETSTRUCT(proctup);
4043 :
4044 : /* Print schema name only if it's not pg_catalog */
4045 590 : if (procform->pronamespace != PG_CATALOG_NAMESPACE)
4046 : {
4047 : const char *schemaname;
4048 :
4049 12 : schemaname = get_namespace_name(procform->pronamespace);
4050 12 : appendStringInfo(buf, "%s.", quote_identifier(schemaname));
4051 : }
4052 :
4053 : /* Always print the function name */
4054 590 : proname = NameStr(procform->proname);
4055 590 : appendStringInfoString(buf, quote_identifier(proname));
4056 :
4057 590 : ReleaseSysCache(proctup);
4058 590 : }
4059 :
4060 : /*
4061 : * Appends a sort or group clause.
4062 : *
4063 : * Like get_rule_sortgroupclause(), returns the expression tree, so caller
4064 : * need not find it again.
4065 : */
4066 : static Node *
4067 290 : deparseSortGroupClause(Index ref, List *tlist, bool force_colno,
4068 : deparse_expr_cxt *context)
4069 : {
4070 290 : StringInfo buf = context->buf;
4071 : TargetEntry *tle;
4072 : Expr *expr;
4073 :
4074 290 : tle = get_sortgroupref_tle(ref, tlist);
4075 290 : expr = tle->expr;
4076 :
4077 290 : if (force_colno)
4078 : {
4079 : /* Use column-number form when requested by caller. */
4080 : Assert(!tle->resjunk);
4081 226 : appendStringInfo(buf, "%d", tle->resno);
4082 : }
4083 64 : else if (expr && IsA(expr, Const))
4084 : {
4085 : /*
4086 : * Force a typecast here so that we don't emit something like "GROUP
4087 : * BY 2", which will be misconstrued as a column position rather than
4088 : * a constant.
4089 : */
4090 0 : deparseConst((Const *) expr, context, 1);
4091 : }
4092 64 : else if (!expr || IsA(expr, Var))
4093 36 : deparseExpr(expr, context);
4094 : else
4095 : {
4096 : /* Always parenthesize the expression. */
4097 28 : appendStringInfoChar(buf, '(');
4098 28 : deparseExpr(expr, context);
4099 28 : appendStringInfoChar(buf, ')');
4100 : }
4101 :
4102 290 : return (Node *) expr;
4103 : }
4104 :
4105 :
4106 : /*
4107 : * Returns true if given Var is deparsed as a subquery output column, in
4108 : * which case, *relno and *colno are set to the IDs for the relation and
4109 : * column alias to the Var provided by the subquery.
4110 : */
4111 : static bool
4112 16366 : is_subquery_var(Var *node, RelOptInfo *foreignrel, int *relno, int *colno)
4113 : {
4114 16366 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
4115 16366 : RelOptInfo *outerrel = fpinfo->outerrel;
4116 16366 : RelOptInfo *innerrel = fpinfo->innerrel;
4117 :
4118 : /* Should only be called in these cases. */
4119 : Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
4120 :
4121 : /*
4122 : * If the given relation isn't a join relation, it doesn't have any lower
4123 : * subqueries, so the Var isn't a subquery output column.
4124 : */
4125 16366 : if (!IS_JOIN_REL(foreignrel))
4126 3962 : return false;
4127 :
4128 : /*
4129 : * If the Var doesn't belong to any lower subqueries, it isn't a subquery
4130 : * output column.
4131 : */
4132 12404 : if (!bms_is_member(node->varno, fpinfo->lower_subquery_rels))
4133 12172 : return false;
4134 :
4135 232 : if (bms_is_member(node->varno, outerrel->relids))
4136 : {
4137 : /*
4138 : * If outer relation is deparsed as a subquery, the Var is an output
4139 : * column of the subquery; get the IDs for the relation/column alias.
4140 : */
4141 84 : if (fpinfo->make_outerrel_subquery)
4142 : {
4143 84 : get_relation_column_alias_ids(node, outerrel, relno, colno);
4144 84 : return true;
4145 : }
4146 :
4147 : /* Otherwise, recurse into the outer relation. */
4148 0 : return is_subquery_var(node, outerrel, relno, colno);
4149 : }
4150 : else
4151 : {
4152 : Assert(bms_is_member(node->varno, innerrel->relids));
4153 :
4154 : /*
4155 : * If inner relation is deparsed as a subquery, the Var is an output
4156 : * column of the subquery; get the IDs for the relation/column alias.
4157 : */
4158 148 : if (fpinfo->make_innerrel_subquery)
4159 : {
4160 148 : get_relation_column_alias_ids(node, innerrel, relno, colno);
4161 148 : return true;
4162 : }
4163 :
4164 : /* Otherwise, recurse into the inner relation. */
4165 0 : return is_subquery_var(node, innerrel, relno, colno);
4166 : }
4167 : }
4168 :
4169 : /*
4170 : * Get the IDs for the relation and column alias to given Var belonging to
4171 : * given relation, which are returned into *relno and *colno.
4172 : */
4173 : static void
4174 232 : get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
4175 : int *relno, int *colno)
4176 : {
4177 232 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
4178 : int i;
4179 : ListCell *lc;
4180 :
4181 : /* Get the relation alias ID */
4182 232 : *relno = fpinfo->relation_index;
4183 :
4184 : /* Get the column alias ID */
4185 232 : i = 1;
4186 304 : foreach(lc, foreignrel->reltarget->exprs)
4187 : {
4188 304 : Var *tlvar = (Var *) lfirst(lc);
4189 :
4190 : /*
4191 : * Match reltarget entries only on varno/varattno. Ideally there
4192 : * would be some cross-check on varnullingrels, but it's unclear what
4193 : * to do exactly; we don't have enough context to know what that value
4194 : * should be.
4195 : */
4196 304 : if (IsA(tlvar, Var) &&
4197 304 : tlvar->varno == node->varno &&
4198 288 : tlvar->varattno == node->varattno)
4199 : {
4200 232 : *colno = i;
4201 232 : return;
4202 : }
4203 72 : i++;
4204 : }
4205 :
4206 : /* Shouldn't get here */
4207 0 : elog(ERROR, "unexpected expression in subquery output");
4208 : }
|