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