Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * parse_clause.c
4 : : * handle clauses in parser
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/parser/parse_clause.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include "access/htup_details.h"
19 : : #include "access/nbtree.h"
20 : : #include "access/table.h"
21 : : #include "access/tsmapi.h"
22 : : #include "catalog/catalog.h"
23 : : #include "catalog/pg_am.h"
24 : : #include "catalog/pg_amproc.h"
25 : : #include "catalog/pg_constraint.h"
26 : : #include "catalog/pg_type.h"
27 : : #include "commands/defrem.h"
28 : : #include "miscadmin.h"
29 : : #include "nodes/makefuncs.h"
30 : : #include "nodes/nodeFuncs.h"
31 : : #include "optimizer/optimizer.h"
32 : : #include "parser/analyze.h"
33 : : #include "parser/parse_clause.h"
34 : : #include "parser/parse_coerce.h"
35 : : #include "parser/parse_collate.h"
36 : : #include "parser/parse_expr.h"
37 : : #include "parser/parse_func.h"
38 : : #include "parser/parse_oper.h"
39 : : #include "parser/parse_relation.h"
40 : : #include "parser/parse_target.h"
41 : : #include "parser/parse_type.h"
42 : : #include "parser/parser.h"
43 : : #include "rewrite/rewriteManip.h"
44 : : #include "utils/builtins.h"
45 : : #include "utils/catcache.h"
46 : : #include "utils/lsyscache.h"
47 : : #include "utils/rel.h"
48 : : #include "utils/syscache.h"
49 : :
50 : :
51 : : static int extractRemainingColumns(ParseState *pstate,
52 : : ParseNamespaceColumn *src_nscolumns,
53 : : List *src_colnames,
54 : : List **src_colnos,
55 : : List **res_colnames, List **res_colvars,
56 : : ParseNamespaceColumn *res_nscolumns);
57 : : static Node *transformJoinUsingClause(ParseState *pstate,
58 : : List *leftVars, List *rightVars);
59 : : static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
60 : : List *namespace);
61 : : static ParseNamespaceItem *transformTableEntry(ParseState *pstate, RangeVar *r);
62 : : static ParseNamespaceItem *transformRangeSubselect(ParseState *pstate,
63 : : RangeSubselect *r);
64 : : static ParseNamespaceItem *transformRangeFunction(ParseState *pstate,
65 : : RangeFunction *r);
66 : : static ParseNamespaceItem *transformRangeTableFunc(ParseState *pstate,
67 : : RangeTableFunc *rtf);
68 : : static TableSampleClause *transformRangeTableSample(ParseState *pstate,
69 : : RangeTableSample *rts);
70 : : static ParseNamespaceItem *getNSItemForSpecialRelationTypes(ParseState *pstate,
71 : : RangeVar *rv);
72 : : static Node *transformFromClauseItem(ParseState *pstate, Node *n,
73 : : ParseNamespaceItem **top_nsitem,
74 : : List **namespace);
75 : : static Var *buildVarFromNSColumn(ParseState *pstate,
76 : : ParseNamespaceColumn *nscol);
77 : : static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype,
78 : : Var *l_colvar, Var *r_colvar);
79 : : static void markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex);
80 : : static void setNamespaceColumnVisibility(List *namespace, bool cols_visible);
81 : : static void setNamespaceLateralState(List *namespace,
82 : : bool lateral_only, bool lateral_ok);
83 : : static void checkExprIsVarFree(ParseState *pstate, Node *n,
84 : : const char *constructName);
85 : : static TargetEntry *findTargetlistEntrySQL92(ParseState *pstate, Node *node,
86 : : List **tlist, ParseExprKind exprKind);
87 : : static TargetEntry *findTargetlistEntrySQL99(ParseState *pstate, Node *node,
88 : : List **tlist, ParseExprKind exprKind);
89 : : static int get_matching_location(int sortgroupref,
90 : : List *sortgrouprefs, List *exprs);
91 : : static List *resolve_unique_index_expr(ParseState *pstate, InferClause *infer,
92 : : Relation heapRel);
93 : : static List *addTargetToGroupList(ParseState *pstate, TargetEntry *tle,
94 : : List *grouplist, List *targetlist, int location);
95 : : static WindowClause *findWindowClause(List *wclist, const char *name);
96 : : static Node *transformFrameOffset(ParseState *pstate, int frameOptions,
97 : : Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc,
98 : : Node *clause);
99 : :
100 : :
101 : : /*
102 : : * transformFromClause -
103 : : * Process the FROM clause and add items to the query's range table,
104 : : * joinlist, and namespace.
105 : : *
106 : : * Note: we assume that the pstate's p_rtable, p_joinlist, and p_namespace
107 : : * lists were initialized to NIL when the pstate was created.
108 : : * We will add onto any entries already present --- this is needed for rule
109 : : * processing, as well as for UPDATE and DELETE.
110 : : */
111 : : void
112 : 318436 : transformFromClause(ParseState *pstate, List *frmList)
113 : : {
114 : : ListCell *fl;
115 : :
116 : : /*
117 : : * The grammar will have produced a list of RangeVars, RangeSubselects,
118 : : * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
119 : : * entries to the rtable), check for duplicate refnames, and then add it
120 : : * to the joinlist and namespace.
121 : : *
122 : : * Note we must process the items left-to-right for proper handling of
123 : : * LATERAL references.
124 : : */
125 [ + + + + : 564880 : foreach(fl, frmList)
+ + ]
126 : : {
127 : 246933 : Node *n = lfirst(fl);
128 : : ParseNamespaceItem *nsitem;
129 : : List *namespace;
130 : :
131 : 246933 : n = transformFromClauseItem(pstate, n,
132 : : &nsitem,
133 : : &namespace);
134 : :
135 : 246448 : checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
136 : :
137 : : /* Mark the new namespace items as visible only to LATERAL */
138 : 246444 : setNamespaceLateralState(namespace, true, true);
139 : :
140 : 246444 : pstate->p_joinlist = lappend(pstate->p_joinlist, n);
141 : 246444 : pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
142 : : }
143 : :
144 : : /*
145 : : * We're done parsing the FROM list, so make all namespace items
146 : : * unconditionally visible. Note that this will also reset lateral_only
147 : : * for any namespace items that were already present when we were called;
148 : : * but those should have been that way already.
149 : : */
150 : 317947 : setNamespaceLateralState(pstate->p_namespace, false, true);
151 : 317947 : }
152 : :
153 : : /*
154 : : * setTargetTable
155 : : * Add the target relation of INSERT/UPDATE/DELETE/MERGE to the range table,
156 : : * and make the special links to it in the ParseState.
157 : : *
158 : : * We also open the target relation and acquire a write lock on it.
159 : : * This must be done before processing the FROM list, in case the target
160 : : * is also mentioned as a source relation --- we want to be sure to grab
161 : : * the write lock before any read lock.
162 : : *
163 : : * If alsoSource is true, add the target to the query's joinlist and
164 : : * namespace. For INSERT, we don't want the target to be joined to;
165 : : * it's a destination of tuples, not a source. MERGE is actually
166 : : * both, but we'll add it separately to joinlist and namespace, so
167 : : * doing nothing (like INSERT) is correct here. For UPDATE/DELETE,
168 : : * we do need to scan or join the target. (NOTE: we do not bother
169 : : * to check for namespace conflict; we assume that the namespace was
170 : : * initially empty in these cases.)
171 : : *
172 : : * Finally, we mark the relation as requiring the permissions specified
173 : : * by requiredPerms.
174 : : *
175 : : * Returns the rangetable index of the target relation.
176 : : */
177 : : int
178 : 59400 : setTargetTable(ParseState *pstate, RangeVar *relation,
179 : : bool inh, bool alsoSource, AclMode requiredPerms)
180 : : {
181 : : ParseNamespaceItem *nsitem;
182 : :
183 : : /*
184 : : * ENRs hide tables of the same name, so we need to check for them first.
185 : : * In contrast, CTEs don't hide tables (for this purpose).
186 : : */
187 [ + + + + ]: 112852 : if (relation->schemaname == NULL &&
188 : 53452 : scanNameSpaceForENR(pstate, relation->relname))
189 [ + - ]: 4 : ereport(ERROR,
190 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
191 : : errmsg("relation \"%s\" cannot be the target of a modifying statement",
192 : : relation->relname)));
193 : :
194 : : /* Close old target; this could only happen for multi-action rules */
195 [ - + ]: 59396 : if (pstate->p_target_relation != NULL)
196 : 0 : table_close(pstate->p_target_relation, NoLock);
197 : :
198 : : /*
199 : : * Open target rel and grab suitable lock (which we will hold till end of
200 : : * transaction).
201 : : *
202 : : * free_parsestate() will eventually do the corresponding table_close(),
203 : : * but *not* release the lock.
204 : : */
205 : 59396 : pstate->p_target_relation = parserOpenTable(pstate, relation,
206 : : RowExclusiveLock);
207 : :
208 : : /*
209 : : * Now build an RTE and a ParseNamespaceItem.
210 : : */
211 : 59383 : nsitem = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
212 : : RowExclusiveLock,
213 : : relation->alias, inh, false);
214 : :
215 : : /* remember the RTE/nsitem as being the query target */
216 : 59383 : pstate->p_target_nsitem = nsitem;
217 : :
218 : : /*
219 : : * Override addRangeTableEntry's default ACL_SELECT permissions check, and
220 : : * instead mark target table as requiring exactly the specified
221 : : * permissions.
222 : : *
223 : : * If we find an explicit reference to the rel later during parse
224 : : * analysis, we will add the ACL_SELECT bit back again; see
225 : : * markVarForSelectPriv and its callers.
226 : : */
227 : 59383 : nsitem->p_perminfo->requiredPerms = requiredPerms;
228 : :
229 : : /*
230 : : * If UPDATE/DELETE, add table to joinlist and namespace.
231 : : */
232 [ + + ]: 59383 : if (alsoSource)
233 : 12857 : addNSItemToQuery(pstate, nsitem, true, true, true);
234 : :
235 : 59383 : return nsitem->p_rtindex;
236 : : }
237 : :
238 : : /*
239 : : * Extract all not-in-common columns from column lists of a source table
240 : : *
241 : : * src_nscolumns and src_colnames describe the source table.
242 : : *
243 : : * *src_colnos initially contains the column numbers of the already-merged
244 : : * columns. We add to it the column number of each additional column.
245 : : * Also append to *res_colnames the name of each additional column,
246 : : * append to *res_colvars a Var for each additional column, and copy the
247 : : * columns' nscolumns data into res_nscolumns[] (which is caller-allocated
248 : : * space that had better be big enough).
249 : : *
250 : : * Returns the number of columns added.
251 : : */
252 : : static int
253 : 108470 : extractRemainingColumns(ParseState *pstate,
254 : : ParseNamespaceColumn *src_nscolumns,
255 : : List *src_colnames,
256 : : List **src_colnos,
257 : : List **res_colnames, List **res_colvars,
258 : : ParseNamespaceColumn *res_nscolumns)
259 : : {
260 : 108470 : int colcount = 0;
261 : : Bitmapset *prevcols;
262 : : int attnum;
263 : : ListCell *lc;
264 : :
265 : : /*
266 : : * While we could just test "list_member_int(*src_colnos, attnum)" to
267 : : * detect already-merged columns in the loop below, that would be O(N^2)
268 : : * for a wide input table. Instead build a bitmapset of just the merged
269 : : * USING columns, which we won't add to within the main loop.
270 : : */
271 : 108470 : prevcols = NULL;
272 [ + + + + : 110870 : foreach(lc, *src_colnos)
+ + ]
273 : : {
274 : 2400 : prevcols = bms_add_member(prevcols, lfirst_int(lc));
275 : : }
276 : :
277 : 108470 : attnum = 0;
278 [ + + + + : 2145771 : foreach(lc, src_colnames)
+ + ]
279 : : {
280 : 2037301 : char *colname = strVal(lfirst(lc));
281 : :
282 : 2037301 : attnum++;
283 : : /* Non-dropped and not already merged? */
284 [ + + + + ]: 2037301 : if (colname[0] != '\0' && !bms_is_member(attnum, prevcols))
285 : : {
286 : : /* Yes, so emit it as next output column */
287 : 2034582 : *src_colnos = lappend_int(*src_colnos, attnum);
288 : 2034582 : *res_colnames = lappend(*res_colnames, lfirst(lc));
289 : 2034582 : *res_colvars = lappend(*res_colvars,
290 : 2034582 : buildVarFromNSColumn(pstate,
291 : 2034582 : src_nscolumns + attnum - 1));
292 : : /* Copy the input relation's nscolumn data for this column */
293 : 2034582 : res_nscolumns[colcount] = src_nscolumns[attnum - 1];
294 : 2034582 : colcount++;
295 : : }
296 : : }
297 : 108470 : return colcount;
298 : : }
299 : :
300 : : /*
301 : : * transformJoinUsingClause()
302 : : * Build a complete ON clause from a partially-transformed USING list.
303 : : * We are given lists of nodes representing left and right match columns.
304 : : * Result is a transformed qualification expression.
305 : : */
306 : : static Node *
307 : 1045 : transformJoinUsingClause(ParseState *pstate,
308 : : List *leftVars, List *rightVars)
309 : : {
310 : : Node *result;
311 : 1045 : List *andargs = NIL;
312 : : ListCell *lvars,
313 : : *rvars;
314 : :
315 : : /*
316 : : * We cheat a little bit here by building an untransformed operator tree
317 : : * whose leaves are the already-transformed Vars. This requires collusion
318 : : * from transformExpr(), which normally could be expected to complain
319 : : * about already-transformed subnodes. However, this does mean that we
320 : : * have to mark the columns as requiring SELECT privilege for ourselves;
321 : : * transformExpr() won't do it.
322 : : */
323 [ + - + + : 2245 : forboth(lvars, leftVars, rvars, rightVars)
+ - + + +
+ + - +
+ ]
324 : : {
325 : 1200 : Var *lvar = (Var *) lfirst(lvars);
326 : 1200 : Var *rvar = (Var *) lfirst(rvars);
327 : : A_Expr *e;
328 : :
329 : : /* Require read access to the join variables */
330 : 1200 : markVarForSelectPriv(pstate, lvar);
331 : 1200 : markVarForSelectPriv(pstate, rvar);
332 : :
333 : : /* Now create the lvar = rvar join condition */
334 : 1200 : e = makeSimpleA_Expr(AEXPR_OP, "=",
335 : 1200 : (Node *) copyObject(lvar), (Node *) copyObject(rvar),
336 : : -1);
337 : :
338 : : /* Prepare to combine into an AND clause, if multiple join columns */
339 : 1200 : andargs = lappend(andargs, e);
340 : : }
341 : :
342 : : /* Only need an AND if there's more than one join column */
343 [ + + ]: 1045 : if (list_length(andargs) == 1)
344 : 913 : result = (Node *) linitial(andargs);
345 : : else
346 : 132 : result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
347 : :
348 : : /*
349 : : * Since the references are already Vars, and are certainly from the input
350 : : * relations, we don't have to go through the same pushups that
351 : : * transformJoinOnClause() does. Just invoke transformExpr() to fix up
352 : : * the operators, and we're done.
353 : : */
354 : 1045 : result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
355 : :
356 : 1045 : result = coerce_to_boolean(pstate, result, "JOIN/USING");
357 : :
358 : 1045 : return result;
359 : : }
360 : :
361 : : /*
362 : : * transformJoinOnClause()
363 : : * Transform the qual conditions for JOIN/ON.
364 : : * Result is a transformed qualification expression.
365 : : */
366 : : static Node *
367 : 52843 : transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
368 : : {
369 : : Node *result;
370 : : List *save_namespace;
371 : :
372 : : /*
373 : : * The namespace that the join expression should see is just the two
374 : : * subtrees of the JOIN plus any outer references from upper pstate
375 : : * levels. Temporarily set this pstate's namespace accordingly. (We need
376 : : * not check for refname conflicts, because transformFromClauseItem()
377 : : * already did.) All namespace items are marked visible regardless of
378 : : * LATERAL state.
379 : : */
380 : 52843 : setNamespaceLateralState(namespace, false, true);
381 : :
382 : 52843 : save_namespace = pstate->p_namespace;
383 : 52843 : pstate->p_namespace = namespace;
384 : :
385 : 52843 : result = transformWhereClause(pstate, j->quals,
386 : : EXPR_KIND_JOIN_ON, "JOIN/ON");
387 : :
388 : 52831 : pstate->p_namespace = save_namespace;
389 : :
390 : 52831 : return result;
391 : : }
392 : :
393 : : /*
394 : : * transformTableEntry --- transform a RangeVar (simple relation reference)
395 : : */
396 : : static ParseNamespaceItem *
397 : 252340 : transformTableEntry(ParseState *pstate, RangeVar *r)
398 : : {
399 : : /* addRangeTableEntry does all the work */
400 : 252340 : return addRangeTableEntry(pstate, r, r->alias, r->inh, true);
401 : : }
402 : :
403 : : /*
404 : : * transformRangeSubselect --- transform a sub-SELECT appearing in FROM
405 : : */
406 : : static ParseNamespaceItem *
407 : 13812 : transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
408 : : {
409 : : Query *query;
410 : :
411 : : /*
412 : : * Set p_expr_kind to show this parse level is recursing to a subselect.
413 : : * We can't be nested within any expression, so don't need save-restore
414 : : * logic here.
415 : : */
416 : : Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
417 : 13812 : pstate->p_expr_kind = EXPR_KIND_FROM_SUBSELECT;
418 : :
419 : : /*
420 : : * If the subselect is LATERAL, make lateral_only names of this level
421 : : * visible to it. (LATERAL can't nest within a single pstate level, so we
422 : : * don't need save/restore logic here.)
423 : : */
424 : : Assert(!pstate->p_lateral_active);
425 : 13812 : pstate->p_lateral_active = r->lateral;
426 : :
427 : : /*
428 : : * Analyze and transform the subquery. Note that if the subquery doesn't
429 : : * have an alias, it can't be explicitly selected for locking, but locking
430 : : * might still be required (if there is an all-tables locking clause).
431 : : */
432 : 13812 : query = parse_sub_analyze(r->subquery, pstate, NULL,
433 : 13812 : isLockedRefname(pstate,
434 [ + + ]: 13812 : r->alias == NULL ? NULL :
435 : 13638 : r->alias->aliasname),
436 : : true);
437 : :
438 : : /* Restore state */
439 : 13740 : pstate->p_lateral_active = false;
440 : 13740 : pstate->p_expr_kind = EXPR_KIND_NONE;
441 : :
442 : : /*
443 : : * Check that we got a SELECT. Anything else should be impossible given
444 : : * restrictions of the grammar, but check anyway.
445 : : */
446 [ + - ]: 13740 : if (!IsA(query, Query) ||
447 [ - + ]: 13740 : query->commandType != CMD_SELECT)
448 [ # # ]: 0 : elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
449 : :
450 : : /*
451 : : * OK, build an RTE and nsitem for the subquery.
452 : : */
453 : 27476 : return addRangeTableEntryForSubquery(pstate,
454 : : query,
455 : : r->alias,
456 : 13740 : r->lateral,
457 : : true);
458 : : }
459 : :
460 : :
461 : : /*
462 : : * transformRangeFunction --- transform a function call appearing in FROM
463 : : */
464 : : static ParseNamespaceItem *
465 : 29613 : transformRangeFunction(ParseState *pstate, RangeFunction *r)
466 : : {
467 : 29613 : List *funcexprs = NIL;
468 : 29613 : List *funcnames = NIL;
469 : 29613 : List *coldeflists = NIL;
470 : : bool is_lateral;
471 : : ListCell *lc;
472 : :
473 : : /*
474 : : * We make lateral_only names of this level visible, whether or not the
475 : : * RangeFunction is explicitly marked LATERAL. This is needed for SQL
476 : : * spec compliance in the case of UNNEST(), and seems useful on
477 : : * convenience grounds for all functions in FROM.
478 : : *
479 : : * (LATERAL can't nest within a single pstate level, so we don't need
480 : : * save/restore logic here.)
481 : : */
482 : : Assert(!pstate->p_lateral_active);
483 : 29613 : pstate->p_lateral_active = true;
484 : :
485 : : /*
486 : : * Transform the raw expressions.
487 : : *
488 : : * While transforming, also save function names for possible use as alias
489 : : * and column names. We use the same transformation rules as for a SELECT
490 : : * output expression. For a FuncCall node, the result will be the
491 : : * function name, but it is possible for the grammar to hand back other
492 : : * node types.
493 : : *
494 : : * We have to get this info now, because FigureColname only works on raw
495 : : * parsetrees. Actually deciding what to do with the names is left up to
496 : : * addRangeTableEntryForFunction.
497 : : *
498 : : * Likewise, collect column definition lists if there were any. But
499 : : * complain if we find one here and the RangeFunction has one too.
500 : : */
501 [ + - + + : 59245 : foreach(lc, r->functions)
+ + ]
502 : : {
503 : 29747 : List *pair = (List *) lfirst(lc);
504 : : Node *fexpr;
505 : : List *coldeflist;
506 : : Node *newfexpr;
507 : : Node *last_srf;
508 : :
509 : : /* Disassemble the function-call/column-def-list pairs */
510 : : Assert(list_length(pair) == 2);
511 : 29747 : fexpr = (Node *) linitial(pair);
512 : 29747 : coldeflist = (List *) lsecond(pair);
513 : :
514 : : /*
515 : : * If we find a function call unnest() with more than one argument and
516 : : * no special decoration, transform it into separate unnest() calls on
517 : : * each argument. This is a kluge, for sure, but it's less nasty than
518 : : * other ways of implementing the SQL-standard UNNEST() syntax.
519 : : *
520 : : * If there is any decoration (including a coldeflist), we don't
521 : : * transform, which probably means a no-such-function error later. We
522 : : * could alternatively throw an error right now, but that doesn't seem
523 : : * tremendously helpful. If someone is using any such decoration,
524 : : * then they're not using the SQL-standard syntax, and they're more
525 : : * likely expecting an un-tweaked function call.
526 : : *
527 : : * Note: the transformation changes a non-schema-qualified unnest()
528 : : * function name into schema-qualified pg_catalog.unnest(). This
529 : : * choice is also a bit debatable, but it seems reasonable to force
530 : : * use of built-in unnest() when we make this transformation.
531 : : */
532 [ + + ]: 29747 : if (IsA(fexpr, FuncCall))
533 : : {
534 : 29651 : FuncCall *fc = (FuncCall *) fexpr;
535 : :
536 [ + + ]: 29651 : if (list_length(fc->funcname) == 1 &&
537 [ + + + + ]: 21166 : strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
538 : 1757 : list_length(fc->args) > 1 &&
539 [ + - ]: 48 : fc->agg_order == NIL &&
540 [ + - ]: 48 : fc->agg_filter == NULL &&
541 [ + - ]: 48 : fc->over == NULL &&
542 [ + - ]: 48 : !fc->agg_star &&
543 [ + - ]: 48 : !fc->agg_distinct &&
544 [ + - + - ]: 48 : !fc->func_variadic &&
545 : : coldeflist == NIL)
546 : 48 : {
547 : : ListCell *lc2;
548 : :
549 [ + - + + : 170 : foreach(lc2, fc->args)
+ + ]
550 : : {
551 : 122 : Node *arg = (Node *) lfirst(lc2);
552 : : FuncCall *newfc;
553 : :
554 : 122 : last_srf = pstate->p_last_srf;
555 : :
556 : 122 : newfc = makeFuncCall(SystemFuncName("unnest"),
557 : : list_make1(arg),
558 : : COERCE_EXPLICIT_CALL,
559 : : fc->location);
560 : :
561 : 122 : newfexpr = transformExpr(pstate, (Node *) newfc,
562 : : EXPR_KIND_FROM_FUNCTION);
563 : :
564 : : /* nodeFunctionscan.c requires SRFs to be at top level */
565 [ + - ]: 122 : if (pstate->p_last_srf != last_srf &&
566 [ - + ]: 122 : pstate->p_last_srf != newfexpr)
567 [ # # ]: 0 : ereport(ERROR,
568 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
569 : : errmsg("set-returning functions must appear at top level of FROM"),
570 : : parser_errposition(pstate,
571 : : exprLocation(pstate->p_last_srf))));
572 : :
573 : 122 : funcexprs = lappend(funcexprs, newfexpr);
574 : :
575 : 122 : funcnames = lappend(funcnames,
576 : 122 : FigureColname((Node *) newfc));
577 : :
578 : : /* coldeflist is empty, so no error is possible */
579 : :
580 : 122 : coldeflists = lappend(coldeflists, coldeflist);
581 : : }
582 : 48 : continue; /* done with this function item */
583 : : }
584 : : }
585 : :
586 : : /* normal case ... */
587 : 29699 : last_srf = pstate->p_last_srf;
588 : :
589 : 29699 : newfexpr = transformExpr(pstate, fexpr,
590 : : EXPR_KIND_FROM_FUNCTION);
591 : :
592 : : /* nodeFunctionscan.c requires SRFs to be at top level */
593 [ + + ]: 29588 : if (pstate->p_last_srf != last_srf &&
594 [ + + ]: 23815 : pstate->p_last_srf != newfexpr)
595 [ + - ]: 4 : ereport(ERROR,
596 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
597 : : errmsg("set-returning functions must appear at top level of FROM"),
598 : : parser_errposition(pstate,
599 : : exprLocation(pstate->p_last_srf))));
600 : :
601 : 29584 : funcexprs = lappend(funcexprs, newfexpr);
602 : :
603 : 29584 : funcnames = lappend(funcnames,
604 : 29584 : FigureColname(fexpr));
605 : :
606 [ + + - + ]: 29584 : if (coldeflist && r->coldeflist)
607 [ # # ]: 0 : ereport(ERROR,
608 : : (errcode(ERRCODE_SYNTAX_ERROR),
609 : : errmsg("multiple column definition lists are not allowed for the same function"),
610 : : parser_errposition(pstate,
611 : : exprLocation((Node *) r->coldeflist))));
612 : :
613 : 29584 : coldeflists = lappend(coldeflists, coldeflist);
614 : : }
615 : :
616 : 29498 : pstate->p_lateral_active = false;
617 : :
618 : : /*
619 : : * We must assign collations now so that the RTE exposes correct collation
620 : : * info for Vars created from it.
621 : : */
622 : 29498 : assign_list_collations(pstate, funcexprs);
623 : :
624 : : /*
625 : : * Install the top-level coldeflist if there was one (we already checked
626 : : * that there was no conflicting per-function coldeflist).
627 : : *
628 : : * We only allow this when there's a single function (even after UNNEST
629 : : * expansion) and no WITH ORDINALITY. The reason for the latter
630 : : * restriction is that it's not real clear whether the ordinality column
631 : : * should be in the coldeflist, and users are too likely to make mistakes
632 : : * in one direction or the other. Putting the coldeflist inside ROWS
633 : : * FROM() is much clearer in this case.
634 : : */
635 [ + + ]: 29498 : if (r->coldeflist)
636 : : {
637 [ - + ]: 464 : if (list_length(funcexprs) != 1)
638 : : {
639 [ # # ]: 0 : if (r->is_rowsfrom)
640 [ # # ]: 0 : ereport(ERROR,
641 : : (errcode(ERRCODE_SYNTAX_ERROR),
642 : : errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
643 : : errhint("Put a separate column definition list for each function inside ROWS FROM()."),
644 : : parser_errposition(pstate,
645 : : exprLocation((Node *) r->coldeflist))));
646 : : else
647 [ # # ]: 0 : ereport(ERROR,
648 : : (errcode(ERRCODE_SYNTAX_ERROR),
649 : : errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
650 : : errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
651 : : parser_errposition(pstate,
652 : : exprLocation((Node *) r->coldeflist))));
653 : : }
654 [ - + ]: 464 : if (r->ordinality)
655 [ # # ]: 0 : ereport(ERROR,
656 : : (errcode(ERRCODE_SYNTAX_ERROR),
657 : : errmsg("WITH ORDINALITY cannot be used with a column definition list"),
658 : : errhint("Put the column definition list inside ROWS FROM()."),
659 : : parser_errposition(pstate,
660 : : exprLocation((Node *) r->coldeflist))));
661 : :
662 : 464 : coldeflists = list_make1(r->coldeflist);
663 : : }
664 : :
665 : : /*
666 : : * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
667 : : * there are any lateral cross-references in it.
668 : : */
669 [ + + + + ]: 29498 : is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
670 : :
671 : : /*
672 : : * OK, build an RTE and nsitem for the function.
673 : : */
674 : 29498 : return addRangeTableEntryForFunction(pstate,
675 : : funcnames, funcexprs, coldeflists,
676 : : r, is_lateral, true);
677 : : }
678 : :
679 : : /*
680 : : * transformRangeTableFunc -
681 : : * Transform a raw RangeTableFunc into TableFunc.
682 : : *
683 : : * Transform the namespace clauses, the document-generating expression, the
684 : : * row-generating expression, the column-generating expressions, and the
685 : : * default value expressions.
686 : : */
687 : : static ParseNamespaceItem *
688 : 146 : transformRangeTableFunc(ParseState *pstate, RangeTableFunc *rtf)
689 : : {
690 : 146 : TableFunc *tf = makeNode(TableFunc);
691 : : const char *constructName;
692 : : Oid docType;
693 : : bool is_lateral;
694 : : ListCell *col;
695 : : char **names;
696 : : int colno;
697 : :
698 : : /*
699 : : * Currently we only support XMLTABLE here. See transformJsonTable() for
700 : : * JSON_TABLE support.
701 : : */
702 : 146 : tf->functype = TFT_XMLTABLE;
703 : 146 : constructName = "XMLTABLE";
704 : 146 : docType = XMLOID;
705 : :
706 : : /*
707 : : * We make lateral_only names of this level visible, whether or not the
708 : : * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
709 : : * spec compliance and seems useful on convenience grounds for all
710 : : * functions in FROM.
711 : : *
712 : : * (LATERAL can't nest within a single pstate level, so we don't need
713 : : * save/restore logic here.)
714 : : */
715 : : Assert(!pstate->p_lateral_active);
716 : 146 : pstate->p_lateral_active = true;
717 : :
718 : : /* Transform and apply typecast to the row-generating expression ... */
719 : : Assert(rtf->rowexpr != NULL);
720 : 146 : tf->rowexpr = coerce_to_specific_type(pstate,
721 : : transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION),
722 : : TEXTOID,
723 : : constructName);
724 : 146 : assign_expr_collations(pstate, tf->rowexpr);
725 : :
726 : : /* ... and to the document itself */
727 : : Assert(rtf->docexpr != NULL);
728 : 146 : tf->docexpr = coerce_to_specific_type(pstate,
729 : : transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION),
730 : : docType,
731 : : constructName);
732 : 146 : assign_expr_collations(pstate, tf->docexpr);
733 : :
734 : : /* undef ordinality column number */
735 : 146 : tf->ordinalitycol = -1;
736 : :
737 : : /* Process column specs */
738 : 146 : names = palloc_array(char *, list_length(rtf->columns));
739 : :
740 : 146 : colno = 0;
741 [ + - + + : 643 : foreach(col, rtf->columns)
+ + ]
742 : : {
743 : 497 : RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
744 : : Oid typid;
745 : : int32 typmod;
746 : : Node *colexpr;
747 : : Node *coldefexpr;
748 : : int j;
749 : :
750 : 497 : tf->colnames = lappend(tf->colnames,
751 : 497 : makeString(pstrdup(rawc->colname)));
752 : :
753 : : /*
754 : : * Determine the type and typmod for the new column. FOR ORDINALITY
755 : : * columns are INTEGER per spec; the others are user-specified.
756 : : */
757 [ + + ]: 497 : if (rawc->for_ordinality)
758 : : {
759 [ - + ]: 41 : if (tf->ordinalitycol != -1)
760 [ # # ]: 0 : ereport(ERROR,
761 : : (errcode(ERRCODE_SYNTAX_ERROR),
762 : : errmsg("only one FOR ORDINALITY column is allowed"),
763 : : parser_errposition(pstate, rawc->location)));
764 : :
765 : 41 : typid = INT4OID;
766 : 41 : typmod = -1;
767 : 41 : tf->ordinalitycol = colno;
768 : : }
769 : : else
770 : : {
771 [ - + ]: 456 : if (rawc->typeName->setof)
772 [ # # ]: 0 : ereport(ERROR,
773 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
774 : : errmsg("column \"%s\" cannot be declared SETOF",
775 : : rawc->colname),
776 : : parser_errposition(pstate, rawc->location)));
777 : :
778 : 456 : typenameTypeIdAndMod(pstate, rawc->typeName,
779 : : &typid, &typmod);
780 : : }
781 : :
782 : 497 : tf->coltypes = lappend_oid(tf->coltypes, typid);
783 : 497 : tf->coltypmods = lappend_int(tf->coltypmods, typmod);
784 : 497 : tf->colcollations = lappend_oid(tf->colcollations,
785 : : get_typcollation(typid));
786 : :
787 : : /* Transform the PATH and DEFAULT expressions */
788 [ + + ]: 497 : if (rawc->colexpr)
789 : : {
790 : 324 : colexpr = coerce_to_specific_type(pstate,
791 : : transformExpr(pstate, rawc->colexpr,
792 : : EXPR_KIND_FROM_FUNCTION),
793 : : TEXTOID,
794 : : constructName);
795 : 324 : assign_expr_collations(pstate, colexpr);
796 : : }
797 : : else
798 : 173 : colexpr = NULL;
799 : :
800 [ + + ]: 497 : if (rawc->coldefexpr)
801 : : {
802 : 37 : coldefexpr = coerce_to_specific_type_typmod(pstate,
803 : : transformExpr(pstate, rawc->coldefexpr,
804 : : EXPR_KIND_FROM_FUNCTION),
805 : : typid, typmod,
806 : : constructName);
807 : 37 : assign_expr_collations(pstate, coldefexpr);
808 : : }
809 : : else
810 : 460 : coldefexpr = NULL;
811 : :
812 : 497 : tf->colexprs = lappend(tf->colexprs, colexpr);
813 : 497 : tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
814 : :
815 [ + + ]: 497 : if (rawc->is_not_null)
816 : 37 : tf->notnulls = bms_add_member(tf->notnulls, colno);
817 : :
818 : : /* make sure column names are unique */
819 [ + + ]: 1677 : for (j = 0; j < colno; j++)
820 [ - + ]: 1180 : if (strcmp(names[j], rawc->colname) == 0)
821 [ # # ]: 0 : ereport(ERROR,
822 : : (errcode(ERRCODE_SYNTAX_ERROR),
823 : : errmsg("column name \"%s\" is not unique",
824 : : rawc->colname),
825 : : parser_errposition(pstate, rawc->location)));
826 : 497 : names[colno] = rawc->colname;
827 : :
828 : 497 : colno++;
829 : : }
830 : 146 : pfree(names);
831 : :
832 : : /* Namespaces, if any, also need to be transformed */
833 [ + + ]: 146 : if (rtf->namespaces != NIL)
834 : : {
835 : : ListCell *ns;
836 : : ListCell *lc2;
837 : 13 : List *ns_uris = NIL;
838 : 13 : List *ns_names = NIL;
839 : 13 : bool default_ns_seen = false;
840 : :
841 [ + - + + : 26 : foreach(ns, rtf->namespaces)
+ + ]
842 : : {
843 : 13 : ResTarget *r = (ResTarget *) lfirst(ns);
844 : : Node *ns_uri;
845 : :
846 : : Assert(IsA(r, ResTarget));
847 : 13 : ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
848 : 13 : ns_uri = coerce_to_specific_type(pstate, ns_uri,
849 : : TEXTOID, constructName);
850 : 13 : assign_expr_collations(pstate, ns_uri);
851 : 13 : ns_uris = lappend(ns_uris, ns_uri);
852 : :
853 : : /* Verify consistency of name list: no dupes, only one DEFAULT */
854 [ + + ]: 13 : if (r->name != NULL)
855 : : {
856 [ - + - - : 9 : foreach(lc2, ns_names)
- + ]
857 : : {
858 : 0 : String *ns_node = lfirst_node(String, lc2);
859 : :
860 [ # # ]: 0 : if (ns_node == NULL)
861 : 0 : continue;
862 [ # # ]: 0 : if (strcmp(strVal(ns_node), r->name) == 0)
863 [ # # ]: 0 : ereport(ERROR,
864 : : (errcode(ERRCODE_SYNTAX_ERROR),
865 : : errmsg("namespace name \"%s\" is not unique",
866 : : r->name),
867 : : parser_errposition(pstate, r->location)));
868 : : }
869 : : }
870 : : else
871 : : {
872 [ - + ]: 4 : if (default_ns_seen)
873 [ # # ]: 0 : ereport(ERROR,
874 : : (errcode(ERRCODE_SYNTAX_ERROR),
875 : : errmsg("only one default namespace is allowed"),
876 : : parser_errposition(pstate, r->location)));
877 : 4 : default_ns_seen = true;
878 : : }
879 : :
880 : : /* We represent DEFAULT by a null pointer */
881 : 13 : ns_names = lappend(ns_names,
882 [ + + ]: 13 : r->name ? makeString(r->name) : NULL);
883 : : }
884 : :
885 : 13 : tf->ns_uris = ns_uris;
886 : 13 : tf->ns_names = ns_names;
887 : : }
888 : :
889 : 146 : tf->location = rtf->location;
890 : :
891 : 146 : pstate->p_lateral_active = false;
892 : :
893 : : /*
894 : : * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
895 : : * there are any lateral cross-references in it.
896 : : */
897 [ + + - + ]: 146 : is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
898 : :
899 : 146 : return addRangeTableEntryForTableFunc(pstate,
900 : : tf, rtf->alias, is_lateral, true);
901 : : }
902 : :
903 : : /*
904 : : * transformRangeTableSample --- transform a TABLESAMPLE clause
905 : : *
906 : : * Caller has already transformed rts->relation, we just have to validate
907 : : * the remaining fields and create a TableSampleClause node.
908 : : */
909 : : static TableSampleClause *
910 : 162 : transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
911 : : {
912 : : TableSampleClause *tablesample;
913 : : Oid handlerOid;
914 : : Oid funcargtypes[1];
915 : : TsmRoutine *tsm;
916 : : List *fargs;
917 : : ListCell *larg,
918 : : *ltyp;
919 : :
920 : : /*
921 : : * To validate the sample method name, look up the handler function, which
922 : : * has the same name, one dummy INTERNAL argument, and a result type of
923 : : * tsm_handler. (Note: tablesample method names are not schema-qualified
924 : : * in the SQL standard; but since they are just functions to us, we allow
925 : : * schema qualification to resolve any potential ambiguity.)
926 : : */
927 : 162 : funcargtypes[0] = INTERNALOID;
928 : :
929 : 162 : handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
930 : :
931 : : /* we want error to complain about no-such-method, not no-such-function */
932 [ + + ]: 162 : if (!OidIsValid(handlerOid))
933 [ + - ]: 4 : ereport(ERROR,
934 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
935 : : errmsg("tablesample method %s does not exist",
936 : : NameListToString(rts->method)),
937 : : parser_errposition(pstate, rts->location)));
938 : :
939 : : /* check that handler has correct return type */
940 [ - + ]: 158 : if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
941 [ # # ]: 0 : ereport(ERROR,
942 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
943 : : errmsg("function %s must return type %s",
944 : : NameListToString(rts->method), "tsm_handler"),
945 : : parser_errposition(pstate, rts->location)));
946 : :
947 : : /* OK, run the handler to get TsmRoutine, for argument type info */
948 : 158 : tsm = GetTsmRoutine(handlerOid);
949 : :
950 : 158 : tablesample = makeNode(TableSampleClause);
951 : 158 : tablesample->tsmhandler = handlerOid;
952 : :
953 : : /* check user provided the expected number of arguments */
954 [ - + ]: 158 : if (list_length(rts->args) != list_length(tsm->parameterTypes))
955 [ # # ]: 0 : ereport(ERROR,
956 : : (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
957 : : errmsg_plural("tablesample method %s requires %d argument, not %d",
958 : : "tablesample method %s requires %d arguments, not %d",
959 : : list_length(tsm->parameterTypes),
960 : : NameListToString(rts->method),
961 : : list_length(tsm->parameterTypes),
962 : : list_length(rts->args)),
963 : : parser_errposition(pstate, rts->location)));
964 : :
965 : : /*
966 : : * Transform the arguments, typecasting them as needed. Note we must also
967 : : * assign collations now, because assign_query_collations() doesn't
968 : : * examine any substructure of RTEs.
969 : : */
970 : 158 : fargs = NIL;
971 [ + - + + : 316 : forboth(larg, rts->args, ltyp, tsm->parameterTypes)
+ - + + +
+ + - +
+ ]
972 : : {
973 : 158 : Node *arg = (Node *) lfirst(larg);
974 : 158 : Oid argtype = lfirst_oid(ltyp);
975 : :
976 : 158 : arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
977 : 158 : arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
978 : 158 : assign_expr_collations(pstate, arg);
979 : 158 : fargs = lappend(fargs, arg);
980 : : }
981 : 158 : tablesample->args = fargs;
982 : :
983 : : /* Process REPEATABLE (seed) */
984 [ + + ]: 158 : if (rts->repeatable != NULL)
985 : : {
986 : : Node *arg;
987 : :
988 [ + + ]: 67 : if (!tsm->repeatable_across_queries)
989 [ + - ]: 2 : ereport(ERROR,
990 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
991 : : errmsg("tablesample method %s does not support REPEATABLE",
992 : : NameListToString(rts->method)),
993 : : parser_errposition(pstate, rts->location)));
994 : :
995 : 65 : arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
996 : 65 : arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
997 : 65 : assign_expr_collations(pstate, arg);
998 : 65 : tablesample->repeatable = (Expr *) arg;
999 : : }
1000 : : else
1001 : 91 : tablesample->repeatable = NULL;
1002 : :
1003 : 156 : return tablesample;
1004 : : }
1005 : :
1006 : : /*
1007 : : * getNSItemForSpecialRelationTypes
1008 : : *
1009 : : * If given RangeVar refers to a CTE or an EphemeralNamedRelation,
1010 : : * build and return an appropriate ParseNamespaceItem, otherwise return NULL
1011 : : */
1012 : : static ParseNamespaceItem *
1013 : 257153 : getNSItemForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
1014 : : {
1015 : : ParseNamespaceItem *nsitem;
1016 : : CommonTableExpr *cte;
1017 : : Index levelsup;
1018 : :
1019 : : /*
1020 : : * if it is a qualified name, it can't be a CTE or tuplestore reference
1021 : : */
1022 [ + + ]: 257153 : if (rv->schemaname)
1023 : 129332 : return NULL;
1024 : :
1025 : 127821 : cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1026 [ + + ]: 127821 : if (cte)
1027 : 4451 : nsitem = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1028 [ + + ]: 123370 : else if (scanNameSpaceForENR(pstate, rv->relname))
1029 : 362 : nsitem = addRangeTableEntryForENR(pstate, rv, true);
1030 : : else
1031 : 123008 : nsitem = NULL;
1032 : :
1033 : 127813 : return nsitem;
1034 : : }
1035 : :
1036 : : /*
1037 : : * transformFromClauseItem -
1038 : : * Transform a FROM-clause item, adding any required entries to the
1039 : : * range table list being built in the ParseState, and return the
1040 : : * transformed item ready to include in the joinlist. Also build a
1041 : : * ParseNamespaceItem list describing the names exposed by this item.
1042 : : * This routine can recurse to handle SQL92 JOIN expressions.
1043 : : *
1044 : : * The function return value is the node to add to the jointree (a
1045 : : * RangeTblRef or JoinExpr). Additional output parameters are:
1046 : : *
1047 : : * *top_nsitem: receives the ParseNamespaceItem directly corresponding to the
1048 : : * jointree item. (This is only used during internal recursion, not by
1049 : : * outside callers.)
1050 : : *
1051 : : * *namespace: receives a List of ParseNamespaceItems for the RTEs exposed
1052 : : * as table/column names by this item. (The lateral_only flags in these items
1053 : : * are indeterminate and should be explicitly set by the caller before use.)
1054 : : */
1055 : : static Node *
1056 : 355645 : transformFromClauseItem(ParseState *pstate, Node *n,
1057 : : ParseNamespaceItem **top_nsitem,
1058 : : List **namespace)
1059 : : {
1060 : : /* Guard against stack overflow due to overly deep subtree */
1061 : 355645 : check_stack_depth();
1062 : :
1063 [ + + ]: 355645 : if (IsA(n, RangeVar))
1064 : : {
1065 : : /* Plain relation reference, or perhaps a CTE reference */
1066 : 257153 : RangeVar *rv = (RangeVar *) n;
1067 : : RangeTblRef *rtr;
1068 : : ParseNamespaceItem *nsitem;
1069 : :
1070 : : /* Check if it's a CTE or tuplestore reference */
1071 : 257153 : nsitem = getNSItemForSpecialRelationTypes(pstate, rv);
1072 : :
1073 : : /* if not found above, must be a table reference */
1074 [ + + ]: 257145 : if (!nsitem)
1075 : 252340 : nsitem = transformTableEntry(pstate, rv);
1076 : :
1077 : 257035 : *top_nsitem = nsitem;
1078 : 257035 : *namespace = list_make1(nsitem);
1079 : 257035 : rtr = makeNode(RangeTblRef);
1080 : 257035 : rtr->rtindex = nsitem->p_rtindex;
1081 : 257035 : return (Node *) rtr;
1082 : : }
1083 [ + + ]: 98492 : else if (IsA(n, RangeSubselect))
1084 : : {
1085 : : /* sub-SELECT is like a plain relation */
1086 : : RangeTblRef *rtr;
1087 : : ParseNamespaceItem *nsitem;
1088 : :
1089 : 13812 : nsitem = transformRangeSubselect(pstate, (RangeSubselect *) n);
1090 : 13736 : *top_nsitem = nsitem;
1091 : 13736 : *namespace = list_make1(nsitem);
1092 : 13736 : rtr = makeNode(RangeTblRef);
1093 : 13736 : rtr->rtindex = nsitem->p_rtindex;
1094 : 13736 : return (Node *) rtr;
1095 : : }
1096 [ + + ]: 84680 : else if (IsA(n, RangeFunction))
1097 : : {
1098 : : /* function is like a plain relation */
1099 : : RangeTblRef *rtr;
1100 : : ParseNamespaceItem *nsitem;
1101 : :
1102 : 29613 : nsitem = transformRangeFunction(pstate, (RangeFunction *) n);
1103 : 29464 : *top_nsitem = nsitem;
1104 : 29464 : *namespace = list_make1(nsitem);
1105 : 29464 : rtr = makeNode(RangeTblRef);
1106 : 29464 : rtr->rtindex = nsitem->p_rtindex;
1107 : 29464 : return (Node *) rtr;
1108 : : }
1109 [ + + + + ]: 55067 : else if (IsA(n, RangeTableFunc) || IsA(n, JsonTable))
1110 : : {
1111 : : /* table function is like a plain relation */
1112 : : RangeTblRef *rtr;
1113 : : ParseNamespaceItem *nsitem;
1114 : :
1115 [ + + ]: 626 : if (IsA(n, JsonTable))
1116 : 480 : nsitem = transformJsonTable(pstate, (JsonTable *) n);
1117 : : else
1118 : 146 : nsitem = transformRangeTableFunc(pstate, (RangeTableFunc *) n);
1119 : :
1120 : 518 : *top_nsitem = nsitem;
1121 : 518 : *namespace = list_make1(nsitem);
1122 : 518 : rtr = makeNode(RangeTblRef);
1123 : 518 : rtr->rtindex = nsitem->p_rtindex;
1124 : 518 : return (Node *) rtr;
1125 : : }
1126 [ + + ]: 54441 : else if (IsA(n, RangeTableSample))
1127 : : {
1128 : : /* TABLESAMPLE clause (wrapping some other valid FROM node) */
1129 : 170 : RangeTableSample *rts = (RangeTableSample *) n;
1130 : : Node *rel;
1131 : : RangeTblEntry *rte;
1132 : :
1133 : : /* Recursively transform the contained relation */
1134 : 170 : rel = transformFromClauseItem(pstate, rts->relation,
1135 : : top_nsitem, namespace);
1136 : 170 : rte = (*top_nsitem)->p_rte;
1137 : : /* We only support this on plain relations and matviews */
1138 [ + + ]: 170 : if (rte->rtekind != RTE_RELATION ||
1139 [ + + ]: 166 : (rte->relkind != RELKIND_RELATION &&
1140 [ + - ]: 16 : rte->relkind != RELKIND_MATVIEW &&
1141 [ + + ]: 16 : rte->relkind != RELKIND_PARTITIONED_TABLE))
1142 [ + - ]: 8 : ereport(ERROR,
1143 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1144 : : errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
1145 : : parser_errposition(pstate, exprLocation(rts->relation))));
1146 : :
1147 : : /* Transform TABLESAMPLE details and attach to the RTE */
1148 : 162 : rte->tablesample = transformRangeTableSample(pstate, rts);
1149 : 156 : return rel;
1150 : : }
1151 [ + - ]: 54271 : else if (IsA(n, JoinExpr))
1152 : : {
1153 : : /* A newfangled join expression */
1154 : 54271 : JoinExpr *j = (JoinExpr *) n;
1155 : : ParseNamespaceItem *nsitem;
1156 : : ParseNamespaceItem *l_nsitem;
1157 : : ParseNamespaceItem *r_nsitem;
1158 : : List *l_namespace,
1159 : : *r_namespace,
1160 : : *my_namespace,
1161 : : *l_colnames,
1162 : : *r_colnames,
1163 : : *res_colnames,
1164 : : *l_colnos,
1165 : : *r_colnos,
1166 : : *res_colvars;
1167 : : ParseNamespaceColumn *l_nscolumns,
1168 : : *r_nscolumns,
1169 : : *res_nscolumns;
1170 : : int res_colindex;
1171 : : bool lateral_ok;
1172 : : int sv_namespace_length;
1173 : : int k;
1174 : :
1175 : : /*
1176 : : * Recursively process the left subtree, then the right. We must do
1177 : : * it in this order for correct visibility of LATERAL references.
1178 : : */
1179 : 54271 : j->larg = transformFromClauseItem(pstate, j->larg,
1180 : : &l_nsitem,
1181 : : &l_namespace);
1182 : :
1183 : : /*
1184 : : * Make the left-side RTEs available for LATERAL access within the
1185 : : * right side, by temporarily adding them to the pstate's namespace
1186 : : * list. Per SQL:2008, if the join type is not INNER or LEFT then the
1187 : : * left-side names must still be exposed, but it's an error to
1188 : : * reference them. (Stupid design, but that's what it says.) Hence,
1189 : : * we always push them into the namespace, but mark them as not
1190 : : * lateral_ok if the jointype is wrong.
1191 : : *
1192 : : * Notice that we don't require the merged namespace list to be
1193 : : * conflict-free. See the comments for scanNameSpaceForRefname().
1194 : : */
1195 [ + + + + ]: 54271 : lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
1196 : 54271 : setNamespaceLateralState(l_namespace, true, lateral_ok);
1197 : :
1198 : 54271 : sv_namespace_length = list_length(pstate->p_namespace);
1199 : 54271 : pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
1200 : :
1201 : : /* And now we can process the RHS */
1202 : 54271 : j->rarg = transformFromClauseItem(pstate, j->rarg,
1203 : : &r_nsitem,
1204 : : &r_namespace);
1205 : :
1206 : : /* Remove the left-side RTEs from the namespace list again */
1207 : 54247 : pstate->p_namespace = list_truncate(pstate->p_namespace,
1208 : : sv_namespace_length);
1209 : :
1210 : : /*
1211 : : * Check for conflicting refnames in left and right subtrees. Must do
1212 : : * this because higher levels will assume I hand back a self-
1213 : : * consistent namespace list.
1214 : : */
1215 : 54247 : checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
1216 : :
1217 : : /*
1218 : : * Generate combined namespace info for possible use below.
1219 : : */
1220 : 54247 : my_namespace = list_concat(l_namespace, r_namespace);
1221 : :
1222 : : /*
1223 : : * We'll work from the nscolumns data and eref alias column names for
1224 : : * each of the input nsitems. Note that these include dropped
1225 : : * columns, which is helpful because we can keep track of physical
1226 : : * input column numbers more easily.
1227 : : */
1228 : 54247 : l_nscolumns = l_nsitem->p_nscolumns;
1229 : 54247 : l_colnames = l_nsitem->p_names->colnames;
1230 : 54247 : r_nscolumns = r_nsitem->p_nscolumns;
1231 : 54247 : r_colnames = r_nsitem->p_names->colnames;
1232 : :
1233 : : /*
1234 : : * Natural join does not explicitly specify columns; must generate
1235 : : * columns to join. Need to run through the list of columns from each
1236 : : * table or join result and match up the column names. Use the first
1237 : : * table, and check every column in the second table for a match.
1238 : : * (We'll check that the matches were unique later on.) The result of
1239 : : * this step is a list of column names just like an explicitly-written
1240 : : * USING list.
1241 : : */
1242 [ + + ]: 54247 : if (j->isNatural)
1243 : : {
1244 : 176 : List *rlist = NIL;
1245 : : ListCell *lx,
1246 : : *rx;
1247 : :
1248 : : Assert(j->usingClause == NIL); /* shouldn't have USING() too */
1249 : :
1250 [ + - + + : 780 : foreach(lx, l_colnames)
+ + ]
1251 : : {
1252 : 604 : char *l_colname = strVal(lfirst(lx));
1253 : 604 : String *m_name = NULL;
1254 : :
1255 [ + + ]: 604 : if (l_colname[0] == '\0')
1256 : 8 : continue; /* ignore dropped columns */
1257 : :
1258 [ + - + + : 1648 : foreach(rx, r_colnames)
+ + ]
1259 : : {
1260 : 1272 : char *r_colname = strVal(lfirst(rx));
1261 : :
1262 [ + + ]: 1272 : if (strcmp(l_colname, r_colname) == 0)
1263 : : {
1264 : 220 : m_name = makeString(l_colname);
1265 : 220 : break;
1266 : : }
1267 : : }
1268 : :
1269 : : /* matched a right column? then keep as join column... */
1270 [ + + ]: 596 : if (m_name != NULL)
1271 : 220 : rlist = lappend(rlist, m_name);
1272 : : }
1273 : :
1274 : 176 : j->usingClause = rlist;
1275 : : }
1276 : :
1277 : : /*
1278 : : * If a USING clause alias was specified, save the USING columns as
1279 : : * its column list.
1280 : : */
1281 [ + + ]: 54247 : if (j->join_using_alias)
1282 : 56 : j->join_using_alias->colnames = j->usingClause;
1283 : :
1284 : : /*
1285 : : * Now transform the join qualifications, if any.
1286 : : */
1287 : 54247 : l_colnos = NIL;
1288 : 54247 : r_colnos = NIL;
1289 : 54247 : res_colnames = NIL;
1290 : 54247 : res_colvars = NIL;
1291 : :
1292 : : /* this may be larger than needed, but it's not worth being exact */
1293 : 54247 : res_nscolumns = palloc0_array(ParseNamespaceColumn,
1294 : : list_length(l_colnames) + list_length(r_colnames));
1295 : 54247 : res_colindex = 0;
1296 : :
1297 [ + + ]: 54247 : if (j->usingClause)
1298 : : {
1299 : : /*
1300 : : * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
1301 : : * the list into an explicit ON-condition.
1302 : : */
1303 : 1045 : List *ucols = j->usingClause;
1304 : 1045 : List *l_usingvars = NIL;
1305 : 1045 : List *r_usingvars = NIL;
1306 : : ListCell *ucol;
1307 : :
1308 : : Assert(j->quals == NULL); /* shouldn't have ON() too */
1309 : :
1310 [ + - + + : 2245 : foreach(ucol, ucols)
+ + ]
1311 : : {
1312 : 1200 : char *u_colname = strVal(lfirst(ucol));
1313 : : ListCell *col;
1314 : : int ndx;
1315 : 1200 : int l_index = -1;
1316 : 1200 : int r_index = -1;
1317 : : Var *l_colvar,
1318 : : *r_colvar;
1319 : :
1320 : : Assert(u_colname[0] != '\0');
1321 : :
1322 : : /* Check for USING(foo,foo) */
1323 [ + + + + : 1386 : foreach(col, res_colnames)
+ + ]
1324 : : {
1325 : 186 : char *res_colname = strVal(lfirst(col));
1326 : :
1327 [ - + ]: 186 : if (strcmp(res_colname, u_colname) == 0)
1328 [ # # ]: 0 : ereport(ERROR,
1329 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
1330 : : errmsg("column name \"%s\" appears more than once in USING clause",
1331 : : u_colname)));
1332 : : }
1333 : :
1334 : : /* Find it in left input */
1335 : 1200 : ndx = 0;
1336 [ + - + + : 5786 : foreach(col, l_colnames)
+ + ]
1337 : : {
1338 : 4586 : char *l_colname = strVal(lfirst(col));
1339 : :
1340 [ + + ]: 4586 : if (strcmp(l_colname, u_colname) == 0)
1341 : : {
1342 [ - + ]: 1200 : if (l_index >= 0)
1343 [ # # ]: 0 : ereport(ERROR,
1344 : : (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1345 : : errmsg("common column name \"%s\" appears more than once in left table",
1346 : : u_colname)));
1347 : 1200 : l_index = ndx;
1348 : : }
1349 : 4586 : ndx++;
1350 : : }
1351 [ - + ]: 1200 : if (l_index < 0)
1352 [ # # ]: 0 : ereport(ERROR,
1353 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
1354 : : errmsg("column \"%s\" specified in USING clause does not exist in left table",
1355 : : u_colname)));
1356 : 1200 : l_colnos = lappend_int(l_colnos, l_index + 1);
1357 : :
1358 : : /* Find it in right input */
1359 : 1200 : ndx = 0;
1360 [ + - + + : 5729 : foreach(col, r_colnames)
+ + ]
1361 : : {
1362 : 4529 : char *r_colname = strVal(lfirst(col));
1363 : :
1364 [ + + ]: 4529 : if (strcmp(r_colname, u_colname) == 0)
1365 : : {
1366 [ - + ]: 1200 : if (r_index >= 0)
1367 [ # # ]: 0 : ereport(ERROR,
1368 : : (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1369 : : errmsg("common column name \"%s\" appears more than once in right table",
1370 : : u_colname)));
1371 : 1200 : r_index = ndx;
1372 : : }
1373 : 4529 : ndx++;
1374 : : }
1375 [ - + ]: 1200 : if (r_index < 0)
1376 [ # # ]: 0 : ereport(ERROR,
1377 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
1378 : : errmsg("column \"%s\" specified in USING clause does not exist in right table",
1379 : : u_colname)));
1380 : 1200 : r_colnos = lappend_int(r_colnos, r_index + 1);
1381 : :
1382 : : /* Build Vars to use in the generated JOIN ON clause */
1383 : 1200 : l_colvar = buildVarFromNSColumn(pstate, l_nscolumns + l_index);
1384 : 1200 : l_usingvars = lappend(l_usingvars, l_colvar);
1385 : 1200 : r_colvar = buildVarFromNSColumn(pstate, r_nscolumns + r_index);
1386 : 1200 : r_usingvars = lappend(r_usingvars, r_colvar);
1387 : :
1388 : : /*
1389 : : * While we're here, add column names to the res_colnames
1390 : : * list. It's a bit ugly to do this here while the
1391 : : * corresponding res_colvars entries are not made till later,
1392 : : * but doing this later would require an additional traversal
1393 : : * of the usingClause list.
1394 : : */
1395 : 1200 : res_colnames = lappend(res_colnames, lfirst(ucol));
1396 : : }
1397 : :
1398 : : /* Construct the generated JOIN ON clause */
1399 : 1045 : j->quals = transformJoinUsingClause(pstate,
1400 : : l_usingvars,
1401 : : r_usingvars);
1402 : : }
1403 [ + + ]: 53202 : else if (j->quals)
1404 : : {
1405 : : /* User-written ON-condition; transform it */
1406 : 52843 : j->quals = transformJoinOnClause(pstate, j, my_namespace);
1407 : : }
1408 : : else
1409 : : {
1410 : : /* CROSS JOIN: no quals */
1411 : : }
1412 : :
1413 : : /*
1414 : : * If this is an outer join, now mark the appropriate child RTEs as
1415 : : * being nulled by this join. We have finished processing the child
1416 : : * join expressions as well as the current join's quals, which deal in
1417 : : * non-nulled input columns. All future references to those RTEs will
1418 : : * see possibly-nulled values, and we should mark generated Vars to
1419 : : * account for that. In particular, the join alias Vars that we're
1420 : : * about to build should reflect the nulling effects of this join.
1421 : : *
1422 : : * A difficulty with doing this is that we need the join's RT index,
1423 : : * which we don't officially have yet. However, no other RTE can get
1424 : : * made between here and the addRangeTableEntryForJoin call, so we can
1425 : : * predict what the assignment will be. (Alternatively, we could call
1426 : : * addRangeTableEntryForJoin before we have all the data computed, but
1427 : : * this seems less ugly.)
1428 : : */
1429 : 54235 : j->rtindex = list_length(pstate->p_rtable) + 1;
1430 : :
1431 [ + + + + : 54235 : switch (j->jointype)
- ]
1432 : : {
1433 : 27175 : case JOIN_INNER:
1434 : 27175 : break;
1435 : 26057 : case JOIN_LEFT:
1436 : 26057 : markRelsAsNulledBy(pstate, j->rarg, j->rtindex);
1437 : 26057 : break;
1438 : 759 : case JOIN_FULL:
1439 : 759 : markRelsAsNulledBy(pstate, j->larg, j->rtindex);
1440 : 759 : markRelsAsNulledBy(pstate, j->rarg, j->rtindex);
1441 : 759 : break;
1442 : 244 : case JOIN_RIGHT:
1443 : 244 : markRelsAsNulledBy(pstate, j->larg, j->rtindex);
1444 : 244 : break;
1445 : 0 : default:
1446 : : /* shouldn't see any other types here */
1447 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
1448 : : (int) j->jointype);
1449 : : break;
1450 : : }
1451 : :
1452 : : /*
1453 : : * Now we can construct join alias expressions for the USING columns.
1454 : : */
1455 [ + + ]: 54235 : if (j->usingClause)
1456 : : {
1457 : : ListCell *lc1,
1458 : : *lc2;
1459 : :
1460 : : /* Scan the colnos lists to recover info from the previous loop */
1461 [ + - + + : 2245 : forboth(lc1, l_colnos, lc2, r_colnos)
+ - + + +
+ + - +
+ ]
1462 : : {
1463 : 1200 : int l_index = lfirst_int(lc1) - 1;
1464 : 1200 : int r_index = lfirst_int(lc2) - 1;
1465 : : Var *l_colvar,
1466 : : *r_colvar;
1467 : : Node *u_colvar;
1468 : : ParseNamespaceColumn *res_nscolumn;
1469 : :
1470 : : /*
1471 : : * Note we re-build these Vars: they might have different
1472 : : * varnullingrels than the ones made in the previous loop.
1473 : : */
1474 : 1200 : l_colvar = buildVarFromNSColumn(pstate, l_nscolumns + l_index);
1475 : 1200 : r_colvar = buildVarFromNSColumn(pstate, r_nscolumns + r_index);
1476 : :
1477 : : /* Construct the join alias Var for this column */
1478 : 1200 : u_colvar = buildMergedJoinVar(pstate,
1479 : : j->jointype,
1480 : : l_colvar,
1481 : : r_colvar);
1482 : 1200 : res_colvars = lappend(res_colvars, u_colvar);
1483 : :
1484 : : /* Construct column's res_nscolumns[] entry */
1485 : 1200 : res_nscolumn = res_nscolumns + res_colindex;
1486 : 1200 : res_colindex++;
1487 [ + + ]: 1200 : if (u_colvar == (Node *) l_colvar)
1488 : : {
1489 : : /* Merged column is equivalent to left input */
1490 : 859 : *res_nscolumn = l_nscolumns[l_index];
1491 : : }
1492 [ + + ]: 341 : else if (u_colvar == (Node *) r_colvar)
1493 : : {
1494 : : /* Merged column is equivalent to right input */
1495 : 28 : *res_nscolumn = r_nscolumns[r_index];
1496 : : }
1497 : : else
1498 : : {
1499 : : /*
1500 : : * Merged column is not semantically equivalent to either
1501 : : * input, so it needs to be referenced as the join output
1502 : : * column.
1503 : : */
1504 : 313 : res_nscolumn->p_varno = j->rtindex;
1505 : 313 : res_nscolumn->p_varattno = res_colindex;
1506 : 313 : res_nscolumn->p_vartype = exprType(u_colvar);
1507 : 313 : res_nscolumn->p_vartypmod = exprTypmod(u_colvar);
1508 : 313 : res_nscolumn->p_varcollid = exprCollation(u_colvar);
1509 : 313 : res_nscolumn->p_varnosyn = j->rtindex;
1510 : 313 : res_nscolumn->p_varattnosyn = res_colindex;
1511 : : }
1512 : : }
1513 : : }
1514 : :
1515 : : /* Add remaining columns from each side to the output columns */
1516 : 54235 : res_colindex +=
1517 : 54235 : extractRemainingColumns(pstate,
1518 : : l_nscolumns, l_colnames, &l_colnos,
1519 : : &res_colnames, &res_colvars,
1520 : 54235 : res_nscolumns + res_colindex);
1521 : 54235 : res_colindex +=
1522 : 54235 : extractRemainingColumns(pstate,
1523 : : r_nscolumns, r_colnames, &r_colnos,
1524 : : &res_colnames, &res_colvars,
1525 : 54235 : res_nscolumns + res_colindex);
1526 : :
1527 : : /* If join has an alias, it syntactically hides all inputs */
1528 [ + + ]: 54235 : if (j->alias)
1529 : : {
1530 [ + + ]: 668 : for (k = 0; k < res_colindex; k++)
1531 : : {
1532 : 548 : ParseNamespaceColumn *nscol = res_nscolumns + k;
1533 : :
1534 : 548 : nscol->p_varnosyn = j->rtindex;
1535 : 548 : nscol->p_varattnosyn = k + 1;
1536 : : }
1537 : : }
1538 : :
1539 : : /*
1540 : : * Now build an RTE and nsitem for the result of the join.
1541 : : */
1542 : 54235 : nsitem = addRangeTableEntryForJoin(pstate,
1543 : : res_colnames,
1544 : : res_nscolumns,
1545 : : j->jointype,
1546 : 54235 : list_length(j->usingClause),
1547 : : res_colvars,
1548 : : l_colnos,
1549 : : r_colnos,
1550 : : j->join_using_alias,
1551 : : j->alias,
1552 : : true);
1553 : :
1554 : : /* Verify that we correctly predicted the join's RT index */
1555 : : Assert(j->rtindex == nsitem->p_rtindex);
1556 : : /* Cross-check number of columns, too */
1557 : : Assert(res_colindex == list_length(nsitem->p_names->colnames));
1558 : :
1559 : : /*
1560 : : * Save a link to the JoinExpr in the proper element of p_joinexprs.
1561 : : * Since we maintain that list lazily, it may be necessary to fill in
1562 : : * empty entries before we can add the JoinExpr in the right place.
1563 : : */
1564 [ + + ]: 143443 : for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
1565 : 89212 : pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
1566 : 54231 : pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
1567 : : Assert(list_length(pstate->p_joinexprs) == j->rtindex);
1568 : :
1569 : : /*
1570 : : * If the join has a USING alias, build a ParseNamespaceItem for that
1571 : : * and add it to the list of nsitems in the join's input.
1572 : : */
1573 [ + + ]: 54231 : if (j->join_using_alias)
1574 : : {
1575 : : ParseNamespaceItem *jnsitem;
1576 : :
1577 : 56 : jnsitem = palloc_object(ParseNamespaceItem);
1578 : 56 : jnsitem->p_names = j->join_using_alias;
1579 : 56 : jnsitem->p_rte = nsitem->p_rte;
1580 : 56 : jnsitem->p_rtindex = nsitem->p_rtindex;
1581 : 56 : jnsitem->p_perminfo = NULL;
1582 : : /* no need to copy the first N columns, just use res_nscolumns */
1583 : 56 : jnsitem->p_nscolumns = res_nscolumns;
1584 : : /* set default visibility flags; might get changed later */
1585 : 56 : jnsitem->p_rel_visible = true;
1586 : 56 : jnsitem->p_cols_visible = true;
1587 : 56 : jnsitem->p_lateral_only = false;
1588 : 56 : jnsitem->p_lateral_ok = true;
1589 : 56 : jnsitem->p_returning_type = VAR_RETURNING_DEFAULT;
1590 : : /* Per SQL, we must check for alias conflicts */
1591 : 56 : checkNameSpaceConflicts(pstate, list_make1(jnsitem), my_namespace);
1592 : 52 : my_namespace = lappend(my_namespace, jnsitem);
1593 : : }
1594 : :
1595 : : /*
1596 : : * Prepare returned namespace list. If the JOIN has an alias then it
1597 : : * hides the contained RTEs completely; otherwise, the contained RTEs
1598 : : * are still visible as table names, but are not visible for
1599 : : * unqualified column-name access.
1600 : : *
1601 : : * Note: if there are nested alias-less JOINs, the lower-level ones
1602 : : * will remain in the list although they have neither p_rel_visible
1603 : : * nor p_cols_visible set. We could delete such list items, but it's
1604 : : * unclear that it's worth expending cycles to do so.
1605 : : */
1606 [ + + ]: 54227 : if (j->alias != NULL)
1607 : 116 : my_namespace = NIL;
1608 : : else
1609 : 54111 : setNamespaceColumnVisibility(my_namespace, false);
1610 : :
1611 : : /*
1612 : : * The join RTE itself is always made visible for unqualified column
1613 : : * names. It's visible as a relation name only if it has an alias.
1614 : : */
1615 : 54227 : nsitem->p_rel_visible = (j->alias != NULL);
1616 : 54227 : nsitem->p_cols_visible = true;
1617 : 54227 : nsitem->p_lateral_only = false;
1618 : 54227 : nsitem->p_lateral_ok = true;
1619 : :
1620 : 54227 : *top_nsitem = nsitem;
1621 : 54227 : *namespace = lappend(my_namespace, nsitem);
1622 : :
1623 : 54227 : return (Node *) j;
1624 : : }
1625 : : else
1626 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1627 : : return NULL; /* can't get here, keep compiler quiet */
1628 : : }
1629 : :
1630 : : /*
1631 : : * buildVarFromNSColumn -
1632 : : * build a Var node using ParseNamespaceColumn data
1633 : : *
1634 : : * This is used to construct joinaliasvars entries.
1635 : : * We can assume varlevelsup should be 0, and no location is specified.
1636 : : * Note also that no column SELECT privilege is requested here; that would
1637 : : * happen only if the column is actually referenced in the query.
1638 : : */
1639 : : static Var *
1640 : 2039382 : buildVarFromNSColumn(ParseState *pstate, ParseNamespaceColumn *nscol)
1641 : : {
1642 : : Var *var;
1643 : :
1644 : : Assert(nscol->p_varno > 0); /* i.e., not deleted column */
1645 : 2039382 : var = makeVar(nscol->p_varno,
1646 : 2039382 : nscol->p_varattno,
1647 : : nscol->p_vartype,
1648 : : nscol->p_vartypmod,
1649 : : nscol->p_varcollid,
1650 : : 0);
1651 : : /* makeVar doesn't offer parameters for these, so set by hand: */
1652 : 2039382 : var->varreturningtype = nscol->p_varreturningtype;
1653 : 2039382 : var->varnosyn = nscol->p_varnosyn;
1654 : 2039382 : var->varattnosyn = nscol->p_varattnosyn;
1655 : :
1656 : : /* ... and update varnullingrels */
1657 : 2039382 : markNullableIfNeeded(pstate, var);
1658 : :
1659 : 2039382 : return var;
1660 : : }
1661 : :
1662 : : /*
1663 : : * buildMergedJoinVar -
1664 : : * generate a suitable replacement expression for a merged join column
1665 : : */
1666 : : static Node *
1667 : 1200 : buildMergedJoinVar(ParseState *pstate, JoinType jointype,
1668 : : Var *l_colvar, Var *r_colvar)
1669 : : {
1670 : : Oid outcoltype;
1671 : : int32 outcoltypmod;
1672 : : Node *l_node,
1673 : : *r_node,
1674 : : *res_node;
1675 : :
1676 : 1200 : outcoltype = select_common_type(pstate,
1677 : : list_make2(l_colvar, r_colvar),
1678 : : "JOIN/USING",
1679 : : NULL);
1680 : 1200 : outcoltypmod = select_common_typmod(pstate,
1681 : : list_make2(l_colvar, r_colvar),
1682 : : outcoltype);
1683 : :
1684 : : /*
1685 : : * Insert coercion functions if needed. Note that a difference in typmod
1686 : : * can only happen if input has typmod but outcoltypmod is -1. In that
1687 : : * case we insert a RelabelType to clearly mark that result's typmod is
1688 : : * not same as input. We never need coerce_type_typmod.
1689 : : */
1690 [ + + ]: 1200 : if (l_colvar->vartype != outcoltype)
1691 : 60 : l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1692 : : outcoltype, outcoltypmod,
1693 : : COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1694 [ - + ]: 1140 : else if (l_colvar->vartypmod != outcoltypmod)
1695 : 0 : l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1696 : : outcoltype, outcoltypmod,
1697 : : InvalidOid, /* fixed below */
1698 : : COERCE_IMPLICIT_CAST);
1699 : : else
1700 : 1140 : l_node = (Node *) l_colvar;
1701 : :
1702 [ + + ]: 1200 : if (r_colvar->vartype != outcoltype)
1703 : 20 : r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1704 : : outcoltype, outcoltypmod,
1705 : : COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1706 [ - + ]: 1180 : else if (r_colvar->vartypmod != outcoltypmod)
1707 : 0 : r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1708 : : outcoltype, outcoltypmod,
1709 : : InvalidOid, /* fixed below */
1710 : : COERCE_IMPLICIT_CAST);
1711 : : else
1712 : 1180 : r_node = (Node *) r_colvar;
1713 : :
1714 : : /*
1715 : : * Choose what to emit
1716 : : */
1717 [ + + + + : 1200 : switch (jointype)
- ]
1718 : : {
1719 : 767 : case JOIN_INNER:
1720 : :
1721 : : /*
1722 : : * We can use either var; prefer non-coerced one if available.
1723 : : */
1724 [ + + ]: 767 : if (IsA(l_node, Var))
1725 : 747 : res_node = l_node;
1726 [ + - ]: 20 : else if (IsA(r_node, Var))
1727 : 20 : res_node = r_node;
1728 : : else
1729 : 0 : res_node = l_node;
1730 : 767 : break;
1731 : 152 : case JOIN_LEFT:
1732 : : /* Always use left var */
1733 : 152 : res_node = l_node;
1734 : 152 : break;
1735 : 8 : case JOIN_RIGHT:
1736 : : /* Always use right var */
1737 : 8 : res_node = r_node;
1738 : 8 : break;
1739 : 273 : case JOIN_FULL:
1740 : : {
1741 : : /*
1742 : : * Here we must build a COALESCE expression to ensure that the
1743 : : * join output is non-null if either input is.
1744 : : */
1745 : 273 : CoalesceExpr *c = makeNode(CoalesceExpr);
1746 : :
1747 : 273 : c->coalescetype = outcoltype;
1748 : : /* coalescecollid will get set below */
1749 : 273 : c->args = list_make2(l_node, r_node);
1750 : 273 : c->location = -1;
1751 : 273 : res_node = (Node *) c;
1752 : 273 : break;
1753 : : }
1754 : 0 : default:
1755 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d", (int) jointype);
1756 : : res_node = NULL; /* keep compiler quiet */
1757 : : break;
1758 : : }
1759 : :
1760 : : /*
1761 : : * Apply assign_expr_collations to fix up the collation info in the
1762 : : * coercion and CoalesceExpr nodes, if we made any. This must be done now
1763 : : * so that the join node's alias vars show correct collation info.
1764 : : */
1765 : 1200 : assign_expr_collations(pstate, res_node);
1766 : :
1767 : 1200 : return res_node;
1768 : : }
1769 : :
1770 : : /*
1771 : : * markRelsAsNulledBy -
1772 : : * Mark the given jointree node and its children as nulled by join jindex
1773 : : */
1774 : : static void
1775 : 30169 : markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex)
1776 : : {
1777 : : int varno;
1778 : : ListCell *lc;
1779 : :
1780 : : /* Note: we can't see FromExpr here */
1781 [ + + ]: 30169 : if (IsA(n, RangeTblRef))
1782 : : {
1783 : 28994 : varno = ((RangeTblRef *) n)->rtindex;
1784 : : }
1785 [ + - ]: 1175 : else if (IsA(n, JoinExpr))
1786 : : {
1787 : 1175 : JoinExpr *j = (JoinExpr *) n;
1788 : :
1789 : : /* recurse to children */
1790 : 1175 : markRelsAsNulledBy(pstate, j->larg, jindex);
1791 : 1175 : markRelsAsNulledBy(pstate, j->rarg, jindex);
1792 : 1175 : varno = j->rtindex;
1793 : : }
1794 : : else
1795 : : {
1796 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1797 : : varno = 0; /* keep compiler quiet */
1798 : : }
1799 : :
1800 : : /*
1801 : : * Now add jindex to the p_nullingrels set for relation varno. Since we
1802 : : * maintain the p_nullingrels list lazily, we might need to extend it to
1803 : : * make the varno'th entry exist.
1804 : : */
1805 [ + + ]: 96978 : while (list_length(pstate->p_nullingrels) < varno)
1806 : 66809 : pstate->p_nullingrels = lappend(pstate->p_nullingrels, NULL);
1807 : 30169 : lc = list_nth_cell(pstate->p_nullingrels, varno - 1);
1808 : 30169 : lfirst(lc) = bms_add_member((Bitmapset *) lfirst(lc), jindex);
1809 : 30169 : }
1810 : :
1811 : : /*
1812 : : * setNamespaceColumnVisibility -
1813 : : * Convenience subroutine to update cols_visible flags in a namespace list.
1814 : : */
1815 : : static void
1816 : 54111 : setNamespaceColumnVisibility(List *namespace, bool cols_visible)
1817 : : {
1818 : : ListCell *lc;
1819 : :
1820 [ + - + + : 224683 : foreach(lc, namespace)
+ + ]
1821 : : {
1822 : 170572 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1823 : :
1824 : 170572 : nsitem->p_cols_visible = cols_visible;
1825 : : }
1826 : 54111 : }
1827 : :
1828 : : /*
1829 : : * setNamespaceLateralState -
1830 : : * Convenience subroutine to update LATERAL flags in a namespace list.
1831 : : */
1832 : : static void
1833 : 671505 : setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
1834 : : {
1835 : : ListCell *lc;
1836 : :
1837 [ + + + + : 1675869 : foreach(lc, namespace)
+ + ]
1838 : : {
1839 : 1004364 : ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1840 : :
1841 : 1004364 : nsitem->p_lateral_only = lateral_only;
1842 : 1004364 : nsitem->p_lateral_ok = lateral_ok;
1843 : : }
1844 : 671505 : }
1845 : :
1846 : :
1847 : : /*
1848 : : * transformWhereClause -
1849 : : * Transform the qualification and make sure it is of type boolean.
1850 : : * Used for WHERE and allied clauses.
1851 : : *
1852 : : * constructName does not affect the semantics, but is used in error messages
1853 : : */
1854 : : Node *
1855 : 672120 : transformWhereClause(ParseState *pstate, Node *clause,
1856 : : ParseExprKind exprKind, const char *constructName)
1857 : : {
1858 : : Node *qual;
1859 : :
1860 [ + + ]: 672120 : if (clause == NULL)
1861 : 466896 : return NULL;
1862 : :
1863 : 205224 : qual = transformExpr(pstate, clause, exprKind);
1864 : :
1865 : 205085 : qual = coerce_to_boolean(pstate, qual, constructName);
1866 : :
1867 : 205081 : return qual;
1868 : : }
1869 : :
1870 : :
1871 : : /*
1872 : : * transformLimitClause -
1873 : : * Transform the expression and make sure it is of type bigint.
1874 : : * Used for LIMIT and allied clauses.
1875 : : *
1876 : : * Note: as of Postgres 8.2, LIMIT expressions are expected to yield int8,
1877 : : * rather than int4 as before.
1878 : : *
1879 : : * constructName does not affect the semantics, but is used in error messages
1880 : : */
1881 : : Node *
1882 : 628464 : transformLimitClause(ParseState *pstate, Node *clause,
1883 : : ParseExprKind exprKind, const char *constructName,
1884 : : LimitOption limitOption)
1885 : : {
1886 : : Node *qual;
1887 : :
1888 [ + + ]: 628464 : if (clause == NULL)
1889 : 625015 : return NULL;
1890 : :
1891 : 3449 : qual = transformExpr(pstate, clause, exprKind);
1892 : :
1893 : 3445 : qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1894 : :
1895 : : /* LIMIT can't refer to any variables of the current query */
1896 : 3445 : checkExprIsVarFree(pstate, qual, constructName);
1897 : :
1898 : : /*
1899 : : * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1900 : : * extremely simplistic, in that you can pass a NULL anyway by hiding it
1901 : : * inside an expression -- but this protects ruleutils against emitting an
1902 : : * unadorned NULL that's not accepted back by the grammar.
1903 : : */
1904 [ + + + + ]: 3445 : if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1905 [ + + + + ]: 38 : IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1906 [ + - ]: 4 : ereport(ERROR,
1907 : : (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1908 : : errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1909 : :
1910 : 3441 : return qual;
1911 : : }
1912 : :
1913 : : /*
1914 : : * checkExprIsVarFree
1915 : : * Check that given expr has no Vars of the current query level
1916 : : * (aggregates and window functions should have been rejected already).
1917 : : *
1918 : : * This is used to check expressions that have to have a consistent value
1919 : : * across all rows of the query, such as a LIMIT. Arguably it should reject
1920 : : * volatile functions, too, but we don't do that --- whatever value the
1921 : : * function gives on first execution is what you get.
1922 : : *
1923 : : * constructName does not affect the semantics, but is used in error messages
1924 : : */
1925 : : static void
1926 : 4771 : checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
1927 : : {
1928 [ + + ]: 4771 : if (contain_vars_of_level(n, 0))
1929 : : {
1930 [ + - ]: 4 : ereport(ERROR,
1931 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1932 : : /* translator: %s is name of a SQL construct, eg LIMIT */
1933 : : errmsg("argument of %s must not contain variables",
1934 : : constructName),
1935 : : parser_errposition(pstate,
1936 : : locate_var_of_level(n, 0))));
1937 : : }
1938 : 4767 : }
1939 : :
1940 : :
1941 : : /*
1942 : : * checkTargetlistEntrySQL92 -
1943 : : * Validate a targetlist entry found by findTargetlistEntrySQL92
1944 : : *
1945 : : * When we select a pre-existing tlist entry as a result of syntax such
1946 : : * as "GROUP BY 1", we have to make sure it is acceptable for use in the
1947 : : * indicated clause type; transformExpr() will have treated it as a regular
1948 : : * targetlist item.
1949 : : */
1950 : : static void
1951 : 49230 : checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle,
1952 : : ParseExprKind exprKind)
1953 : : {
1954 [ + + + - ]: 49230 : switch (exprKind)
1955 : : {
1956 : 514 : case EXPR_KIND_GROUP_BY:
1957 : : /* reject aggregates and window functions */
1958 [ + + - + ]: 920 : if (pstate->p_hasAggs &&
1959 : 406 : contain_aggs_of_level((Node *) tle->expr, 0))
1960 [ # # ]: 0 : ereport(ERROR,
1961 : : (errcode(ERRCODE_GROUPING_ERROR),
1962 : : /* translator: %s is name of a SQL construct, eg GROUP BY */
1963 : : errmsg("aggregate functions are not allowed in %s",
1964 : : ParseExprKindName(exprKind)),
1965 : : parser_errposition(pstate,
1966 : : locate_agg_of_level((Node *) tle->expr, 0))));
1967 [ + + + - ]: 518 : if (pstate->p_hasWindowFuncs &&
1968 : 4 : contain_windowfuncs((Node *) tle->expr))
1969 [ + - ]: 4 : ereport(ERROR,
1970 : : (errcode(ERRCODE_WINDOWING_ERROR),
1971 : : /* translator: %s is name of a SQL construct, eg GROUP BY */
1972 : : errmsg("window functions are not allowed in %s",
1973 : : ParseExprKindName(exprKind)),
1974 : : parser_errposition(pstate,
1975 : : locate_windowfunc((Node *) tle->expr))));
1976 : 510 : break;
1977 : 48508 : case EXPR_KIND_ORDER_BY:
1978 : : /* no extra checks needed */
1979 : 48508 : break;
1980 : 208 : case EXPR_KIND_DISTINCT_ON:
1981 : : /* no extra checks needed */
1982 : 208 : break;
1983 : 0 : default:
1984 [ # # ]: 0 : elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1985 : : break;
1986 : : }
1987 : 49226 : }
1988 : :
1989 : : /*
1990 : : * findTargetlistEntrySQL92 -
1991 : : * Returns the targetlist entry matching the given (untransformed) node.
1992 : : * If no matching entry exists, one is created and appended to the target
1993 : : * list as a "resjunk" node.
1994 : : *
1995 : : * This function supports the old SQL92 ORDER BY interpretation, where the
1996 : : * expression is an output column name or number. If we fail to find a
1997 : : * match of that sort, we fall through to the SQL99 rules. For historical
1998 : : * reasons, Postgres also allows this interpretation for GROUP BY, though
1999 : : * the standard never did. However, for GROUP BY we prefer a SQL99 match.
2000 : : * This function is *not* used for WINDOW definitions.
2001 : : *
2002 : : * node the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched
2003 : : * tlist the target list (passed by reference so we can append to it)
2004 : : * exprKind identifies clause type being processed
2005 : : */
2006 : : static TargetEntry *
2007 : 75233 : findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist,
2008 : : ParseExprKind exprKind)
2009 : : {
2010 : : ListCell *tl;
2011 : :
2012 : : /*----------
2013 : : * Handle two special cases as mandated by the SQL92 spec:
2014 : : *
2015 : : * 1. Bare ColumnName (no qualifier or subscripts)
2016 : : * For a bare identifier, we search for a matching column name
2017 : : * in the existing target list. Multiple matches are an error
2018 : : * unless they refer to identical values; for example,
2019 : : * we allow SELECT a, a FROM table ORDER BY a
2020 : : * but not SELECT a AS b, b FROM table ORDER BY b
2021 : : * If no match is found, we fall through and treat the identifier
2022 : : * as an expression.
2023 : : * For GROUP BY, it is incorrect to match the grouping item against
2024 : : * targetlist entries: according to SQL92, an identifier in GROUP BY
2025 : : * is a reference to a column name exposed by FROM, not to a target
2026 : : * list column. However, many implementations (including pre-7.0
2027 : : * PostgreSQL) accept this anyway. So for GROUP BY, we look first
2028 : : * to see if the identifier matches any FROM column name, and only
2029 : : * try for a targetlist name if it doesn't. This ensures that we
2030 : : * adhere to the spec in the case where the name could be both.
2031 : : * DISTINCT ON isn't in the standard, so we can do what we like there;
2032 : : * we choose to make it work like ORDER BY, on the rather flimsy
2033 : : * grounds that ordinary DISTINCT works on targetlist entries.
2034 : : *
2035 : : * 2. IntegerConstant
2036 : : * This means to use the n'th item in the existing target list.
2037 : : * Note that it would make no sense to order/group/distinct by an
2038 : : * actual constant, so this does not create a conflict with SQL99.
2039 : : * GROUP BY column-number is not allowed by SQL92, but since
2040 : : * the standard has no other behavior defined for this syntax,
2041 : : * we may as well accept this common extension.
2042 : : *
2043 : : * Note that pre-existing resjunk targets must not be used in either case,
2044 : : * since the user didn't write them in his SELECT list.
2045 : : *
2046 : : * If neither special case applies, fall through to treat the item as
2047 : : * an expression per SQL99.
2048 : : *----------
2049 : : */
2050 [ + + + + ]: 118704 : if (IsA(node, ColumnRef) &&
2051 : 43471 : list_length(((ColumnRef *) node)->fields) == 1 &&
2052 [ + - ]: 31379 : IsA(linitial(((ColumnRef *) node)->fields), String))
2053 : : {
2054 : 31379 : char *name = strVal(linitial(((ColumnRef *) node)->fields));
2055 : 31379 : int location = ((ColumnRef *) node)->location;
2056 : :
2057 [ + + ]: 31379 : if (exprKind == EXPR_KIND_GROUP_BY)
2058 : : {
2059 : : /*
2060 : : * In GROUP BY, we must prefer a match against a FROM-clause
2061 : : * column to one against the targetlist. Look to see if there is
2062 : : * a matching column. If so, fall through to use SQL99 rules.
2063 : : * NOTE: if name could refer ambiguously to more than one column
2064 : : * name exposed by FROM, colNameToVar will ereport(ERROR). That's
2065 : : * just what we want here.
2066 : : *
2067 : : * Small tweak for 7.4.3: ignore matches in upper query levels.
2068 : : * This effectively changes the search order for bare names to (1)
2069 : : * local FROM variables, (2) local targetlist aliases, (3) outer
2070 : : * FROM variables, whereas before it was (1) (3) (2). SQL92 and
2071 : : * SQL99 do not allow GROUPing BY an outer reference, so this
2072 : : * breaks no cases that are legal per spec, and it seems a more
2073 : : * self-consistent behavior.
2074 : : */
2075 [ + + ]: 3658 : if (colNameToVar(pstate, name, true, location) != NULL)
2076 : 3570 : name = NULL;
2077 : : }
2078 : :
2079 [ + + ]: 31379 : if (name != NULL)
2080 : : {
2081 : 27809 : TargetEntry *target_result = NULL;
2082 : :
2083 [ + - + + : 149814 : foreach(tl, *tlist)
+ + ]
2084 : : {
2085 : 122005 : TargetEntry *tle = (TargetEntry *) lfirst(tl);
2086 : :
2087 [ + + ]: 122005 : if (!tle->resjunk &&
2088 [ + + ]: 121541 : strcmp(tle->resname, name) == 0)
2089 : : {
2090 [ + + ]: 24192 : if (target_result != NULL)
2091 : : {
2092 [ - + ]: 6 : if (!equal(target_result->expr, tle->expr))
2093 [ # # ]: 0 : ereport(ERROR,
2094 : : (errcode(ERRCODE_AMBIGUOUS_COLUMN),
2095 : :
2096 : : /*------
2097 : : translator: first %s is name of a SQL construct, eg ORDER BY */
2098 : : errmsg("%s \"%s\" is ambiguous",
2099 : : ParseExprKindName(exprKind),
2100 : : name),
2101 : : parser_errposition(pstate, location)));
2102 : : }
2103 : : else
2104 : 24186 : target_result = tle;
2105 : : /* Stay in loop to check for ambiguity */
2106 : : }
2107 : : }
2108 [ + + ]: 27809 : if (target_result != NULL)
2109 : : {
2110 : : /* return the first match, after suitable validation */
2111 : 24186 : checkTargetlistEntrySQL92(pstate, target_result, exprKind);
2112 : 24186 : return target_result;
2113 : : }
2114 : : }
2115 : : }
2116 [ + + ]: 51047 : if (IsA(node, A_Const))
2117 : : {
2118 : 25048 : A_Const *aconst = castNode(A_Const, node);
2119 : 25048 : int targetlist_pos = 0;
2120 : : int target_pos;
2121 : :
2122 [ - + ]: 25048 : if (!IsA(&aconst->val, Integer))
2123 [ # # ]: 0 : ereport(ERROR,
2124 : : (errcode(ERRCODE_SYNTAX_ERROR),
2125 : : /* translator: %s is name of a SQL construct, eg ORDER BY */
2126 : : errmsg("non-integer constant in %s",
2127 : : ParseExprKindName(exprKind)),
2128 : : parser_errposition(pstate, aconst->location)));
2129 : :
2130 : 25048 : target_pos = intVal(&aconst->val);
2131 [ + - + + : 42057 : foreach(tl, *tlist)
+ + ]
2132 : : {
2133 : 42053 : TargetEntry *tle = (TargetEntry *) lfirst(tl);
2134 : :
2135 [ + - ]: 42053 : if (!tle->resjunk)
2136 : : {
2137 [ + + ]: 42053 : if (++targetlist_pos == target_pos)
2138 : : {
2139 : : /* return the unique match, after suitable validation */
2140 : 25044 : checkTargetlistEntrySQL92(pstate, tle, exprKind);
2141 : 25040 : return tle;
2142 : : }
2143 : : }
2144 : : }
2145 [ + - ]: 4 : ereport(ERROR,
2146 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2147 : : /* translator: %s is name of a SQL construct, eg ORDER BY */
2148 : : errmsg("%s position %d is not in select list",
2149 : : ParseExprKindName(exprKind), target_pos),
2150 : : parser_errposition(pstate, aconst->location)));
2151 : : }
2152 : :
2153 : : /*
2154 : : * Otherwise, we have an expression, so process it per SQL99 rules.
2155 : : */
2156 : 25999 : return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
2157 : : }
2158 : :
2159 : : /*
2160 : : * findTargetlistEntrySQL99 -
2161 : : * Returns the targetlist entry matching the given (untransformed) node.
2162 : : * If no matching entry exists, one is created and appended to the target
2163 : : * list as a "resjunk" node.
2164 : : *
2165 : : * This function supports the SQL99 interpretation, wherein the expression
2166 : : * is just an ordinary expression referencing input column names.
2167 : : *
2168 : : * node the ORDER BY, GROUP BY, etc expression to be matched
2169 : : * tlist the target list (passed by reference so we can append to it)
2170 : : * exprKind identifies clause type being processed
2171 : : */
2172 : : static TargetEntry *
2173 : 29997 : findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist,
2174 : : ParseExprKind exprKind)
2175 : : {
2176 : : TargetEntry *target_result;
2177 : : ListCell *tl;
2178 : : Node *expr;
2179 : :
2180 : : /*
2181 : : * Convert the untransformed node to a transformed expression, and search
2182 : : * for a match in the tlist. NOTE: it doesn't really matter whether there
2183 : : * is more than one match. Also, we are willing to match an existing
2184 : : * resjunk target here, though the SQL92 cases above must ignore resjunk
2185 : : * targets.
2186 : : */
2187 : 29997 : expr = transformExpr(pstate, node, exprKind);
2188 : :
2189 [ + + + + : 111808 : foreach(tl, *tlist)
+ + ]
2190 : : {
2191 : 94152 : TargetEntry *tle = (TargetEntry *) lfirst(tl);
2192 : : Node *texpr;
2193 : :
2194 : : /*
2195 : : * Ignore any implicit cast on the existing tlist expression.
2196 : : *
2197 : : * This essentially allows the ORDER/GROUP/etc item to adopt the same
2198 : : * datatype previously selected for a textually-equivalent tlist item.
2199 : : * There can't be any implicit cast at top level in an ordinary SELECT
2200 : : * tlist at this stage, but the case does arise with ORDER BY in an
2201 : : * aggregate function.
2202 : : */
2203 : 94152 : texpr = strip_implicit_coercions((Node *) tle->expr);
2204 : :
2205 [ + + ]: 94152 : if (equal(expr, texpr))
2206 : 12297 : return tle;
2207 : : }
2208 : :
2209 : : /*
2210 : : * If no matches, construct a new target entry which is appended to the
2211 : : * end of the target list. This target is given resjunk = true so that it
2212 : : * will not be projected into the final tuple.
2213 : : */
2214 : 17656 : target_result = transformTargetEntry(pstate, node, expr, exprKind,
2215 : : NULL, true);
2216 : :
2217 : 17656 : *tlist = lappend(*tlist, target_result);
2218 : :
2219 : 17656 : return target_result;
2220 : : }
2221 : :
2222 : : /*-------------------------------------------------------------------------
2223 : : * Flatten out parenthesized sublists in grouping lists, and some cases
2224 : : * of nested grouping sets.
2225 : : *
2226 : : * Inside a grouping set (ROLLUP, CUBE, or GROUPING SETS), we expect the
2227 : : * content to be nested no more than 2 deep: i.e. ROLLUP((a,b),(c,d)) is
2228 : : * ok, but ROLLUP((a,(b,c)),d) is flattened to ((a,b,c),d), which we then
2229 : : * (later) normalize to ((a,b,c),(d)).
2230 : : *
2231 : : * CUBE or ROLLUP can be nested inside GROUPING SETS (but not the reverse),
2232 : : * and we leave that alone if we find it. But if we see GROUPING SETS inside
2233 : : * GROUPING SETS, we can flatten and normalize as follows:
2234 : : * GROUPING SETS (a, (b,c), GROUPING SETS ((c,d),(e)), (f,g))
2235 : : * becomes
2236 : : * GROUPING SETS ((a), (b,c), (c,d), (e), (f,g))
2237 : : *
2238 : : * This is per the spec's syntax transformations, but these are the only such
2239 : : * transformations we do in parse analysis, so that queries retain the
2240 : : * originally specified grouping set syntax for CUBE and ROLLUP as much as
2241 : : * possible when deparsed. (Full expansion of the result into a list of
2242 : : * grouping sets is left to the planner.)
2243 : : *
2244 : : * When we're done, the resulting list should contain only these possible
2245 : : * elements:
2246 : : * - an expression
2247 : : * - a CUBE or ROLLUP with a list of expressions nested 2 deep
2248 : : * - a GROUPING SET containing any of:
2249 : : * - expression lists
2250 : : * - empty grouping sets
2251 : : * - CUBE or ROLLUP nodes with lists nested 2 deep
2252 : : * The return is a new list, but doesn't deep-copy the old nodes except for
2253 : : * GroupingSet nodes.
2254 : : *
2255 : : * As a side effect, flag whether the list has any GroupingSet nodes.
2256 : : *-------------------------------------------------------------------------
2257 : : */
2258 : : static Node *
2259 : 310567 : flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
2260 : : {
2261 : : /* just in case of pathological input */
2262 : 310567 : check_stack_depth();
2263 : :
2264 [ + + ]: 310567 : if (expr == (Node *) NIL)
2265 : 298059 : return (Node *) NIL;
2266 : :
2267 [ + + + + ]: 12508 : switch (expr->type)
2268 : : {
2269 : 242 : case T_RowExpr:
2270 : : {
2271 : 242 : RowExpr *r = (RowExpr *) expr;
2272 : :
2273 [ + - ]: 242 : if (r->row_format == COERCE_IMPLICIT_CAST)
2274 : 242 : return flatten_grouping_sets((Node *) r->args,
2275 : : false, NULL);
2276 : : }
2277 : 0 : break;
2278 : 1080 : case T_GroupingSet:
2279 : : {
2280 : 1080 : GroupingSet *gset = (GroupingSet *) expr;
2281 : : ListCell *l2;
2282 : 1080 : List *result_set = NIL;
2283 : :
2284 [ + + ]: 1080 : if (hasGroupingSets)
2285 : 798 : *hasGroupingSets = true;
2286 : :
2287 : : /*
2288 : : * at the top level, we skip over all empty grouping sets; the
2289 : : * caller can supply the canonical GROUP BY () if nothing is
2290 : : * left.
2291 : : */
2292 : :
2293 [ + + + + ]: 1080 : if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2294 : 28 : return (Node *) NIL;
2295 : :
2296 [ + + + + : 2756 : foreach(l2, gset->content)
+ + ]
2297 : : {
2298 : 1704 : Node *n1 = lfirst(l2);
2299 : 1704 : Node *n2 = flatten_grouping_sets(n1, false, NULL);
2300 : :
2301 [ + + ]: 1704 : if (IsA(n1, GroupingSet) &&
2302 [ + + ]: 282 : ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2303 : 68 : result_set = list_concat(result_set, (List *) n2);
2304 : : else
2305 : 1636 : result_set = lappend(result_set, n2);
2306 : : }
2307 : :
2308 : : /*
2309 : : * At top level, keep the grouping set node; but if we're in a
2310 : : * nested grouping set, then we need to concat the flattened
2311 : : * result into the outer list if it's simply nested.
2312 : : */
2313 : :
2314 [ + + + + ]: 1052 : if (toplevel || (gset->kind != GROUPING_SET_SETS))
2315 : : {
2316 : 984 : return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2317 : : }
2318 : : else
2319 : 68 : return (Node *) result_set;
2320 : : }
2321 : 4396 : case T_List:
2322 : : {
2323 : 4396 : List *result = NIL;
2324 : : ListCell *l;
2325 : :
2326 [ + - + + : 10804 : foreach(l, (List *) expr)
+ + ]
2327 : : {
2328 : 6408 : Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2329 : :
2330 [ + + ]: 6408 : if (n != (Node *) NIL)
2331 : : {
2332 [ + + ]: 6380 : if (IsA(n, List))
2333 : 30 : result = list_concat(result, (List *) n);
2334 : : else
2335 : 6350 : result = lappend(result, n);
2336 : : }
2337 : : }
2338 : :
2339 : 4396 : return (Node *) result;
2340 : : }
2341 : 6790 : default:
2342 : 6790 : break;
2343 : : }
2344 : :
2345 : 6790 : return expr;
2346 : : }
2347 : :
2348 : : /*
2349 : : * Transform a single expression within a GROUP BY clause or grouping set.
2350 : : *
2351 : : * The expression is added to the targetlist if not already present, and to the
2352 : : * flatresult list (which will become the groupClause) if not already present
2353 : : * there. The sortClause is consulted for operator and sort order hints.
2354 : : *
2355 : : * Returns the ressortgroupref of the expression.
2356 : : *
2357 : : * flatresult reference to flat list of SortGroupClause nodes
2358 : : * seen_local bitmapset of sortgrouprefs already seen at the local level
2359 : : * pstate ParseState
2360 : : * gexpr node to transform
2361 : : * targetlist reference to TargetEntry list
2362 : : * sortClause ORDER BY clause (SortGroupClause nodes)
2363 : : * exprKind expression kind
2364 : : * useSQL99 SQL99 rather than SQL92 syntax
2365 : : * toplevel false if within any grouping set
2366 : : */
2367 : : static Index
2368 : 6790 : transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local,
2369 : : ParseState *pstate, Node *gexpr,
2370 : : List **targetlist, List *sortClause,
2371 : : ParseExprKind exprKind, bool useSQL99, bool toplevel)
2372 : : {
2373 : : TargetEntry *tle;
2374 : 6790 : bool found = false;
2375 : :
2376 [ + + ]: 6790 : if (useSQL99)
2377 : 801 : tle = findTargetlistEntrySQL99(pstate, gexpr,
2378 : : targetlist, exprKind);
2379 : : else
2380 : 5989 : tle = findTargetlistEntrySQL92(pstate, gexpr,
2381 : : targetlist, exprKind);
2382 : :
2383 [ + + ]: 6770 : if (tle->ressortgroupref > 0)
2384 : : {
2385 : : ListCell *sl;
2386 : :
2387 : : /*
2388 : : * Eliminate duplicates (GROUP BY x, x) but only at local level.
2389 : : * (Duplicates in grouping sets can affect the number of returned
2390 : : * rows, so can't be dropped indiscriminately.)
2391 : : *
2392 : : * Since we don't care about anything except the sortgroupref, we can
2393 : : * use a bitmapset rather than scanning lists.
2394 : : */
2395 [ + + ]: 2052 : if (bms_is_member(tle->ressortgroupref, seen_local))
2396 : 16 : return 0;
2397 : :
2398 : : /*
2399 : : * If we're already in the flat clause list, we don't need to consider
2400 : : * adding ourselves again.
2401 : : */
2402 : 2036 : found = targetIsInSortList(tle, InvalidOid, *flatresult);
2403 [ + + ]: 2036 : if (found)
2404 : 174 : return tle->ressortgroupref;
2405 : :
2406 : : /*
2407 : : * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
2408 : : * info from the (first) matching ORDER BY item. This means that if
2409 : : * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
2410 : : * GROUP BY operation silently takes on the equality semantics implied
2411 : : * by the ORDER BY. There are two reasons to do this: it improves the
2412 : : * odds that we can implement both GROUP BY and ORDER BY with a single
2413 : : * sort step, and it allows the user to choose the equality semantics
2414 : : * used by GROUP BY, should she be working with a datatype that has
2415 : : * more than one equality operator.
2416 : : *
2417 : : * If we're in a grouping set, though, we force our requested ordering
2418 : : * to be NULLS LAST, because if we have any hope of using a sorted agg
2419 : : * for the job, we're going to be tacking on generated NULL values
2420 : : * after the corresponding groups. If the user demands nulls first,
2421 : : * another sort step is going to be inevitable, but that's the
2422 : : * planner's problem.
2423 : : */
2424 : :
2425 [ + + + + : 2525 : foreach(sl, sortClause)
+ + ]
2426 : : {
2427 : 2400 : SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2428 : :
2429 [ + + ]: 2400 : if (sc->tleSortGroupRef == tle->ressortgroupref)
2430 : : {
2431 : 1737 : SortGroupClause *grpc = copyObject(sc);
2432 : :
2433 [ + + ]: 1737 : if (!toplevel)
2434 : 466 : grpc->nulls_first = false;
2435 : 1737 : *flatresult = lappend(*flatresult, grpc);
2436 : 1737 : found = true;
2437 : 1737 : break;
2438 : : }
2439 : : }
2440 : : }
2441 : :
2442 : : /*
2443 : : * If no match in ORDER BY, just add it to the result using default
2444 : : * sort/group semantics.
2445 : : */
2446 [ + + ]: 6580 : if (!found)
2447 : 4843 : *flatresult = addTargetToGroupList(pstate, tle,
2448 : : *flatresult, *targetlist,
2449 : : exprLocation(gexpr));
2450 : :
2451 : : /*
2452 : : * _something_ must have assigned us a sortgroupref by now...
2453 : : */
2454 : :
2455 : 6580 : return tle->ressortgroupref;
2456 : : }
2457 : :
2458 : : /*
2459 : : * Transform a list of expressions within a GROUP BY clause or grouping set.
2460 : : *
2461 : : * The list of expressions belongs to a single clause within which duplicates
2462 : : * can be safely eliminated.
2463 : : *
2464 : : * Returns an integer list of ressortgroupref values.
2465 : : *
2466 : : * flatresult reference to flat list of SortGroupClause nodes
2467 : : * pstate ParseState
2468 : : * list nodes to transform
2469 : : * targetlist reference to TargetEntry list
2470 : : * sortClause ORDER BY clause (SortGroupClause nodes)
2471 : : * exprKind expression kind
2472 : : * useSQL99 SQL99 rather than SQL92 syntax
2473 : : * toplevel false if within any grouping set
2474 : : */
2475 : : static List *
2476 : 212 : transformGroupClauseList(List **flatresult,
2477 : : ParseState *pstate, List *list,
2478 : : List **targetlist, List *sortClause,
2479 : : ParseExprKind exprKind, bool useSQL99, bool toplevel)
2480 : : {
2481 : 212 : Bitmapset *seen_local = NULL;
2482 : 212 : List *result = NIL;
2483 : : ListCell *gl;
2484 : :
2485 [ + - + + : 652 : foreach(gl, list)
+ + ]
2486 : : {
2487 : 440 : Node *gexpr = (Node *) lfirst(gl);
2488 : :
2489 : 440 : Index ref = transformGroupClauseExpr(flatresult,
2490 : : seen_local,
2491 : : pstate,
2492 : : gexpr,
2493 : : targetlist,
2494 : : sortClause,
2495 : : exprKind,
2496 : : useSQL99,
2497 : : toplevel);
2498 : :
2499 [ + + ]: 440 : if (ref > 0)
2500 : : {
2501 : 432 : seen_local = bms_add_member(seen_local, ref);
2502 : 432 : result = lappend_int(result, ref);
2503 : : }
2504 : : }
2505 : :
2506 : 212 : return result;
2507 : : }
2508 : :
2509 : : /*
2510 : : * Transform a grouping set and (recursively) its content.
2511 : : *
2512 : : * The grouping set might be a GROUPING SETS node with other grouping sets
2513 : : * inside it, but SETS within SETS have already been flattened out before
2514 : : * reaching here.
2515 : : *
2516 : : * Returns the transformed node, which now contains SIMPLE nodes with lists
2517 : : * of ressortgrouprefs rather than expressions.
2518 : : *
2519 : : * flatresult reference to flat list of SortGroupClause nodes
2520 : : * pstate ParseState
2521 : : * gset grouping set to transform
2522 : : * targetlist reference to TargetEntry list
2523 : : * sortClause ORDER BY clause (SortGroupClause nodes)
2524 : : * exprKind expression kind
2525 : : * useSQL99 SQL99 rather than SQL92 syntax
2526 : : * toplevel false if within any grouping set
2527 : : */
2528 : : static Node *
2529 : 984 : transformGroupingSet(List **flatresult,
2530 : : ParseState *pstate, GroupingSet *gset,
2531 : : List **targetlist, List *sortClause,
2532 : : ParseExprKind exprKind, bool useSQL99, bool toplevel)
2533 : : {
2534 : : ListCell *gl;
2535 : 984 : List *content = NIL;
2536 : :
2537 : : Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2538 : :
2539 [ + + + + : 2620 : foreach(gl, gset->content)
+ + ]
2540 : : {
2541 : 1636 : Node *n = lfirst(gl);
2542 : :
2543 [ + + ]: 1636 : if (IsA(n, List))
2544 : : {
2545 : 212 : List *l = transformGroupClauseList(flatresult,
2546 : : pstate, (List *) n,
2547 : : targetlist, sortClause,
2548 : : exprKind, useSQL99, false);
2549 : :
2550 : 212 : content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2551 : : l,
2552 : : exprLocation(n)));
2553 : : }
2554 [ + + ]: 1424 : else if (IsA(n, GroupingSet))
2555 : : {
2556 : 214 : GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2557 : :
2558 : 214 : content = lappend(content, transformGroupingSet(flatresult,
2559 : : pstate, gset2,
2560 : : targetlist, sortClause,
2561 : : exprKind, useSQL99, false));
2562 : : }
2563 : : else
2564 : : {
2565 : 1210 : Index ref = transformGroupClauseExpr(flatresult,
2566 : : NULL,
2567 : : pstate,
2568 : : n,
2569 : : targetlist,
2570 : : sortClause,
2571 : : exprKind,
2572 : : useSQL99,
2573 : : false);
2574 : :
2575 : 1210 : content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2576 : : list_make1_int(ref),
2577 : : exprLocation(n)));
2578 : : }
2579 : : }
2580 : :
2581 : : /* Arbitrarily cap the size of CUBE, which has exponential growth */
2582 [ + + ]: 984 : if (gset->kind == GROUPING_SET_CUBE)
2583 : : {
2584 [ - + ]: 122 : if (list_length(content) > 12)
2585 [ # # ]: 0 : ereport(ERROR,
2586 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2587 : : errmsg("CUBE is limited to 12 elements"),
2588 : : parser_errposition(pstate, gset->location)));
2589 : : }
2590 : :
2591 : 984 : return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2592 : : }
2593 : :
2594 : :
2595 : : /*
2596 : : * transformGroupClause -
2597 : : * transform a GROUP BY clause
2598 : : *
2599 : : * GROUP BY items will be added to the targetlist (as resjunk columns)
2600 : : * if not already present, so the targetlist must be passed by reference.
2601 : : *
2602 : : * This is also used for window PARTITION BY clauses (which act almost the
2603 : : * same, but are always interpreted per SQL99 rules).
2604 : : *
2605 : : * Grouping sets make this a lot more complex than it was. Our goal here is
2606 : : * twofold: we make a flat list of SortGroupClause nodes referencing each
2607 : : * distinct expression used for grouping, with those expressions added to the
2608 : : * targetlist if needed. At the same time, we build the groupingSets tree,
2609 : : * which stores only ressortgrouprefs as integer lists inside GroupingSet nodes
2610 : : * (possibly nested, but limited in depth: a GROUPING_SET_SETS node can contain
2611 : : * nested SIMPLE, CUBE or ROLLUP nodes, but not more sets - we flatten that
2612 : : * out; while CUBE and ROLLUP can contain only SIMPLE nodes).
2613 : : *
2614 : : * We skip much of the hard work if there are no grouping sets.
2615 : : *
2616 : : * One subtlety is that the groupClause list can end up empty while the
2617 : : * groupingSets list is not; this happens if there are only empty grouping
2618 : : * sets, or an explicit GROUP BY (). This has the same effect as specifying
2619 : : * aggregates or a HAVING clause with no GROUP BY; the output is one row per
2620 : : * grouping set even if the input is empty.
2621 : : *
2622 : : * Returns the transformed (flat) groupClause.
2623 : : *
2624 : : * pstate ParseState
2625 : : * grouplist clause to transform
2626 : : * groupingSets reference to list to contain the grouping set tree
2627 : : * targetlist reference to TargetEntry list
2628 : : * sortClause ORDER BY clause (SortGroupClause nodes)
2629 : : * exprKind expression kind
2630 : : * useSQL99 SQL99 rather than SQL92 syntax
2631 : : */
2632 : : List *
2633 : 302213 : transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets,
2634 : : List **targetlist, List *sortClause,
2635 : : ParseExprKind exprKind, bool useSQL99)
2636 : : {
2637 : 302213 : List *result = NIL;
2638 : : List *flat_grouplist;
2639 : 302213 : List *gsets = NIL;
2640 : : ListCell *gl;
2641 : 302213 : bool hasGroupingSets = false;
2642 : 302213 : Bitmapset *seen_local = NULL;
2643 : :
2644 : : /*
2645 : : * Recursively flatten implicit RowExprs. (Technically this is only needed
2646 : : * for GROUP BY, per the syntax rules for grouping sets, but we do it
2647 : : * anyway.)
2648 : : */
2649 : 302213 : flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2650 : : true,
2651 : : &hasGroupingSets);
2652 : :
2653 : : /*
2654 : : * If the list is now empty, but hasGroupingSets is true, it's because we
2655 : : * elided redundant empty grouping sets. Restore a single empty grouping
2656 : : * set to leave a canonical form: GROUP BY ()
2657 : : */
2658 : :
2659 [ + + + + ]: 302213 : if (flat_grouplist == NIL && hasGroupingSets)
2660 : : {
2661 : 28 : flat_grouplist = list_make1(makeGroupingSet(GROUPING_SET_EMPTY,
2662 : : NIL,
2663 : : exprLocation((Node *) grouplist)));
2664 : : }
2665 : :
2666 [ + + + + : 308131 : foreach(gl, flat_grouplist)
+ + ]
2667 : : {
2668 : 5938 : Node *gexpr = (Node *) lfirst(gl);
2669 : :
2670 [ + + ]: 5938 : if (IsA(gexpr, GroupingSet))
2671 : : {
2672 : 798 : GroupingSet *gset = (GroupingSet *) gexpr;
2673 : :
2674 [ + - + - ]: 798 : switch (gset->kind)
2675 : : {
2676 : 28 : case GROUPING_SET_EMPTY:
2677 : 28 : gsets = lappend(gsets, gset);
2678 : 28 : break;
2679 : 0 : case GROUPING_SET_SIMPLE:
2680 : : /* can't happen */
2681 : : Assert(false);
2682 : 0 : break;
2683 : 770 : case GROUPING_SET_SETS:
2684 : : case GROUPING_SET_CUBE:
2685 : : case GROUPING_SET_ROLLUP:
2686 : 770 : gsets = lappend(gsets,
2687 : 770 : transformGroupingSet(&result,
2688 : : pstate, gset,
2689 : : targetlist, sortClause,
2690 : : exprKind, useSQL99, true));
2691 : 770 : break;
2692 : : }
2693 : : }
2694 : : else
2695 : : {
2696 : 5140 : Index ref = transformGroupClauseExpr(&result, seen_local,
2697 : : pstate, gexpr,
2698 : : targetlist, sortClause,
2699 : : exprKind, useSQL99, true);
2700 : :
2701 [ + + ]: 5120 : if (ref > 0)
2702 : : {
2703 : 5112 : seen_local = bms_add_member(seen_local, ref);
2704 [ + + ]: 5112 : if (hasGroupingSets)
2705 : 32 : gsets = lappend(gsets,
2706 : 32 : makeGroupingSet(GROUPING_SET_SIMPLE,
2707 : : list_make1_int(ref),
2708 : : exprLocation(gexpr)));
2709 : : }
2710 : : }
2711 : : }
2712 : :
2713 : : /* parser should prevent this */
2714 : : Assert(gsets == NIL || groupingSets != NULL);
2715 : :
2716 [ + + ]: 302193 : if (groupingSets)
2717 : 300018 : *groupingSets = gsets;
2718 : :
2719 : 302193 : return result;
2720 : : }
2721 : :
2722 : : /*
2723 : : * transformSortClause -
2724 : : * transform an ORDER BY clause
2725 : : *
2726 : : * ORDER BY items will be added to the targetlist (as resjunk columns)
2727 : : * if not already present, so the targetlist must be passed by reference.
2728 : : *
2729 : : * This is also used for window and aggregate ORDER BY clauses (which act
2730 : : * almost the same, but are always interpreted per SQL99 rules).
2731 : : */
2732 : : List *
2733 : 347190 : transformSortClause(ParseState *pstate,
2734 : : List *orderlist,
2735 : : List **targetlist,
2736 : : ParseExprKind exprKind,
2737 : : bool useSQL99)
2738 : : {
2739 : 347190 : List *sortlist = NIL;
2740 : : ListCell *olitem;
2741 : :
2742 [ + + + + : 419307 : foreach(olitem, orderlist)
+ + ]
2743 : : {
2744 : 72149 : SortBy *sortby = (SortBy *) lfirst(olitem);
2745 : : TargetEntry *tle;
2746 : :
2747 [ + + ]: 72149 : if (useSQL99)
2748 : 3197 : tle = findTargetlistEntrySQL99(pstate, sortby->node,
2749 : : targetlist, exprKind);
2750 : : else
2751 : 68952 : tle = findTargetlistEntrySQL92(pstate, sortby->node,
2752 : : targetlist, exprKind);
2753 : :
2754 : 72121 : sortlist = addTargetToSortList(pstate, tle,
2755 : : sortlist, *targetlist, sortby);
2756 : : }
2757 : :
2758 : 347158 : return sortlist;
2759 : : }
2760 : :
2761 : : /*
2762 : : * transformWindowDefinitions -
2763 : : * transform window definitions (WindowDef to WindowClause)
2764 : : */
2765 : : List *
2766 : 300002 : transformWindowDefinitions(ParseState *pstate,
2767 : : List *windowdefs,
2768 : : List **targetlist)
2769 : : {
2770 : 300002 : List *result = NIL;
2771 : 300002 : Index winref = 0;
2772 : : ListCell *lc;
2773 : :
2774 [ + + + + : 302137 : foreach(lc, windowdefs)
+ + ]
2775 : : {
2776 : 2191 : WindowDef *windef = (WindowDef *) lfirst(lc);
2777 : 2191 : WindowClause *refwc = NULL;
2778 : : List *partitionClause;
2779 : : List *orderClause;
2780 : 2191 : Oid rangeopfamily = InvalidOid;
2781 : 2191 : Oid rangeopcintype = InvalidOid;
2782 : : WindowClause *wc;
2783 : :
2784 : 2191 : winref++;
2785 : :
2786 : : /*
2787 : : * Check for duplicate window names.
2788 : : */
2789 [ + + + + ]: 2617 : if (windef->name &&
2790 : 426 : findWindowClause(result, windef->name) != NULL)
2791 [ + - ]: 4 : ereport(ERROR,
2792 : : (errcode(ERRCODE_WINDOWING_ERROR),
2793 : : errmsg("window \"%s\" is already defined", windef->name),
2794 : : parser_errposition(pstate, windef->location)));
2795 : :
2796 : : /*
2797 : : * If it references a previous window, look that up.
2798 : : */
2799 [ + + ]: 2187 : if (windef->refname)
2800 : : {
2801 : 28 : refwc = findWindowClause(result, windef->refname);
2802 [ - + ]: 28 : if (refwc == NULL)
2803 [ # # ]: 0 : ereport(ERROR,
2804 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2805 : : errmsg("window \"%s\" does not exist",
2806 : : windef->refname),
2807 : : parser_errposition(pstate, windef->location)));
2808 : : }
2809 : :
2810 : : /*
2811 : : * Transform PARTITION and ORDER specs, if any. These are treated
2812 : : * almost exactly like top-level GROUP BY and ORDER BY clauses,
2813 : : * including the special handling of nondefault operator semantics.
2814 : : */
2815 : 2187 : orderClause = transformSortClause(pstate,
2816 : : windef->orderClause,
2817 : : targetlist,
2818 : : EXPR_KIND_WINDOW_ORDER,
2819 : : true /* force SQL99 rules */ );
2820 : 2179 : partitionClause = transformGroupClause(pstate,
2821 : : windef->partitionClause,
2822 : : NULL,
2823 : : targetlist,
2824 : : orderClause,
2825 : : EXPR_KIND_WINDOW_PARTITION,
2826 : : true /* force SQL99 rules */ );
2827 : :
2828 : : /*
2829 : : * And prepare the new WindowClause.
2830 : : */
2831 : 2175 : wc = makeNode(WindowClause);
2832 : 2175 : wc->name = windef->name;
2833 : 2175 : wc->refname = windef->refname;
2834 : :
2835 : : /*
2836 : : * Per spec, a windowdef that references a previous one copies the
2837 : : * previous partition clause (and mustn't specify its own). It can
2838 : : * specify its own ordering clause, but only if the previous one had
2839 : : * none. It always specifies its own frame clause, and the previous
2840 : : * one must not have a frame clause. Yeah, it's bizarre that each of
2841 : : * these cases works differently, but SQL:2008 says so; see 7.11
2842 : : * <window clause> syntax rule 10 and general rule 1. The frame
2843 : : * clause rule is especially bizarre because it makes "OVER foo"
2844 : : * different from "OVER (foo)", and requires the latter to throw an
2845 : : * error if foo has a nondefault frame clause. Well, ours not to
2846 : : * reason why, but we do go out of our way to throw a useful error
2847 : : * message for such cases.
2848 : : */
2849 [ + + ]: 2175 : if (refwc)
2850 : : {
2851 [ - + ]: 28 : if (partitionClause)
2852 [ # # ]: 0 : ereport(ERROR,
2853 : : (errcode(ERRCODE_WINDOWING_ERROR),
2854 : : errmsg("cannot override PARTITION BY clause of window \"%s\"",
2855 : : windef->refname),
2856 : : parser_errposition(pstate, windef->location)));
2857 : 28 : wc->partitionClause = copyObject(refwc->partitionClause);
2858 : : }
2859 : : else
2860 : 2147 : wc->partitionClause = partitionClause;
2861 [ + + ]: 2175 : if (refwc)
2862 : : {
2863 [ + + - + ]: 28 : if (orderClause && refwc->orderClause)
2864 [ # # ]: 0 : ereport(ERROR,
2865 : : (errcode(ERRCODE_WINDOWING_ERROR),
2866 : : errmsg("cannot override ORDER BY clause of window \"%s\"",
2867 : : windef->refname),
2868 : : parser_errposition(pstate, windef->location)));
2869 [ + + ]: 28 : if (orderClause)
2870 : : {
2871 : 12 : wc->orderClause = orderClause;
2872 : 12 : wc->copiedOrder = false;
2873 : : }
2874 : : else
2875 : : {
2876 : 16 : wc->orderClause = copyObject(refwc->orderClause);
2877 : 16 : wc->copiedOrder = true;
2878 : : }
2879 : : }
2880 : : else
2881 : : {
2882 : 2147 : wc->orderClause = orderClause;
2883 : 2147 : wc->copiedOrder = false;
2884 : : }
2885 [ + + - + ]: 2175 : if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2886 : : {
2887 : : /*
2888 : : * Use this message if this is a WINDOW clause, or if it's an OVER
2889 : : * clause that includes ORDER BY or framing clauses. (We already
2890 : : * rejected PARTITION BY above, so no need to check that.)
2891 : : */
2892 [ # # # # ]: 0 : if (windef->name ||
2893 [ # # ]: 0 : orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2894 [ # # ]: 0 : ereport(ERROR,
2895 : : (errcode(ERRCODE_WINDOWING_ERROR),
2896 : : errmsg("cannot copy window \"%s\" because it has a frame clause",
2897 : : windef->refname),
2898 : : parser_errposition(pstate, windef->location)));
2899 : : /* Else this clause is just OVER (foo), so say this: */
2900 [ # # ]: 0 : ereport(ERROR,
2901 : : (errcode(ERRCODE_WINDOWING_ERROR),
2902 : : errmsg("cannot copy window \"%s\" because it has a frame clause",
2903 : : windef->refname),
2904 : : errhint("Omit the parentheses in this OVER clause."),
2905 : : parser_errposition(pstate, windef->location)));
2906 : : }
2907 : 2175 : wc->frameOptions = windef->frameOptions;
2908 : :
2909 : : /*
2910 : : * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2911 : : * column; check that and get its sort opfamily info.
2912 : : */
2913 [ + + ]: 2175 : if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2914 [ + + ]: 1541 : (wc->frameOptions & (FRAMEOPTION_START_OFFSET |
2915 : : FRAMEOPTION_END_OFFSET)))
2916 : : {
2917 : : SortGroupClause *sortcl;
2918 : : Node *sortkey;
2919 : : CompareType rangecmptype;
2920 : :
2921 [ + + ]: 424 : if (list_length(wc->orderClause) != 1)
2922 [ + - ]: 12 : ereport(ERROR,
2923 : : (errcode(ERRCODE_WINDOWING_ERROR),
2924 : : errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2925 : : parser_errposition(pstate, windef->location)));
2926 : 412 : sortcl = linitial_node(SortGroupClause, wc->orderClause);
2927 : 412 : sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2928 : : /* Find the sort operator in pg_amop */
2929 [ - + ]: 412 : if (!get_ordering_op_properties(sortcl->sortop,
2930 : : &rangeopfamily,
2931 : : &rangeopcintype,
2932 : : &rangecmptype))
2933 [ # # ]: 0 : elog(ERROR, "operator %u is not a valid ordering operator",
2934 : : sortcl->sortop);
2935 : : /* Record properties of sort ordering */
2936 : 412 : wc->inRangeColl = exprCollation(sortkey);
2937 : 412 : wc->inRangeAsc = !sortcl->reverse_sort;
2938 : 412 : wc->inRangeNullsFirst = sortcl->nulls_first;
2939 : : }
2940 : :
2941 : : /* Per spec, GROUPS mode requires an ORDER BY clause */
2942 [ + + ]: 2163 : if (wc->frameOptions & FRAMEOPTION_GROUPS)
2943 : : {
2944 [ + + ]: 136 : if (wc->orderClause == NIL)
2945 [ + - ]: 4 : ereport(ERROR,
2946 : : (errcode(ERRCODE_WINDOWING_ERROR),
2947 : : errmsg("GROUPS mode requires an ORDER BY clause"),
2948 : : parser_errposition(pstate, windef->location)));
2949 : : }
2950 : :
2951 : : /* Process frame offset expressions */
2952 : 2159 : wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2953 : : rangeopfamily, rangeopcintype,
2954 : : &wc->startInRangeFunc,
2955 : : windef->startOffset);
2956 : 2143 : wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2957 : : rangeopfamily, rangeopcintype,
2958 : : &wc->endInRangeFunc,
2959 : : windef->endOffset);
2960 : 2135 : wc->winref = winref;
2961 : :
2962 : 2135 : result = lappend(result, wc);
2963 : : }
2964 : :
2965 : 299946 : return result;
2966 : : }
2967 : :
2968 : : /*
2969 : : * transformDistinctClause -
2970 : : * transform a DISTINCT clause
2971 : : *
2972 : : * Since we may need to add items to the query's targetlist, that list
2973 : : * is passed by reference.
2974 : : *
2975 : : * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
2976 : : * possible into the distinctClause. This avoids a possible need to re-sort,
2977 : : * and allows the user to choose the equality semantics used by DISTINCT,
2978 : : * should she be working with a datatype that has more than one equality
2979 : : * operator.
2980 : : *
2981 : : * is_agg is true if we are transforming an aggregate(DISTINCT ...)
2982 : : * function call. This does not affect any behavior, only the phrasing
2983 : : * of error messages.
2984 : : */
2985 : : List *
2986 : 2596 : transformDistinctClause(ParseState *pstate,
2987 : : List **targetlist, List *sortClause, bool is_agg)
2988 : : {
2989 : 2596 : List *result = NIL;
2990 : : ListCell *slitem;
2991 : : ListCell *tlitem;
2992 : :
2993 : : /*
2994 : : * The distinctClause should consist of all ORDER BY items followed by all
2995 : : * other non-resjunk targetlist items. There must not be any resjunk
2996 : : * ORDER BY items --- that would imply that we are sorting by a value that
2997 : : * isn't necessarily unique within a DISTINCT group, so the results
2998 : : * wouldn't be well-defined. This construction ensures we follow the rule
2999 : : * that sortClause and distinctClause match; in fact the sortClause will
3000 : : * always be a prefix of distinctClause.
3001 : : *
3002 : : * Note a corner case: the same TLE could be in the ORDER BY list multiple
3003 : : * times with different sortops. We have to include it in the
3004 : : * distinctClause the same way to preserve the prefix property. The net
3005 : : * effect will be that the TLE value will be made unique according to both
3006 : : * sortops.
3007 : : */
3008 [ + + + + : 3011 : foreach(slitem, sortClause)
+ + ]
3009 : : {
3010 : 439 : SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
3011 : 439 : TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
3012 : :
3013 [ + + ]: 439 : if (tle->resjunk)
3014 [ + - + - ]: 24 : ereport(ERROR,
3015 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3016 : : is_agg ?
3017 : : errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
3018 : : errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
3019 : : parser_errposition(pstate,
3020 : : exprLocation((Node *) tle->expr))));
3021 : 415 : result = lappend(result, copyObject(scl));
3022 : : }
3023 : :
3024 : : /*
3025 : : * Now add any remaining non-resjunk tlist items, using default sort/group
3026 : : * semantics for their data types.
3027 : : */
3028 [ + - + + : 10162 : foreach(tlitem, *targetlist)
+ + ]
3029 : : {
3030 : 7590 : TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
3031 : :
3032 [ + + ]: 7590 : if (tle->resjunk)
3033 : 2 : continue; /* ignore junk */
3034 : 7588 : result = addTargetToGroupList(pstate, tle,
3035 : : result, *targetlist,
3036 : 7588 : exprLocation((Node *) tle->expr));
3037 : : }
3038 : :
3039 : : /*
3040 : : * Complain if we found nothing to make DISTINCT. Returning an empty list
3041 : : * would cause the parsed Query to look like it didn't have DISTINCT, with
3042 : : * results that would probably surprise the user. Note: this case is
3043 : : * presently impossible for aggregates because of grammar restrictions,
3044 : : * but we check anyway.
3045 : : */
3046 [ - + ]: 2572 : if (result == NIL)
3047 [ # # # # ]: 0 : ereport(ERROR,
3048 : : (errcode(ERRCODE_SYNTAX_ERROR),
3049 : : is_agg ?
3050 : : errmsg("an aggregate with DISTINCT must have at least one argument") :
3051 : : errmsg("SELECT DISTINCT must have at least one column")));
3052 : :
3053 : 2572 : return result;
3054 : : }
3055 : :
3056 : : /*
3057 : : * transformDistinctOnClause -
3058 : : * transform a DISTINCT ON clause
3059 : : *
3060 : : * Since we may need to add items to the query's targetlist, that list
3061 : : * is passed by reference.
3062 : : *
3063 : : * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
3064 : : * possible into the distinctClause. This avoids a possible need to re-sort,
3065 : : * and allows the user to choose the equality semantics used by DISTINCT,
3066 : : * should she be working with a datatype that has more than one equality
3067 : : * operator.
3068 : : */
3069 : : List *
3070 : 208 : transformDistinctOnClause(ParseState *pstate, List *distinctlist,
3071 : : List **targetlist, List *sortClause)
3072 : : {
3073 : 208 : List *result = NIL;
3074 : 208 : List *sortgrouprefs = NIL;
3075 : : bool skipped_sortitem;
3076 : : ListCell *lc;
3077 : : ListCell *lc2;
3078 : :
3079 : : /*
3080 : : * Add all the DISTINCT ON expressions to the tlist (if not already
3081 : : * present, they are added as resjunk items). Assign sortgroupref numbers
3082 : : * to them, and make a list of these numbers. (NB: we rely below on the
3083 : : * sortgrouprefs list being one-for-one with the original distinctlist.
3084 : : * Also notice that we could have duplicate DISTINCT ON expressions and
3085 : : * hence duplicate entries in sortgrouprefs.)
3086 : : */
3087 [ + - + + : 496 : foreach(lc, distinctlist)
+ + ]
3088 : : {
3089 : 292 : Node *dexpr = (Node *) lfirst(lc);
3090 : : int sortgroupref;
3091 : : TargetEntry *tle;
3092 : :
3093 : 292 : tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
3094 : : EXPR_KIND_DISTINCT_ON);
3095 : 288 : sortgroupref = assignSortGroupRef(tle, *targetlist);
3096 : 288 : sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
3097 : : }
3098 : :
3099 : : /*
3100 : : * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
3101 : : * semantics from ORDER BY items that match DISTINCT ON items, and also
3102 : : * adopt their column sort order. We insist that the distinctClause and
3103 : : * sortClause match, so throw error if we find the need to add any more
3104 : : * distinctClause items after we've skipped an ORDER BY item that wasn't
3105 : : * in DISTINCT ON.
3106 : : */
3107 : 204 : skipped_sortitem = false;
3108 [ + + + + : 497 : foreach(lc, sortClause)
+ + ]
3109 : : {
3110 : 297 : SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
3111 : :
3112 [ + + ]: 297 : if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
3113 : : {
3114 [ + + ]: 208 : if (skipped_sortitem)
3115 [ + - ]: 4 : ereport(ERROR,
3116 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3117 : : errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3118 : : parser_errposition(pstate,
3119 : : get_matching_location(scl->tleSortGroupRef,
3120 : : sortgrouprefs,
3121 : : distinctlist))));
3122 : : else
3123 : 204 : result = lappend(result, copyObject(scl));
3124 : : }
3125 : : else
3126 : 89 : skipped_sortitem = true;
3127 : : }
3128 : :
3129 : : /*
3130 : : * Now add any remaining DISTINCT ON items, using default sort/group
3131 : : * semantics for their data types. (Note: this is pretty questionable; if
3132 : : * the ORDER BY list doesn't include all the DISTINCT ON items and more
3133 : : * besides, you certainly aren't using DISTINCT ON in the intended way,
3134 : : * and you probably aren't going to get consistent results. It might be
3135 : : * better to throw an error or warning here. But historically we've
3136 : : * allowed it, so keep doing so.)
3137 : : */
3138 [ + - + + : 480 : forboth(lc, distinctlist, lc2, sortgrouprefs)
+ - + + +
+ + - +
+ ]
3139 : : {
3140 : 280 : Node *dexpr = (Node *) lfirst(lc);
3141 : 280 : int sortgroupref = lfirst_int(lc2);
3142 : 280 : TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3143 : :
3144 [ + + ]: 280 : if (targetIsInSortList(tle, InvalidOid, result))
3145 : 200 : continue; /* already in list (with some semantics) */
3146 [ - + ]: 80 : if (skipped_sortitem)
3147 [ # # ]: 0 : ereport(ERROR,
3148 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3149 : : errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3150 : : parser_errposition(pstate, exprLocation(dexpr))));
3151 : 80 : result = addTargetToGroupList(pstate, tle,
3152 : : result, *targetlist,
3153 : : exprLocation(dexpr));
3154 : : }
3155 : :
3156 : : /*
3157 : : * An empty result list is impossible here because of grammar
3158 : : * restrictions.
3159 : : */
3160 : : Assert(result != NIL);
3161 : :
3162 : 200 : return result;
3163 : : }
3164 : :
3165 : : /*
3166 : : * get_matching_location
3167 : : * Get the exprLocation of the exprs member corresponding to the
3168 : : * (first) member of sortgrouprefs that equals sortgroupref.
3169 : : *
3170 : : * This is used so that we can point at a troublesome DISTINCT ON entry.
3171 : : * (Note that we need to use the original untransformed DISTINCT ON list
3172 : : * item, as whatever TLE it corresponds to will very possibly have a
3173 : : * parse location pointing to some matching entry in the SELECT list
3174 : : * or ORDER BY list.)
3175 : : */
3176 : : static int
3177 : 4 : get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
3178 : : {
3179 : : ListCell *lcs;
3180 : : ListCell *lce;
3181 : :
3182 [ + - + - : 8 : forboth(lcs, sortgrouprefs, lce, exprs)
+ - + - +
- + - +
- ]
3183 : : {
3184 [ + + ]: 8 : if (lfirst_int(lcs) == sortgroupref)
3185 : 4 : return exprLocation((Node *) lfirst(lce));
3186 : : }
3187 : : /* if no match, caller blew it */
3188 [ # # ]: 0 : elog(ERROR, "get_matching_location: no matching sortgroupref");
3189 : : return -1; /* keep compiler quiet */
3190 : : }
3191 : :
3192 : : /*
3193 : : * resolve_unique_index_expr
3194 : : * Infer a unique index from a list of indexElems, for ON
3195 : : * CONFLICT clause
3196 : : *
3197 : : * Perform parse analysis of expressions and columns appearing within ON
3198 : : * CONFLICT clause. During planning, the returned list of expressions is used
3199 : : * to infer which unique index to use.
3200 : : */
3201 : : static List *
3202 : 1267 : resolve_unique_index_expr(ParseState *pstate, InferClause *infer,
3203 : : Relation heapRel)
3204 : : {
3205 : 1267 : List *result = NIL;
3206 : : ListCell *l;
3207 : :
3208 [ + - + + : 2824 : foreach(l, infer->indexElems)
+ + ]
3209 : : {
3210 : 1573 : IndexElem *ielem = (IndexElem *) lfirst(l);
3211 : 1573 : InferenceElem *pInfer = makeNode(InferenceElem);
3212 : : Node *parse;
3213 : :
3214 : : /*
3215 : : * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3216 : : * inference clause, and so will accept opclasses by name and so on.
3217 : : *
3218 : : * Make no attempt to match ASC or DESC ordering, NULLS FIRST/NULLS
3219 : : * LAST ordering or opclass options, since those are not significant
3220 : : * for inference purposes (any unique index matching the inference
3221 : : * specification in other regards is accepted indifferently). Actively
3222 : : * reject this as wrong-headed.
3223 : : */
3224 [ + + ]: 1573 : if (ielem->ordering != SORTBY_DEFAULT)
3225 [ + - ]: 4 : ereport(ERROR,
3226 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3227 : : errmsg("%s is not allowed in ON CONFLICT clause",
3228 : : "ASC/DESC"),
3229 : : parser_errposition(pstate, ielem->location)));
3230 [ + + ]: 1569 : if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3231 [ + - ]: 4 : ereport(ERROR,
3232 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3233 : : errmsg("%s is not allowed in ON CONFLICT clause",
3234 : : "NULLS FIRST/LAST"),
3235 : : parser_errposition(pstate, ielem->location)));
3236 [ + + ]: 1565 : if (ielem->opclassopts)
3237 [ + - ]: 4 : ereport(ERROR,
3238 : : errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3239 : : errmsg("operator class options are not allowed in ON CONFLICT clause"),
3240 : : parser_errposition(pstate, ielem->location));
3241 : :
3242 [ + + ]: 1561 : if (!ielem->expr)
3243 : : {
3244 : : /* Simple index attribute */
3245 : : ColumnRef *n;
3246 : :
3247 : : /*
3248 : : * Grammar won't have built raw expression for us in event of
3249 : : * plain column reference. Create one directly, and perform
3250 : : * expression transformation. Planner expects this, and performs
3251 : : * its own normalization for the purposes of matching against
3252 : : * pg_index.
3253 : : */
3254 : 1447 : n = makeNode(ColumnRef);
3255 : 1447 : n->fields = list_make1(makeString(ielem->name));
3256 : : /* Location is approximately that of inference specification */
3257 : 1447 : n->location = infer->location;
3258 : 1447 : parse = (Node *) n;
3259 : : }
3260 : : else
3261 : : {
3262 : : /* Do parse transformation of the raw expression */
3263 : 114 : parse = (Node *) ielem->expr;
3264 : : }
3265 : :
3266 : : /*
3267 : : * transformExpr() will reject subqueries, aggregates, window
3268 : : * functions, and SRFs, based on being passed
3269 : : * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3270 : : * further ... not that they would match any available index
3271 : : * expression anyway.
3272 : : */
3273 : 1561 : pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3274 : :
3275 : : /* Perform lookup of collation and operator class as required */
3276 [ + + ]: 1557 : if (!ielem->collation)
3277 : 1529 : pInfer->infercollid = InvalidOid;
3278 : : else
3279 : 28 : pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3280 : : ielem->location);
3281 : :
3282 [ + + ]: 1557 : if (!ielem->opclass)
3283 : 1529 : pInfer->inferopclass = InvalidOid;
3284 : : else
3285 : 28 : pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3286 : : ielem->opclass, false);
3287 : :
3288 : 1557 : result = lappend(result, pInfer);
3289 : : }
3290 : :
3291 : 1251 : return result;
3292 : : }
3293 : :
3294 : : /*
3295 : : * transformOnConflictArbiter -
3296 : : * transform arbiter expressions in an ON CONFLICT clause.
3297 : : *
3298 : : * Transformed expressions used to infer one unique index relation to serve as
3299 : : * an ON CONFLICT arbiter. Partial unique indexes may be inferred using WHERE
3300 : : * clause from inference specification clause.
3301 : : */
3302 : : void
3303 : 1557 : transformOnConflictArbiter(ParseState *pstate,
3304 : : OnConflictClause *onConflictClause,
3305 : : List **arbiterExpr, Node **arbiterWhere,
3306 : : Oid *constraint)
3307 : : {
3308 : 1557 : InferClause *infer = onConflictClause->infer;
3309 : :
3310 : 1557 : *arbiterExpr = NIL;
3311 : 1557 : *arbiterWhere = NULL;
3312 : 1557 : *constraint = InvalidOid;
3313 : :
3314 [ + + ]: 1557 : if ((onConflictClause->action == ONCONFLICT_UPDATE ||
3315 [ + + + + ]: 1557 : onConflictClause->action == ONCONFLICT_SELECT) && !infer)
3316 [ + - + - ]: 4 : ereport(ERROR,
3317 : : errcode(ERRCODE_SYNTAX_ERROR),
3318 : : errmsg("ON CONFLICT DO %s requires inference specification or constraint name",
3319 : : onConflictClause->action == ONCONFLICT_UPDATE ? "UPDATE" : "SELECT"),
3320 : : errhint("For example, ON CONFLICT (column_name)."),
3321 : : parser_errposition(pstate,
3322 : : exprLocation((Node *) onConflictClause)));
3323 : :
3324 : : /*
3325 : : * To simplify certain aspects of its design, speculative insertion into
3326 : : * system catalogs is disallowed
3327 : : */
3328 [ - + ]: 1553 : if (IsCatalogRelation(pstate->p_target_relation))
3329 [ # # ]: 0 : ereport(ERROR,
3330 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3331 : : errmsg("ON CONFLICT is not supported with system catalog tables"),
3332 : : parser_errposition(pstate,
3333 : : exprLocation((Node *) onConflictClause))));
3334 : :
3335 : : /* Same applies to table used by logical decoding as catalog table */
3336 [ + + + + : 1553 : if (RelationIsUsedAsCatalogTable(pstate->p_target_relation))
- + - + ]
3337 [ # # ]: 0 : ereport(ERROR,
3338 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3339 : : errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3340 : : RelationGetRelationName(pstate->p_target_relation)),
3341 : : parser_errposition(pstate,
3342 : : exprLocation((Node *) onConflictClause))));
3343 : :
3344 : : /* ON CONFLICT DO NOTHING does not require an inference clause */
3345 [ + + ]: 1553 : if (infer)
3346 : : {
3347 [ + + ]: 1405 : if (infer->indexElems)
3348 : 1267 : *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3349 : : pstate->p_target_relation);
3350 : :
3351 : : /*
3352 : : * Handling inference WHERE clause (for partial unique index
3353 : : * inference)
3354 : : */
3355 [ + + ]: 1389 : if (infer->whereClause)
3356 : 34 : *arbiterWhere = transformExpr(pstate, infer->whereClause,
3357 : : EXPR_KIND_INDEX_PREDICATE);
3358 : :
3359 : : /*
3360 : : * If the arbiter is specified by constraint name, get the constraint
3361 : : * OID and mark the constrained columns as requiring SELECT privilege,
3362 : : * in the same way as would have happened if the arbiter had been
3363 : : * specified by explicit reference to the constraint's index columns.
3364 : : */
3365 [ + + ]: 1389 : if (infer->conname)
3366 : : {
3367 : 138 : Oid relid = RelationGetRelid(pstate->p_target_relation);
3368 : 138 : RTEPermissionInfo *perminfo = pstate->p_target_nsitem->p_perminfo;
3369 : : Bitmapset *conattnos;
3370 : :
3371 : 138 : conattnos = get_relation_constraint_attnos(relid, infer->conname,
3372 : : false, constraint);
3373 : :
3374 : : /* Make sure the rel as a whole is marked for SELECT access */
3375 : 138 : perminfo->requiredPerms |= ACL_SELECT;
3376 : : /* Mark the constrained columns as requiring SELECT access */
3377 : 138 : perminfo->selectedCols = bms_add_members(perminfo->selectedCols,
3378 : : conattnos);
3379 : : }
3380 : : }
3381 : :
3382 : : /*
3383 : : * It's convenient to form a list of expressions based on the
3384 : : * representation used by CREATE INDEX, since the same restrictions are
3385 : : * appropriate (e.g. on subqueries). However, from here on, a dedicated
3386 : : * primnode representation is used for inference elements, and so
3387 : : * assign_query_collations() can be trusted to do the right thing with the
3388 : : * post parse analysis query tree inference clause representation.
3389 : : */
3390 : 1537 : }
3391 : :
3392 : : /*
3393 : : * addTargetToSortList
3394 : : * If the given targetlist entry isn't already in the SortGroupClause
3395 : : * list, add it to the end of the list, using the given sort ordering
3396 : : * info.
3397 : : *
3398 : : * Returns the updated SortGroupClause list.
3399 : : */
3400 : : List *
3401 : 72364 : addTargetToSortList(ParseState *pstate, TargetEntry *tle,
3402 : : List *sortlist, List *targetlist, SortBy *sortby)
3403 : : {
3404 : 72364 : Oid restype = exprType((Node *) tle->expr);
3405 : : Oid sortop;
3406 : : Oid eqop;
3407 : : bool hashable;
3408 : : bool reverse;
3409 : : int location;
3410 : : ParseCallbackState pcbstate;
3411 : :
3412 : : /* if tlist item is an UNKNOWN literal, change it to TEXT */
3413 [ + + ]: 72364 : if (restype == UNKNOWNOID)
3414 : : {
3415 : 8 : tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3416 : : restype, TEXTOID, -1,
3417 : : COERCION_IMPLICIT,
3418 : : COERCE_IMPLICIT_CAST,
3419 : : -1);
3420 : 8 : restype = TEXTOID;
3421 : : }
3422 : :
3423 : : /*
3424 : : * Rather than clutter the API of get_sort_group_operators and the other
3425 : : * functions we're about to use, make use of error context callback to
3426 : : * mark any error reports with a parse position. We point to the operator
3427 : : * location if present, else to the expression being sorted. (NB: use the
3428 : : * original untransformed expression here; the TLE entry might well point
3429 : : * at a duplicate expression in the regular SELECT list.)
3430 : : */
3431 : 72364 : location = sortby->location;
3432 [ + + ]: 72364 : if (location < 0)
3433 : 72222 : location = exprLocation(sortby->node);
3434 : 72364 : setup_parser_errposition_callback(&pcbstate, pstate, location);
3435 : :
3436 : : /* determine the sortop, eqop, and directionality */
3437 [ + + + - ]: 72364 : switch (sortby->sortby_dir)
3438 : : {
3439 : 69899 : case SORTBY_DEFAULT:
3440 : : case SORTBY_ASC:
3441 : 69899 : get_sort_group_operators(restype,
3442 : : true, true, false,
3443 : : &sortop, &eqop, NULL,
3444 : : &hashable);
3445 : 69895 : reverse = false;
3446 : 69895 : break;
3447 : 2323 : case SORTBY_DESC:
3448 : 2323 : get_sort_group_operators(restype,
3449 : : false, true, true,
3450 : : NULL, &eqop, &sortop,
3451 : : &hashable);
3452 : 2323 : reverse = true;
3453 : 2323 : break;
3454 : 142 : case SORTBY_USING:
3455 : : Assert(sortby->useOp != NIL);
3456 : 142 : sortop = compatible_oper_opid(sortby->useOp,
3457 : : restype,
3458 : : restype,
3459 : : false);
3460 : :
3461 : : /*
3462 : : * Verify it's a valid ordering operator, fetch the corresponding
3463 : : * equality operator, and determine whether to consider it like
3464 : : * ASC or DESC.
3465 : : */
3466 : 142 : eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3467 [ - + ]: 142 : if (!OidIsValid(eqop))
3468 [ # # ]: 0 : ereport(ERROR,
3469 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3470 : : errmsg("operator %s is not a valid ordering operator",
3471 : : strVal(llast(sortby->useOp))),
3472 : : errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3473 : :
3474 : : /*
3475 : : * Also see if the equality operator is hashable.
3476 : : */
3477 : 142 : hashable = op_hashjoinable(eqop, restype);
3478 : 142 : break;
3479 : 0 : default:
3480 [ # # ]: 0 : elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3481 : : sortop = InvalidOid; /* keep compiler quiet */
3482 : : eqop = InvalidOid;
3483 : : hashable = false;
3484 : : reverse = false;
3485 : : break;
3486 : : }
3487 : :
3488 : 72360 : cancel_parser_errposition_callback(&pcbstate);
3489 : :
3490 : : /* avoid making duplicate sortlist entries */
3491 [ + - ]: 72360 : if (!targetIsInSortList(tle, sortop, sortlist))
3492 : : {
3493 : 72360 : SortGroupClause *sortcl = makeNode(SortGroupClause);
3494 : :
3495 : 72360 : sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3496 : :
3497 : 72360 : sortcl->eqop = eqop;
3498 : 72360 : sortcl->sortop = sortop;
3499 : 72360 : sortcl->hashable = hashable;
3500 : 72360 : sortcl->reverse_sort = reverse;
3501 : :
3502 [ + + + - ]: 72360 : switch (sortby->sortby_nulls)
3503 : : {
3504 : 71265 : case SORTBY_NULLS_DEFAULT:
3505 : : /* NULLS FIRST is default for DESC; other way for ASC */
3506 : 71265 : sortcl->nulls_first = reverse;
3507 : 71265 : break;
3508 : 203 : case SORTBY_NULLS_FIRST:
3509 : 203 : sortcl->nulls_first = true;
3510 : 203 : break;
3511 : 892 : case SORTBY_NULLS_LAST:
3512 : 892 : sortcl->nulls_first = false;
3513 : 892 : break;
3514 : 0 : default:
3515 [ # # ]: 0 : elog(ERROR, "unrecognized sortby_nulls: %d",
3516 : : sortby->sortby_nulls);
3517 : : break;
3518 : : }
3519 : :
3520 : 72360 : sortlist = lappend(sortlist, sortcl);
3521 : : }
3522 : :
3523 : 72360 : return sortlist;
3524 : : }
3525 : :
3526 : : /*
3527 : : * addTargetToGroupList
3528 : : * If the given targetlist entry isn't already in the SortGroupClause
3529 : : * list, add it to the end of the list, using default sort/group
3530 : : * semantics.
3531 : : *
3532 : : * This is very similar to addTargetToSortList, except that we allow the
3533 : : * case where only a grouping (equality) operator can be found, and that
3534 : : * the TLE is considered "already in the list" if it appears there with any
3535 : : * sorting semantics.
3536 : : *
3537 : : * location is the parse location to be fingered in event of trouble. Note
3538 : : * that we can't rely on exprLocation(tle->expr), because that might point
3539 : : * to a SELECT item that matches the GROUP BY item; it'd be pretty confusing
3540 : : * to report such a location.
3541 : : *
3542 : : * Returns the updated SortGroupClause list.
3543 : : */
3544 : : static List *
3545 : 12511 : addTargetToGroupList(ParseState *pstate, TargetEntry *tle,
3546 : : List *grouplist, List *targetlist, int location)
3547 : : {
3548 : 12511 : Oid restype = exprType((Node *) tle->expr);
3549 : :
3550 : : /* if tlist item is an UNKNOWN literal, change it to TEXT */
3551 [ + + ]: 12511 : if (restype == UNKNOWNOID)
3552 : : {
3553 : 10 : tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3554 : : restype, TEXTOID, -1,
3555 : : COERCION_IMPLICIT,
3556 : : COERCE_IMPLICIT_CAST,
3557 : : -1);
3558 : 10 : restype = TEXTOID;
3559 : : }
3560 : :
3561 : : /* avoid making duplicate grouplist entries */
3562 [ + + ]: 12511 : if (!targetIsInSortList(tle, InvalidOid, grouplist))
3563 : : {
3564 : 12112 : SortGroupClause *grpcl = makeNode(SortGroupClause);
3565 : : Oid sortop;
3566 : : Oid eqop;
3567 : : bool hashable;
3568 : : ParseCallbackState pcbstate;
3569 : :
3570 : 12112 : setup_parser_errposition_callback(&pcbstate, pstate, location);
3571 : :
3572 : : /* determine the eqop and optional sortop */
3573 : 12112 : get_sort_group_operators(restype,
3574 : : false, true, false,
3575 : : &sortop, &eqop, NULL,
3576 : : &hashable);
3577 : :
3578 : 12112 : cancel_parser_errposition_callback(&pcbstate);
3579 : :
3580 : 12112 : grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3581 : 12112 : grpcl->eqop = eqop;
3582 : 12112 : grpcl->sortop = sortop;
3583 : 12112 : grpcl->reverse_sort = false; /* sortop is "less than", or
3584 : : * InvalidOid */
3585 : 12112 : grpcl->nulls_first = false; /* OK with or without sortop */
3586 : 12112 : grpcl->hashable = hashable;
3587 : :
3588 : 12112 : grouplist = lappend(grouplist, grpcl);
3589 : : }
3590 : :
3591 : 12511 : return grouplist;
3592 : : }
3593 : :
3594 : : /*
3595 : : * assignSortGroupRef
3596 : : * Assign the targetentry an unused ressortgroupref, if it doesn't
3597 : : * already have one. Return the assigned or pre-existing refnumber.
3598 : : *
3599 : : * 'tlist' is the targetlist containing (or to contain) the given targetentry.
3600 : : */
3601 : : Index
3602 : 125165 : assignSortGroupRef(TargetEntry *tle, List *tlist)
3603 : : {
3604 : : Index maxRef;
3605 : : ListCell *l;
3606 : :
3607 [ + + ]: 125165 : if (tle->ressortgroupref) /* already has one? */
3608 : 4457 : return tle->ressortgroupref;
3609 : :
3610 : : /* easiest way to pick an unused refnumber: max used + 1 */
3611 : 120708 : maxRef = 0;
3612 [ + - + + : 686554 : foreach(l, tlist)
+ + ]
3613 : : {
3614 : 565846 : Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3615 : :
3616 [ + + ]: 565846 : if (ref > maxRef)
3617 : 98026 : maxRef = ref;
3618 : : }
3619 : 120708 : tle->ressortgroupref = maxRef + 1;
3620 : 120708 : return tle->ressortgroupref;
3621 : : }
3622 : :
3623 : : /*
3624 : : * targetIsInSortList
3625 : : * Is the given target item already in the sortlist?
3626 : : * If sortop is not InvalidOid, also test for a match to the sortop.
3627 : : *
3628 : : * It is not an oversight that this function ignores the nulls_first flag.
3629 : : * We check sortop when determining if an ORDER BY item is redundant with
3630 : : * earlier ORDER BY items, because it's conceivable that "ORDER BY
3631 : : * foo USING <, foo USING <<<" is not redundant, if <<< distinguishes
3632 : : * values that < considers equal. We need not check nulls_first
3633 : : * however, because a lower-order column with the same sortop but
3634 : : * opposite nulls direction is redundant. Also, we can consider
3635 : : * ORDER BY foo ASC, foo DESC redundant, so check for a commutator match.
3636 : : *
3637 : : * Works for both ordering and grouping lists (sortop would normally be
3638 : : * InvalidOid when considering grouping). Note that the main reason we need
3639 : : * this routine (and not just a quick test for nonzeroness of ressortgroupref)
3640 : : * is that a TLE might be in only one of the lists.
3641 : : */
3642 : : bool
3643 : 90464 : targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
3644 : : {
3645 : 90464 : Index ref = tle->ressortgroupref;
3646 : : ListCell *l;
3647 : :
3648 : : /* no need to scan list if tle has no marker */
3649 [ + + ]: 90464 : if (ref == 0)
3650 : 85617 : return false;
3651 : :
3652 [ + + + + : 6317 : foreach(l, sortList)
+ + ]
3653 : : {
3654 : 3679 : SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3655 : :
3656 [ + + - + ]: 3679 : if (scl->tleSortGroupRef == ref &&
3657 : 0 : (sortop == InvalidOid ||
3658 [ # # # # ]: 0 : sortop == scl->sortop ||
3659 : 0 : sortop == get_commutator(scl->sortop)))
3660 : 2209 : return true;
3661 : : }
3662 : 2638 : return false;
3663 : : }
3664 : :
3665 : : /*
3666 : : * findWindowClause
3667 : : * Find the named WindowClause in the list, or return NULL if not there
3668 : : */
3669 : : static WindowClause *
3670 : 454 : findWindowClause(List *wclist, const char *name)
3671 : : {
3672 : : ListCell *l;
3673 : :
3674 [ + + + + : 470 : foreach(l, wclist)
+ + ]
3675 : : {
3676 : 48 : WindowClause *wc = (WindowClause *) lfirst(l);
3677 : :
3678 [ + - + + ]: 48 : if (wc->name && strcmp(wc->name, name) == 0)
3679 : 32 : return wc;
3680 : : }
3681 : :
3682 : 422 : return NULL;
3683 : : }
3684 : :
3685 : : /*
3686 : : * transformFrameOffset
3687 : : * Process a window frame offset expression
3688 : : *
3689 : : * In RANGE mode, rangeopfamily is the sort opfamily for the input ORDER BY
3690 : : * column, and rangeopcintype is the input data type the sort operator is
3691 : : * registered with. We expect the in_range function to be registered with
3692 : : * that same type. (In binary-compatible cases, it might be different from
3693 : : * the input column's actual type, so we can't use that for the lookups.)
3694 : : * We'll return the OID of the in_range function to *inRangeFunc.
3695 : : */
3696 : : static Node *
3697 : 4302 : transformFrameOffset(ParseState *pstate, int frameOptions,
3698 : : Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc,
3699 : : Node *clause)
3700 : : {
3701 : 4302 : const char *constructName = NULL;
3702 : : Node *node;
3703 : :
3704 : 4302 : *inRangeFunc = InvalidOid; /* default result */
3705 : :
3706 : : /* Quick exit if no offset expression */
3707 [ + + ]: 4302 : if (clause == NULL)
3708 : 2956 : return NULL;
3709 : :
3710 [ + + ]: 1346 : if (frameOptions & FRAMEOPTION_ROWS)
3711 : : {
3712 : : /* Transform the raw expression tree */
3713 : 374 : node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3714 : :
3715 : : /*
3716 : : * Like LIMIT clause, simply coerce to int8
3717 : : */
3718 : 370 : constructName = "ROWS";
3719 : 370 : node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3720 : : }
3721 [ + + ]: 972 : else if (frameOptions & FRAMEOPTION_RANGE)
3722 : : {
3723 : : /*
3724 : : * We must look up the in_range support function that's to be used,
3725 : : * possibly choosing one of several, and coerce the "offset" value to
3726 : : * the appropriate input type.
3727 : : */
3728 : : Oid nodeType;
3729 : : Oid preferredType;
3730 : 768 : int nfuncs = 0;
3731 : 768 : int nmatches = 0;
3732 : 768 : Oid selectedType = InvalidOid;
3733 : 768 : Oid selectedFunc = InvalidOid;
3734 : : CatCList *proclist;
3735 : : int i;
3736 : :
3737 : : /* Transform the raw expression tree */
3738 : 768 : node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3739 : 768 : nodeType = exprType(node);
3740 : :
3741 : : /*
3742 : : * If there are multiple candidates, we'll prefer the one that exactly
3743 : : * matches nodeType; or if nodeType is as yet unknown, prefer the one
3744 : : * that exactly matches the sort column type. (The second rule is
3745 : : * like what we do for "known_type operator unknown".)
3746 : : */
3747 [ + + ]: 768 : preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype;
3748 : :
3749 : : /* Find the in_range support functions applicable to this case */
3750 : 768 : proclist = SearchSysCacheList2(AMPROCNUM,
3751 : : ObjectIdGetDatum(rangeopfamily),
3752 : : ObjectIdGetDatum(rangeopcintype));
3753 [ + + ]: 5340 : for (i = 0; i < proclist->n_members; i++)
3754 : : {
3755 : 4572 : HeapTuple proctup = &proclist->members[i]->tuple;
3756 : 4572 : Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
3757 : :
3758 : : /* The search will find all support proc types; ignore others */
3759 [ + + ]: 4572 : if (procform->amprocnum != BTINRANGE_PROC)
3760 : 3400 : continue;
3761 : 1172 : nfuncs++;
3762 : :
3763 : : /* Ignore function if given value can't be coerced to that type */
3764 [ + + ]: 1172 : if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype,
3765 : : COERCION_IMPLICIT))
3766 : 220 : continue;
3767 : 952 : nmatches++;
3768 : :
3769 : : /* Remember preferred match, or any match if didn't find that */
3770 [ + + ]: 952 : if (selectedType != preferredType)
3771 : : {
3772 : 912 : selectedType = procform->amprocrighttype;
3773 : 912 : selectedFunc = procform->amproc;
3774 : : }
3775 : : }
3776 : 768 : ReleaseCatCacheList(proclist);
3777 : :
3778 : : /*
3779 : : * Throw error if needed. It seems worth taking the trouble to
3780 : : * distinguish "no support at all" from "you didn't match any
3781 : : * available offset type".
3782 : : */
3783 [ + + ]: 768 : if (nfuncs == 0)
3784 [ + - ]: 4 : ereport(ERROR,
3785 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3786 : : errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s",
3787 : : format_type_be(rangeopcintype)),
3788 : : parser_errposition(pstate, exprLocation(node))));
3789 [ + + ]: 764 : if (nmatches == 0)
3790 [ + - ]: 12 : ereport(ERROR,
3791 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3792 : : errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s",
3793 : : format_type_be(rangeopcintype),
3794 : : format_type_be(nodeType)),
3795 : : errhint("Cast the offset value to an appropriate type."),
3796 : : parser_errposition(pstate, exprLocation(node))));
3797 [ + + - + ]: 752 : if (nmatches != 1 && selectedType != preferredType)
3798 [ # # ]: 0 : ereport(ERROR,
3799 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3800 : : errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s",
3801 : : format_type_be(rangeopcintype),
3802 : : format_type_be(nodeType)),
3803 : : errhint("Cast the offset value to the exact intended type."),
3804 : : parser_errposition(pstate, exprLocation(node))));
3805 : :
3806 : : /* OK, coerce the offset to the right type */
3807 : 752 : constructName = "RANGE";
3808 : 752 : node = coerce_to_specific_type(pstate, node,
3809 : : selectedType, constructName);
3810 : 752 : *inRangeFunc = selectedFunc;
3811 : : }
3812 [ + - ]: 204 : else if (frameOptions & FRAMEOPTION_GROUPS)
3813 : : {
3814 : : /* Transform the raw expression tree */
3815 : 204 : node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS);
3816 : :
3817 : : /*
3818 : : * Like LIMIT clause, simply coerce to int8
3819 : : */
3820 : 204 : constructName = "GROUPS";
3821 : 204 : node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3822 : : }
3823 : : else
3824 : : {
3825 : : Assert(false);
3826 : 0 : node = NULL;
3827 : : }
3828 : :
3829 : : /* Disallow variables in frame offsets */
3830 : 1326 : checkExprIsVarFree(pstate, node, constructName);
3831 : :
3832 : 1322 : return node;
3833 : : }
|