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