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