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