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