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