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