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