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