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