1 /*-------------------------------------------------------------------------
4 * handle expressions 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_expr.c,v 1.235 2008/10/06 17:39:26 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "catalog/pg_type.h"
19 #include "commands/dbcommands.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "parser/analyze.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_expr.h"
26 #include "parser/parse_func.h"
27 #include "parser/parse_oper.h"
28 #include "parser/parse_relation.h"
29 #include "parser/parse_target.h"
30 #include "parser/parse_type.h"
31 #include "utils/builtins.h"
32 #include "utils/lsyscache.h"
33 #include "utils/xml.h"
36 bool Transform_null_equals = false;
38 static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
39 static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
40 static Node *transformAExprAnd(ParseState *pstate, A_Expr *a);
41 static Node *transformAExprOr(ParseState *pstate, A_Expr *a);
42 static Node *transformAExprNot(ParseState *pstate, A_Expr *a);
43 static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
44 static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
45 static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
46 static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
47 static Node *transformAExprOf(ParseState *pstate, A_Expr *a);
48 static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
49 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
50 static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
51 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
52 static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
53 Oid array_type, Oid element_type, int32 typmod);
54 static Node *transformRowExpr(ParseState *pstate, RowExpr *r);
55 static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
56 static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
57 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
58 static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
59 static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
60 static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
61 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
62 static Node *transformWholeRowRef(ParseState *pstate, char *schemaname,
63 char *relname, int location);
64 static Node *transformIndirection(ParseState *pstate, Node *basenode,
66 static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
67 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
68 List *largs, List *rargs, int location);
69 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
70 RowExpr *lrow, RowExpr *rrow, int location);
71 static Expr *make_distinct_op(ParseState *pstate, List *opname,
72 Node *ltree, Node *rtree, int location);
77 * Analyze and transform expressions. Type checking and type casting is
78 * done here. The optimizer and the executor cannot handle the original
79 * (raw) expressions collected by the parse tree. Hence the transformation
82 * NOTE: there are various cases in which this routine will get applied to
83 * an already-transformed expression. Some examples:
84 * 1. At least one construct (BETWEEN/AND) puts the same nodes
85 * into two branches of the parse tree; hence, some nodes
86 * are transformed twice.
87 * 2. Another way it can happen is that coercion of an operator or
88 * function argument to the required type (via coerce_type())
89 * can apply transformExpr to an already-transformed subexpression.
90 * An example here is "SELECT count(*) + 1.0 FROM table".
91 * While it might be possible to eliminate these cases, the path of
92 * least resistance so far has been to ensure that transformExpr() does
93 * no damage if applied to an already-transformed tree. This is pretty
94 * easy for cases where the transformation replaces one node type with
95 * another, such as A_Const => Const; we just do nothing when handed
96 * a Const. More care is needed for node types that are used as both
97 * input and output of transformExpr; see SubLink for example.
100 transformExpr(ParseState *pstate, Node *expr)
107 /* Guard against stack overflow due to overly complex expressions */
110 switch (nodeTag(expr))
113 result = transformColumnRef(pstate, (ColumnRef *) expr);
117 result = transformParamRef(pstate, (ParamRef *) expr);
122 A_Const *con = (A_Const *) expr;
123 Value *val = &con->val;
125 result = (Node *) make_const(pstate, val, con->location);
129 case T_A_Indirection:
131 A_Indirection *ind = (A_Indirection *) expr;
133 result = transformExpr(pstate, ind->arg);
134 result = transformIndirection(pstate, result,
140 result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
141 InvalidOid, InvalidOid, -1);
146 TypeCast *tc = (TypeCast *) expr;
149 * If the subject of the typecast is an ARRAY[] construct
150 * and the target type is an array type, we invoke
151 * transformArrayExpr() directly so that we can pass down
152 * the type information. This avoids some cases where
153 * transformArrayExpr() might not infer the correct type.
155 if (IsA(tc->arg, A_ArrayExpr))
161 targetType = typenameTypeId(pstate, tc->typename,
163 elementType = get_element_type(targetType);
164 if (OidIsValid(elementType))
166 result = transformArrayExpr(pstate,
167 (A_ArrayExpr *) tc->arg,
175 * Corner case: ARRAY[] cast to a non-array type.
176 * Fall through to do it the standard way.
180 result = transformTypeCast(pstate, tc);
186 A_Expr *a = (A_Expr *) expr;
191 result = transformAExprOp(pstate, a);
194 result = transformAExprAnd(pstate, a);
197 result = transformAExprOr(pstate, a);
200 result = transformAExprNot(pstate, a);
203 result = transformAExprOpAny(pstate, a);
206 result = transformAExprOpAll(pstate, a);
209 result = transformAExprDistinct(pstate, a);
212 result = transformAExprNullIf(pstate, a);
215 result = transformAExprOf(pstate, a);
218 result = transformAExprIn(pstate, a);
221 elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
227 result = transformFuncCall(pstate, (FuncCall *) expr);
231 result = transformSubLink(pstate, (SubLink *) expr);
235 result = transformCaseExpr(pstate, (CaseExpr *) expr);
239 result = transformRowExpr(pstate, (RowExpr *) expr);
243 result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
247 result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
251 result = transformXmlExpr(pstate, (XmlExpr *) expr);
255 result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
260 NullTest *n = (NullTest *) expr;
262 n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
263 /* the argument can be any type, so don't coerce it */
269 result = transformBooleanTest(pstate, (BooleanTest *) expr);
272 case T_CurrentOfExpr:
273 result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
276 /*********************************************
277 * Quietly accept node types that may be presented when we are
278 * called on an already-transformed tree.
280 * Do any other node types need to be accepted? For now we are
281 * taking a conservative approach, and only accepting node
282 * types that are demonstrably necessary to accept.
283 *********************************************/
292 case T_ScalarArrayOpExpr:
299 case T_ArrayCoerceExpr:
300 case T_ConvertRowtypeExpr:
302 case T_CoerceToDomain:
303 case T_CoerceToDomainValue:
306 result = (Node *) expr;
311 /* should not reach here */
312 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
320 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
322 Node *result = basenode;
323 List *subscripts = NIL;
327 * We have to split any field-selection operations apart from
328 * subscripting. Adjacent A_Indices nodes have to be treated as a single
329 * multidimensional subscript operation.
331 foreach(i, indirection)
335 if (IsA(n, A_Indices))
336 subscripts = lappend(subscripts, n);
337 else if (IsA(n, A_Star))
340 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
341 errmsg("row expansion via \"*\" is not supported here"),
342 parser_errposition(pstate, exprLocation(basenode))));
346 Assert(IsA(n, String));
348 /* process subscripts before this field selection */
350 result = (Node *) transformArraySubscripts(pstate,
359 result = ParseFuncOrColumn(pstate,
366 /* process trailing subscripts, if any */
368 result = (Node *) transformArraySubscripts(pstate,
380 transformColumnRef(ParseState *pstate, ColumnRef *cref)
382 int numnames = list_length(cref->fields);
387 * The allowed syntaxes are:
389 * A First try to resolve as unqualified column name;
390 * if no luck, try to resolve as unqualified table name (A.*).
391 * A.B A is an unqualified table name; B is either a
392 * column or function name (trying column name first).
393 * A.B.C schema A, table B, col or func name C.
394 * A.B.C.D catalog A, schema B, table C, col or func D.
395 * A.* A is an unqualified table name; means whole-row value.
396 * A.B.* whole-row value of table B in schema A.
397 * A.B.C.* whole-row value of table C in schema B in catalog A.
399 * We do not need to cope with bare "*"; that will only be accepted by
400 * the grammar at the top level of a SELECT list, and transformTargetList
401 * will take care of it before it ever gets here. Also, "A.*" etc will
402 * be expanded by transformTargetList if they appear at SELECT top level,
403 * so here we are only going to see them as function or operator inputs.
405 * Currently, if a catalog name is given then it must equal the current
406 * database name; we check it here and then discard it.
413 Node *field1 = (Node *) linitial(cref->fields);
416 Assert(IsA(field1, String));
417 name1 = strVal(field1);
419 /* Try to identify as an unqualified column */
420 node = colNameToVar(pstate, name1, false, cref->location);
425 * Not known as a column of any range-table entry.
427 * Consider the possibility that it's VALUE in a domain
428 * check expression. (We handle VALUE as a name, not a
429 * keyword, to avoid breaking a lot of applications that
430 * have used VALUE as a column name in the past.)
432 if (pstate->p_value_substitute != NULL &&
433 strcmp(name1, "value") == 0)
435 node = (Node *) copyObject(pstate->p_value_substitute);
438 * Try to propagate location knowledge. This should
439 * be extended if p_value_substitute can ever take on
442 if (IsA(node, CoerceToDomainValue))
443 ((CoerceToDomainValue *) node)->location = cref->location;
448 * Try to find the name as a relation. Note that only
449 * relations already entered into the rangetable will be
452 * This is a hack for backwards compatibility with
453 * PostQUEL-inspired syntax. The preferred form now is
456 if (refnameRangeTblEntry(pstate, NULL, name1,
459 node = transformWholeRowRef(pstate, NULL, name1,
463 (errcode(ERRCODE_UNDEFINED_COLUMN),
464 errmsg("column \"%s\" does not exist",
466 parser_errposition(pstate, cref->location)));
472 Node *field1 = (Node *) linitial(cref->fields);
473 Node *field2 = (Node *) lsecond(cref->fields);
477 Assert(IsA(field1, String));
478 name1 = strVal(field1);
480 /* Whole-row reference? */
481 if (IsA(field2, A_Star))
483 node = transformWholeRowRef(pstate, NULL, name1,
488 Assert(IsA(field2, String));
489 name2 = strVal(field2);
491 /* Try to identify as a once-qualified column */
492 node = qualifiedNameToVar(pstate, NULL, name1, name2, true,
497 * Not known as a column of any range-table entry, so try
498 * it as a function call. Here, we will create an
499 * implicit RTE for tables not already entered.
501 node = transformWholeRowRef(pstate, NULL, name1,
503 node = ParseFuncOrColumn(pstate,
504 list_make1(makeString(name2)),
507 true, cref->location);
513 Node *field1 = (Node *) linitial(cref->fields);
514 Node *field2 = (Node *) lsecond(cref->fields);
515 Node *field3 = (Node *) lthird(cref->fields);
520 Assert(IsA(field1, String));
521 name1 = strVal(field1);
522 Assert(IsA(field2, String));
523 name2 = strVal(field2);
525 /* Whole-row reference? */
526 if (IsA(field3, A_Star))
528 node = transformWholeRowRef(pstate, name1, name2,
533 Assert(IsA(field3, String));
534 name3 = strVal(field3);
536 /* Try to identify as a twice-qualified column */
537 node = qualifiedNameToVar(pstate, name1, name2, name3, true,
541 /* Try it as a function call */
542 node = transformWholeRowRef(pstate, name1, name2,
544 node = ParseFuncOrColumn(pstate,
545 list_make1(makeString(name3)),
548 true, cref->location);
554 Node *field1 = (Node *) linitial(cref->fields);
555 Node *field2 = (Node *) lsecond(cref->fields);
556 Node *field3 = (Node *) lthird(cref->fields);
557 Node *field4 = (Node *) lfourth(cref->fields);
563 Assert(IsA(field1, String));
564 name1 = strVal(field1);
565 Assert(IsA(field2, String));
566 name2 = strVal(field2);
567 Assert(IsA(field3, String));
568 name3 = strVal(field3);
571 * We check the catalog name and then ignore it.
573 if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
575 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
576 errmsg("cross-database references are not implemented: %s",
577 NameListToString(cref->fields)),
578 parser_errposition(pstate, cref->location)));
580 /* Whole-row reference? */
581 if (IsA(field4, A_Star))
583 node = transformWholeRowRef(pstate, name2, name3,
588 Assert(IsA(field4, String));
589 name4 = strVal(field4);
591 /* Try to identify as a twice-qualified column */
592 node = qualifiedNameToVar(pstate, name2, name3, name4, true,
596 /* Try it as a function call */
597 node = transformWholeRowRef(pstate, name2, name3,
599 node = ParseFuncOrColumn(pstate,
600 list_make1(makeString(name4)),
603 true, cref->location);
609 (errcode(ERRCODE_SYNTAX_ERROR),
610 errmsg("improper qualified name (too many dotted names): %s",
611 NameListToString(cref->fields)),
612 parser_errposition(pstate, cref->location)));
613 node = NULL; /* keep compiler quiet */
621 * Locate the parameter type info for the given parameter number, and
622 * return a pointer to it.
625 find_param_type(ParseState *pstate, int paramno, int location)
630 * Find topmost ParseState, which is where paramtype info lives.
632 while (pstate->parentParseState != NULL)
633 pstate = pstate->parentParseState;
635 /* Check parameter number is in range */
636 if (paramno <= 0) /* probably can't happen? */
638 (errcode(ERRCODE_UNDEFINED_PARAMETER),
639 errmsg("there is no parameter $%d", paramno),
640 parser_errposition(pstate, location)));
641 if (paramno > pstate->p_numparams)
643 if (!pstate->p_variableparams)
645 (errcode(ERRCODE_UNDEFINED_PARAMETER),
646 errmsg("there is no parameter $%d", paramno),
647 parser_errposition(pstate, location)));
648 /* Okay to enlarge param array */
649 if (pstate->p_paramtypes)
650 pstate->p_paramtypes = (Oid *) repalloc(pstate->p_paramtypes,
651 paramno * sizeof(Oid));
653 pstate->p_paramtypes = (Oid *) palloc(paramno * sizeof(Oid));
654 /* Zero out the previously-unreferenced slots */
655 MemSet(pstate->p_paramtypes + pstate->p_numparams,
657 (paramno - pstate->p_numparams) * sizeof(Oid));
658 pstate->p_numparams = paramno;
661 result = &pstate->p_paramtypes[paramno - 1];
663 if (pstate->p_variableparams)
665 /* If not seen before, initialize to UNKNOWN type */
666 if (*result == InvalidOid)
667 *result = UNKNOWNOID;
674 transformParamRef(ParseState *pstate, ParamRef *pref)
676 int paramno = pref->number;
677 Oid *pptype = find_param_type(pstate, paramno, pref->location);
680 param = makeNode(Param);
681 param->paramkind = PARAM_EXTERN;
682 param->paramid = paramno;
683 param->paramtype = *pptype;
684 param->paramtypmod = -1;
685 param->location = pref->location;
687 return (Node *) param;
690 /* Test whether an a_expr is a plain NULL constant or not */
692 exprIsNullConstant(Node *arg)
694 if (arg && IsA(arg, A_Const))
696 A_Const *con = (A_Const *) arg;
698 if (con->val.type == T_Null)
705 transformAExprOp(ParseState *pstate, A_Expr *a)
707 Node *lexpr = a->lexpr;
708 Node *rexpr = a->rexpr;
712 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
713 * standards-broken products (like Microsoft's). Turn these into IS NULL
716 if (Transform_null_equals &&
717 list_length(a->name) == 1 &&
718 strcmp(strVal(linitial(a->name)), "=") == 0 &&
719 (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)))
721 NullTest *n = makeNode(NullTest);
723 n->nulltesttype = IS_NULL;
725 if (exprIsNullConstant(lexpr))
726 n->arg = (Expr *) rexpr;
728 n->arg = (Expr *) lexpr;
730 result = transformExpr(pstate, (Node *) n);
732 else if (lexpr && IsA(lexpr, RowExpr) &&
733 rexpr && IsA(rexpr, SubLink) &&
734 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
737 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
738 * grammar did this, but now that a row construct is allowed anywhere
739 * in expressions, it's easier to do it here.
741 SubLink *s = (SubLink *) rexpr;
743 s->subLinkType = ROWCOMPARE_SUBLINK;
745 s->operName = a->name;
746 s->location = a->location;
747 result = transformExpr(pstate, (Node *) s);
749 else if (lexpr && IsA(lexpr, RowExpr) &&
750 rexpr && IsA(rexpr, RowExpr))
753 lexpr = transformExpr(pstate, lexpr);
754 rexpr = transformExpr(pstate, rexpr);
755 Assert(IsA(lexpr, RowExpr));
756 Assert(IsA(rexpr, RowExpr));
758 result = make_row_comparison_op(pstate,
760 ((RowExpr *) lexpr)->args,
761 ((RowExpr *) rexpr)->args,
766 /* Ordinary scalar operator */
767 lexpr = transformExpr(pstate, lexpr);
768 rexpr = transformExpr(pstate, rexpr);
770 result = (Node *) make_op(pstate,
781 transformAExprAnd(ParseState *pstate, A_Expr *a)
783 Node *lexpr = transformExpr(pstate, a->lexpr);
784 Node *rexpr = transformExpr(pstate, a->rexpr);
786 lexpr = coerce_to_boolean(pstate, lexpr, "AND");
787 rexpr = coerce_to_boolean(pstate, rexpr, "AND");
789 return (Node *) makeBoolExpr(AND_EXPR,
790 list_make2(lexpr, rexpr),
795 transformAExprOr(ParseState *pstate, A_Expr *a)
797 Node *lexpr = transformExpr(pstate, a->lexpr);
798 Node *rexpr = transformExpr(pstate, a->rexpr);
800 lexpr = coerce_to_boolean(pstate, lexpr, "OR");
801 rexpr = coerce_to_boolean(pstate, rexpr, "OR");
803 return (Node *) makeBoolExpr(OR_EXPR,
804 list_make2(lexpr, rexpr),
809 transformAExprNot(ParseState *pstate, A_Expr *a)
811 Node *rexpr = transformExpr(pstate, a->rexpr);
813 rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
815 return (Node *) makeBoolExpr(NOT_EXPR,
821 transformAExprOpAny(ParseState *pstate, A_Expr *a)
823 Node *lexpr = transformExpr(pstate, a->lexpr);
824 Node *rexpr = transformExpr(pstate, a->rexpr);
826 return (Node *) make_scalar_array_op(pstate,
835 transformAExprOpAll(ParseState *pstate, A_Expr *a)
837 Node *lexpr = transformExpr(pstate, a->lexpr);
838 Node *rexpr = transformExpr(pstate, a->rexpr);
840 return (Node *) make_scalar_array_op(pstate,
849 transformAExprDistinct(ParseState *pstate, A_Expr *a)
851 Node *lexpr = transformExpr(pstate, a->lexpr);
852 Node *rexpr = transformExpr(pstate, a->rexpr);
854 if (lexpr && IsA(lexpr, RowExpr) &&
855 rexpr && IsA(rexpr, RowExpr))
858 return make_row_distinct_op(pstate, a->name,
865 /* Ordinary scalar operator */
866 return (Node *) make_distinct_op(pstate,
875 transformAExprNullIf(ParseState *pstate, A_Expr *a)
877 Node *lexpr = transformExpr(pstate, a->lexpr);
878 Node *rexpr = transformExpr(pstate, a->rexpr);
881 result = (Node *) make_op(pstate,
886 if (((OpExpr *) result)->opresulttype != BOOLOID)
888 (errcode(ERRCODE_DATATYPE_MISMATCH),
889 errmsg("NULLIF requires = operator to yield boolean"),
890 parser_errposition(pstate, a->location)));
893 * We rely on NullIfExpr and OpExpr being the same struct
895 NodeSetTag(result, T_NullIfExpr);
901 transformAExprOf(ParseState *pstate, A_Expr *a)
904 * Checking an expression for match to a list of type names. Will result
905 * in a boolean constant node.
907 Node *lexpr = transformExpr(pstate, a->lexpr);
912 bool matched = false;
914 ltype = exprType(lexpr);
915 foreach(telem, (List *) a->rexpr)
917 rtype = typenameTypeId(pstate, lfirst(telem), NULL);
918 matched = (rtype == ltype);
924 * We have two forms: equals or not equals. Flip the sense of the result
927 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
928 matched = (!matched);
930 result = (Const *) makeBoolConst(matched, false);
932 /* Make the result have the original input's parse location */
933 result->location = exprLocation((Node *) a);
935 return (Node *) result;
939 transformAExprIn(ParseState *pstate, A_Expr *a)
949 * If the operator is <>, combine with AND not OR.
951 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
957 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
958 * possible if the inputs are all scalars (no RowExprs) and there is a
959 * suitable array type available. If not, we fall back to a boolean
960 * condition tree with multiple copies of the lefthand expression.
962 * First step: transform all the inputs, and detect whether any are
965 lexpr = transformExpr(pstate, a->lexpr);
966 haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
968 foreach(l, (List *) a->rexpr)
970 Node *rexpr = transformExpr(pstate, lfirst(l));
972 haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
973 rexprs = lappend(rexprs, rexpr);
977 * If not forced by presence of RowExpr, try to resolve a common scalar
978 * type for all the expressions, and see if it has an array type. (But if
979 * there's only one righthand expression, we may as well just fall through
980 * and generate a simple = comparison.)
982 if (!haveRowExpr && list_length(rexprs) != 1)
989 * Select a common type for the array elements. Note that since the
990 * LHS' type is first in the list, it will be preferred when there is
991 * doubt (eg, when all the RHS items are unknown literals).
993 * Note: use list_concat here not lcons, to avoid damaging rexprs.
995 allexprs = list_concat(list_make1(lexpr), rexprs);
996 scalar_type = select_common_type(pstate, allexprs, "IN", NULL);
998 /* Do we have an array type to use? */
999 array_type = get_array_type(scalar_type);
1000 if (array_type != InvalidOid)
1003 * OK: coerce all the right-hand inputs to the common type and
1004 * build an ArrayExpr for them.
1012 Node *rexpr = (Node *) lfirst(l);
1014 rexpr = coerce_to_common_type(pstate, rexpr,
1017 aexprs = lappend(aexprs, rexpr);
1019 newa = makeNode(ArrayExpr);
1020 newa->array_typeid = array_type;
1021 newa->element_typeid = scalar_type;
1022 newa->elements = aexprs;
1023 newa->multidims = false;
1024 newa->location = -1;
1026 return (Node *) make_scalar_array_op(pstate,
1036 * Must do it the hard way, ie, with a boolean expression tree.
1041 Node *rexpr = (Node *) lfirst(l);
1046 if (!IsA(lexpr, RowExpr) ||
1047 !IsA(rexpr, RowExpr))
1049 (errcode(ERRCODE_SYNTAX_ERROR),
1050 errmsg("arguments of row IN must all be row expressions"),
1051 parser_errposition(pstate, a->location)));
1052 cmp = make_row_comparison_op(pstate,
1054 (List *) copyObject(((RowExpr *) lexpr)->args),
1055 ((RowExpr *) rexpr)->args,
1059 cmp = (Node *) make_op(pstate,
1065 cmp = coerce_to_boolean(pstate, cmp, "IN");
1069 result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1070 list_make2(result, cmp),
1078 transformFuncCall(ParseState *pstate, FuncCall *fn)
1083 /* Transform the list of arguments ... */
1085 foreach(args, fn->args)
1087 targs = lappend(targs, transformExpr(pstate,
1088 (Node *) lfirst(args)));
1091 /* ... and hand off to ParseFuncOrColumn */
1092 return ParseFuncOrColumn(pstate,
1103 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1107 CaseTestExpr *placeholder;
1114 /* If we already transformed this node, do nothing */
1115 if (OidIsValid(c->casetype))
1118 newc = makeNode(CaseExpr);
1120 /* transform the test expression, if any */
1121 arg = transformExpr(pstate, (Node *) c->arg);
1123 /* generate placeholder for test expression */
1127 * If test expression is an untyped literal, force it to text. We have
1128 * to do something now because we won't be able to do this coercion on
1129 * the placeholder. This is not as flexible as what was done in 7.4
1130 * and before, but it's good enough to handle the sort of silly coding
1133 if (exprType(arg) == UNKNOWNOID)
1134 arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1136 placeholder = makeNode(CaseTestExpr);
1137 placeholder->typeId = exprType(arg);
1138 placeholder->typeMod = exprTypmod(arg);
1143 newc->arg = (Expr *) arg;
1145 /* transform the list of arguments */
1150 CaseWhen *w = (CaseWhen *) lfirst(l);
1151 CaseWhen *neww = makeNode(CaseWhen);
1154 Assert(IsA(w, CaseWhen));
1156 warg = (Node *) w->expr;
1159 /* shorthand form was specified, so expand... */
1160 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1161 (Node *) placeholder,
1165 neww->expr = (Expr *) transformExpr(pstate, warg);
1167 neww->expr = (Expr *) coerce_to_boolean(pstate,
1168 (Node *) neww->expr,
1171 warg = (Node *) w->result;
1172 neww->result = (Expr *) transformExpr(pstate, warg);
1173 neww->location = w->location;
1175 newargs = lappend(newargs, neww);
1176 resultexprs = lappend(resultexprs, neww->result);
1179 newc->args = newargs;
1181 /* transform the default clause */
1182 defresult = (Node *) c->defresult;
1183 if (defresult == NULL)
1185 A_Const *n = makeNode(A_Const);
1187 n->val.type = T_Null;
1189 defresult = (Node *) n;
1191 newc->defresult = (Expr *) transformExpr(pstate, defresult);
1194 * Note: default result is considered the most significant type in
1195 * determining preferred type. This is how the code worked before, but it
1196 * seems a little bogus to me --- tgl
1198 resultexprs = lcons(newc->defresult, resultexprs);
1200 ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1201 Assert(OidIsValid(ptype));
1202 newc->casetype = ptype;
1204 /* Convert default result clause, if necessary */
1205 newc->defresult = (Expr *)
1206 coerce_to_common_type(pstate,
1207 (Node *) newc->defresult,
1211 /* Convert when-clause results, if necessary */
1212 foreach(l, newc->args)
1214 CaseWhen *w = (CaseWhen *) lfirst(l);
1216 w->result = (Expr *)
1217 coerce_to_common_type(pstate,
1223 newc->location = c->location;
1225 return (Node *) newc;
1229 transformSubLink(ParseState *pstate, SubLink *sublink)
1231 Node *result = (Node *) sublink;
1234 /* If we already transformed this node, do nothing */
1235 if (IsA(sublink->subselect, Query))
1238 pstate->p_hasSubLinks = true;
1239 qtree = parse_sub_analyze(sublink->subselect, pstate);
1242 * Check that we got something reasonable. Many of these conditions are
1243 * impossible given restrictions of the grammar, but check 'em anyway.
1245 if (!IsA(qtree, Query) ||
1246 qtree->commandType != CMD_SELECT ||
1247 qtree->utilityStmt != NULL)
1248 elog(ERROR, "unexpected non-SELECT command in SubLink");
1249 if (qtree->intoClause)
1251 (errcode(ERRCODE_SYNTAX_ERROR),
1252 errmsg("subquery cannot have SELECT INTO"),
1253 parser_errposition(pstate,
1254 exprLocation((Node *) qtree->intoClause))));
1256 sublink->subselect = (Node *) qtree;
1258 if (sublink->subLinkType == EXISTS_SUBLINK)
1261 * EXISTS needs no test expression or combining operator. These fields
1262 * should be null already, but make sure.
1264 sublink->testexpr = NULL;
1265 sublink->operName = NIL;
1267 else if (sublink->subLinkType == EXPR_SUBLINK ||
1268 sublink->subLinkType == ARRAY_SUBLINK)
1270 ListCell *tlist_item = list_head(qtree->targetList);
1273 * Make sure the subselect delivers a single column (ignoring resjunk
1276 if (tlist_item == NULL ||
1277 ((TargetEntry *) lfirst(tlist_item))->resjunk)
1279 (errcode(ERRCODE_SYNTAX_ERROR),
1280 errmsg("subquery must return a column"),
1281 parser_errposition(pstate, sublink->location)));
1282 while ((tlist_item = lnext(tlist_item)) != NULL)
1284 if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1286 (errcode(ERRCODE_SYNTAX_ERROR),
1287 errmsg("subquery must return only one column"),
1288 parser_errposition(pstate, sublink->location)));
1292 * EXPR and ARRAY need no test expression or combining operator. These
1293 * fields should be null already, but make sure.
1295 sublink->testexpr = NULL;
1296 sublink->operName = NIL;
1300 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1307 * Transform lefthand expression, and convert to a list
1309 lefthand = transformExpr(pstate, sublink->testexpr);
1310 if (lefthand && IsA(lefthand, RowExpr))
1311 left_list = ((RowExpr *) lefthand)->args;
1313 left_list = list_make1(lefthand);
1316 * Build a list of PARAM_SUBLINK nodes representing the output columns
1320 foreach(l, qtree->targetList)
1322 TargetEntry *tent = (TargetEntry *) lfirst(l);
1328 param = makeNode(Param);
1329 param->paramkind = PARAM_SUBLINK;
1330 param->paramid = tent->resno;
1331 param->paramtype = exprType((Node *) tent->expr);
1332 param->paramtypmod = exprTypmod((Node *) tent->expr);
1333 param->location = -1;
1335 right_list = lappend(right_list, param);
1339 * We could rely on make_row_comparison_op to complain if the list
1340 * lengths differ, but we prefer to generate a more specific error
1343 if (list_length(left_list) < list_length(right_list))
1345 (errcode(ERRCODE_SYNTAX_ERROR),
1346 errmsg("subquery has too many columns"),
1347 parser_errposition(pstate, sublink->location)));
1348 if (list_length(left_list) > list_length(right_list))
1350 (errcode(ERRCODE_SYNTAX_ERROR),
1351 errmsg("subquery has too few columns"),
1352 parser_errposition(pstate, sublink->location)));
1355 * Identify the combining operator(s) and generate a suitable
1356 * row-comparison expression.
1358 sublink->testexpr = make_row_comparison_op(pstate,
1369 * transformArrayExpr
1371 * If the caller specifies the target type, the resulting array will
1372 * be of exactly that type. Otherwise we try to infer a common type
1373 * for the elements using select_common_type().
1376 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
1377 Oid array_type, Oid element_type, int32 typmod)
1379 ArrayExpr *newa = makeNode(ArrayExpr);
1380 List *newelems = NIL;
1381 List *newcoercedelems = NIL;
1387 * Transform the element expressions
1389 * Assume that the array is one-dimensional unless we find an
1390 * array-type element expression.
1392 newa->multidims = false;
1393 foreach(element, a->elements)
1395 Node *e = (Node *) lfirst(element);
1399 * If an element is itself an A_ArrayExpr, recurse directly so that
1400 * we can pass down any target type we were given.
1402 if (IsA(e, A_ArrayExpr))
1404 newe = transformArrayExpr(pstate,
1409 /* we certainly have an array here */
1410 Assert(array_type == InvalidOid || array_type == exprType(newe));
1411 newa->multidims = true;
1415 newe = transformExpr(pstate, e);
1417 * Check for sub-array expressions, if we haven't already
1420 if (!newa->multidims && type_is_array(exprType(newe)))
1421 newa->multidims = true;
1424 newelems = lappend(newelems, newe);
1428 * Select a target type for the elements.
1430 * If we haven't been given a target array type, we must try to deduce a
1431 * common type based on the types of the individual elements present.
1433 if (OidIsValid(array_type))
1435 /* Caller must ensure array_type matches element_type */
1436 Assert(OidIsValid(element_type));
1437 coerce_type = (newa->multidims ? array_type : element_type);
1442 /* Can't handle an empty array without a target type */
1443 if (newelems == NIL)
1445 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1446 errmsg("cannot determine type of empty array"),
1447 errhint("Explicitly cast to the desired type, "
1448 "for example ARRAY[]::integer[]."),
1449 parser_errposition(pstate, a->location)));
1451 /* Select a common type for the elements */
1452 coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1454 if (newa->multidims)
1456 array_type = coerce_type;
1457 element_type = get_element_type(array_type);
1458 if (!OidIsValid(element_type))
1460 (errcode(ERRCODE_UNDEFINED_OBJECT),
1461 errmsg("could not find element type for data type %s",
1462 format_type_be(array_type)),
1463 parser_errposition(pstate, a->location)));
1467 element_type = coerce_type;
1468 array_type = get_array_type(element_type);
1469 if (!OidIsValid(array_type))
1471 (errcode(ERRCODE_UNDEFINED_OBJECT),
1472 errmsg("could not find array type for data type %s",
1473 format_type_be(element_type)),
1474 parser_errposition(pstate, a->location)));
1476 coerce_hard = false;
1480 * Coerce elements to target type
1482 * If the array has been explicitly cast, then the elements are in turn
1483 * explicitly coerced.
1485 * If the array's type was merely derived from the common type of its
1486 * elements, then the elements are implicitly coerced to the common type.
1487 * This is consistent with other uses of select_common_type().
1489 foreach(element, newelems)
1491 Node *e = (Node *) lfirst(element);
1496 newe = coerce_to_target_type(pstate, e,
1501 COERCE_EXPLICIT_CAST,
1505 (errcode(ERRCODE_CANNOT_COERCE),
1506 errmsg("cannot cast type %s to %s",
1507 format_type_be(exprType(e)),
1508 format_type_be(coerce_type)),
1509 parser_errposition(pstate, exprLocation(e))));
1512 newe = coerce_to_common_type(pstate, e,
1515 newcoercedelems = lappend(newcoercedelems, newe);
1518 newa->array_typeid = array_type;
1519 newa->element_typeid = element_type;
1520 newa->elements = newcoercedelems;
1521 newa->location = a->location;
1523 return (Node *) newa;
1527 transformRowExpr(ParseState *pstate, RowExpr *r)
1529 RowExpr *newr = makeNode(RowExpr);
1531 /* Transform the field expressions */
1532 newr->args = transformExpressionList(pstate, r->args);
1534 /* Barring later casting, we consider the type RECORD */
1535 newr->row_typeid = RECORDOID;
1536 newr->row_format = COERCE_IMPLICIT_CAST;
1537 newr->colnames = NIL; /* ROW() has anonymous columns */
1538 newr->location = r->location;
1540 return (Node *) newr;
1544 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
1546 CoalesceExpr *newc = makeNode(CoalesceExpr);
1547 List *newargs = NIL;
1548 List *newcoercedargs = NIL;
1551 foreach(args, c->args)
1553 Node *e = (Node *) lfirst(args);
1556 newe = transformExpr(pstate, e);
1557 newargs = lappend(newargs, newe);
1560 newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1562 /* Convert arguments if necessary */
1563 foreach(args, newargs)
1565 Node *e = (Node *) lfirst(args);
1568 newe = coerce_to_common_type(pstate, e,
1571 newcoercedargs = lappend(newcoercedargs, newe);
1574 newc->args = newcoercedargs;
1575 newc->location = c->location;
1576 return (Node *) newc;
1580 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
1582 MinMaxExpr *newm = makeNode(MinMaxExpr);
1583 List *newargs = NIL;
1584 List *newcoercedargs = NIL;
1585 const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1589 foreach(args, m->args)
1591 Node *e = (Node *) lfirst(args);
1594 newe = transformExpr(pstate, e);
1595 newargs = lappend(newargs, newe);
1598 newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1600 /* Convert arguments if necessary */
1601 foreach(args, newargs)
1603 Node *e = (Node *) lfirst(args);
1606 newe = coerce_to_common_type(pstate, e,
1609 newcoercedargs = lappend(newcoercedargs, newe);
1612 newm->args = newcoercedargs;
1613 newm->location = m->location;
1614 return (Node *) newm;
1618 transformXmlExpr(ParseState *pstate, XmlExpr *x)
1620 XmlExpr *newx = makeNode(XmlExpr);
1626 newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1629 newx->xmloption = x->xmloption;
1630 newx->location = x->location;
1633 * gram.y built the named args as a list of ResTarget. Transform each,
1634 * and break the names out as a separate list.
1636 newx->named_args = NIL;
1637 newx->arg_names = NIL;
1639 foreach(lc, x->named_args)
1641 ResTarget *r = (ResTarget *) lfirst(lc);
1645 Assert(IsA(r, ResTarget));
1647 expr = transformExpr(pstate, r->val);
1650 argname = map_sql_identifier_to_xml_name(r->name, false, false);
1651 else if (IsA(r->val, ColumnRef))
1652 argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1657 (errcode(ERRCODE_SYNTAX_ERROR),
1658 x->op == IS_XMLELEMENT
1659 ? errmsg("unnamed XML attribute value must be a column reference")
1660 : errmsg("unnamed XML element value must be a column reference"),
1661 parser_errposition(pstate, r->location)));
1662 argname = NULL; /* keep compiler quiet */
1665 /* reject duplicate argnames in XMLELEMENT only */
1666 if (x->op == IS_XMLELEMENT)
1670 foreach(lc2, newx->arg_names)
1672 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1674 (errcode(ERRCODE_SYNTAX_ERROR),
1675 errmsg("XML attribute name \"%s\" appears more than once",
1677 parser_errposition(pstate, r->location)));
1681 newx->named_args = lappend(newx->named_args, expr);
1682 newx->arg_names = lappend(newx->arg_names, makeString(argname));
1685 /* The other arguments are of varying types depending on the function */
1688 foreach(lc, x->args)
1690 Node *e = (Node *) lfirst(lc);
1693 newe = transformExpr(pstate, e);
1697 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1701 /* no coercion necessary */
1704 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1709 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1712 newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
1715 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1720 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1723 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1726 newe = coerce_to_specific_type(pstate, newe, INT4OID,
1729 case IS_XMLSERIALIZE:
1730 /* not handled here */
1734 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1738 newx->args = lappend(newx->args, newe);
1742 return (Node *) newx;
1746 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1753 xexpr = makeNode(XmlExpr);
1754 xexpr->op = IS_XMLSERIALIZE;
1755 xexpr->args = list_make1(coerce_to_specific_type(pstate,
1756 transformExpr(pstate, xs->expr),
1760 targetType = typenameTypeId(pstate, xs->typename, &targetTypmod);
1762 xexpr->xmloption = xs->xmloption;
1763 xexpr->location = xs->location;
1764 /* We actually only need these to be able to parse back the expression. */
1765 xexpr->type = targetType;
1766 xexpr->typmod = targetTypmod;
1769 * The actual target type is determined this way. SQL allows char and
1770 * varchar as target types. We allow anything that can be cast implicitly
1771 * from text. This way, user-defined text-like data types automatically
1774 result = coerce_to_target_type(pstate, (Node *) xexpr,
1775 TEXTOID, targetType, targetTypmod,
1777 COERCE_IMPLICIT_CAST,
1781 (errcode(ERRCODE_CANNOT_COERCE),
1782 errmsg("cannot cast XMLSERIALIZE result to %s",
1783 format_type_be(targetType)),
1784 parser_errposition(pstate, xexpr->location)));
1789 transformBooleanTest(ParseState *pstate, BooleanTest *b)
1791 const char *clausename;
1793 switch (b->booltesttype)
1796 clausename = "IS TRUE";
1799 clausename = "IS NOT TRUE";
1802 clausename = "IS FALSE";
1805 clausename = "IS NOT FALSE";
1808 clausename = "IS UNKNOWN";
1810 case IS_NOT_UNKNOWN:
1811 clausename = "IS NOT UNKNOWN";
1814 elog(ERROR, "unrecognized booltesttype: %d",
1815 (int) b->booltesttype);
1816 clausename = NULL; /* keep compiler quiet */
1819 b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
1821 b->arg = (Expr *) coerce_to_boolean(pstate,
1829 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1833 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1834 Assert(pstate->p_target_rangetblentry != NULL);
1835 cexpr->cvarno = RTERangeTablePosn(pstate,
1836 pstate->p_target_rangetblentry,
1838 Assert(sublevels_up == 0);
1840 /* If a parameter is used, it must be of type REFCURSOR */
1841 if (cexpr->cursor_name == NULL)
1843 Oid *pptype = find_param_type(pstate, cexpr->cursor_param, -1);
1845 if (pstate->p_variableparams && *pptype == UNKNOWNOID)
1847 /* resolve unknown param type as REFCURSOR */
1848 *pptype = REFCURSOROID;
1850 else if (*pptype != REFCURSOROID)
1853 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
1854 errmsg("inconsistent types deduced for parameter $%d",
1855 cexpr->cursor_param),
1856 errdetail("%s versus %s",
1857 format_type_be(*pptype),
1858 format_type_be(REFCURSOROID))));
1862 return (Node *) cexpr;
1866 * Construct a whole-row reference to represent the notation "relation.*".
1868 * A whole-row reference is a Var with varno set to the correct range
1869 * table entry, and varattno == 0 to signal that it references the whole
1870 * tuple. (Use of zero here is unclean, since it could easily be confused
1871 * with error cases, but it's not worth changing now.) The vartype indicates
1872 * a rowtype; either a named composite type, or RECORD.
1875 transformWholeRowRef(ParseState *pstate, char *schemaname, char *relname,
1884 /* Look up the referenced RTE, creating it if needed */
1886 rte = refnameRangeTblEntry(pstate, schemaname, relname, location,
1890 rte = addImplicitRTE(pstate,
1891 makeRangeVar(schemaname, relname, location));
1893 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
1895 /* Build the appropriate referencing node */
1897 switch (rte->rtekind)
1900 /* relation: the rowtype is a named composite type */
1901 toid = get_rel_type_id(rte->relid);
1902 if (!OidIsValid(toid))
1903 elog(ERROR, "could not find type OID for relation %u",
1905 result = makeVar(vnum,
1912 toid = exprType(rte->funcexpr);
1913 if (type_is_rowtype(toid))
1915 /* func returns composite; same as relation case */
1916 result = makeVar(vnum,
1925 * func returns scalar; instead of making a whole-row Var,
1926 * just reference the function's scalar output. (XXX this
1927 * seems a tad inconsistent, especially if "f.*" was
1928 * explicitly written ...)
1930 result = makeVar(vnum,
1939 /* returns composite; same as relation case */
1940 result = makeVar(vnum,
1949 * RTE is a join or subselect. We represent this as a whole-row
1950 * Var of RECORD type. (Note that in most cases the Var will be
1951 * expanded to a RowExpr during planning, but that is not our
1954 result = makeVar(vnum,
1962 /* location is not filled in by makeVar */
1963 result->location = location;
1965 return (Node *) result;
1969 * Handle an explicit CAST construct.
1971 * Transform the argument, then look up the type name and apply any necessary
1972 * coercion function(s).
1975 transformTypeCast(ParseState *pstate, TypeCast *tc)
1978 Node *expr = transformExpr(pstate, tc->arg);
1979 Oid inputType = exprType(expr);
1984 targetType = typenameTypeId(pstate, tc->typename, &targetTypmod);
1986 if (inputType == InvalidOid)
1987 return expr; /* do nothing if NULL input */
1990 * Location of the coercion is preferentially the location of the :: or
1991 * CAST symbol, but if there is none then use the location of the type
1992 * name (this can happen in TypeName 'string' syntax, for instance).
1994 location = tc->location;
1996 location = tc->typename->location;
1998 result = coerce_to_target_type(pstate, expr, inputType,
1999 targetType, targetTypmod,
2001 COERCE_EXPLICIT_CAST,
2005 (errcode(ERRCODE_CANNOT_COERCE),
2006 errmsg("cannot cast type %s to %s",
2007 format_type_be(inputType),
2008 format_type_be(targetType)),
2009 parser_coercion_errposition(pstate, location, expr)));
2015 * Transform a "row compare-op row" construct
2017 * The inputs are lists of already-transformed expressions.
2018 * As with coerce_type, pstate may be NULL if no special unknown-Param
2019 * processing is wanted.
2021 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2022 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2023 * The AND, OR, and RowCompareExpr cases further imply things about the
2024 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2027 make_row_comparison_op(ParseState *pstate, List *opname,
2028 List *largs, List *rargs, int location)
2030 RowCompareExpr *rcexpr;
2031 RowCompareType rctype;
2037 List **opfamily_lists;
2038 List **opstrat_lists;
2043 nopers = list_length(largs);
2044 if (nopers != list_length(rargs))
2046 (errcode(ERRCODE_SYNTAX_ERROR),
2047 errmsg("unequal number of entries in row expressions"),
2048 parser_errposition(pstate, location)));
2051 * We can't compare zero-length rows because there is no principled basis
2052 * for figuring out what the operator is.
2056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2057 errmsg("cannot compare rows of zero length"),
2058 parser_errposition(pstate, location)));
2061 * Identify all the pairwise operators, using make_op so that behavior is
2062 * the same as in the simple scalar case.
2065 forboth(l, largs, r, rargs)
2067 Node *larg = (Node *) lfirst(l);
2068 Node *rarg = (Node *) lfirst(r);
2071 cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2072 Assert(IsA(cmp, OpExpr));
2075 * We don't use coerce_to_boolean here because we insist on the
2076 * operator yielding boolean directly, not via coercion. If it
2077 * doesn't yield bool it won't be in any index opfamilies...
2079 if (cmp->opresulttype != BOOLOID)
2081 (errcode(ERRCODE_DATATYPE_MISMATCH),
2082 errmsg("row comparison operator must yield type boolean, "
2084 format_type_be(cmp->opresulttype)),
2085 parser_errposition(pstate, location)));
2086 if (expression_returns_set((Node *) cmp))
2088 (errcode(ERRCODE_DATATYPE_MISMATCH),
2089 errmsg("row comparison operator must not return a set"),
2090 parser_errposition(pstate, location)));
2091 opexprs = lappend(opexprs, cmp);
2095 * If rows are length 1, just return the single operator. In this case we
2096 * don't insist on identifying btree semantics for the operator (but we
2097 * still require it to return boolean).
2100 return (Node *) linitial(opexprs);
2103 * Now we must determine which row comparison semantics (= <> < <= > >=)
2104 * apply to this set of operators. We look for btree opfamilies
2105 * containing the operators, and see which interpretations (strategy
2106 * numbers) exist for each operator.
2108 opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2109 opstrat_lists = (List **) palloc(nopers * sizeof(List *));
2114 Oid opno = ((OpExpr *) lfirst(l))->opno;
2115 Bitmapset *this_strats;
2118 get_op_btree_interpretation(opno,
2119 &opfamily_lists[i], &opstrat_lists[i]);
2122 * convert strategy number list to a Bitmapset to make the
2123 * intersection calculation easy.
2126 foreach(j, opstrat_lists[i])
2128 this_strats = bms_add_member(this_strats, lfirst_int(j));
2131 strats = this_strats;
2133 strats = bms_int_members(strats, this_strats);
2138 * If there are multiple common interpretations, we may use any one of
2139 * them ... this coding arbitrarily picks the lowest btree strategy
2142 i = bms_first_member(strats);
2145 /* No common interpretation, so fail */
2147 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2148 errmsg("could not determine interpretation of row comparison operator %s",
2149 strVal(llast(opname))),
2150 errhint("Row comparison operators must be associated with btree operator families."),
2151 parser_errposition(pstate, location)));
2153 rctype = (RowCompareType) i;
2156 * For = and <> cases, we just combine the pairwise operators with AND or
2159 * Note: this is presently the only place where the parser generates
2160 * BoolExpr with more than two arguments. Should be OK since the rest of
2161 * the system thinks BoolExpr is N-argument anyway.
2163 if (rctype == ROWCOMPARE_EQ)
2164 return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2165 if (rctype == ROWCOMPARE_NE)
2166 return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2169 * Otherwise we need to choose exactly which opfamily to associate with
2173 for (i = 0; i < nopers; i++)
2175 Oid opfamily = InvalidOid;
2177 forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2179 int opstrat = lfirst_int(r);
2181 if (opstrat == rctype)
2183 opfamily = lfirst_oid(l);
2187 if (OidIsValid(opfamily))
2188 opfamilies = lappend_oid(opfamilies, opfamily);
2189 else /* should not happen */
2191 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2192 errmsg("could not determine interpretation of row comparison operator %s",
2193 strVal(llast(opname))),
2194 errdetail("There are multiple equally-plausible candidates."),
2195 parser_errposition(pstate, location)));
2199 * Now deconstruct the OpExprs and create a RowCompareExpr.
2201 * Note: can't just reuse the passed largs/rargs lists, because of
2202 * possibility that make_op inserted coercion operations.
2209 OpExpr *cmp = (OpExpr *) lfirst(l);
2211 opnos = lappend_oid(opnos, cmp->opno);
2212 largs = lappend(largs, linitial(cmp->args));
2213 rargs = lappend(rargs, lsecond(cmp->args));
2216 rcexpr = makeNode(RowCompareExpr);
2217 rcexpr->rctype = rctype;
2218 rcexpr->opnos = opnos;
2219 rcexpr->opfamilies = opfamilies;
2220 rcexpr->largs = largs;
2221 rcexpr->rargs = rargs;
2223 return (Node *) rcexpr;
2227 * Transform a "row IS DISTINCT FROM row" construct
2229 * The input RowExprs are already transformed
2232 make_row_distinct_op(ParseState *pstate, List *opname,
2233 RowExpr *lrow, RowExpr *rrow,
2236 Node *result = NULL;
2237 List *largs = lrow->args;
2238 List *rargs = rrow->args;
2242 if (list_length(largs) != list_length(rargs))
2244 (errcode(ERRCODE_SYNTAX_ERROR),
2245 errmsg("unequal number of entries in row expressions"),
2246 parser_errposition(pstate, location)));
2248 forboth(l, largs, r, rargs)
2250 Node *larg = (Node *) lfirst(l);
2251 Node *rarg = (Node *) lfirst(r);
2254 cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2258 result = (Node *) makeBoolExpr(OR_EXPR,
2259 list_make2(result, cmp),
2265 /* zero-length rows? Generate constant FALSE */
2266 result = makeBoolConst(false, false);
2273 * make the node for an IS DISTINCT FROM operator
2276 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
2281 result = make_op(pstate, opname, ltree, rtree, location);
2282 if (((OpExpr *) result)->opresulttype != BOOLOID)
2284 (errcode(ERRCODE_DATATYPE_MISMATCH),
2285 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2286 parser_errposition(pstate, location)));
2289 * We rely on DistinctExpr and OpExpr being same struct
2291 NodeSetTag(result, T_DistinctExpr);