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