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