1 /*-------------------------------------------------------------------------
4 * handle clauses in parser
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_clause.c,v 1.153 2006/07/14 14:52:21 momjian Exp $
13 *-------------------------------------------------------------------------
18 #include "access/heapam.h"
19 #include "catalog/heap.h"
20 #include "catalog/pg_type.h"
21 #include "commands/defrem.h"
22 #include "nodes/makefuncs.h"
23 #include "optimizer/clauses.h"
24 #include "optimizer/tlist.h"
25 #include "optimizer/var.h"
26 #include "parser/analyze.h"
27 #include "parser/parsetree.h"
28 #include "parser/parse_clause.h"
29 #include "parser/parse_coerce.h"
30 #include "parser/parse_expr.h"
31 #include "parser/parse_oper.h"
32 #include "parser/parse_relation.h"
33 #include "parser/parse_target.h"
34 #include "rewrite/rewriteManip.h"
35 #include "utils/guc.h"
38 #define ORDER_CLAUSE 0
39 #define GROUP_CLAUSE 1
40 #define DISTINCT_ON_CLAUSE 2
42 static char *clauseText[] = {"ORDER BY", "GROUP BY", "DISTINCT ON"};
44 static void extractRemainingColumns(List *common_colnames,
45 List *src_colnames, List *src_colvars,
46 List **res_colnames, List **res_colvars);
47 static Node *transformJoinUsingClause(ParseState *pstate,
48 List *leftVars, List *rightVars);
49 static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
53 Relids containedRels);
54 static RangeTblEntry *transformTableEntry(ParseState *pstate, RangeVar *r);
55 static RangeTblEntry *transformRangeSubselect(ParseState *pstate,
57 static RangeTblEntry *transformRangeFunction(ParseState *pstate,
59 static Node *transformFromClauseItem(ParseState *pstate, Node *n,
60 RangeTblEntry **top_rte, int *top_rti,
62 Relids *containedRels);
63 static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype,
64 Var *l_colvar, Var *r_colvar);
65 static TargetEntry *findTargetlistEntry(ParseState *pstate, Node *node,
66 List **tlist, int clause);
70 * transformFromClause -
71 * Process the FROM clause and add items to the query's range table,
72 * joinlist, and namespaces.
74 * Note: we assume that pstate's p_rtable, p_joinlist, p_relnamespace, and
75 * p_varnamespace lists were initialized to NIL when the pstate was created.
76 * We will add onto any entries already present --- this is needed for rule
77 * processing, as well as for UPDATE and DELETE.
79 * The range table may grow still further when we transform the expressions
80 * in the query's quals and target list. (This is possible because in
81 * POSTQUEL, we allowed references to relations not specified in the
82 * from-clause. PostgreSQL keeps this extension to standard SQL.)
85 transformFromClause(ParseState *pstate, List *frmList)
90 * The grammar will have produced a list of RangeVars, RangeSubselects,
91 * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
92 * entries to the rtable), check for duplicate refnames, and then add it
93 * to the joinlist and namespaces.
101 Relids containedRels;
103 n = transformFromClauseItem(pstate, n,
108 checkNameSpaceConflicts(pstate, pstate->p_relnamespace, relnamespace);
109 pstate->p_joinlist = lappend(pstate->p_joinlist, n);
110 pstate->p_relnamespace = list_concat(pstate->p_relnamespace,
112 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
113 bms_free(containedRels);
119 * Add the target relation of INSERT/UPDATE/DELETE to the range table,
120 * and make the special links to it in the ParseState.
122 * We also open the target relation and acquire a write lock on it.
123 * This must be done before processing the FROM list, in case the target
124 * is also mentioned as a source relation --- we want to be sure to grab
125 * the write lock before any read lock.
127 * If alsoSource is true, add the target to the query's joinlist and
128 * namespace. For INSERT, we don't want the target to be joined to;
129 * it's a destination of tuples, not a source. For UPDATE/DELETE,
130 * we do need to scan or join the target. (NOTE: we do not bother
131 * to check for namespace conflict; we assume that the namespace was
132 * initially empty in these cases.)
134 * Finally, we mark the relation as requiring the permissions specified
137 * Returns the rangetable index of the target relation.
140 setTargetTable(ParseState *pstate, RangeVar *relation,
141 bool inh, bool alsoSource, AclMode requiredPerms)
146 /* Close old target; this could only happen for multi-action rules */
147 if (pstate->p_target_relation != NULL)
148 heap_close(pstate->p_target_relation, NoLock);
151 * Open target rel and grab suitable lock (which we will hold till end of
154 * analyze.c will eventually do the corresponding heap_close(), but *not*
157 pstate->p_target_relation = heap_openrv(relation, RowExclusiveLock);
162 rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
163 relation->alias, inh, false);
164 pstate->p_target_rangetblentry = rte;
166 /* assume new rte is at end */
167 rtindex = list_length(pstate->p_rtable);
168 Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
171 * Override addRangeTableEntry's default ACL_SELECT permissions check, and
172 * instead mark target table as requiring exactly the specified
175 * If we find an explicit reference to the rel later during parse
176 * analysis, scanRTEForColumn will add the ACL_SELECT bit back again. That
177 * can't happen for INSERT but it is possible for UPDATE and DELETE.
179 rte->requiredPerms = requiredPerms;
182 * If UPDATE/DELETE, add table to joinlist and namespaces.
185 addRTEtoQuery(pstate, rte, true, true, true);
191 * Simplify InhOption (yes/no/default) into boolean yes/no.
193 * The reason we do things this way is that we don't want to examine the
194 * SQL_inheritance option flag until parse_analyze is run. Otherwise,
195 * we'd do the wrong thing with query strings that intermix SET commands
199 interpretInhOption(InhOption inhOpt)
208 return SQL_inheritance;
210 elog(ERROR, "bogus InhOption value: %d", inhOpt);
211 return false; /* keep compiler quiet */
215 * Given a relation-options list (of DefElems), return true iff the specified
216 * table/result set should be created with OIDs. This needs to be done after
217 * parsing the query string because the return value can depend upon the
218 * default_with_oids GUC var.
221 interpretOidsOption(List *defList)
225 /* Scan list to see if OIDS was included */
226 foreach(cell, defList)
228 DefElem *def = (DefElem *) lfirst(cell);
230 if (pg_strcasecmp(def->defname, "oids") == 0)
231 return defGetBoolean(def);
234 /* OIDS option was not specified, so use default. */
235 return default_with_oids;
239 * Extract all not-in-common columns from column lists of a source table
242 extractRemainingColumns(List *common_colnames,
243 List *src_colnames, List *src_colvars,
244 List **res_colnames, List **res_colvars)
246 List *new_colnames = NIL;
247 List *new_colvars = NIL;
251 Assert(list_length(src_colnames) == list_length(src_colvars));
253 forboth(lnames, src_colnames, lvars, src_colvars)
255 char *colname = strVal(lfirst(lnames));
259 foreach(cnames, common_colnames)
261 char *ccolname = strVal(lfirst(cnames));
263 if (strcmp(colname, ccolname) == 0)
272 new_colnames = lappend(new_colnames, lfirst(lnames));
273 new_colvars = lappend(new_colvars, lfirst(lvars));
277 *res_colnames = new_colnames;
278 *res_colvars = new_colvars;
281 /* transformJoinUsingClause()
282 * Build a complete ON clause from a partially-transformed USING list.
283 * We are given lists of nodes representing left and right match columns.
284 * Result is a transformed qualification expression.
287 transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
294 * We cheat a little bit here by building an untransformed operator tree
295 * whose leaves are the already-transformed Vars. This is OK because
296 * transformExpr() won't complain about already-transformed subnodes.
298 forboth(lvars, leftVars, rvars, rightVars)
300 Node *lvar = (Node *) lfirst(lvars);
301 Node *rvar = (Node *) lfirst(rvars);
304 e = makeSimpleA_Expr(AEXPR_OP, "=",
305 copyObject(lvar), copyObject(rvar),
314 a = makeA_Expr(AEXPR_AND, NIL, result, (Node *) e, -1);
320 * Since the references are already Vars, and are certainly from the input
321 * relations, we don't have to go through the same pushups that
322 * transformJoinOnClause() does. Just invoke transformExpr() to fix up
323 * the operators, and we're done.
325 result = transformExpr(pstate, result);
327 result = coerce_to_boolean(pstate, result, "JOIN/USING");
332 /* transformJoinOnClause()
333 * Transform the qual conditions for JOIN/ON.
334 * Result is a transformed qualification expression.
337 transformJoinOnClause(ParseState *pstate, JoinExpr *j,
338 RangeTblEntry *l_rte,
339 RangeTblEntry *r_rte,
341 Relids containedRels)
344 List *save_relnamespace;
345 List *save_varnamespace;
346 Relids clause_varnos;
350 * This is a tad tricky, for two reasons. First, the namespace that the
351 * join expression should see is just the two subtrees of the JOIN plus
352 * any outer references from upper pstate levels. So, temporarily set
353 * this pstate's namespace accordingly. (We need not check for refname
354 * conflicts, because transformFromClauseItem() already did.) NOTE: this
355 * code is OK only because the ON clause can't legally alter the namespace
356 * by causing implicit relation refs to be added.
358 save_relnamespace = pstate->p_relnamespace;
359 save_varnamespace = pstate->p_varnamespace;
361 pstate->p_relnamespace = relnamespace;
362 pstate->p_varnamespace = list_make2(l_rte, r_rte);
364 result = transformWhereClause(pstate, j->quals, "JOIN/ON");
366 pstate->p_relnamespace = save_relnamespace;
367 pstate->p_varnamespace = save_varnamespace;
370 * Second, we need to check that the ON condition doesn't refer to any
371 * rels outside the input subtrees of the JOIN. It could do that despite
372 * our hack on the namespace if it uses fully-qualified names. So, grovel
373 * through the transformed clause and make sure there are no bogus
374 * references. (Outer references are OK, and are ignored here.)
376 clause_varnos = pull_varnos(result);
377 clause_varnos = bms_del_members(clause_varnos, containedRels);
378 if ((varno = bms_first_member(clause_varnos)) >= 0)
381 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
382 errmsg("JOIN/ON clause refers to \"%s\", which is not part of JOIN",
383 rt_fetch(varno, pstate->p_rtable)->eref->aliasname)));
385 bms_free(clause_varnos);
391 * transformTableEntry --- transform a RangeVar (simple relation reference)
393 static RangeTblEntry *
394 transformTableEntry(ParseState *pstate, RangeVar *r)
399 * mark this entry to indicate it comes from the FROM clause. In SQL, the
400 * target list can only refer to range variables specified in the from
401 * clause but we follow the more powerful POSTQUEL semantics and
402 * automatically generate the range variable if not specified. However
403 * there are times we need to know whether the entries are legitimate.
405 rte = addRangeTableEntry(pstate, r, r->alias,
406 interpretInhOption(r->inhOpt), true);
413 * transformRangeSubselect --- transform a sub-SELECT appearing in FROM
415 static RangeTblEntry *
416 transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
423 * We require user to supply an alias for a subselect, per SQL92. To relax
424 * this, we'd have to be prepared to gin up a unique alias for an
425 * unlabeled subselect.
427 if (r->alias == NULL)
429 (errcode(ERRCODE_SYNTAX_ERROR),
430 errmsg("subquery in FROM must have an alias")));
433 * Analyze and transform the subquery.
435 parsetrees = parse_sub_analyze(r->subquery, pstate);
438 * Check that we got something reasonable. Most of these conditions are
439 * probably impossible given restrictions of the grammar, but check 'em
442 if (list_length(parsetrees) != 1)
443 elog(ERROR, "unexpected parse analysis result for subquery in FROM");
444 query = (Query *) linitial(parsetrees);
445 if (query == NULL || !IsA(query, Query))
446 elog(ERROR, "unexpected parse analysis result for subquery in FROM");
448 if (query->commandType != CMD_SELECT)
449 elog(ERROR, "expected SELECT query from subquery in FROM");
450 if (query->resultRelation != 0 || query->into != NULL)
452 (errcode(ERRCODE_SYNTAX_ERROR),
453 errmsg("subquery in FROM may not have SELECT INTO")));
456 * The subquery cannot make use of any variables from FROM items created
457 * earlier in the current query. Per SQL92, the scope of a FROM item does
458 * not include other FROM items. Formerly we hacked the namespace so that
459 * the other variables weren't even visible, but it seems more useful to
460 * leave them visible and give a specific error message.
462 * XXX this will need further work to support SQL99's LATERAL() feature,
463 * wherein such references would indeed be legal.
465 * We can skip groveling through the subquery if there's not anything
466 * visible in the current query. Also note that outer references are OK.
468 if (pstate->p_relnamespace || pstate->p_varnamespace)
470 if (contain_vars_of_level((Node *) query, 1))
472 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
473 errmsg("subquery in FROM may not refer to other relations of same query level")));
477 * OK, build an RTE for the subquery.
479 rte = addRangeTableEntryForSubquery(pstate, query, r->alias, true);
486 * transformRangeFunction --- transform a function call appearing in FROM
488 static RangeTblEntry *
489 transformRangeFunction(ParseState *pstate, RangeFunction *r)
496 * Get function name for possible use as alias. We use the same
497 * transformation rules as for a SELECT output expression. For a FuncCall
498 * node, the result will be the function name, but it is possible for the
499 * grammar to hand back other node types.
501 funcname = FigureColname(r->funccallnode);
504 * Transform the raw expression.
506 funcexpr = transformExpr(pstate, r->funccallnode);
509 * The function parameters cannot make use of any variables from other
510 * FROM items. (Compare to transformRangeSubselect(); the coding is
511 * different though because we didn't parse as a sub-select with its own
512 * level of namespace.)
514 * XXX this will need further work to support SQL99's LATERAL() feature,
515 * wherein such references would indeed be legal.
517 if (pstate->p_relnamespace || pstate->p_varnamespace)
519 if (contain_vars_of_level(funcexpr, 0))
521 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
522 errmsg("function expression in FROM may not refer to other relations of same query level")));
526 * Disallow aggregate functions in the expression. (No reason to postpone
527 * this check until parseCheckAggregates.)
529 if (pstate->p_hasAggs)
531 if (checkExprHasAggs(funcexpr))
533 (errcode(ERRCODE_GROUPING_ERROR),
534 errmsg("cannot use aggregate function in function expression in FROM")));
538 * OK, build an RTE for the function.
540 rte = addRangeTableEntryForFunction(pstate, funcname, funcexpr,
544 * If a coldeflist was supplied, ensure it defines a legal set of names
545 * (no duplicates) and datatypes (no pseudo-types, for instance).
546 * addRangeTableEntryForFunction looked up the type names but didn't
547 * check them further than that.
553 tupdesc = BuildDescFromLists(rte->eref->colnames,
555 rte->funccoltypmods);
556 CheckAttributeNamesTypes(tupdesc, RELKIND_COMPOSITE_TYPE);
564 * transformFromClauseItem -
565 * Transform a FROM-clause item, adding any required entries to the
566 * range table list being built in the ParseState, and return the
567 * transformed item ready to include in the joinlist and namespaces.
568 * This routine can recurse to handle SQL92 JOIN expressions.
570 * The function return value is the node to add to the jointree (a
571 * RangeTblRef or JoinExpr). Additional output parameters are:
573 * *top_rte: receives the RTE corresponding to the jointree item.
574 * (We could extract this from the function return node, but it saves cycles
575 * to pass it back separately.)
577 * *top_rti: receives the rangetable index of top_rte. (Ditto.)
579 * *relnamespace: receives a List of the RTEs exposed as relation names
582 * *containedRels: receives a bitmap set of the rangetable indexes
583 * of all the base and join relations represented in this jointree item.
584 * This is needed for checking JOIN/ON conditions in higher levels.
586 * We do not need to pass back an explicit varnamespace value, because
587 * in all cases the varnamespace contribution is exactly top_rte.
590 transformFromClauseItem(ParseState *pstate, Node *n,
591 RangeTblEntry **top_rte, int *top_rti,
593 Relids *containedRels)
595 if (IsA(n, RangeVar))
597 /* Plain relation reference */
602 rte = transformTableEntry(pstate, (RangeVar *) n);
603 /* assume new rte is at end */
604 rtindex = list_length(pstate->p_rtable);
605 Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
608 *relnamespace = list_make1(rte);
609 *containedRels = bms_make_singleton(rtindex);
610 rtr = makeNode(RangeTblRef);
611 rtr->rtindex = rtindex;
614 else if (IsA(n, RangeSubselect))
616 /* sub-SELECT is like a plain relation */
621 rte = transformRangeSubselect(pstate, (RangeSubselect *) n);
622 /* assume new rte is at end */
623 rtindex = list_length(pstate->p_rtable);
624 Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
627 *relnamespace = list_make1(rte);
628 *containedRels = bms_make_singleton(rtindex);
629 rtr = makeNode(RangeTblRef);
630 rtr->rtindex = rtindex;
633 else if (IsA(n, RangeFunction))
635 /* function is like a plain relation */
640 rte = transformRangeFunction(pstate, (RangeFunction *) n);
641 /* assume new rte is at end */
642 rtindex = list_length(pstate->p_rtable);
643 Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
646 *relnamespace = list_make1(rte);
647 *containedRels = bms_make_singleton(rtindex);
648 rtr = makeNode(RangeTblRef);
649 rtr->rtindex = rtindex;
652 else if (IsA(n, JoinExpr))
654 /* A newfangled join expression */
655 JoinExpr *j = (JoinExpr *) n;
656 RangeTblEntry *l_rte;
657 RangeTblEntry *r_rte;
660 Relids l_containedRels,
663 List *l_relnamespace,
675 * Recursively process the left and right subtrees
677 j->larg = transformFromClauseItem(pstate, j->larg,
682 j->rarg = transformFromClauseItem(pstate, j->rarg,
689 * Check for conflicting refnames in left and right subtrees. Must do
690 * this because higher levels will assume I hand back a self-
691 * consistent namespace subtree.
693 checkNameSpaceConflicts(pstate, l_relnamespace, r_relnamespace);
696 * Generate combined relation membership info for possible use by
697 * transformJoinOnClause below.
699 my_relnamespace = list_concat(l_relnamespace, r_relnamespace);
700 my_containedRels = bms_join(l_containedRels, r_containedRels);
702 pfree(r_relnamespace); /* free unneeded list header */
705 * Extract column name and var lists from both subtrees
707 * Note: expandRTE returns new lists, safe for me to modify
709 expandRTE(l_rte, l_rtindex, 0, false,
710 &l_colnames, &l_colvars);
711 expandRTE(r_rte, r_rtindex, 0, false,
712 &r_colnames, &r_colvars);
715 * Natural join does not explicitly specify columns; must generate
716 * columns to join. Need to run through the list of columns from each
717 * table or join result and match up the column names. Use the first
718 * table, and check every column in the second table for a match.
719 * (We'll check that the matches were unique later on.) The result of
720 * this step is a list of column names just like an explicitly-written
729 Assert(j->using == NIL); /* shouldn't have USING() too */
731 foreach(lx, l_colnames)
733 char *l_colname = strVal(lfirst(lx));
734 Value *m_name = NULL;
736 foreach(rx, r_colnames)
738 char *r_colname = strVal(lfirst(rx));
740 if (strcmp(l_colname, r_colname) == 0)
742 m_name = makeString(l_colname);
747 /* matched a right column? then keep as join column... */
749 rlist = lappend(rlist, m_name);
756 * Now transform the join qualifications, if any.
764 * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
765 * the list into an explicit ON-condition, and generate a list of
766 * merged result columns.
768 List *ucols = j->using;
769 List *l_usingvars = NIL;
770 List *r_usingvars = NIL;
773 Assert(j->quals == NULL); /* shouldn't have ON() too */
777 char *u_colname = strVal(lfirst(ucol));
785 /* Check for USING(foo,foo) */
786 foreach(col, res_colnames)
788 char *res_colname = strVal(lfirst(col));
790 if (strcmp(res_colname, u_colname) == 0)
792 (errcode(ERRCODE_DUPLICATE_COLUMN),
793 errmsg("column name \"%s\" appears more than once in USING clause",
797 /* Find it in left input */
799 foreach(col, l_colnames)
801 char *l_colname = strVal(lfirst(col));
803 if (strcmp(l_colname, u_colname) == 0)
807 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
808 errmsg("common column name \"%s\" appears more than once in left table",
816 (errcode(ERRCODE_UNDEFINED_COLUMN),
817 errmsg("column \"%s\" specified in USING clause does not exist in left table",
820 /* Find it in right input */
822 foreach(col, r_colnames)
824 char *r_colname = strVal(lfirst(col));
826 if (strcmp(r_colname, u_colname) == 0)
830 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
831 errmsg("common column name \"%s\" appears more than once in right table",
839 (errcode(ERRCODE_UNDEFINED_COLUMN),
840 errmsg("column \"%s\" specified in USING clause does not exist in right table",
843 l_colvar = list_nth(l_colvars, l_index);
844 l_usingvars = lappend(l_usingvars, l_colvar);
845 r_colvar = list_nth(r_colvars, r_index);
846 r_usingvars = lappend(r_usingvars, r_colvar);
848 res_colnames = lappend(res_colnames, lfirst(ucol));
849 res_colvars = lappend(res_colvars,
850 buildMergedJoinVar(pstate,
856 j->quals = transformJoinUsingClause(pstate,
862 /* User-written ON-condition; transform it */
863 j->quals = transformJoinOnClause(pstate, j,
870 /* CROSS JOIN: no quals */
873 /* Add remaining columns from each side to the output columns */
874 extractRemainingColumns(res_colnames,
875 l_colnames, l_colvars,
876 &l_colnames, &l_colvars);
877 extractRemainingColumns(res_colnames,
878 r_colnames, r_colvars,
879 &r_colnames, &r_colvars);
880 res_colnames = list_concat(res_colnames, l_colnames);
881 res_colvars = list_concat(res_colvars, l_colvars);
882 res_colnames = list_concat(res_colnames, r_colnames);
883 res_colvars = list_concat(res_colvars, r_colvars);
886 * Check alias (AS clause), if any.
890 if (j->alias->colnames != NIL)
892 if (list_length(j->alias->colnames) > list_length(res_colnames))
894 (errcode(ERRCODE_SYNTAX_ERROR),
895 errmsg("column alias list for \"%s\" has too many entries",
896 j->alias->aliasname)));
901 * Now build an RTE for the result of the join
903 rte = addRangeTableEntryForJoin(pstate,
910 /* assume new rte is at end */
911 j->rtindex = list_length(pstate->p_rtable);
912 Assert(rte == rt_fetch(j->rtindex, pstate->p_rtable));
915 *top_rti = j->rtindex;
918 * Prepare returned namespace list. If the JOIN has an alias then it
919 * hides the contained RTEs as far as the relnamespace goes;
920 * otherwise, put the contained RTEs and *not* the JOIN into
925 *relnamespace = list_make1(rte);
926 list_free(my_relnamespace);
929 *relnamespace = my_relnamespace;
932 * Include join RTE in returned containedRels set
934 *containedRels = bms_add_member(my_containedRels, j->rtindex);
939 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
940 return NULL; /* can't get here, keep compiler quiet */
944 * buildMergedJoinVar -
945 * generate a suitable replacement expression for a merged join column
948 buildMergedJoinVar(ParseState *pstate, JoinType jointype,
949 Var *l_colvar, Var *r_colvar)
958 * Choose output type if input types are dissimilar.
960 outcoltype = l_colvar->vartype;
961 outcoltypmod = l_colvar->vartypmod;
962 if (outcoltype != r_colvar->vartype)
964 outcoltype = select_common_type(list_make2_oid(l_colvar->vartype,
967 outcoltypmod = -1; /* ie, unknown */
969 else if (outcoltypmod != r_colvar->vartypmod)
971 /* same type, but not same typmod */
972 outcoltypmod = -1; /* ie, unknown */
976 * Insert coercion functions if needed. Note that a difference in typmod
977 * can only happen if input has typmod but outcoltypmod is -1. In that
978 * case we insert a RelabelType to clearly mark that result's typmod is
979 * not same as input. We never need coerce_type_typmod.
981 if (l_colvar->vartype != outcoltype)
982 l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
983 outcoltype, outcoltypmod,
984 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
985 else if (l_colvar->vartypmod != outcoltypmod)
986 l_node = (Node *) makeRelabelType((Expr *) l_colvar,
987 outcoltype, outcoltypmod,
988 COERCE_IMPLICIT_CAST);
990 l_node = (Node *) l_colvar;
992 if (r_colvar->vartype != outcoltype)
993 r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
994 outcoltype, outcoltypmod,
995 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
996 else if (r_colvar->vartypmod != outcoltypmod)
997 r_node = (Node *) makeRelabelType((Expr *) r_colvar,
998 outcoltype, outcoltypmod,
999 COERCE_IMPLICIT_CAST);
1001 r_node = (Node *) r_colvar;
1004 * Choose what to emit
1011 * We can use either var; prefer non-coerced one if available.
1013 if (IsA(l_node, Var))
1015 else if (IsA(r_node, Var))
1021 /* Always use left var */
1025 /* Always use right var */
1031 * Here we must build a COALESCE expression to ensure that the
1032 * join output is non-null if either input is.
1034 CoalesceExpr *c = makeNode(CoalesceExpr);
1036 c->coalescetype = outcoltype;
1037 c->args = list_make2(l_node, r_node);
1038 res_node = (Node *) c;
1042 elog(ERROR, "unrecognized join type: %d", (int) jointype);
1043 res_node = NULL; /* keep compiler quiet */
1052 * transformWhereClause -
1053 * Transform the qualification and make sure it is of type boolean.
1054 * Used for WHERE and allied clauses.
1056 * constructName does not affect the semantics, but is used in error messages
1059 transformWhereClause(ParseState *pstate, Node *clause,
1060 const char *constructName)
1067 qual = transformExpr(pstate, clause);
1069 qual = coerce_to_boolean(pstate, qual, constructName);
1076 * transformLimitClause -
1077 * Transform the expression and make sure it is of type integer.
1078 * Used for LIMIT and allied clauses.
1080 * constructName does not affect the semantics, but is used in error messages
1083 transformLimitClause(ParseState *pstate, Node *clause,
1084 const char *constructName)
1091 qual = transformExpr(pstate, clause);
1093 qual = coerce_to_integer(pstate, qual, constructName);
1096 * LIMIT can't refer to any vars or aggregates of the current query; we
1097 * don't allow subselects either (though that case would at least be
1100 if (contain_vars_of_level(qual, 0))
1103 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1104 /* translator: %s is name of a SQL construct, eg LIMIT */
1105 errmsg("argument of %s must not contain variables",
1108 if (checkExprHasAggs(qual))
1111 (errcode(ERRCODE_GROUPING_ERROR),
1112 /* translator: %s is name of a SQL construct, eg LIMIT */
1113 errmsg("argument of %s must not contain aggregates",
1116 if (contain_subplans(qual))
1119 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1120 /* translator: %s is name of a SQL construct, eg LIMIT */
1121 errmsg("argument of %s must not contain subqueries",
1130 * findTargetlistEntry -
1131 * Returns the targetlist entry matching the given (untransformed) node.
1132 * If no matching entry exists, one is created and appended to the target
1133 * list as a "resjunk" node.
1135 * node the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched
1136 * tlist the target list (passed by reference so we can append to it)
1137 * clause identifies clause type being processed
1139 static TargetEntry *
1140 findTargetlistEntry(ParseState *pstate, Node *node, List **tlist, int clause)
1142 TargetEntry *target_result = NULL;
1147 * Handle two special cases as mandated by the SQL92 spec:
1149 * 1. Bare ColumnName (no qualifier or subscripts)
1150 * For a bare identifier, we search for a matching column name
1151 * in the existing target list. Multiple matches are an error
1152 * unless they refer to identical values; for example,
1153 * we allow SELECT a, a FROM table ORDER BY a
1154 * but not SELECT a AS b, b FROM table ORDER BY b
1155 * If no match is found, we fall through and treat the identifier
1157 * For GROUP BY, it is incorrect to match the grouping item against
1158 * targetlist entries: according to SQL92, an identifier in GROUP BY
1159 * is a reference to a column name exposed by FROM, not to a target
1160 * list column. However, many implementations (including pre-7.0
1161 * PostgreSQL) accept this anyway. So for GROUP BY, we look first
1162 * to see if the identifier matches any FROM column name, and only
1163 * try for a targetlist name if it doesn't. This ensures that we
1164 * adhere to the spec in the case where the name could be both.
1165 * DISTINCT ON isn't in the standard, so we can do what we like there;
1166 * we choose to make it work like ORDER BY, on the rather flimsy
1167 * grounds that ordinary DISTINCT works on targetlist entries.
1169 * 2. IntegerConstant
1170 * This means to use the n'th item in the existing target list.
1171 * Note that it would make no sense to order/group/distinct by an
1172 * actual constant, so this does not create a conflict with our
1173 * extension to order/group by an expression.
1174 * GROUP BY column-number is not allowed by SQL92, but since
1175 * the standard has no other behavior defined for this syntax,
1176 * we may as well accept this common extension.
1178 * Note that pre-existing resjunk targets must not be used in either case,
1179 * since the user didn't write them in his SELECT list.
1181 * If neither special case applies, fall through to treat the item as
1185 if (IsA(node, ColumnRef) &&
1186 list_length(((ColumnRef *) node)->fields) == 1)
1188 char *name = strVal(linitial(((ColumnRef *) node)->fields));
1189 int location = ((ColumnRef *) node)->location;
1191 if (clause == GROUP_CLAUSE)
1194 * In GROUP BY, we must prefer a match against a FROM-clause
1195 * column to one against the targetlist. Look to see if there is
1196 * a matching column. If so, fall through to let transformExpr()
1197 * do the rest. NOTE: if name could refer ambiguously to more
1198 * than one column name exposed by FROM, colNameToVar will
1199 * ereport(ERROR). That's just what we want here.
1201 * Small tweak for 7.4.3: ignore matches in upper query levels.
1202 * This effectively changes the search order for bare names to (1)
1203 * local FROM variables, (2) local targetlist aliases, (3) outer
1204 * FROM variables, whereas before it was (1) (3) (2). SQL92 and
1205 * SQL99 do not allow GROUPing BY an outer reference, so this
1206 * breaks no cases that are legal per spec, and it seems a more
1207 * self-consistent behavior.
1209 if (colNameToVar(pstate, name, true, location) != NULL)
1217 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1219 if (!tle->resjunk &&
1220 strcmp(tle->resname, name) == 0)
1222 if (target_result != NULL)
1224 if (!equal(target_result->expr, tle->expr))
1226 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1229 * translator: first %s is name of a SQL
1230 * construct, eg ORDER BY
1232 errmsg("%s \"%s\" is ambiguous",
1233 clauseText[clause], name),
1234 parser_errposition(pstate, location)));
1237 target_result = tle;
1238 /* Stay in loop to check for ambiguity */
1241 if (target_result != NULL)
1242 return target_result; /* return the first match */
1245 if (IsA(node, A_Const))
1247 Value *val = &((A_Const *) node)->val;
1248 int targetlist_pos = 0;
1251 if (!IsA(val, Integer))
1253 (errcode(ERRCODE_SYNTAX_ERROR),
1254 /* translator: %s is name of a SQL construct, eg ORDER BY */
1255 errmsg("non-integer constant in %s",
1256 clauseText[clause])));
1257 target_pos = intVal(val);
1260 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1264 if (++targetlist_pos == target_pos)
1265 return tle; /* return the unique match */
1269 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1270 /* translator: %s is name of a SQL construct, eg ORDER BY */
1271 errmsg("%s position %d is not in select list",
1272 clauseText[clause], target_pos)));
1276 * Otherwise, we have an expression (this is a Postgres extension not
1277 * found in SQL92). Convert the untransformed node to a transformed
1278 * expression, and search for a match in the tlist. NOTE: it doesn't
1279 * really matter whether there is more than one match. Also, we are
1280 * willing to match a resjunk target here, though the above cases must
1281 * ignore resjunk targets.
1283 expr = transformExpr(pstate, node);
1287 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1289 if (equal(expr, tle->expr))
1294 * If no matches, construct a new target entry which is appended to the
1295 * end of the target list. This target is given resjunk = TRUE so that it
1296 * will not be projected into the final tuple.
1298 target_result = transformTargetEntry(pstate, node, expr, NULL, true);
1300 *tlist = lappend(*tlist, target_result);
1302 return target_result;
1305 static GroupClause *
1306 make_group_clause(TargetEntry *tle, List *targetlist, Oid sortop)
1308 GroupClause *result;
1310 result = makeNode(GroupClause);
1311 result->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
1312 result->sortop = sortop;
1317 * transformGroupClause -
1318 * transform a GROUP BY clause
1320 * GROUP BY items will be added to the targetlist (as resjunk columns)
1321 * if not already present, so the targetlist must be passed by reference.
1323 * The order of the elements of the grouping clause does not affect
1324 * the semantics of the query. However, the optimizer is not currently
1325 * smart enough to reorder the grouping clause, so we try to do some
1326 * primitive reordering here.
1329 transformGroupClause(ParseState *pstate, List *grouplist,
1330 List **targetlist, List *sortClause)
1333 List *tle_list = NIL;
1336 /* Preprocess the grouping clause, lookup TLEs */
1337 foreach (l, grouplist)
1342 tle = findTargetlistEntry(pstate, lfirst(l),
1343 targetlist, GROUP_CLAUSE);
1345 /* if tlist item is an UNKNOWN literal, change it to TEXT */
1346 restype = exprType((Node *) tle->expr);
1348 if (restype == UNKNOWNOID)
1349 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
1350 restype, TEXTOID, -1,
1352 COERCE_IMPLICIT_CAST);
1354 tle_list = lappend(tle_list, tle);
1358 * Now iterate through the ORDER BY clause. If we find a grouping
1359 * element that matches the ORDER BY element, append the grouping
1360 * element to the result set immediately. Otherwise, stop
1361 * iterating. The effect of this is to look for a prefix of the
1362 * ORDER BY list in the grouping clauses, and to move that prefix
1363 * to the front of the GROUP BY.
1365 foreach (l, sortClause)
1367 SortClause *sc = (SortClause *) lfirst(l);
1368 ListCell *prev = NULL;
1372 foreach (tl, tle_list)
1374 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1376 if (sc->tleSortGroupRef == tle->ressortgroupref)
1380 tle_list = list_delete_cell(tle_list, tl, prev);
1382 /* Use the sort clause's sorting operator */
1383 gc = make_group_clause(tle, *targetlist, sc->sortop);
1384 result = lappend(result, gc);
1392 /* As soon as we've failed to match an ORDER BY element, stop */
1398 * Now add any remaining elements of the GROUP BY list in the
1399 * order we received them.
1401 * XXX: are there any additional criteria to consider when
1402 * ordering grouping clauses?
1404 foreach(l, tle_list)
1406 TargetEntry *tle = (TargetEntry *) lfirst(l);
1410 /* avoid making duplicate grouplist entries */
1411 if (targetIsInSortList(tle, result))
1414 sort_op = ordering_oper_opid(exprType((Node *) tle->expr));
1415 gc = make_group_clause(tle, *targetlist, sort_op);
1416 result = lappend(result, gc);
1419 list_free(tle_list);
1424 * transformSortClause -
1425 * transform an ORDER BY clause
1427 * ORDER BY items will be added to the targetlist (as resjunk columns)
1428 * if not already present, so the targetlist must be passed by reference.
1431 transformSortClause(ParseState *pstate,
1434 bool resolveUnknown)
1436 List *sortlist = NIL;
1439 foreach(olitem, orderlist)
1441 SortBy *sortby = lfirst(olitem);
1444 tle = findTargetlistEntry(pstate, sortby->node,
1445 targetlist, ORDER_CLAUSE);
1447 sortlist = addTargetToSortList(pstate, tle,
1448 sortlist, *targetlist,
1449 sortby->sortby_kind,
1458 * transformDistinctClause -
1459 * transform a DISTINCT or DISTINCT ON clause
1461 * Since we may need to add items to the query's sortClause list, that list
1462 * is passed by reference. Likewise for the targetlist.
1465 transformDistinctClause(ParseState *pstate, List *distinctlist,
1466 List **targetlist, List **sortClause)
1472 /* No work if there was no DISTINCT clause */
1473 if (distinctlist == NIL)
1476 if (linitial(distinctlist) == NULL)
1478 /* We had SELECT DISTINCT */
1481 * All non-resjunk elements from target list that are not already in
1482 * the sort list should be added to it. (We don't really care what
1483 * order the DISTINCT fields are checked in, so we can leave the
1484 * user's ORDER BY spec alone, and just add additional sort keys to it
1485 * to ensure that all targetlist items get sorted.)
1487 *sortClause = addAllTargetsToSortList(pstate,
1493 * Now, DISTINCT list consists of all non-resjunk sortlist items.
1494 * Actually, all the sortlist items had better be non-resjunk!
1495 * Otherwise, user wrote SELECT DISTINCT with an ORDER BY item that
1496 * does not appear anywhere in the SELECT targetlist, and we can't
1497 * implement that with only one sorting pass...
1499 foreach(slitem, *sortClause)
1501 SortClause *scl = (SortClause *) lfirst(slitem);
1502 TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
1506 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1507 errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list")));
1509 result = lappend(result, copyObject(scl));
1514 /* We had SELECT DISTINCT ON (expr, ...) */
1517 * If the user writes both DISTINCT ON and ORDER BY, then the two
1518 * expression lists must match (until one or the other runs out).
1519 * Otherwise the ORDER BY requires a different sort order than the
1520 * DISTINCT does, and we can't implement that with only one sort pass
1521 * (and if we do two passes, the results will be rather
1522 * unpredictable). However, it's OK to have more DISTINCT ON
1523 * expressions than ORDER BY expressions; we can just add the extra
1524 * DISTINCT values to the sort list, much as we did above for ordinary
1527 * Actually, it'd be OK for the common prefixes of the two lists to
1528 * match in any order, but implementing that check seems like more
1529 * trouble than it's worth.
1531 ListCell *nextsortlist = list_head(*sortClause);
1533 foreach(dlitem, distinctlist)
1537 tle = findTargetlistEntry(pstate, lfirst(dlitem),
1538 targetlist, DISTINCT_ON_CLAUSE);
1540 if (nextsortlist != NULL)
1542 SortClause *scl = (SortClause *) lfirst(nextsortlist);
1544 if (tle->ressortgroupref != scl->tleSortGroupRef)
1546 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1547 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions")));
1548 result = lappend(result, copyObject(scl));
1549 nextsortlist = lnext(nextsortlist);
1553 *sortClause = addTargetToSortList(pstate, tle,
1554 *sortClause, *targetlist,
1555 SORTBY_ASC, NIL, true);
1558 * Probably, the tle should always have been added at the end
1559 * of the sort list ... but search to be safe.
1561 foreach(slitem, *sortClause)
1563 SortClause *scl = (SortClause *) lfirst(slitem);
1565 if (tle->ressortgroupref == scl->tleSortGroupRef)
1567 result = lappend(result, copyObject(scl));
1571 if (slitem == NULL) /* should not happen */
1572 elog(ERROR, "failed to add DISTINCT ON clause to target list");
1581 * addAllTargetsToSortList
1582 * Make sure all non-resjunk targets in the targetlist are in the
1583 * ORDER BY list, adding the not-yet-sorted ones to the end of the list.
1584 * This is typically used to help implement SELECT DISTINCT.
1586 * See addTargetToSortList for info about pstate and resolveUnknown inputs.
1588 * Returns the updated ORDER BY list.
1591 addAllTargetsToSortList(ParseState *pstate, List *sortlist,
1592 List *targetlist, bool resolveUnknown)
1596 foreach(l, targetlist)
1598 TargetEntry *tle = (TargetEntry *) lfirst(l);
1601 sortlist = addTargetToSortList(pstate, tle,
1602 sortlist, targetlist,
1610 * addTargetToSortList
1611 * If the given targetlist entry isn't already in the ORDER BY list,
1612 * add it to the end of the list, using the sortop with given name
1613 * or the default sort operator if opname == NIL.
1615 * If resolveUnknown is TRUE, convert TLEs of type UNKNOWN to TEXT. If not,
1616 * do nothing (which implies the search for a sort operator will fail).
1617 * pstate should be provided if resolveUnknown is TRUE, but can be NULL
1620 * Returns the updated ORDER BY list.
1623 addTargetToSortList(ParseState *pstate, TargetEntry *tle,
1624 List *sortlist, List *targetlist,
1625 int sortby_kind, List *sortby_opname,
1626 bool resolveUnknown)
1628 /* avoid making duplicate sortlist entries */
1629 if (!targetIsInSortList(tle, sortlist))
1631 SortClause *sortcl = makeNode(SortClause);
1632 Oid restype = exprType((Node *) tle->expr);
1634 /* if tlist item is an UNKNOWN literal, change it to TEXT */
1635 if (restype == UNKNOWNOID && resolveUnknown)
1637 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
1638 restype, TEXTOID, -1,
1640 COERCE_IMPLICIT_CAST);
1644 sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
1646 switch (sortby_kind)
1649 sortcl->sortop = ordering_oper_opid(restype);
1652 sortcl->sortop = reverse_ordering_oper_opid(restype);
1655 Assert(sortby_opname != NIL);
1656 sortcl->sortop = compatible_oper_opid(sortby_opname,
1662 elog(ERROR, "unrecognized sortby_kind: %d", sortby_kind);
1666 sortlist = lappend(sortlist, sortcl);
1672 * assignSortGroupRef
1673 * Assign the targetentry an unused ressortgroupref, if it doesn't
1674 * already have one. Return the assigned or pre-existing refnumber.
1676 * 'tlist' is the targetlist containing (or to contain) the given targetentry.
1679 assignSortGroupRef(TargetEntry *tle, List *tlist)
1684 if (tle->ressortgroupref) /* already has one? */
1685 return tle->ressortgroupref;
1687 /* easiest way to pick an unused refnumber: max used + 1 */
1691 Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
1696 tle->ressortgroupref = maxRef + 1;
1697 return tle->ressortgroupref;
1701 * targetIsInSortList
1702 * Is the given target item already in the sortlist?
1704 * Works for both SortClause and GroupClause lists. Note that the main
1705 * reason we need this routine (and not just a quick test for nonzeroness
1706 * of ressortgroupref) is that a TLE might be in only one of the lists.
1709 targetIsInSortList(TargetEntry *tle, List *sortList)
1711 Index ref = tle->ressortgroupref;
1714 /* no need to scan list if tle has no marker */
1718 foreach(l, sortList)
1720 SortClause *scl = (SortClause *) lfirst(l);
1722 if (scl->tleSortGroupRef == ref)