1 /*-------------------------------------------------------------------------
4 * handle clauses in parser
6 * Portions Copyright (c) 1996-2008, 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.172 2008/08/02 21:32:00 tgl 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"
36 #include "utils/lsyscache.h"
37 #include "utils/rel.h"
40 #define ORDER_CLAUSE 0
41 #define GROUP_CLAUSE 1
42 #define DISTINCT_ON_CLAUSE 2
44 static char *clauseText[] = {"ORDER BY", "GROUP BY", "DISTINCT ON"};
46 static void extractRemainingColumns(List *common_colnames,
47 List *src_colnames, List *src_colvars,
48 List **res_colnames, List **res_colvars);
49 static Node *transformJoinUsingClause(ParseState *pstate,
50 List *leftVars, List *rightVars);
51 static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
55 Relids containedRels);
56 static RangeTblEntry *transformTableEntry(ParseState *pstate, RangeVar *r);
57 static RangeTblEntry *transformRangeSubselect(ParseState *pstate,
59 static RangeTblEntry *transformRangeFunction(ParseState *pstate,
61 static Node *transformFromClauseItem(ParseState *pstate, Node *n,
62 RangeTblEntry **top_rte, int *top_rti,
64 Relids *containedRels);
65 static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype,
66 Var *l_colvar, Var *r_colvar);
67 static TargetEntry *findTargetlistEntry(ParseState *pstate, Node *node,
68 List **tlist, int clause);
69 static List *addTargetToSortList(ParseState *pstate, TargetEntry *tle,
70 List *sortlist, List *targetlist,
71 SortByDir sortby_dir, SortByNulls sortby_nulls,
72 List *sortby_opname, bool resolveUnknown);
76 * transformFromClause -
77 * Process the FROM clause and add items to the query's range table,
78 * joinlist, and namespaces.
80 * Note: we assume that pstate's p_rtable, p_joinlist, p_relnamespace, and
81 * p_varnamespace lists were initialized to NIL when the pstate was created.
82 * We will add onto any entries already present --- this is needed for rule
83 * processing, as well as for UPDATE and DELETE.
85 * The range table may grow still further when we transform the expressions
86 * in the query's quals and target list. (This is possible because in
87 * POSTQUEL, we allowed references to relations not specified in the
88 * from-clause. PostgreSQL keeps this extension to standard SQL.)
91 transformFromClause(ParseState *pstate, List *frmList)
96 * The grammar will have produced a list of RangeVars, RangeSubselects,
97 * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
98 * entries to the rtable), check for duplicate refnames, and then add it
99 * to the joinlist and namespaces.
103 Node *n = lfirst(fl);
107 Relids containedRels;
109 n = transformFromClauseItem(pstate, n,
114 checkNameSpaceConflicts(pstate, pstate->p_relnamespace, relnamespace);
115 pstate->p_joinlist = lappend(pstate->p_joinlist, n);
116 pstate->p_relnamespace = list_concat(pstate->p_relnamespace,
118 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
119 bms_free(containedRels);
125 * Add the target relation of INSERT/UPDATE/DELETE to the range table,
126 * and make the special links to it in the ParseState.
128 * We also open the target relation and acquire a write lock on it.
129 * This must be done before processing the FROM list, in case the target
130 * is also mentioned as a source relation --- we want to be sure to grab
131 * the write lock before any read lock.
133 * If alsoSource is true, add the target to the query's joinlist and
134 * namespace. For INSERT, we don't want the target to be joined to;
135 * it's a destination of tuples, not a source. For UPDATE/DELETE,
136 * we do need to scan or join the target. (NOTE: we do not bother
137 * to check for namespace conflict; we assume that the namespace was
138 * initially empty in these cases.)
140 * Finally, we mark the relation as requiring the permissions specified
143 * Returns the rangetable index of the target relation.
146 setTargetTable(ParseState *pstate, RangeVar *relation,
147 bool inh, bool alsoSource, AclMode requiredPerms)
152 /* Close old target; this could only happen for multi-action rules */
153 if (pstate->p_target_relation != NULL)
154 heap_close(pstate->p_target_relation, NoLock);
157 * Open target rel and grab suitable lock (which we will hold till end of
160 * free_parsestate() will eventually do the corresponding heap_close(),
161 * but *not* release the lock.
163 pstate->p_target_relation = heap_openrv(relation, RowExclusiveLock);
168 rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
169 relation->alias, inh, false);
170 pstate->p_target_rangetblentry = rte;
172 /* assume new rte is at end */
173 rtindex = list_length(pstate->p_rtable);
174 Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
177 * Override addRangeTableEntry's default ACL_SELECT permissions check, and
178 * instead mark target table as requiring exactly the specified
181 * If we find an explicit reference to the rel later during parse
182 * analysis, we will add the ACL_SELECT bit back again; see
183 * scanRTEForColumn (for simple field references), ExpandColumnRefStar
184 * (for foo.*) and ExpandAllTables (for *).
186 rte->requiredPerms = requiredPerms;
189 * If UPDATE/DELETE, add table to joinlist and namespaces.
192 addRTEtoQuery(pstate, rte, true, true, true);
198 * Simplify InhOption (yes/no/default) into boolean yes/no.
200 * The reason we do things this way is that we don't want to examine the
201 * SQL_inheritance option flag until parse_analyze() is run. Otherwise,
202 * we'd do the wrong thing with query strings that intermix SET commands
206 interpretInhOption(InhOption inhOpt)
215 return SQL_inheritance;
217 elog(ERROR, "bogus InhOption value: %d", inhOpt);
218 return false; /* keep compiler quiet */
222 * Given a relation-options list (of DefElems), return true iff the specified
223 * table/result set should be created with OIDs. This needs to be done after
224 * parsing the query string because the return value can depend upon the
225 * default_with_oids GUC var.
228 interpretOidsOption(List *defList)
232 /* Scan list to see if OIDS was included */
233 foreach(cell, defList)
235 DefElem *def = (DefElem *) lfirst(cell);
237 if (pg_strcasecmp(def->defname, "oids") == 0)
238 return defGetBoolean(def);
241 /* OIDS option was not specified, so use default. */
242 return default_with_oids;
246 * Extract all not-in-common columns from column lists of a source table
249 extractRemainingColumns(List *common_colnames,
250 List *src_colnames, List *src_colvars,
251 List **res_colnames, List **res_colvars)
253 List *new_colnames = NIL;
254 List *new_colvars = NIL;
258 Assert(list_length(src_colnames) == list_length(src_colvars));
260 forboth(lnames, src_colnames, lvars, src_colvars)
262 char *colname = strVal(lfirst(lnames));
266 foreach(cnames, common_colnames)
268 char *ccolname = strVal(lfirst(cnames));
270 if (strcmp(colname, ccolname) == 0)
279 new_colnames = lappend(new_colnames, lfirst(lnames));
280 new_colvars = lappend(new_colvars, lfirst(lvars));
284 *res_colnames = new_colnames;
285 *res_colvars = new_colvars;
288 /* transformJoinUsingClause()
289 * Build a complete ON clause from a partially-transformed USING list.
290 * We are given lists of nodes representing left and right match columns.
291 * Result is a transformed qualification expression.
294 transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
301 * We cheat a little bit here by building an untransformed operator tree
302 * whose leaves are the already-transformed Vars. This is OK because
303 * transformExpr() won't complain about already-transformed subnodes.
305 forboth(lvars, leftVars, rvars, rightVars)
307 Node *lvar = (Node *) lfirst(lvars);
308 Node *rvar = (Node *) lfirst(rvars);
311 e = makeSimpleA_Expr(AEXPR_OP, "=",
312 copyObject(lvar), copyObject(rvar),
321 a = makeA_Expr(AEXPR_AND, NIL, result, (Node *) e, -1);
327 * Since the references are already Vars, and are certainly from the input
328 * relations, we don't have to go through the same pushups that
329 * transformJoinOnClause() does. Just invoke transformExpr() to fix up
330 * the operators, and we're done.
332 result = transformExpr(pstate, result);
334 result = coerce_to_boolean(pstate, result, "JOIN/USING");
339 /* transformJoinOnClause()
340 * Transform the qual conditions for JOIN/ON.
341 * Result is a transformed qualification expression.
344 transformJoinOnClause(ParseState *pstate, JoinExpr *j,
345 RangeTblEntry *l_rte,
346 RangeTblEntry *r_rte,
348 Relids containedRels)
351 List *save_relnamespace;
352 List *save_varnamespace;
353 Relids clause_varnos;
357 * This is a tad tricky, for two reasons. First, the namespace that the
358 * join expression should see is just the two subtrees of the JOIN plus
359 * any outer references from upper pstate levels. So, temporarily set
360 * this pstate's namespace accordingly. (We need not check for refname
361 * conflicts, because transformFromClauseItem() already did.) NOTE: this
362 * code is OK only because the ON clause can't legally alter the namespace
363 * by causing implicit relation refs to be added.
365 save_relnamespace = pstate->p_relnamespace;
366 save_varnamespace = pstate->p_varnamespace;
368 pstate->p_relnamespace = relnamespace;
369 pstate->p_varnamespace = list_make2(l_rte, r_rte);
371 result = transformWhereClause(pstate, j->quals, "JOIN/ON");
373 pstate->p_relnamespace = save_relnamespace;
374 pstate->p_varnamespace = save_varnamespace;
377 * Second, we need to check that the ON condition doesn't refer to any
378 * rels outside the input subtrees of the JOIN. It could do that despite
379 * our hack on the namespace if it uses fully-qualified names. So, grovel
380 * through the transformed clause and make sure there are no bogus
381 * references. (Outer references are OK, and are ignored here.)
383 clause_varnos = pull_varnos(result);
384 clause_varnos = bms_del_members(clause_varnos, containedRels);
385 if ((varno = bms_first_member(clause_varnos)) >= 0)
388 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
389 errmsg("JOIN/ON clause refers to \"%s\", which is not part of JOIN",
390 rt_fetch(varno, pstate->p_rtable)->eref->aliasname)));
392 bms_free(clause_varnos);
398 * transformTableEntry --- transform a RangeVar (simple relation reference)
400 static RangeTblEntry *
401 transformTableEntry(ParseState *pstate, RangeVar *r)
406 * mark this entry to indicate it comes from the FROM clause. In SQL, the
407 * target list can only refer to range variables specified in the from
408 * clause but we follow the more powerful POSTQUEL semantics and
409 * automatically generate the range variable if not specified. However
410 * there are times we need to know whether the entries are legitimate.
412 rte = addRangeTableEntry(pstate, r, r->alias,
413 interpretInhOption(r->inhOpt), true);
420 * transformRangeSubselect --- transform a sub-SELECT appearing in FROM
422 static RangeTblEntry *
423 transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
429 * We require user to supply an alias for a subselect, per SQL92. To relax
430 * this, we'd have to be prepared to gin up a unique alias for an
431 * unlabeled subselect.
433 if (r->alias == NULL)
435 (errcode(ERRCODE_SYNTAX_ERROR),
436 errmsg("subquery in FROM must have an alias")));
439 * Analyze and transform the subquery.
441 query = parse_sub_analyze(r->subquery, pstate);
444 * Check that we got something reasonable. Many of these conditions are
445 * impossible given restrictions of the grammar, but check 'em anyway.
447 if (query->commandType != CMD_SELECT ||
448 query->utilityStmt != NULL)
449 elog(ERROR, "expected SELECT query from subquery in FROM");
450 if (query->intoClause != NULL)
452 (errcode(ERRCODE_SYNTAX_ERROR),
453 errmsg("subquery in FROM cannot 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 cannot 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 cannot 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 check
547 * 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 bigint.
1078 * Used for LIMIT and allied clauses.
1080 * Note: as of Postgres 8.2, LIMIT expressions are expected to yield int8,
1081 * rather than int4 as before.
1083 * constructName does not affect the semantics, but is used in error messages
1086 transformLimitClause(ParseState *pstate, Node *clause,
1087 const char *constructName)
1094 qual = transformExpr(pstate, clause);
1096 qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1099 * LIMIT can't refer to any vars or aggregates of the current query
1101 if (contain_vars_of_level(qual, 0))
1104 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1105 /* translator: %s is name of a SQL construct, eg LIMIT */
1106 errmsg("argument of %s must not contain variables",
1109 if (checkExprHasAggs(qual))
1112 (errcode(ERRCODE_GROUPING_ERROR),
1113 /* translator: %s is name of a SQL construct, eg LIMIT */
1114 errmsg("argument of %s must not contain aggregates",
1123 * findTargetlistEntry -
1124 * Returns the targetlist entry matching the given (untransformed) node.
1125 * If no matching entry exists, one is created and appended to the target
1126 * list as a "resjunk" node.
1128 * node the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched
1129 * tlist the target list (passed by reference so we can append to it)
1130 * clause identifies clause type being processed
1132 static TargetEntry *
1133 findTargetlistEntry(ParseState *pstate, Node *node, List **tlist, int clause)
1135 TargetEntry *target_result = NULL;
1140 * Handle two special cases as mandated by the SQL92 spec:
1142 * 1. Bare ColumnName (no qualifier or subscripts)
1143 * For a bare identifier, we search for a matching column name
1144 * in the existing target list. Multiple matches are an error
1145 * unless they refer to identical values; for example,
1146 * we allow SELECT a, a FROM table ORDER BY a
1147 * but not SELECT a AS b, b FROM table ORDER BY b
1148 * If no match is found, we fall through and treat the identifier
1150 * For GROUP BY, it is incorrect to match the grouping item against
1151 * targetlist entries: according to SQL92, an identifier in GROUP BY
1152 * is a reference to a column name exposed by FROM, not to a target
1153 * list column. However, many implementations (including pre-7.0
1154 * PostgreSQL) accept this anyway. So for GROUP BY, we look first
1155 * to see if the identifier matches any FROM column name, and only
1156 * try for a targetlist name if it doesn't. This ensures that we
1157 * adhere to the spec in the case where the name could be both.
1158 * DISTINCT ON isn't in the standard, so we can do what we like there;
1159 * we choose to make it work like ORDER BY, on the rather flimsy
1160 * grounds that ordinary DISTINCT works on targetlist entries.
1162 * 2. IntegerConstant
1163 * This means to use the n'th item in the existing target list.
1164 * Note that it would make no sense to order/group/distinct by an
1165 * actual constant, so this does not create a conflict with our
1166 * extension to order/group by an expression.
1167 * GROUP BY column-number is not allowed by SQL92, but since
1168 * the standard has no other behavior defined for this syntax,
1169 * we may as well accept this common extension.
1171 * Note that pre-existing resjunk targets must not be used in either case,
1172 * since the user didn't write them in his SELECT list.
1174 * If neither special case applies, fall through to treat the item as
1178 if (IsA(node, ColumnRef) &&
1179 list_length(((ColumnRef *) node)->fields) == 1)
1181 char *name = strVal(linitial(((ColumnRef *) node)->fields));
1182 int location = ((ColumnRef *) node)->location;
1184 if (clause == GROUP_CLAUSE)
1187 * In GROUP BY, we must prefer a match against a FROM-clause
1188 * column to one against the targetlist. Look to see if there is
1189 * a matching column. If so, fall through to let transformExpr()
1190 * do the rest. NOTE: if name could refer ambiguously to more
1191 * than one column name exposed by FROM, colNameToVar will
1192 * ereport(ERROR). That's just what we want here.
1194 * Small tweak for 7.4.3: ignore matches in upper query levels.
1195 * This effectively changes the search order for bare names to (1)
1196 * local FROM variables, (2) local targetlist aliases, (3) outer
1197 * FROM variables, whereas before it was (1) (3) (2). SQL92 and
1198 * SQL99 do not allow GROUPing BY an outer reference, so this
1199 * breaks no cases that are legal per spec, and it seems a more
1200 * self-consistent behavior.
1202 if (colNameToVar(pstate, name, true, location) != NULL)
1210 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1212 if (!tle->resjunk &&
1213 strcmp(tle->resname, name) == 0)
1215 if (target_result != NULL)
1217 if (!equal(target_result->expr, tle->expr))
1219 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1222 translator: first %s is name of a SQL construct, eg ORDER BY */
1223 errmsg("%s \"%s\" is ambiguous",
1224 clauseText[clause], name),
1225 parser_errposition(pstate, location)));
1228 target_result = tle;
1229 /* Stay in loop to check for ambiguity */
1232 if (target_result != NULL)
1233 return target_result; /* return the first match */
1236 if (IsA(node, A_Const))
1238 Value *val = &((A_Const *) node)->val;
1239 int targetlist_pos = 0;
1242 if (!IsA(val, Integer))
1244 (errcode(ERRCODE_SYNTAX_ERROR),
1245 /* translator: %s is name of a SQL construct, eg ORDER BY */
1246 errmsg("non-integer constant in %s",
1247 clauseText[clause])));
1248 target_pos = intVal(val);
1251 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1255 if (++targetlist_pos == target_pos)
1256 return tle; /* return the unique match */
1260 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1261 /* translator: %s is name of a SQL construct, eg ORDER BY */
1262 errmsg("%s position %d is not in select list",
1263 clauseText[clause], target_pos)));
1267 * Otherwise, we have an expression (this is a Postgres extension not
1268 * found in SQL92). Convert the untransformed node to a transformed
1269 * expression, and search for a match in the tlist. NOTE: it doesn't
1270 * really matter whether there is more than one match. Also, we are
1271 * willing to match a resjunk target here, though the above cases must
1272 * ignore resjunk targets.
1274 expr = transformExpr(pstate, node);
1278 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1280 if (equal(expr, tle->expr))
1285 * If no matches, construct a new target entry which is appended to the
1286 * end of the target list. This target is given resjunk = TRUE so that it
1287 * will not be projected into the final tuple.
1289 target_result = transformTargetEntry(pstate, node, expr, NULL, true);
1291 *tlist = lappend(*tlist, target_result);
1293 return target_result;
1297 * transformGroupClause -
1298 * transform a GROUP BY clause
1300 * GROUP BY items will be added to the targetlist (as resjunk columns)
1301 * if not already present, so the targetlist must be passed by reference.
1304 transformGroupClause(ParseState *pstate, List *grouplist,
1305 List **targetlist, List *sortClause)
1310 foreach(gl, grouplist)
1312 Node *gexpr = (Node *) lfirst(gl);
1316 tle = findTargetlistEntry(pstate, gexpr,
1317 targetlist, GROUP_CLAUSE);
1319 /* Eliminate duplicates (GROUP BY x, x) */
1320 if (targetIsInSortList(tle, InvalidOid, result))
1324 * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
1325 * info from the (first) matching ORDER BY item. This means that if
1326 * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
1327 * GROUP BY operation silently takes on the equality semantics implied
1328 * by the ORDER BY. There are two reasons to do this: it improves
1329 * the odds that we can implement both GROUP BY and ORDER BY with a
1330 * single sort step, and it allows the user to choose the equality
1331 * semantics used by GROUP BY, should she be working with a datatype
1332 * that has more than one equality operator.
1334 if (tle->ressortgroupref > 0)
1338 foreach(sl, sortClause)
1340 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1342 if (sc->tleSortGroupRef == tle->ressortgroupref)
1344 result = lappend(result, copyObject(sc));
1352 * If no match in ORDER BY, just add it to the result using
1353 * default sort/group semantics.
1355 * XXX for now, the planner requires groupClause to be sortable,
1356 * so we have to insist on that here.
1359 result = addTargetToGroupList(pstate, tle,
1360 result, *targetlist,
1361 true, /* XXX for now */
1369 * transformSortClause -
1370 * transform an ORDER BY clause
1372 * ORDER BY items will be added to the targetlist (as resjunk columns)
1373 * if not already present, so the targetlist must be passed by reference.
1376 transformSortClause(ParseState *pstate,
1379 bool resolveUnknown)
1381 List *sortlist = NIL;
1384 foreach(olitem, orderlist)
1386 SortBy *sortby = (SortBy *) lfirst(olitem);
1389 tle = findTargetlistEntry(pstate, sortby->node,
1390 targetlist, ORDER_CLAUSE);
1392 sortlist = addTargetToSortList(pstate, tle,
1393 sortlist, *targetlist,
1395 sortby->sortby_nulls,
1404 * transformDistinctClause -
1405 * transform a DISTINCT clause
1407 * Since we may need to add items to the query's targetlist, that list
1408 * is passed by reference.
1410 * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
1411 * possible into the distinctClause. This avoids a possible need to re-sort,
1412 * and allows the user to choose the equality semantics used by DISTINCT,
1413 * should she be working with a datatype that has more than one equality
1417 transformDistinctClause(ParseState *pstate,
1418 List **targetlist, List *sortClause)
1425 * The distinctClause should consist of all ORDER BY items followed
1426 * by all other non-resjunk targetlist items. There must not be any
1427 * resjunk ORDER BY items --- that would imply that we are sorting
1428 * by a value that isn't necessarily unique within a DISTINCT group,
1429 * so the results wouldn't be well-defined. This construction
1430 * ensures we follow the rule that sortClause and distinctClause match;
1431 * in fact the sortClause will always be a prefix of distinctClause.
1433 * Note a corner case: the same TLE could be in the ORDER BY list
1434 * multiple times with different sortops. We have to include it in
1435 * the distinctClause the same way to preserve the prefix property.
1436 * The net effect will be that the TLE value will be made unique
1437 * according to both sortops.
1439 foreach(slitem, sortClause)
1441 SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
1442 TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
1446 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1447 errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list")));
1448 result = lappend(result, copyObject(scl));
1452 * Now add any remaining non-resjunk tlist items, using default
1453 * sort/group semantics for their data types.
1455 * XXX for now, the planner requires distinctClause to be sortable,
1456 * so we have to insist on that here.
1458 foreach(tlitem, *targetlist)
1460 TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
1463 continue; /* ignore junk */
1464 result = addTargetToGroupList(pstate, tle,
1465 result, *targetlist,
1466 true, /* XXX for now */
1474 * transformDistinctOnClause -
1475 * transform a DISTINCT ON clause
1477 * Since we may need to add items to the query's targetlist, that list
1478 * is passed by reference.
1480 * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
1481 * possible into the distinctClause. This avoids a possible need to re-sort,
1482 * and allows the user to choose the equality semantics used by DISTINCT,
1483 * should she be working with a datatype that has more than one equality
1487 transformDistinctOnClause(ParseState *pstate, List *distinctlist,
1488 List **targetlist, List *sortClause)
1493 Bitmapset *refnos = NULL;
1495 bool skipped_sortitem;
1498 * Add all the DISTINCT ON expressions to the tlist (if not already
1499 * present, they are added as resjunk items). Assign sortgroupref
1500 * numbers to them, and form a bitmapset of these numbers. (A
1501 * bitmapset is convenient here because we don't care about order
1502 * and we can discard duplicates.)
1504 foreach(dlitem, distinctlist)
1506 Node *dexpr = (Node *) lfirst(dlitem);
1509 tle = findTargetlistEntry(pstate, dexpr,
1510 targetlist, DISTINCT_ON_CLAUSE);
1511 sortgroupref = assignSortGroupRef(tle, *targetlist);
1512 refnos = bms_add_member(refnos, sortgroupref);
1516 * If the user writes both DISTINCT ON and ORDER BY, adopt the
1517 * sorting semantics from ORDER BY items that match DISTINCT ON
1518 * items, and also adopt their column sort order. We insist that
1519 * the distinctClause and sortClause match, so throw error if we
1520 * find the need to add any more distinctClause items after we've
1521 * skipped an ORDER BY item that wasn't in DISTINCT ON.
1523 skipped_sortitem = false;
1524 foreach(slitem, sortClause)
1526 SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
1528 if (bms_is_member(scl->tleSortGroupRef, refnos))
1530 if (skipped_sortitem)
1532 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1533 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions")));
1535 result = lappend(result, copyObject(scl));
1538 skipped_sortitem = true;
1542 * Now add any remaining DISTINCT ON items, using default sort/group
1543 * semantics for their data types. (Note: this is pretty questionable;
1544 * if the ORDER BY list doesn't include all the DISTINCT ON items and more
1545 * besides, you certainly aren't using DISTINCT ON in the intended way,
1546 * and you probably aren't going to get consistent results. It might be
1547 * better to throw an error or warning here. But historically we've
1548 * allowed it, so keep doing so.)
1550 while ((sortgroupref = bms_first_member(refnos)) >= 0)
1552 TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
1554 if (targetIsInSortList(tle, InvalidOid, result))
1555 continue; /* already in list (with some semantics) */
1556 if (skipped_sortitem)
1558 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1559 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions")));
1560 result = addTargetToGroupList(pstate, tle,
1561 result, *targetlist,
1562 true, /* someday allow hash-only? */
1570 * addTargetToSortList
1571 * If the given targetlist entry isn't already in the SortGroupClause
1572 * list, add it to the end of the list, using the given sort ordering
1575 * If resolveUnknown is TRUE, convert TLEs of type UNKNOWN to TEXT. If not,
1576 * do nothing (which implies the search for a sort operator will fail).
1577 * pstate should be provided if resolveUnknown is TRUE, but can be NULL
1580 * Returns the updated SortGroupClause list.
1583 addTargetToSortList(ParseState *pstate, TargetEntry *tle,
1584 List *sortlist, List *targetlist,
1585 SortByDir sortby_dir, SortByNulls sortby_nulls,
1586 List *sortby_opname, bool resolveUnknown)
1588 Oid restype = exprType((Node *) tle->expr);
1593 /* if tlist item is an UNKNOWN literal, change it to TEXT */
1594 if (restype == UNKNOWNOID && resolveUnknown)
1596 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
1597 restype, TEXTOID, -1,
1599 COERCE_IMPLICIT_CAST);
1603 /* determine the sortop, eqop, and directionality */
1606 case SORTBY_DEFAULT:
1608 get_sort_group_operators(restype,
1610 &sortop, &eqop, NULL);
1614 get_sort_group_operators(restype,
1616 NULL, &eqop, &sortop);
1620 Assert(sortby_opname != NIL);
1621 sortop = compatible_oper_opid(sortby_opname,
1627 * Verify it's a valid ordering operator, fetch the corresponding
1628 * equality operator, and determine whether to consider it like
1631 eqop = get_equality_op_for_ordering_op(sortop, &reverse);
1632 if (!OidIsValid(eqop))
1634 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1635 errmsg("operator %s is not a valid ordering operator",
1636 strVal(llast(sortby_opname))),
1637 errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
1640 elog(ERROR, "unrecognized sortby_dir: %d", sortby_dir);
1641 sortop = InvalidOid; /* keep compiler quiet */
1647 /* avoid making duplicate sortlist entries */
1648 if (!targetIsInSortList(tle, sortop, sortlist))
1650 SortGroupClause *sortcl = makeNode(SortGroupClause);
1652 sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
1654 sortcl->eqop = eqop;
1655 sortcl->sortop = sortop;
1657 switch (sortby_nulls)
1659 case SORTBY_NULLS_DEFAULT:
1660 /* NULLS FIRST is default for DESC; other way for ASC */
1661 sortcl->nulls_first = reverse;
1663 case SORTBY_NULLS_FIRST:
1664 sortcl->nulls_first = true;
1666 case SORTBY_NULLS_LAST:
1667 sortcl->nulls_first = false;
1670 elog(ERROR, "unrecognized sortby_nulls: %d", sortby_nulls);
1674 sortlist = lappend(sortlist, sortcl);
1681 * addTargetToGroupList
1682 * If the given targetlist entry isn't already in the SortGroupClause
1683 * list, add it to the end of the list, using default sort/group
1686 * This is very similar to addTargetToSortList, except that we allow the
1687 * case where only a grouping (equality) operator can be found, and that
1688 * the TLE is considered "already in the list" if it appears there with any
1689 * sorting semantics.
1691 * If requireSortOp is TRUE, we require a sorting operator to be found too.
1692 * XXX this argument should eventually be obsolete, but for now there are
1693 * parts of the system that can't support non-sortable grouping lists.
1695 * If resolveUnknown is TRUE, convert TLEs of type UNKNOWN to TEXT. If not,
1696 * do nothing (which implies the search for an equality operator will fail).
1697 * pstate should be provided if resolveUnknown is TRUE, but can be NULL
1700 * Returns the updated SortGroupClause list.
1703 addTargetToGroupList(ParseState *pstate, TargetEntry *tle,
1704 List *grouplist, List *targetlist,
1705 bool requireSortOp, bool resolveUnknown)
1707 Oid restype = exprType((Node *) tle->expr);
1711 /* if tlist item is an UNKNOWN literal, change it to TEXT */
1712 if (restype == UNKNOWNOID && resolveUnknown)
1714 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
1715 restype, TEXTOID, -1,
1717 COERCE_IMPLICIT_CAST);
1721 /* avoid making duplicate grouplist entries */
1722 if (!targetIsInSortList(tle, InvalidOid, grouplist))
1724 SortGroupClause *grpcl = makeNode(SortGroupClause);
1726 /* determine the eqop and optional sortop */
1727 get_sort_group_operators(restype,
1728 requireSortOp, true, false,
1729 &sortop, &eqop, NULL);
1731 grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
1733 grpcl->sortop = sortop;
1734 grpcl->nulls_first = false; /* OK with or without sortop */
1736 grouplist = lappend(grouplist, grpcl);
1743 * assignSortGroupRef
1744 * Assign the targetentry an unused ressortgroupref, if it doesn't
1745 * already have one. Return the assigned or pre-existing refnumber.
1747 * 'tlist' is the targetlist containing (or to contain) the given targetentry.
1750 assignSortGroupRef(TargetEntry *tle, List *tlist)
1755 if (tle->ressortgroupref) /* already has one? */
1756 return tle->ressortgroupref;
1758 /* easiest way to pick an unused refnumber: max used + 1 */
1762 Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
1767 tle->ressortgroupref = maxRef + 1;
1768 return tle->ressortgroupref;
1772 * targetIsInSortList
1773 * Is the given target item already in the sortlist?
1774 * If sortop is not InvalidOid, also test for a match to the sortop.
1776 * It is not an oversight that this function ignores the nulls_first flag.
1777 * We check sortop when determining if an ORDER BY item is redundant with
1778 * earlier ORDER BY items, because it's conceivable that "ORDER BY
1779 * foo USING <, foo USING <<<" is not redundant, if <<< distinguishes
1780 * values that < considers equal. We need not check nulls_first
1781 * however, because a lower-order column with the same sortop but
1782 * opposite nulls direction is redundant. Also, we can consider
1783 * ORDER BY foo ASC, foo DESC redundant, so check for a commutator match.
1785 * Works for both ordering and grouping lists (sortop would normally be
1786 * InvalidOid when considering grouping). Note that the main reason we need
1787 * this routine (and not just a quick test for nonzeroness of ressortgroupref)
1788 * is that a TLE might be in only one of the lists.
1791 targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
1793 Index ref = tle->ressortgroupref;
1796 /* no need to scan list if tle has no marker */
1800 foreach(l, sortList)
1802 SortGroupClause *scl = (SortGroupClause *) lfirst(l);
1804 if (scl->tleSortGroupRef == ref &&
1805 (sortop == InvalidOid ||
1806 sortop == scl->sortop ||
1807 sortop == get_commutator(scl->sortop)))