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