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