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
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 "optimizer/var.h"
24 #include "parser/analyze.h"
25 #include "parser/parse_coerce.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_func.h"
28 #include "parser/parse_oper.h"
29 #include "parser/parse_relation.h"
30 #include "parser/parse_target.h"
31 #include "parser/parse_type.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/xml.h"
37 bool Transform_null_equals
= false;
39 static Node
*transformParamRef(ParseState
*pstate
, ParamRef
*pref
);
40 static Node
*transformAExprOp(ParseState
*pstate
, A_Expr
*a
);
41 static Node
*transformAExprAnd(ParseState
*pstate
, A_Expr
*a
);
42 static Node
*transformAExprOr(ParseState
*pstate
, A_Expr
*a
);
43 static Node
*transformAExprNot(ParseState
*pstate
, A_Expr
*a
);
44 static Node
*transformAExprOpAny(ParseState
*pstate
, A_Expr
*a
);
45 static Node
*transformAExprOpAll(ParseState
*pstate
, A_Expr
*a
);
46 static Node
*transformAExprDistinct(ParseState
*pstate
, A_Expr
*a
);
47 static Node
*transformAExprNullIf(ParseState
*pstate
, A_Expr
*a
);
48 static Node
*transformAExprOf(ParseState
*pstate
, A_Expr
*a
);
49 static Node
*transformAExprIn(ParseState
*pstate
, A_Expr
*a
);
50 static Node
*transformFuncCall(ParseState
*pstate
, FuncCall
*fn
);
51 static Node
*transformCaseExpr(ParseState
*pstate
, CaseExpr
*c
);
52 static Node
*transformSubLink(ParseState
*pstate
, SubLink
*sublink
);
53 static Node
*transformArrayExpr(ParseState
*pstate
, A_ArrayExpr
*a
,
54 Oid array_type
, Oid element_type
, int32 typmod
);
55 static Node
*transformRowExpr(ParseState
*pstate
, RowExpr
*r
);
56 static Node
*transformCoalesceExpr(ParseState
*pstate
, CoalesceExpr
*c
);
57 static Node
*transformMinMaxExpr(ParseState
*pstate
, MinMaxExpr
*m
);
58 static Node
*transformXmlExpr(ParseState
*pstate
, XmlExpr
*x
);
59 static Node
*transformXmlSerialize(ParseState
*pstate
, XmlSerialize
*xs
);
60 static Node
*transformBooleanTest(ParseState
*pstate
, BooleanTest
*b
);
61 static Node
*transformCurrentOfExpr(ParseState
*pstate
, CurrentOfExpr
*cexpr
);
62 static Node
*transformColumnRef(ParseState
*pstate
, ColumnRef
*cref
);
63 static Node
*transformWholeRowRef(ParseState
*pstate
, char *schemaname
,
64 char *relname
, int location
);
65 static Node
*transformIndirection(ParseState
*pstate
, Node
*basenode
,
67 static Node
*transformTypeCast(ParseState
*pstate
, TypeCast
*tc
);
68 static Node
*make_row_comparison_op(ParseState
*pstate
, List
*opname
,
69 List
*largs
, List
*rargs
, int location
);
70 static Node
*make_row_distinct_op(ParseState
*pstate
, List
*opname
,
71 RowExpr
*lrow
, RowExpr
*rrow
, int location
);
72 static Expr
*make_distinct_op(ParseState
*pstate
, List
*opname
,
73 Node
*ltree
, Node
*rtree
, int location
);
78 * Analyze and transform expressions. Type checking and type casting is
79 * done here. The optimizer and the executor cannot handle the original
80 * (raw) expressions collected by the parse tree. Hence the transformation
83 * NOTE: there are various cases in which this routine will get applied to
84 * an already-transformed expression. Some examples:
85 * 1. At least one construct (BETWEEN/AND) puts the same nodes
86 * into two branches of the parse tree; hence, some nodes
87 * are transformed twice.
88 * 2. Another way it can happen is that coercion of an operator or
89 * function argument to the required type (via coerce_type())
90 * can apply transformExpr to an already-transformed subexpression.
91 * An example here is "SELECT count(*) + 1.0 FROM table".
92 * While it might be possible to eliminate these cases, the path of
93 * least resistance so far has been to ensure that transformExpr() does
94 * no damage if applied to an already-transformed tree. This is pretty
95 * easy for cases where the transformation replaces one node type with
96 * another, such as A_Const => Const; we just do nothing when handed
97 * a Const. More care is needed for node types that are used as both
98 * input and output of transformExpr; see SubLink for example.
101 transformExpr(ParseState
*pstate
, Node
*expr
)
108 /* Guard against stack overflow due to overly complex expressions */
111 switch (nodeTag(expr
))
114 result
= transformColumnRef(pstate
, (ColumnRef
*) expr
);
118 result
= transformParamRef(pstate
, (ParamRef
*) expr
);
123 A_Const
*con
= (A_Const
*) expr
;
124 Value
*val
= &con
->val
;
126 result
= (Node
*) make_const(pstate
, val
, con
->location
);
130 case T_A_Indirection
:
132 A_Indirection
*ind
= (A_Indirection
*) expr
;
134 result
= transformExpr(pstate
, ind
->arg
);
135 result
= transformIndirection(pstate
, result
,
141 result
= transformArrayExpr(pstate
, (A_ArrayExpr
*) expr
,
142 InvalidOid
, InvalidOid
, -1);
147 TypeCast
*tc
= (TypeCast
*) expr
;
150 * If the subject of the typecast is an ARRAY[] construct
151 * and the target type is an array type, we invoke
152 * transformArrayExpr() directly so that we can pass down
153 * the type information. This avoids some cases where
154 * transformArrayExpr() might not infer the correct type.
156 if (IsA(tc
->arg
, A_ArrayExpr
))
162 targetType
= typenameTypeId(pstate
, tc
->typename
,
164 elementType
= get_element_type(targetType
);
165 if (OidIsValid(elementType
))
167 result
= transformArrayExpr(pstate
,
168 (A_ArrayExpr
*) tc
->arg
,
176 * Corner case: ARRAY[] cast to a non-array type.
177 * Fall through to do it the standard way.
181 result
= transformTypeCast(pstate
, tc
);
187 A_Expr
*a
= (A_Expr
*) expr
;
192 result
= transformAExprOp(pstate
, a
);
195 result
= transformAExprAnd(pstate
, a
);
198 result
= transformAExprOr(pstate
, a
);
201 result
= transformAExprNot(pstate
, a
);
204 result
= transformAExprOpAny(pstate
, a
);
207 result
= transformAExprOpAll(pstate
, a
);
210 result
= transformAExprDistinct(pstate
, a
);
213 result
= transformAExprNullIf(pstate
, a
);
216 result
= transformAExprOf(pstate
, a
);
219 result
= transformAExprIn(pstate
, a
);
222 elog(ERROR
, "unrecognized A_Expr kind: %d", a
->kind
);
228 result
= transformFuncCall(pstate
, (FuncCall
*) expr
);
232 result
= transformSubLink(pstate
, (SubLink
*) expr
);
236 result
= transformCaseExpr(pstate
, (CaseExpr
*) expr
);
240 result
= transformRowExpr(pstate
, (RowExpr
*) expr
);
244 result
= transformCoalesceExpr(pstate
, (CoalesceExpr
*) expr
);
248 result
= transformMinMaxExpr(pstate
, (MinMaxExpr
*) expr
);
252 result
= transformXmlExpr(pstate
, (XmlExpr
*) expr
);
256 result
= transformXmlSerialize(pstate
, (XmlSerialize
*) expr
);
261 NullTest
*n
= (NullTest
*) expr
;
263 n
->arg
= (Expr
*) transformExpr(pstate
, (Node
*) n
->arg
);
264 /* the argument can be any type, so don't coerce it */
270 result
= transformBooleanTest(pstate
, (BooleanTest
*) expr
);
273 case T_CurrentOfExpr
:
274 result
= transformCurrentOfExpr(pstate
, (CurrentOfExpr
*) expr
);
277 /*********************************************
278 * Quietly accept node types that may be presented when we are
279 * called on an already-transformed tree.
281 * Do any other node types need to be accepted? For now we are
282 * taking a conservative approach, and only accepting node
283 * types that are demonstrably necessary to accept.
284 *********************************************/
293 case T_ScalarArrayOpExpr
:
300 case T_ArrayCoerceExpr
:
301 case T_ConvertRowtypeExpr
:
303 case T_CoerceToDomain
:
304 case T_CoerceToDomainValue
:
307 result
= (Node
*) expr
;
312 /* should not reach here */
313 elog(ERROR
, "unrecognized node type: %d", (int) nodeTag(expr
));
321 transformIndirection(ParseState
*pstate
, Node
*basenode
, List
*indirection
)
323 Node
*result
= basenode
;
324 List
*subscripts
= NIL
;
328 * We have to split any field-selection operations apart from
329 * subscripting. Adjacent A_Indices nodes have to be treated as a single
330 * multidimensional subscript operation.
332 foreach(i
, indirection
)
336 if (IsA(n
, A_Indices
))
337 subscripts
= lappend(subscripts
, n
);
338 else if (IsA(n
, A_Star
))
341 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
342 errmsg("row expansion via \"*\" is not supported here"),
343 parser_errposition(pstate
, exprLocation(basenode
))));
347 Assert(IsA(n
, String
));
349 /* process subscripts before this field selection */
351 result
= (Node
*) transformArraySubscripts(pstate
,
360 result
= ParseFuncOrColumn(pstate
,
367 /* process trailing subscripts, if any */
369 result
= (Node
*) transformArraySubscripts(pstate
,
381 transformColumnRef(ParseState
*pstate
, ColumnRef
*cref
)
383 int numnames
= list_length(cref
->fields
);
388 * The allowed syntaxes are:
390 * A First try to resolve as unqualified column name;
391 * if no luck, try to resolve as unqualified table name (A.*).
392 * A.B A is an unqualified table name; B is either a
393 * column or function name (trying column name first).
394 * A.B.C schema A, table B, col or func name C.
395 * A.B.C.D catalog A, schema B, table C, col or func D.
396 * A.* A is an unqualified table name; means whole-row value.
397 * A.B.* whole-row value of table B in schema A.
398 * A.B.C.* whole-row value of table C in schema B in catalog A.
400 * We do not need to cope with bare "*"; that will only be accepted by
401 * the grammar at the top level of a SELECT list, and transformTargetList
402 * will take care of it before it ever gets here. Also, "A.*" etc will
403 * be expanded by transformTargetList if they appear at SELECT top level,
404 * so here we are only going to see them as function or operator inputs.
406 * Currently, if a catalog name is given then it must equal the current
407 * database name; we check it here and then discard it.
414 Node
*field1
= (Node
*) linitial(cref
->fields
);
417 Assert(IsA(field1
, String
));
418 name1
= strVal(field1
);
420 /* Try to identify as an unqualified column */
421 node
= colNameToVar(pstate
, name1
, false, cref
->location
);
426 * Not known as a column of any range-table entry.
428 * Consider the possibility that it's VALUE in a domain
429 * check expression. (We handle VALUE as a name, not a
430 * keyword, to avoid breaking a lot of applications that
431 * have used VALUE as a column name in the past.)
433 if (pstate
->p_value_substitute
!= NULL
&&
434 strcmp(name1
, "value") == 0)
436 node
= (Node
*) copyObject(pstate
->p_value_substitute
);
439 * Try to propagate location knowledge. This should
440 * be extended if p_value_substitute can ever take on
443 if (IsA(node
, CoerceToDomainValue
))
444 ((CoerceToDomainValue
*) node
)->location
= cref
->location
;
449 * Try to find the name as a relation. Note that only
450 * relations already entered into the rangetable will be
453 * This is a hack for backwards compatibility with
454 * PostQUEL-inspired syntax. The preferred form now is
457 if (refnameRangeTblEntry(pstate
, NULL
, name1
,
460 node
= transformWholeRowRef(pstate
, NULL
, name1
,
464 (errcode(ERRCODE_UNDEFINED_COLUMN
),
465 errmsg("column \"%s\" does not exist",
467 parser_errposition(pstate
, cref
->location
)));
473 Node
*field1
= (Node
*) linitial(cref
->fields
);
474 Node
*field2
= (Node
*) lsecond(cref
->fields
);
478 Assert(IsA(field1
, String
));
479 name1
= strVal(field1
);
481 /* Whole-row reference? */
482 if (IsA(field2
, A_Star
))
484 node
= transformWholeRowRef(pstate
, NULL
, name1
,
489 Assert(IsA(field2
, String
));
490 name2
= strVal(field2
);
492 /* Try to identify as a once-qualified column */
493 node
= qualifiedNameToVar(pstate
, NULL
, name1
, name2
, true,
498 * Not known as a column of any range-table entry, so try
499 * it as a function call. Here, we will create an
500 * implicit RTE for tables not already entered.
502 node
= transformWholeRowRef(pstate
, NULL
, name1
,
504 node
= ParseFuncOrColumn(pstate
,
505 list_make1(makeString(name2
)),
508 true, cref
->location
);
514 Node
*field1
= (Node
*) linitial(cref
->fields
);
515 Node
*field2
= (Node
*) lsecond(cref
->fields
);
516 Node
*field3
= (Node
*) lthird(cref
->fields
);
521 Assert(IsA(field1
, String
));
522 name1
= strVal(field1
);
523 Assert(IsA(field2
, String
));
524 name2
= strVal(field2
);
526 /* Whole-row reference? */
527 if (IsA(field3
, A_Star
))
529 node
= transformWholeRowRef(pstate
, name1
, name2
,
534 Assert(IsA(field3
, String
));
535 name3
= strVal(field3
);
537 /* Try to identify as a twice-qualified column */
538 node
= qualifiedNameToVar(pstate
, name1
, name2
, name3
, true,
542 /* Try it as a function call */
543 node
= transformWholeRowRef(pstate
, name1
, name2
,
545 node
= ParseFuncOrColumn(pstate
,
546 list_make1(makeString(name3
)),
549 true, cref
->location
);
555 Node
*field1
= (Node
*) linitial(cref
->fields
);
556 Node
*field2
= (Node
*) lsecond(cref
->fields
);
557 Node
*field3
= (Node
*) lthird(cref
->fields
);
558 Node
*field4
= (Node
*) lfourth(cref
->fields
);
564 Assert(IsA(field1
, String
));
565 name1
= strVal(field1
);
566 Assert(IsA(field2
, String
));
567 name2
= strVal(field2
);
568 Assert(IsA(field3
, String
));
569 name3
= strVal(field3
);
572 * We check the catalog name and then ignore it.
574 if (strcmp(name1
, get_database_name(MyDatabaseId
)) != 0)
576 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
577 errmsg("cross-database references are not implemented: %s",
578 NameListToString(cref
->fields
)),
579 parser_errposition(pstate
, cref
->location
)));
581 /* Whole-row reference? */
582 if (IsA(field4
, A_Star
))
584 node
= transformWholeRowRef(pstate
, name2
, name3
,
589 Assert(IsA(field4
, String
));
590 name4
= strVal(field4
);
592 /* Try to identify as a twice-qualified column */
593 node
= qualifiedNameToVar(pstate
, name2
, name3
, name4
, true,
597 /* Try it as a function call */
598 node
= transformWholeRowRef(pstate
, name2
, name3
,
600 node
= ParseFuncOrColumn(pstate
,
601 list_make1(makeString(name4
)),
604 true, cref
->location
);
610 (errcode(ERRCODE_SYNTAX_ERROR
),
611 errmsg("improper qualified name (too many dotted names): %s",
612 NameListToString(cref
->fields
)),
613 parser_errposition(pstate
, cref
->location
)));
614 node
= NULL
; /* keep compiler quiet */
622 * Locate the parameter type info for the given parameter number, and
623 * return a pointer to it.
626 find_param_type(ParseState
*pstate
, int paramno
, int location
)
631 * Find topmost ParseState, which is where paramtype info lives.
633 while (pstate
->parentParseState
!= NULL
)
634 pstate
= pstate
->parentParseState
;
636 /* Check parameter number is in range */
637 if (paramno
<= 0) /* probably can't happen? */
639 (errcode(ERRCODE_UNDEFINED_PARAMETER
),
640 errmsg("there is no parameter $%d", paramno
),
641 parser_errposition(pstate
, location
)));
642 if (paramno
> pstate
->p_numparams
)
644 if (!pstate
->p_variableparams
)
646 (errcode(ERRCODE_UNDEFINED_PARAMETER
),
647 errmsg("there is no parameter $%d", paramno
),
648 parser_errposition(pstate
, location
)));
649 /* Okay to enlarge param array */
650 if (pstate
->p_paramtypes
)
651 pstate
->p_paramtypes
= (Oid
*) repalloc(pstate
->p_paramtypes
,
652 paramno
* sizeof(Oid
));
654 pstate
->p_paramtypes
= (Oid
*) palloc(paramno
* sizeof(Oid
));
655 /* Zero out the previously-unreferenced slots */
656 MemSet(pstate
->p_paramtypes
+ pstate
->p_numparams
,
658 (paramno
- pstate
->p_numparams
) * sizeof(Oid
));
659 pstate
->p_numparams
= paramno
;
662 result
= &pstate
->p_paramtypes
[paramno
- 1];
664 if (pstate
->p_variableparams
)
666 /* If not seen before, initialize to UNKNOWN type */
667 if (*result
== InvalidOid
)
668 *result
= UNKNOWNOID
;
675 transformParamRef(ParseState
*pstate
, ParamRef
*pref
)
677 int paramno
= pref
->number
;
678 Oid
*pptype
= find_param_type(pstate
, paramno
, pref
->location
);
681 param
= makeNode(Param
);
682 param
->paramkind
= PARAM_EXTERN
;
683 param
->paramid
= paramno
;
684 param
->paramtype
= *pptype
;
685 param
->paramtypmod
= -1;
686 param
->location
= pref
->location
;
688 return (Node
*) param
;
691 /* Test whether an a_expr is a plain NULL constant or not */
693 exprIsNullConstant(Node
*arg
)
695 if (arg
&& IsA(arg
, A_Const
))
697 A_Const
*con
= (A_Const
*) arg
;
699 if (con
->val
.type
== T_Null
)
706 transformAExprOp(ParseState
*pstate
, A_Expr
*a
)
708 Node
*lexpr
= a
->lexpr
;
709 Node
*rexpr
= a
->rexpr
;
713 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
714 * standards-broken products (like Microsoft's). Turn these into IS NULL
717 if (Transform_null_equals
&&
718 list_length(a
->name
) == 1 &&
719 strcmp(strVal(linitial(a
->name
)), "=") == 0 &&
720 (exprIsNullConstant(lexpr
) || exprIsNullConstant(rexpr
)))
722 NullTest
*n
= makeNode(NullTest
);
724 n
->nulltesttype
= IS_NULL
;
726 if (exprIsNullConstant(lexpr
))
727 n
->arg
= (Expr
*) rexpr
;
729 n
->arg
= (Expr
*) lexpr
;
731 result
= transformExpr(pstate
, (Node
*) n
);
733 else if (lexpr
&& IsA(lexpr
, RowExpr
) &&
734 rexpr
&& IsA(rexpr
, SubLink
) &&
735 ((SubLink
*) rexpr
)->subLinkType
== EXPR_SUBLINK
)
738 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
739 * grammar did this, but now that a row construct is allowed anywhere
740 * in expressions, it's easier to do it here.
742 SubLink
*s
= (SubLink
*) rexpr
;
744 s
->subLinkType
= ROWCOMPARE_SUBLINK
;
746 s
->operName
= a
->name
;
747 s
->location
= a
->location
;
748 result
= transformExpr(pstate
, (Node
*) s
);
750 else if (lexpr
&& IsA(lexpr
, RowExpr
) &&
751 rexpr
&& IsA(rexpr
, RowExpr
))
754 lexpr
= transformExpr(pstate
, lexpr
);
755 rexpr
= transformExpr(pstate
, rexpr
);
756 Assert(IsA(lexpr
, RowExpr
));
757 Assert(IsA(rexpr
, RowExpr
));
759 result
= make_row_comparison_op(pstate
,
761 ((RowExpr
*) lexpr
)->args
,
762 ((RowExpr
*) rexpr
)->args
,
767 /* Ordinary scalar operator */
768 lexpr
= transformExpr(pstate
, lexpr
);
769 rexpr
= transformExpr(pstate
, rexpr
);
771 result
= (Node
*) make_op(pstate
,
782 transformAExprAnd(ParseState
*pstate
, A_Expr
*a
)
784 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
785 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
787 lexpr
= coerce_to_boolean(pstate
, lexpr
, "AND");
788 rexpr
= coerce_to_boolean(pstate
, rexpr
, "AND");
790 return (Node
*) makeBoolExpr(AND_EXPR
,
791 list_make2(lexpr
, rexpr
),
796 transformAExprOr(ParseState
*pstate
, A_Expr
*a
)
798 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
799 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
801 lexpr
= coerce_to_boolean(pstate
, lexpr
, "OR");
802 rexpr
= coerce_to_boolean(pstate
, rexpr
, "OR");
804 return (Node
*) makeBoolExpr(OR_EXPR
,
805 list_make2(lexpr
, rexpr
),
810 transformAExprNot(ParseState
*pstate
, A_Expr
*a
)
812 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
814 rexpr
= coerce_to_boolean(pstate
, rexpr
, "NOT");
816 return (Node
*) makeBoolExpr(NOT_EXPR
,
822 transformAExprOpAny(ParseState
*pstate
, A_Expr
*a
)
824 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
825 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
827 return (Node
*) make_scalar_array_op(pstate
,
836 transformAExprOpAll(ParseState
*pstate
, A_Expr
*a
)
838 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
839 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
841 return (Node
*) make_scalar_array_op(pstate
,
850 transformAExprDistinct(ParseState
*pstate
, A_Expr
*a
)
852 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
853 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
855 if (lexpr
&& IsA(lexpr
, RowExpr
) &&
856 rexpr
&& IsA(rexpr
, RowExpr
))
859 return make_row_distinct_op(pstate
, a
->name
,
866 /* Ordinary scalar operator */
867 return (Node
*) make_distinct_op(pstate
,
876 transformAExprNullIf(ParseState
*pstate
, A_Expr
*a
)
878 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
879 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
882 result
= (Node
*) make_op(pstate
,
887 if (((OpExpr
*) result
)->opresulttype
!= BOOLOID
)
889 (errcode(ERRCODE_DATATYPE_MISMATCH
),
890 errmsg("NULLIF requires = operator to yield boolean"),
891 parser_errposition(pstate
, a
->location
)));
894 * We rely on NullIfExpr and OpExpr being the same struct
896 NodeSetTag(result
, T_NullIfExpr
);
902 transformAExprOf(ParseState
*pstate
, A_Expr
*a
)
905 * Checking an expression for match to a list of type names. Will result
906 * in a boolean constant node.
908 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
913 bool matched
= false;
915 ltype
= exprType(lexpr
);
916 foreach(telem
, (List
*) a
->rexpr
)
918 rtype
= typenameTypeId(pstate
, lfirst(telem
), NULL
);
919 matched
= (rtype
== ltype
);
925 * We have two forms: equals or not equals. Flip the sense of the result
928 if (strcmp(strVal(linitial(a
->name
)), "<>") == 0)
929 matched
= (!matched
);
931 result
= (Const
*) makeBoolConst(matched
, false);
933 /* Make the result have the original input's parse location */
934 result
->location
= exprLocation((Node
*) a
);
936 return (Node
*) result
;
940 transformAExprIn(ParseState
*pstate
, A_Expr
*a
)
952 * If the operator is <>, combine with AND not OR.
954 if (strcmp(strVal(linitial(a
->name
)), "<>") == 0)
960 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
961 * possible if the inputs are all scalars (no RowExprs) and there is a
962 * suitable array type available. If not, we fall back to a boolean
963 * condition tree with multiple copies of the lefthand expression.
964 * Also, any IN-list items that contain Vars are handled as separate
965 * boolean conditions, because that gives the planner more scope for
966 * optimization on such clauses.
968 * First step: transform all the inputs, and detect whether any are
969 * RowExprs or contain Vars.
971 lexpr
= transformExpr(pstate
, a
->lexpr
);
972 haveRowExpr
= (lexpr
&& IsA(lexpr
, RowExpr
));
973 rexprs
= rvars
= rnonvars
= NIL
;
974 foreach(l
, (List
*) a
->rexpr
)
976 Node
*rexpr
= transformExpr(pstate
, lfirst(l
));
978 haveRowExpr
|= (rexpr
&& IsA(rexpr
, RowExpr
));
979 rexprs
= lappend(rexprs
, rexpr
);
980 if (contain_vars_of_level(rexpr
, 0))
981 rvars
= lappend(rvars
, rexpr
);
983 rnonvars
= lappend(rnonvars
, rexpr
);
987 * ScalarArrayOpExpr is only going to be useful if there's more than
988 * one non-Var righthand item. Also, it won't work for RowExprs.
990 if (!haveRowExpr
&& list_length(rnonvars
) > 1)
997 * Try to select a common type for the array elements. Note that
998 * since the LHS' type is first in the list, it will be preferred when
999 * there is doubt (eg, when all the RHS items are unknown literals).
1001 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1003 allexprs
= list_concat(list_make1(lexpr
), rnonvars
);
1004 scalar_type
= select_common_type(pstate
, allexprs
, NULL
, NULL
);
1006 /* Do we have an array type to use? */
1007 if (OidIsValid(scalar_type
))
1008 array_type
= get_array_type(scalar_type
);
1010 array_type
= InvalidOid
;
1011 if (array_type
!= InvalidOid
)
1014 * OK: coerce all the right-hand non-Var inputs to the common type
1015 * and build an ArrayExpr for them.
1021 foreach(l
, rnonvars
)
1023 Node
*rexpr
= (Node
*) lfirst(l
);
1025 rexpr
= coerce_to_common_type(pstate
, rexpr
,
1028 aexprs
= lappend(aexprs
, rexpr
);
1030 newa
= makeNode(ArrayExpr
);
1031 newa
->array_typeid
= array_type
;
1032 newa
->element_typeid
= scalar_type
;
1033 newa
->elements
= aexprs
;
1034 newa
->multidims
= false;
1035 newa
->location
= -1;
1037 result
= (Node
*) make_scalar_array_op(pstate
,
1044 /* Consider only the Vars (if any) in the loop below */
1050 * Must do it the hard way, ie, with a boolean expression tree.
1054 Node
*rexpr
= (Node
*) lfirst(l
);
1059 if (!IsA(lexpr
, RowExpr
) ||
1060 !IsA(rexpr
, RowExpr
))
1062 (errcode(ERRCODE_SYNTAX_ERROR
),
1063 errmsg("arguments of row IN must all be row expressions"),
1064 parser_errposition(pstate
, a
->location
)));
1065 cmp
= make_row_comparison_op(pstate
,
1067 (List
*) copyObject(((RowExpr
*) lexpr
)->args
),
1068 ((RowExpr
*) rexpr
)->args
,
1072 cmp
= (Node
*) make_op(pstate
,
1078 cmp
= coerce_to_boolean(pstate
, cmp
, "IN");
1082 result
= (Node
*) makeBoolExpr(useOr
? OR_EXPR
: AND_EXPR
,
1083 list_make2(result
, cmp
),
1091 transformFuncCall(ParseState
*pstate
, FuncCall
*fn
)
1096 /* Transform the list of arguments ... */
1098 foreach(args
, fn
->args
)
1100 targs
= lappend(targs
, transformExpr(pstate
,
1101 (Node
*) lfirst(args
)));
1104 /* ... and hand off to ParseFuncOrColumn */
1105 return ParseFuncOrColumn(pstate
,
1116 transformCaseExpr(ParseState
*pstate
, CaseExpr
*c
)
1120 CaseTestExpr
*placeholder
;
1127 /* If we already transformed this node, do nothing */
1128 if (OidIsValid(c
->casetype
))
1131 newc
= makeNode(CaseExpr
);
1133 /* transform the test expression, if any */
1134 arg
= transformExpr(pstate
, (Node
*) c
->arg
);
1136 /* generate placeholder for test expression */
1140 * If test expression is an untyped literal, force it to text. We have
1141 * to do something now because we won't be able to do this coercion on
1142 * the placeholder. This is not as flexible as what was done in 7.4
1143 * and before, but it's good enough to handle the sort of silly coding
1146 if (exprType(arg
) == UNKNOWNOID
)
1147 arg
= coerce_to_common_type(pstate
, arg
, TEXTOID
, "CASE");
1149 placeholder
= makeNode(CaseTestExpr
);
1150 placeholder
->typeId
= exprType(arg
);
1151 placeholder
->typeMod
= exprTypmod(arg
);
1156 newc
->arg
= (Expr
*) arg
;
1158 /* transform the list of arguments */
1163 CaseWhen
*w
= (CaseWhen
*) lfirst(l
);
1164 CaseWhen
*neww
= makeNode(CaseWhen
);
1167 Assert(IsA(w
, CaseWhen
));
1169 warg
= (Node
*) w
->expr
;
1172 /* shorthand form was specified, so expand... */
1173 warg
= (Node
*) makeSimpleA_Expr(AEXPR_OP
, "=",
1174 (Node
*) placeholder
,
1178 neww
->expr
= (Expr
*) transformExpr(pstate
, warg
);
1180 neww
->expr
= (Expr
*) coerce_to_boolean(pstate
,
1181 (Node
*) neww
->expr
,
1184 warg
= (Node
*) w
->result
;
1185 neww
->result
= (Expr
*) transformExpr(pstate
, warg
);
1186 neww
->location
= w
->location
;
1188 newargs
= lappend(newargs
, neww
);
1189 resultexprs
= lappend(resultexprs
, neww
->result
);
1192 newc
->args
= newargs
;
1194 /* transform the default clause */
1195 defresult
= (Node
*) c
->defresult
;
1196 if (defresult
== NULL
)
1198 A_Const
*n
= makeNode(A_Const
);
1200 n
->val
.type
= T_Null
;
1202 defresult
= (Node
*) n
;
1204 newc
->defresult
= (Expr
*) transformExpr(pstate
, defresult
);
1207 * Note: default result is considered the most significant type in
1208 * determining preferred type. This is how the code worked before, but it
1209 * seems a little bogus to me --- tgl
1211 resultexprs
= lcons(newc
->defresult
, resultexprs
);
1213 ptype
= select_common_type(pstate
, resultexprs
, "CASE", NULL
);
1214 Assert(OidIsValid(ptype
));
1215 newc
->casetype
= ptype
;
1217 /* Convert default result clause, if necessary */
1218 newc
->defresult
= (Expr
*)
1219 coerce_to_common_type(pstate
,
1220 (Node
*) newc
->defresult
,
1224 /* Convert when-clause results, if necessary */
1225 foreach(l
, newc
->args
)
1227 CaseWhen
*w
= (CaseWhen
*) lfirst(l
);
1229 w
->result
= (Expr
*)
1230 coerce_to_common_type(pstate
,
1236 newc
->location
= c
->location
;
1238 return (Node
*) newc
;
1242 transformSubLink(ParseState
*pstate
, SubLink
*sublink
)
1244 Node
*result
= (Node
*) sublink
;
1247 /* If we already transformed this node, do nothing */
1248 if (IsA(sublink
->subselect
, Query
))
1251 pstate
->p_hasSubLinks
= true;
1252 qtree
= parse_sub_analyze(sublink
->subselect
, pstate
);
1255 * Check that we got something reasonable. Many of these conditions are
1256 * impossible given restrictions of the grammar, but check 'em anyway.
1258 if (!IsA(qtree
, Query
) ||
1259 qtree
->commandType
!= CMD_SELECT
||
1260 qtree
->utilityStmt
!= NULL
)
1261 elog(ERROR
, "unexpected non-SELECT command in SubLink");
1262 if (qtree
->intoClause
)
1264 (errcode(ERRCODE_SYNTAX_ERROR
),
1265 errmsg("subquery cannot have SELECT INTO"),
1266 parser_errposition(pstate
,
1267 exprLocation((Node
*) qtree
->intoClause
))));
1269 sublink
->subselect
= (Node
*) qtree
;
1271 if (sublink
->subLinkType
== EXISTS_SUBLINK
)
1274 * EXISTS needs no test expression or combining operator. These fields
1275 * should be null already, but make sure.
1277 sublink
->testexpr
= NULL
;
1278 sublink
->operName
= NIL
;
1280 else if (sublink
->subLinkType
== EXPR_SUBLINK
||
1281 sublink
->subLinkType
== ARRAY_SUBLINK
)
1283 ListCell
*tlist_item
= list_head(qtree
->targetList
);
1286 * Make sure the subselect delivers a single column (ignoring resjunk
1289 if (tlist_item
== NULL
||
1290 ((TargetEntry
*) lfirst(tlist_item
))->resjunk
)
1292 (errcode(ERRCODE_SYNTAX_ERROR
),
1293 errmsg("subquery must return a column"),
1294 parser_errposition(pstate
, sublink
->location
)));
1295 while ((tlist_item
= lnext(tlist_item
)) != NULL
)
1297 if (!((TargetEntry
*) lfirst(tlist_item
))->resjunk
)
1299 (errcode(ERRCODE_SYNTAX_ERROR
),
1300 errmsg("subquery must return only one column"),
1301 parser_errposition(pstate
, sublink
->location
)));
1305 * EXPR and ARRAY need no test expression or combining operator. These
1306 * fields should be null already, but make sure.
1308 sublink
->testexpr
= NULL
;
1309 sublink
->operName
= NIL
;
1313 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1320 * Transform lefthand expression, and convert to a list
1322 lefthand
= transformExpr(pstate
, sublink
->testexpr
);
1323 if (lefthand
&& IsA(lefthand
, RowExpr
))
1324 left_list
= ((RowExpr
*) lefthand
)->args
;
1326 left_list
= list_make1(lefthand
);
1329 * Build a list of PARAM_SUBLINK nodes representing the output columns
1333 foreach(l
, qtree
->targetList
)
1335 TargetEntry
*tent
= (TargetEntry
*) lfirst(l
);
1341 param
= makeNode(Param
);
1342 param
->paramkind
= PARAM_SUBLINK
;
1343 param
->paramid
= tent
->resno
;
1344 param
->paramtype
= exprType((Node
*) tent
->expr
);
1345 param
->paramtypmod
= exprTypmod((Node
*) tent
->expr
);
1346 param
->location
= -1;
1348 right_list
= lappend(right_list
, param
);
1352 * We could rely on make_row_comparison_op to complain if the list
1353 * lengths differ, but we prefer to generate a more specific error
1356 if (list_length(left_list
) < list_length(right_list
))
1358 (errcode(ERRCODE_SYNTAX_ERROR
),
1359 errmsg("subquery has too many columns"),
1360 parser_errposition(pstate
, sublink
->location
)));
1361 if (list_length(left_list
) > list_length(right_list
))
1363 (errcode(ERRCODE_SYNTAX_ERROR
),
1364 errmsg("subquery has too few columns"),
1365 parser_errposition(pstate
, sublink
->location
)));
1368 * Identify the combining operator(s) and generate a suitable
1369 * row-comparison expression.
1371 sublink
->testexpr
= make_row_comparison_op(pstate
,
1382 * transformArrayExpr
1384 * If the caller specifies the target type, the resulting array will
1385 * be of exactly that type. Otherwise we try to infer a common type
1386 * for the elements using select_common_type().
1389 transformArrayExpr(ParseState
*pstate
, A_ArrayExpr
*a
,
1390 Oid array_type
, Oid element_type
, int32 typmod
)
1392 ArrayExpr
*newa
= makeNode(ArrayExpr
);
1393 List
*newelems
= NIL
;
1394 List
*newcoercedelems
= NIL
;
1400 * Transform the element expressions
1402 * Assume that the array is one-dimensional unless we find an
1403 * array-type element expression.
1405 newa
->multidims
= false;
1406 foreach(element
, a
->elements
)
1408 Node
*e
= (Node
*) lfirst(element
);
1412 * If an element is itself an A_ArrayExpr, recurse directly so that
1413 * we can pass down any target type we were given.
1415 if (IsA(e
, A_ArrayExpr
))
1417 newe
= transformArrayExpr(pstate
,
1422 /* we certainly have an array here */
1423 Assert(array_type
== InvalidOid
|| array_type
== exprType(newe
));
1424 newa
->multidims
= true;
1428 newe
= transformExpr(pstate
, e
);
1430 * Check for sub-array expressions, if we haven't already
1433 if (!newa
->multidims
&& type_is_array(exprType(newe
)))
1434 newa
->multidims
= true;
1437 newelems
= lappend(newelems
, newe
);
1441 * Select a target type for the elements.
1443 * If we haven't been given a target array type, we must try to deduce a
1444 * common type based on the types of the individual elements present.
1446 if (OidIsValid(array_type
))
1448 /* Caller must ensure array_type matches element_type */
1449 Assert(OidIsValid(element_type
));
1450 coerce_type
= (newa
->multidims
? array_type
: element_type
);
1455 /* Can't handle an empty array without a target type */
1456 if (newelems
== NIL
)
1458 (errcode(ERRCODE_INDETERMINATE_DATATYPE
),
1459 errmsg("cannot determine type of empty array"),
1460 errhint("Explicitly cast to the desired type, "
1461 "for example ARRAY[]::integer[]."),
1462 parser_errposition(pstate
, a
->location
)));
1464 /* Select a common type for the elements */
1465 coerce_type
= select_common_type(pstate
, newelems
, "ARRAY", NULL
);
1467 if (newa
->multidims
)
1469 array_type
= coerce_type
;
1470 element_type
= get_element_type(array_type
);
1471 if (!OidIsValid(element_type
))
1473 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1474 errmsg("could not find element type for data type %s",
1475 format_type_be(array_type
)),
1476 parser_errposition(pstate
, a
->location
)));
1480 element_type
= coerce_type
;
1481 array_type
= get_array_type(element_type
);
1482 if (!OidIsValid(array_type
))
1484 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1485 errmsg("could not find array type for data type %s",
1486 format_type_be(element_type
)),
1487 parser_errposition(pstate
, a
->location
)));
1489 coerce_hard
= false;
1493 * Coerce elements to target type
1495 * If the array has been explicitly cast, then the elements are in turn
1496 * explicitly coerced.
1498 * If the array's type was merely derived from the common type of its
1499 * elements, then the elements are implicitly coerced to the common type.
1500 * This is consistent with other uses of select_common_type().
1502 foreach(element
, newelems
)
1504 Node
*e
= (Node
*) lfirst(element
);
1509 newe
= coerce_to_target_type(pstate
, e
,
1514 COERCE_EXPLICIT_CAST
,
1518 (errcode(ERRCODE_CANNOT_COERCE
),
1519 errmsg("cannot cast type %s to %s",
1520 format_type_be(exprType(e
)),
1521 format_type_be(coerce_type
)),
1522 parser_errposition(pstate
, exprLocation(e
))));
1525 newe
= coerce_to_common_type(pstate
, e
,
1528 newcoercedelems
= lappend(newcoercedelems
, newe
);
1531 newa
->array_typeid
= array_type
;
1532 newa
->element_typeid
= element_type
;
1533 newa
->elements
= newcoercedelems
;
1534 newa
->location
= a
->location
;
1536 return (Node
*) newa
;
1540 transformRowExpr(ParseState
*pstate
, RowExpr
*r
)
1542 RowExpr
*newr
= makeNode(RowExpr
);
1544 /* Transform the field expressions */
1545 newr
->args
= transformExpressionList(pstate
, r
->args
);
1547 /* Barring later casting, we consider the type RECORD */
1548 newr
->row_typeid
= RECORDOID
;
1549 newr
->row_format
= COERCE_IMPLICIT_CAST
;
1550 newr
->colnames
= NIL
; /* ROW() has anonymous columns */
1551 newr
->location
= r
->location
;
1553 return (Node
*) newr
;
1557 transformCoalesceExpr(ParseState
*pstate
, CoalesceExpr
*c
)
1559 CoalesceExpr
*newc
= makeNode(CoalesceExpr
);
1560 List
*newargs
= NIL
;
1561 List
*newcoercedargs
= NIL
;
1564 foreach(args
, c
->args
)
1566 Node
*e
= (Node
*) lfirst(args
);
1569 newe
= transformExpr(pstate
, e
);
1570 newargs
= lappend(newargs
, newe
);
1573 newc
->coalescetype
= select_common_type(pstate
, newargs
, "COALESCE", NULL
);
1575 /* Convert arguments if necessary */
1576 foreach(args
, newargs
)
1578 Node
*e
= (Node
*) lfirst(args
);
1581 newe
= coerce_to_common_type(pstate
, e
,
1584 newcoercedargs
= lappend(newcoercedargs
, newe
);
1587 newc
->args
= newcoercedargs
;
1588 newc
->location
= c
->location
;
1589 return (Node
*) newc
;
1593 transformMinMaxExpr(ParseState
*pstate
, MinMaxExpr
*m
)
1595 MinMaxExpr
*newm
= makeNode(MinMaxExpr
);
1596 List
*newargs
= NIL
;
1597 List
*newcoercedargs
= NIL
;
1598 const char *funcname
= (m
->op
== IS_GREATEST
) ? "GREATEST" : "LEAST";
1602 foreach(args
, m
->args
)
1604 Node
*e
= (Node
*) lfirst(args
);
1607 newe
= transformExpr(pstate
, e
);
1608 newargs
= lappend(newargs
, newe
);
1611 newm
->minmaxtype
= select_common_type(pstate
, newargs
, funcname
, NULL
);
1613 /* Convert arguments if necessary */
1614 foreach(args
, newargs
)
1616 Node
*e
= (Node
*) lfirst(args
);
1619 newe
= coerce_to_common_type(pstate
, e
,
1622 newcoercedargs
= lappend(newcoercedargs
, newe
);
1625 newm
->args
= newcoercedargs
;
1626 newm
->location
= m
->location
;
1627 return (Node
*) newm
;
1631 transformXmlExpr(ParseState
*pstate
, XmlExpr
*x
)
1633 XmlExpr
*newx
= makeNode(XmlExpr
);
1639 newx
->name
= map_sql_identifier_to_xml_name(x
->name
, false, false);
1642 newx
->xmloption
= x
->xmloption
;
1643 newx
->location
= x
->location
;
1646 * gram.y built the named args as a list of ResTarget. Transform each,
1647 * and break the names out as a separate list.
1649 newx
->named_args
= NIL
;
1650 newx
->arg_names
= NIL
;
1652 foreach(lc
, x
->named_args
)
1654 ResTarget
*r
= (ResTarget
*) lfirst(lc
);
1658 Assert(IsA(r
, ResTarget
));
1660 expr
= transformExpr(pstate
, r
->val
);
1663 argname
= map_sql_identifier_to_xml_name(r
->name
, false, false);
1664 else if (IsA(r
->val
, ColumnRef
))
1665 argname
= map_sql_identifier_to_xml_name(FigureColname(r
->val
),
1670 (errcode(ERRCODE_SYNTAX_ERROR
),
1671 x
->op
== IS_XMLELEMENT
1672 ? errmsg("unnamed XML attribute value must be a column reference")
1673 : errmsg("unnamed XML element value must be a column reference"),
1674 parser_errposition(pstate
, r
->location
)));
1675 argname
= NULL
; /* keep compiler quiet */
1678 /* reject duplicate argnames in XMLELEMENT only */
1679 if (x
->op
== IS_XMLELEMENT
)
1683 foreach(lc2
, newx
->arg_names
)
1685 if (strcmp(argname
, strVal(lfirst(lc2
))) == 0)
1687 (errcode(ERRCODE_SYNTAX_ERROR
),
1688 errmsg("XML attribute name \"%s\" appears more than once",
1690 parser_errposition(pstate
, r
->location
)));
1694 newx
->named_args
= lappend(newx
->named_args
, expr
);
1695 newx
->arg_names
= lappend(newx
->arg_names
, makeString(argname
));
1698 /* The other arguments are of varying types depending on the function */
1701 foreach(lc
, x
->args
)
1703 Node
*e
= (Node
*) lfirst(lc
);
1706 newe
= transformExpr(pstate
, e
);
1710 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1714 /* no coercion necessary */
1717 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1722 newe
= coerce_to_specific_type(pstate
, newe
, TEXTOID
,
1725 newe
= coerce_to_boolean(pstate
, newe
, "XMLPARSE");
1728 newe
= coerce_to_specific_type(pstate
, newe
, TEXTOID
,
1733 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1736 newe
= coerce_to_specific_type(pstate
, newe
, TEXTOID
,
1739 newe
= coerce_to_specific_type(pstate
, newe
, INT4OID
,
1742 case IS_XMLSERIALIZE
:
1743 /* not handled here */
1747 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1751 newx
->args
= lappend(newx
->args
, newe
);
1755 return (Node
*) newx
;
1759 transformXmlSerialize(ParseState
*pstate
, XmlSerialize
*xs
)
1766 xexpr
= makeNode(XmlExpr
);
1767 xexpr
->op
= IS_XMLSERIALIZE
;
1768 xexpr
->args
= list_make1(coerce_to_specific_type(pstate
,
1769 transformExpr(pstate
, xs
->expr
),
1773 targetType
= typenameTypeId(pstate
, xs
->typename
, &targetTypmod
);
1775 xexpr
->xmloption
= xs
->xmloption
;
1776 xexpr
->location
= xs
->location
;
1777 /* We actually only need these to be able to parse back the expression. */
1778 xexpr
->type
= targetType
;
1779 xexpr
->typmod
= targetTypmod
;
1782 * The actual target type is determined this way. SQL allows char and
1783 * varchar as target types. We allow anything that can be cast implicitly
1784 * from text. This way, user-defined text-like data types automatically
1787 result
= coerce_to_target_type(pstate
, (Node
*) xexpr
,
1788 TEXTOID
, targetType
, targetTypmod
,
1790 COERCE_IMPLICIT_CAST
,
1794 (errcode(ERRCODE_CANNOT_COERCE
),
1795 errmsg("cannot cast XMLSERIALIZE result to %s",
1796 format_type_be(targetType
)),
1797 parser_errposition(pstate
, xexpr
->location
)));
1802 transformBooleanTest(ParseState
*pstate
, BooleanTest
*b
)
1804 const char *clausename
;
1806 switch (b
->booltesttype
)
1809 clausename
= "IS TRUE";
1812 clausename
= "IS NOT TRUE";
1815 clausename
= "IS FALSE";
1818 clausename
= "IS NOT FALSE";
1821 clausename
= "IS UNKNOWN";
1823 case IS_NOT_UNKNOWN
:
1824 clausename
= "IS NOT UNKNOWN";
1827 elog(ERROR
, "unrecognized booltesttype: %d",
1828 (int) b
->booltesttype
);
1829 clausename
= NULL
; /* keep compiler quiet */
1832 b
->arg
= (Expr
*) transformExpr(pstate
, (Node
*) b
->arg
);
1834 b
->arg
= (Expr
*) coerce_to_boolean(pstate
,
1842 transformCurrentOfExpr(ParseState
*pstate
, CurrentOfExpr
*cexpr
)
1846 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1847 Assert(pstate
->p_target_rangetblentry
!= NULL
);
1848 cexpr
->cvarno
= RTERangeTablePosn(pstate
,
1849 pstate
->p_target_rangetblentry
,
1851 Assert(sublevels_up
== 0);
1853 /* If a parameter is used, it must be of type REFCURSOR */
1854 if (cexpr
->cursor_name
== NULL
)
1856 Oid
*pptype
= find_param_type(pstate
, cexpr
->cursor_param
, -1);
1858 if (pstate
->p_variableparams
&& *pptype
== UNKNOWNOID
)
1860 /* resolve unknown param type as REFCURSOR */
1861 *pptype
= REFCURSOROID
;
1863 else if (*pptype
!= REFCURSOROID
)
1866 (errcode(ERRCODE_AMBIGUOUS_PARAMETER
),
1867 errmsg("inconsistent types deduced for parameter $%d",
1868 cexpr
->cursor_param
),
1869 errdetail("%s versus %s",
1870 format_type_be(*pptype
),
1871 format_type_be(REFCURSOROID
))));
1875 return (Node
*) cexpr
;
1879 * Construct a whole-row reference to represent the notation "relation.*".
1881 * A whole-row reference is a Var with varno set to the correct range
1882 * table entry, and varattno == 0 to signal that it references the whole
1883 * tuple. (Use of zero here is unclean, since it could easily be confused
1884 * with error cases, but it's not worth changing now.) The vartype indicates
1885 * a rowtype; either a named composite type, or RECORD.
1888 transformWholeRowRef(ParseState
*pstate
, char *schemaname
, char *relname
,
1897 /* Look up the referenced RTE, creating it if needed */
1899 rte
= refnameRangeTblEntry(pstate
, schemaname
, relname
, location
,
1903 rte
= addImplicitRTE(pstate
,
1904 makeRangeVar(schemaname
, relname
, location
));
1906 vnum
= RTERangeTablePosn(pstate
, rte
, &sublevels_up
);
1908 /* Build the appropriate referencing node */
1910 switch (rte
->rtekind
)
1913 /* relation: the rowtype is a named composite type */
1914 toid
= get_rel_type_id(rte
->relid
);
1915 if (!OidIsValid(toid
))
1916 elog(ERROR
, "could not find type OID for relation %u",
1918 result
= makeVar(vnum
,
1925 toid
= exprType(rte
->funcexpr
);
1926 if (type_is_rowtype(toid
))
1928 /* func returns composite; same as relation case */
1929 result
= makeVar(vnum
,
1938 * func returns scalar; instead of making a whole-row Var,
1939 * just reference the function's scalar output. (XXX this
1940 * seems a tad inconsistent, especially if "f.*" was
1941 * explicitly written ...)
1943 result
= makeVar(vnum
,
1952 /* returns composite; same as relation case */
1953 result
= makeVar(vnum
,
1962 * RTE is a join or subselect. We represent this as a whole-row
1963 * Var of RECORD type. (Note that in most cases the Var will be
1964 * expanded to a RowExpr during planning, but that is not our
1967 result
= makeVar(vnum
,
1975 /* location is not filled in by makeVar */
1976 result
->location
= location
;
1978 return (Node
*) result
;
1982 * Handle an explicit CAST construct.
1984 * Transform the argument, then look up the type name and apply any necessary
1985 * coercion function(s).
1988 transformTypeCast(ParseState
*pstate
, TypeCast
*tc
)
1991 Node
*expr
= transformExpr(pstate
, tc
->arg
);
1992 Oid inputType
= exprType(expr
);
1997 targetType
= typenameTypeId(pstate
, tc
->typename
, &targetTypmod
);
1999 if (inputType
== InvalidOid
)
2000 return expr
; /* do nothing if NULL input */
2003 * Location of the coercion is preferentially the location of the :: or
2004 * CAST symbol, but if there is none then use the location of the type
2005 * name (this can happen in TypeName 'string' syntax, for instance).
2007 location
= tc
->location
;
2009 location
= tc
->typename
->location
;
2011 result
= coerce_to_target_type(pstate
, expr
, inputType
,
2012 targetType
, targetTypmod
,
2014 COERCE_EXPLICIT_CAST
,
2018 (errcode(ERRCODE_CANNOT_COERCE
),
2019 errmsg("cannot cast type %s to %s",
2020 format_type_be(inputType
),
2021 format_type_be(targetType
)),
2022 parser_coercion_errposition(pstate
, location
, expr
)));
2028 * Transform a "row compare-op row" construct
2030 * The inputs are lists of already-transformed expressions.
2031 * As with coerce_type, pstate may be NULL if no special unknown-Param
2032 * processing is wanted.
2034 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2035 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2036 * The AND, OR, and RowCompareExpr cases further imply things about the
2037 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2040 make_row_comparison_op(ParseState
*pstate
, List
*opname
,
2041 List
*largs
, List
*rargs
, int location
)
2043 RowCompareExpr
*rcexpr
;
2044 RowCompareType rctype
;
2050 List
**opfamily_lists
;
2051 List
**opstrat_lists
;
2056 nopers
= list_length(largs
);
2057 if (nopers
!= list_length(rargs
))
2059 (errcode(ERRCODE_SYNTAX_ERROR
),
2060 errmsg("unequal number of entries in row expressions"),
2061 parser_errposition(pstate
, location
)));
2064 * We can't compare zero-length rows because there is no principled basis
2065 * for figuring out what the operator is.
2069 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2070 errmsg("cannot compare rows of zero length"),
2071 parser_errposition(pstate
, location
)));
2074 * Identify all the pairwise operators, using make_op so that behavior is
2075 * the same as in the simple scalar case.
2078 forboth(l
, largs
, r
, rargs
)
2080 Node
*larg
= (Node
*) lfirst(l
);
2081 Node
*rarg
= (Node
*) lfirst(r
);
2084 cmp
= (OpExpr
*) make_op(pstate
, opname
, larg
, rarg
, location
);
2085 Assert(IsA(cmp
, OpExpr
));
2088 * We don't use coerce_to_boolean here because we insist on the
2089 * operator yielding boolean directly, not via coercion. If it
2090 * doesn't yield bool it won't be in any index opfamilies...
2092 if (cmp
->opresulttype
!= BOOLOID
)
2094 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2095 errmsg("row comparison operator must yield type boolean, "
2097 format_type_be(cmp
->opresulttype
)),
2098 parser_errposition(pstate
, location
)));
2099 if (expression_returns_set((Node
*) cmp
))
2101 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2102 errmsg("row comparison operator must not return a set"),
2103 parser_errposition(pstate
, location
)));
2104 opexprs
= lappend(opexprs
, cmp
);
2108 * If rows are length 1, just return the single operator. In this case we
2109 * don't insist on identifying btree semantics for the operator (but we
2110 * still require it to return boolean).
2113 return (Node
*) linitial(opexprs
);
2116 * Now we must determine which row comparison semantics (= <> < <= > >=)
2117 * apply to this set of operators. We look for btree opfamilies
2118 * containing the operators, and see which interpretations (strategy
2119 * numbers) exist for each operator.
2121 opfamily_lists
= (List
**) palloc(nopers
* sizeof(List
*));
2122 opstrat_lists
= (List
**) palloc(nopers
* sizeof(List
*));
2127 Oid opno
= ((OpExpr
*) lfirst(l
))->opno
;
2128 Bitmapset
*this_strats
;
2131 get_op_btree_interpretation(opno
,
2132 &opfamily_lists
[i
], &opstrat_lists
[i
]);
2135 * convert strategy number list to a Bitmapset to make the
2136 * intersection calculation easy.
2139 foreach(j
, opstrat_lists
[i
])
2141 this_strats
= bms_add_member(this_strats
, lfirst_int(j
));
2144 strats
= this_strats
;
2146 strats
= bms_int_members(strats
, this_strats
);
2151 * If there are multiple common interpretations, we may use any one of
2152 * them ... this coding arbitrarily picks the lowest btree strategy
2155 i
= bms_first_member(strats
);
2158 /* No common interpretation, so fail */
2160 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2161 errmsg("could not determine interpretation of row comparison operator %s",
2162 strVal(llast(opname
))),
2163 errhint("Row comparison operators must be associated with btree operator families."),
2164 parser_errposition(pstate
, location
)));
2166 rctype
= (RowCompareType
) i
;
2169 * For = and <> cases, we just combine the pairwise operators with AND or
2172 * Note: this is presently the only place where the parser generates
2173 * BoolExpr with more than two arguments. Should be OK since the rest of
2174 * the system thinks BoolExpr is N-argument anyway.
2176 if (rctype
== ROWCOMPARE_EQ
)
2177 return (Node
*) makeBoolExpr(AND_EXPR
, opexprs
, location
);
2178 if (rctype
== ROWCOMPARE_NE
)
2179 return (Node
*) makeBoolExpr(OR_EXPR
, opexprs
, location
);
2182 * Otherwise we need to choose exactly which opfamily to associate with
2186 for (i
= 0; i
< nopers
; i
++)
2188 Oid opfamily
= InvalidOid
;
2190 forboth(l
, opfamily_lists
[i
], r
, opstrat_lists
[i
])
2192 int opstrat
= lfirst_int(r
);
2194 if (opstrat
== rctype
)
2196 opfamily
= lfirst_oid(l
);
2200 if (OidIsValid(opfamily
))
2201 opfamilies
= lappend_oid(opfamilies
, opfamily
);
2202 else /* should not happen */
2204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2205 errmsg("could not determine interpretation of row comparison operator %s",
2206 strVal(llast(opname
))),
2207 errdetail("There are multiple equally-plausible candidates."),
2208 parser_errposition(pstate
, location
)));
2212 * Now deconstruct the OpExprs and create a RowCompareExpr.
2214 * Note: can't just reuse the passed largs/rargs lists, because of
2215 * possibility that make_op inserted coercion operations.
2222 OpExpr
*cmp
= (OpExpr
*) lfirst(l
);
2224 opnos
= lappend_oid(opnos
, cmp
->opno
);
2225 largs
= lappend(largs
, linitial(cmp
->args
));
2226 rargs
= lappend(rargs
, lsecond(cmp
->args
));
2229 rcexpr
= makeNode(RowCompareExpr
);
2230 rcexpr
->rctype
= rctype
;
2231 rcexpr
->opnos
= opnos
;
2232 rcexpr
->opfamilies
= opfamilies
;
2233 rcexpr
->largs
= largs
;
2234 rcexpr
->rargs
= rargs
;
2236 return (Node
*) rcexpr
;
2240 * Transform a "row IS DISTINCT FROM row" construct
2242 * The input RowExprs are already transformed
2245 make_row_distinct_op(ParseState
*pstate
, List
*opname
,
2246 RowExpr
*lrow
, RowExpr
*rrow
,
2249 Node
*result
= NULL
;
2250 List
*largs
= lrow
->args
;
2251 List
*rargs
= rrow
->args
;
2255 if (list_length(largs
) != list_length(rargs
))
2257 (errcode(ERRCODE_SYNTAX_ERROR
),
2258 errmsg("unequal number of entries in row expressions"),
2259 parser_errposition(pstate
, location
)));
2261 forboth(l
, largs
, r
, rargs
)
2263 Node
*larg
= (Node
*) lfirst(l
);
2264 Node
*rarg
= (Node
*) lfirst(r
);
2267 cmp
= (Node
*) make_distinct_op(pstate
, opname
, larg
, rarg
, location
);
2271 result
= (Node
*) makeBoolExpr(OR_EXPR
,
2272 list_make2(result
, cmp
),
2278 /* zero-length rows? Generate constant FALSE */
2279 result
= makeBoolConst(false, false);
2286 * make the node for an IS DISTINCT FROM operator
2289 make_distinct_op(ParseState
*pstate
, List
*opname
, Node
*ltree
, Node
*rtree
,
2294 result
= make_op(pstate
, opname
, ltree
, rtree
, location
);
2295 if (((OpExpr
*) result
)->opresulttype
!= BOOLOID
)
2297 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2298 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2299 parser_errposition(pstate
, location
)));
2302 * We rely on DistinctExpr and OpExpr being same struct
2304 NodeSetTag(result
, T_DistinctExpr
);