1 /*-------------------------------------------------------------------------
4 * handle expressions in parser
6 * Portions Copyright (c) 1996-2009, 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 and
151 * the target type is an array type, we invoke
152 * transformArrayExpr() directly so that we can pass down the
153 * 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. Fall
177 * 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 *********************************************/
294 case T_ScalarArrayOpExpr
:
301 case T_ArrayCoerceExpr
:
302 case T_ConvertRowtypeExpr
:
304 case T_CoerceToDomain
:
305 case T_CoerceToDomainValue
:
308 result
= (Node
*) expr
;
313 /* should not reach here */
314 elog(ERROR
, "unrecognized node type: %d", (int) nodeTag(expr
));
322 transformIndirection(ParseState
*pstate
, Node
*basenode
, List
*indirection
)
324 Node
*result
= basenode
;
325 List
*subscripts
= NIL
;
329 * We have to split any field-selection operations apart from
330 * subscripting. Adjacent A_Indices nodes have to be treated as a single
331 * multidimensional subscript operation.
333 foreach(i
, indirection
)
337 if (IsA(n
, A_Indices
))
338 subscripts
= lappend(subscripts
, n
);
339 else if (IsA(n
, A_Star
))
342 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
343 errmsg("row expansion via \"*\" is not supported here"),
344 parser_errposition(pstate
, exprLocation(basenode
))));
348 Assert(IsA(n
, String
));
350 /* process subscripts before this field selection */
352 result
= (Node
*) transformArraySubscripts(pstate
,
361 result
= ParseFuncOrColumn(pstate
,
368 /* process trailing subscripts, if any */
370 result
= (Node
*) transformArraySubscripts(pstate
,
382 transformColumnRef(ParseState
*pstate
, ColumnRef
*cref
)
384 int numnames
= list_length(cref
->fields
);
389 * The allowed syntaxes are:
391 * A First try to resolve as unqualified column name;
392 * if no luck, try to resolve as unqualified table name (A.*).
393 * A.B A is an unqualified table name; B is either a
394 * column or function name (trying column name first).
395 * A.B.C schema A, table B, col or func name C.
396 * A.B.C.D catalog A, schema B, table C, col or func D.
397 * A.* A is an unqualified table name; means whole-row value.
398 * A.B.* whole-row value of table B in schema A.
399 * A.B.C.* whole-row value of table C in schema B in catalog A.
401 * We do not need to cope with bare "*"; that will only be accepted by
402 * the grammar at the top level of a SELECT list, and transformTargetList
403 * will take care of it before it ever gets here. Also, "A.*" etc will
404 * be expanded by transformTargetList if they appear at SELECT top level,
405 * so here we are only going to see them as function or operator inputs.
407 * Currently, if a catalog name is given then it must equal the current
408 * database name; we check it here and then discard it.
415 Node
*field1
= (Node
*) linitial(cref
->fields
);
418 Assert(IsA(field1
, String
));
419 name1
= strVal(field1
);
421 /* Try to identify as an unqualified column */
422 node
= colNameToVar(pstate
, name1
, false, cref
->location
);
427 * Not known as a column of any range-table entry.
429 * Consider the possibility that it's VALUE in a domain
430 * check expression. (We handle VALUE as a name, not a
431 * keyword, to avoid breaking a lot of applications that
432 * have used VALUE as a column name in the past.)
434 if (pstate
->p_value_substitute
!= NULL
&&
435 strcmp(name1
, "value") == 0)
437 node
= (Node
*) copyObject(pstate
->p_value_substitute
);
440 * Try to propagate location knowledge. This should
441 * be extended if p_value_substitute can ever take on
444 if (IsA(node
, CoerceToDomainValue
))
445 ((CoerceToDomainValue
*) node
)->location
= cref
->location
;
450 * Try to find the name as a relation. Note that only
451 * relations already entered into the rangetable will be
454 * This is a hack for backwards compatibility with
455 * PostQUEL-inspired syntax. The preferred form now is
458 if (refnameRangeTblEntry(pstate
, NULL
, name1
,
461 node
= transformWholeRowRef(pstate
, NULL
, name1
,
465 (errcode(ERRCODE_UNDEFINED_COLUMN
),
466 errmsg("column \"%s\" does not exist",
468 parser_errposition(pstate
, cref
->location
)));
474 Node
*field1
= (Node
*) linitial(cref
->fields
);
475 Node
*field2
= (Node
*) lsecond(cref
->fields
);
479 Assert(IsA(field1
, String
));
480 name1
= strVal(field1
);
482 /* Whole-row reference? */
483 if (IsA(field2
, A_Star
))
485 node
= transformWholeRowRef(pstate
, NULL
, name1
,
490 Assert(IsA(field2
, String
));
491 name2
= strVal(field2
);
493 /* Try to identify as a once-qualified column */
494 node
= qualifiedNameToVar(pstate
, NULL
, name1
, name2
, true,
499 * Not known as a column of any range-table entry, so try
500 * it as a function call. Here, we will create an
501 * implicit RTE for tables not already entered.
503 node
= transformWholeRowRef(pstate
, NULL
, name1
,
505 node
= ParseFuncOrColumn(pstate
,
506 list_make1(makeString(name2
)),
509 NULL
, true, cref
->location
);
515 Node
*field1
= (Node
*) linitial(cref
->fields
);
516 Node
*field2
= (Node
*) lsecond(cref
->fields
);
517 Node
*field3
= (Node
*) lthird(cref
->fields
);
522 Assert(IsA(field1
, String
));
523 name1
= strVal(field1
);
524 Assert(IsA(field2
, String
));
525 name2
= strVal(field2
);
527 /* Whole-row reference? */
528 if (IsA(field3
, A_Star
))
530 node
= transformWholeRowRef(pstate
, name1
, name2
,
535 Assert(IsA(field3
, String
));
536 name3
= strVal(field3
);
538 /* Try to identify as a twice-qualified column */
539 node
= qualifiedNameToVar(pstate
, name1
, name2
, name3
, true,
543 /* Try it as a function call */
544 node
= transformWholeRowRef(pstate
, name1
, name2
,
546 node
= ParseFuncOrColumn(pstate
,
547 list_make1(makeString(name3
)),
550 NULL
, true, cref
->location
);
556 Node
*field1
= (Node
*) linitial(cref
->fields
);
557 Node
*field2
= (Node
*) lsecond(cref
->fields
);
558 Node
*field3
= (Node
*) lthird(cref
->fields
);
559 Node
*field4
= (Node
*) lfourth(cref
->fields
);
565 Assert(IsA(field1
, String
));
566 name1
= strVal(field1
);
567 Assert(IsA(field2
, String
));
568 name2
= strVal(field2
);
569 Assert(IsA(field3
, String
));
570 name3
= strVal(field3
);
573 * We check the catalog name and then ignore it.
575 if (strcmp(name1
, get_database_name(MyDatabaseId
)) != 0)
577 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
578 errmsg("cross-database references are not implemented: %s",
579 NameListToString(cref
->fields
)),
580 parser_errposition(pstate
, cref
->location
)));
582 /* Whole-row reference? */
583 if (IsA(field4
, A_Star
))
585 node
= transformWholeRowRef(pstate
, name2
, name3
,
590 Assert(IsA(field4
, String
));
591 name4
= strVal(field4
);
593 /* Try to identify as a twice-qualified column */
594 node
= qualifiedNameToVar(pstate
, name2
, name3
, name4
, true,
598 /* Try it as a function call */
599 node
= transformWholeRowRef(pstate
, name2
, name3
,
601 node
= ParseFuncOrColumn(pstate
,
602 list_make1(makeString(name4
)),
605 NULL
, true, cref
->location
);
611 (errcode(ERRCODE_SYNTAX_ERROR
),
612 errmsg("improper qualified name (too many dotted names): %s",
613 NameListToString(cref
->fields
)),
614 parser_errposition(pstate
, cref
->location
)));
615 node
= NULL
; /* keep compiler quiet */
623 * Locate the parameter type info for the given parameter number, and
624 * return a pointer to it.
627 find_param_type(ParseState
*pstate
, int paramno
, int location
)
632 * Find topmost ParseState, which is where paramtype info lives.
634 while (pstate
->parentParseState
!= NULL
)
635 pstate
= pstate
->parentParseState
;
637 /* Check parameter number is in range */
638 if (paramno
<= 0) /* probably can't happen? */
640 (errcode(ERRCODE_UNDEFINED_PARAMETER
),
641 errmsg("there is no parameter $%d", paramno
),
642 parser_errposition(pstate
, location
)));
643 if (paramno
> pstate
->p_numparams
)
645 if (!pstate
->p_variableparams
)
647 (errcode(ERRCODE_UNDEFINED_PARAMETER
),
648 errmsg("there is no parameter $%d", paramno
),
649 parser_errposition(pstate
, location
)));
650 /* Okay to enlarge param array */
651 if (pstate
->p_paramtypes
)
652 pstate
->p_paramtypes
= (Oid
*) repalloc(pstate
->p_paramtypes
,
653 paramno
* sizeof(Oid
));
655 pstate
->p_paramtypes
= (Oid
*) palloc(paramno
* sizeof(Oid
));
656 /* Zero out the previously-unreferenced slots */
657 MemSet(pstate
->p_paramtypes
+ pstate
->p_numparams
,
659 (paramno
- pstate
->p_numparams
) * sizeof(Oid
));
660 pstate
->p_numparams
= paramno
;
663 result
= &pstate
->p_paramtypes
[paramno
- 1];
665 if (pstate
->p_variableparams
)
667 /* If not seen before, initialize to UNKNOWN type */
668 if (*result
== InvalidOid
)
669 *result
= UNKNOWNOID
;
676 transformParamRef(ParseState
*pstate
, ParamRef
*pref
)
678 int paramno
= pref
->number
;
679 Oid
*pptype
= find_param_type(pstate
, paramno
, pref
->location
);
682 param
= makeNode(Param
);
683 param
->paramkind
= PARAM_EXTERN
;
684 param
->paramid
= paramno
;
685 param
->paramtype
= *pptype
;
686 param
->paramtypmod
= -1;
687 param
->location
= pref
->location
;
689 return (Node
*) param
;
692 /* Test whether an a_expr is a plain NULL constant or not */
694 exprIsNullConstant(Node
*arg
)
696 if (arg
&& IsA(arg
, A_Const
))
698 A_Const
*con
= (A_Const
*) arg
;
700 if (con
->val
.type
== T_Null
)
707 transformAExprOp(ParseState
*pstate
, A_Expr
*a
)
709 Node
*lexpr
= a
->lexpr
;
710 Node
*rexpr
= a
->rexpr
;
714 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
715 * standards-broken products (like Microsoft's). Turn these into IS NULL
718 if (Transform_null_equals
&&
719 list_length(a
->name
) == 1 &&
720 strcmp(strVal(linitial(a
->name
)), "=") == 0 &&
721 (exprIsNullConstant(lexpr
) || exprIsNullConstant(rexpr
)))
723 NullTest
*n
= makeNode(NullTest
);
725 n
->nulltesttype
= IS_NULL
;
727 if (exprIsNullConstant(lexpr
))
728 n
->arg
= (Expr
*) rexpr
;
730 n
->arg
= (Expr
*) lexpr
;
732 result
= transformExpr(pstate
, (Node
*) n
);
734 else if (lexpr
&& IsA(lexpr
, RowExpr
) &&
735 rexpr
&& IsA(rexpr
, SubLink
) &&
736 ((SubLink
*) rexpr
)->subLinkType
== EXPR_SUBLINK
)
739 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
740 * grammar did this, but now that a row construct is allowed anywhere
741 * in expressions, it's easier to do it here.
743 SubLink
*s
= (SubLink
*) rexpr
;
745 s
->subLinkType
= ROWCOMPARE_SUBLINK
;
747 s
->operName
= a
->name
;
748 s
->location
= a
->location
;
749 result
= transformExpr(pstate
, (Node
*) s
);
751 else if (lexpr
&& IsA(lexpr
, RowExpr
) &&
752 rexpr
&& IsA(rexpr
, RowExpr
))
755 lexpr
= transformExpr(pstate
, lexpr
);
756 rexpr
= transformExpr(pstate
, rexpr
);
757 Assert(IsA(lexpr
, RowExpr
));
758 Assert(IsA(rexpr
, RowExpr
));
760 result
= make_row_comparison_op(pstate
,
762 ((RowExpr
*) lexpr
)->args
,
763 ((RowExpr
*) rexpr
)->args
,
768 /* Ordinary scalar operator */
769 lexpr
= transformExpr(pstate
, lexpr
);
770 rexpr
= transformExpr(pstate
, rexpr
);
772 result
= (Node
*) make_op(pstate
,
783 transformAExprAnd(ParseState
*pstate
, A_Expr
*a
)
785 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
786 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
788 lexpr
= coerce_to_boolean(pstate
, lexpr
, "AND");
789 rexpr
= coerce_to_boolean(pstate
, rexpr
, "AND");
791 return (Node
*) makeBoolExpr(AND_EXPR
,
792 list_make2(lexpr
, rexpr
),
797 transformAExprOr(ParseState
*pstate
, A_Expr
*a
)
799 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
800 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
802 lexpr
= coerce_to_boolean(pstate
, lexpr
, "OR");
803 rexpr
= coerce_to_boolean(pstate
, rexpr
, "OR");
805 return (Node
*) makeBoolExpr(OR_EXPR
,
806 list_make2(lexpr
, rexpr
),
811 transformAExprNot(ParseState
*pstate
, A_Expr
*a
)
813 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
815 rexpr
= coerce_to_boolean(pstate
, rexpr
, "NOT");
817 return (Node
*) makeBoolExpr(NOT_EXPR
,
823 transformAExprOpAny(ParseState
*pstate
, A_Expr
*a
)
825 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
826 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
828 return (Node
*) make_scalar_array_op(pstate
,
837 transformAExprOpAll(ParseState
*pstate
, A_Expr
*a
)
839 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
840 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
842 return (Node
*) make_scalar_array_op(pstate
,
851 transformAExprDistinct(ParseState
*pstate
, A_Expr
*a
)
853 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
854 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
856 if (lexpr
&& IsA(lexpr
, RowExpr
) &&
857 rexpr
&& IsA(rexpr
, RowExpr
))
860 return make_row_distinct_op(pstate
, a
->name
,
867 /* Ordinary scalar operator */
868 return (Node
*) make_distinct_op(pstate
,
877 transformAExprNullIf(ParseState
*pstate
, A_Expr
*a
)
879 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
880 Node
*rexpr
= transformExpr(pstate
, a
->rexpr
);
883 result
= (Node
*) make_op(pstate
,
888 if (((OpExpr
*) result
)->opresulttype
!= BOOLOID
)
890 (errcode(ERRCODE_DATATYPE_MISMATCH
),
891 errmsg("NULLIF requires = operator to yield boolean"),
892 parser_errposition(pstate
, a
->location
)));
895 * We rely on NullIfExpr and OpExpr being the same struct
897 NodeSetTag(result
, T_NullIfExpr
);
903 transformAExprOf(ParseState
*pstate
, A_Expr
*a
)
906 * Checking an expression for match to a list of type names. Will result
907 * in a boolean constant node.
909 Node
*lexpr
= transformExpr(pstate
, a
->lexpr
);
914 bool matched
= false;
916 ltype
= exprType(lexpr
);
917 foreach(telem
, (List
*) a
->rexpr
)
919 rtype
= typenameTypeId(pstate
, lfirst(telem
), NULL
);
920 matched
= (rtype
== ltype
);
926 * We have two forms: equals or not equals. Flip the sense of the result
929 if (strcmp(strVal(linitial(a
->name
)), "<>") == 0)
930 matched
= (!matched
);
932 result
= (Const
*) makeBoolConst(matched
, false);
934 /* Make the result have the original input's parse location */
935 result
->location
= exprLocation((Node
*) a
);
937 return (Node
*) result
;
941 transformAExprIn(ParseState
*pstate
, A_Expr
*a
)
953 * If the operator is <>, combine with AND not OR.
955 if (strcmp(strVal(linitial(a
->name
)), "<>") == 0)
961 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
962 * possible if the inputs are all scalars (no RowExprs) and there is a
963 * suitable array type available. If not, we fall back to a boolean
964 * condition tree with multiple copies of the lefthand expression. Also,
965 * any IN-list items that contain Vars are handled as separate boolean
966 * conditions, because that gives the planner more scope for optimization
969 * First step: transform all the inputs, and detect whether any are
970 * RowExprs or contain Vars.
972 lexpr
= transformExpr(pstate
, a
->lexpr
);
973 haveRowExpr
= (lexpr
&& IsA(lexpr
, RowExpr
));
974 rexprs
= rvars
= rnonvars
= NIL
;
975 foreach(l
, (List
*) a
->rexpr
)
977 Node
*rexpr
= transformExpr(pstate
, lfirst(l
));
979 haveRowExpr
|= (rexpr
&& IsA(rexpr
, RowExpr
));
980 rexprs
= lappend(rexprs
, rexpr
);
981 if (contain_vars_of_level(rexpr
, 0))
982 rvars
= lappend(rvars
, rexpr
);
984 rnonvars
= lappend(rnonvars
, rexpr
);
988 * ScalarArrayOpExpr is only going to be useful if there's more than one
989 * non-Var righthand item. Also, it won't work for RowExprs.
991 if (!haveRowExpr
&& list_length(rnonvars
) > 1)
998 * Try to select a common type for the array elements. Note that
999 * since the LHS' type is first in the list, it will be preferred when
1000 * there is doubt (eg, when all the RHS items are unknown literals).
1002 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1004 allexprs
= list_concat(list_make1(lexpr
), rnonvars
);
1005 scalar_type
= select_common_type(pstate
, allexprs
, NULL
, NULL
);
1007 /* Do we have an array type to use? */
1008 if (OidIsValid(scalar_type
))
1009 array_type
= get_array_type(scalar_type
);
1011 array_type
= InvalidOid
;
1012 if (array_type
!= InvalidOid
)
1015 * OK: coerce all the right-hand non-Var inputs to the common type
1016 * and build an ArrayExpr for them.
1022 foreach(l
, rnonvars
)
1024 Node
*rexpr
= (Node
*) lfirst(l
);
1026 rexpr
= coerce_to_common_type(pstate
, rexpr
,
1029 aexprs
= lappend(aexprs
, rexpr
);
1031 newa
= makeNode(ArrayExpr
);
1032 newa
->array_typeid
= array_type
;
1033 newa
->element_typeid
= scalar_type
;
1034 newa
->elements
= aexprs
;
1035 newa
->multidims
= false;
1036 newa
->location
= -1;
1038 result
= (Node
*) make_scalar_array_op(pstate
,
1045 /* Consider only the Vars (if any) in the loop below */
1051 * Must do it the hard way, ie, with a boolean expression tree.
1055 Node
*rexpr
= (Node
*) lfirst(l
);
1060 if (!IsA(lexpr
, RowExpr
) ||
1061 !IsA(rexpr
, RowExpr
))
1063 (errcode(ERRCODE_SYNTAX_ERROR
),
1064 errmsg("arguments of row IN must all be row expressions"),
1065 parser_errposition(pstate
, a
->location
)));
1066 cmp
= make_row_comparison_op(pstate
,
1068 (List
*) copyObject(((RowExpr
*) lexpr
)->args
),
1069 ((RowExpr
*) rexpr
)->args
,
1073 cmp
= (Node
*) make_op(pstate
,
1079 cmp
= coerce_to_boolean(pstate
, cmp
, "IN");
1083 result
= (Node
*) makeBoolExpr(useOr
? OR_EXPR
: AND_EXPR
,
1084 list_make2(result
, cmp
),
1092 transformFuncCall(ParseState
*pstate
, FuncCall
*fn
)
1097 /* Transform the list of arguments ... */
1099 foreach(args
, fn
->args
)
1101 targs
= lappend(targs
, transformExpr(pstate
,
1102 (Node
*) lfirst(args
)));
1105 /* ... and hand off to ParseFuncOrColumn */
1106 return ParseFuncOrColumn(pstate
,
1118 transformCaseExpr(ParseState
*pstate
, CaseExpr
*c
)
1122 CaseTestExpr
*placeholder
;
1129 /* If we already transformed this node, do nothing */
1130 if (OidIsValid(c
->casetype
))
1133 newc
= makeNode(CaseExpr
);
1135 /* transform the test expression, if any */
1136 arg
= transformExpr(pstate
, (Node
*) c
->arg
);
1138 /* generate placeholder for test expression */
1142 * If test expression is an untyped literal, force it to text. We have
1143 * to do something now because we won't be able to do this coercion on
1144 * the placeholder. This is not as flexible as what was done in 7.4
1145 * and before, but it's good enough to handle the sort of silly coding
1148 if (exprType(arg
) == UNKNOWNOID
)
1149 arg
= coerce_to_common_type(pstate
, arg
, TEXTOID
, "CASE");
1151 placeholder
= makeNode(CaseTestExpr
);
1152 placeholder
->typeId
= exprType(arg
);
1153 placeholder
->typeMod
= exprTypmod(arg
);
1158 newc
->arg
= (Expr
*) arg
;
1160 /* transform the list of arguments */
1165 CaseWhen
*w
= (CaseWhen
*) lfirst(l
);
1166 CaseWhen
*neww
= makeNode(CaseWhen
);
1169 Assert(IsA(w
, CaseWhen
));
1171 warg
= (Node
*) w
->expr
;
1174 /* shorthand form was specified, so expand... */
1175 warg
= (Node
*) makeSimpleA_Expr(AEXPR_OP
, "=",
1176 (Node
*) placeholder
,
1180 neww
->expr
= (Expr
*) transformExpr(pstate
, warg
);
1182 neww
->expr
= (Expr
*) coerce_to_boolean(pstate
,
1183 (Node
*) neww
->expr
,
1186 warg
= (Node
*) w
->result
;
1187 neww
->result
= (Expr
*) transformExpr(pstate
, warg
);
1188 neww
->location
= w
->location
;
1190 newargs
= lappend(newargs
, neww
);
1191 resultexprs
= lappend(resultexprs
, neww
->result
);
1194 newc
->args
= newargs
;
1196 /* transform the default clause */
1197 defresult
= (Node
*) c
->defresult
;
1198 if (defresult
== NULL
)
1200 A_Const
*n
= makeNode(A_Const
);
1202 n
->val
.type
= T_Null
;
1204 defresult
= (Node
*) n
;
1206 newc
->defresult
= (Expr
*) transformExpr(pstate
, defresult
);
1209 * Note: default result is considered the most significant type in
1210 * determining preferred type. This is how the code worked before, but it
1211 * seems a little bogus to me --- tgl
1213 resultexprs
= lcons(newc
->defresult
, resultexprs
);
1215 ptype
= select_common_type(pstate
, resultexprs
, "CASE", NULL
);
1216 Assert(OidIsValid(ptype
));
1217 newc
->casetype
= ptype
;
1219 /* Convert default result clause, if necessary */
1220 newc
->defresult
= (Expr
*)
1221 coerce_to_common_type(pstate
,
1222 (Node
*) newc
->defresult
,
1226 /* Convert when-clause results, if necessary */
1227 foreach(l
, newc
->args
)
1229 CaseWhen
*w
= (CaseWhen
*) lfirst(l
);
1231 w
->result
= (Expr
*)
1232 coerce_to_common_type(pstate
,
1238 newc
->location
= c
->location
;
1240 return (Node
*) newc
;
1244 transformSubLink(ParseState
*pstate
, SubLink
*sublink
)
1246 Node
*result
= (Node
*) sublink
;
1249 /* If we already transformed this node, do nothing */
1250 if (IsA(sublink
->subselect
, Query
))
1253 pstate
->p_hasSubLinks
= true;
1254 qtree
= parse_sub_analyze(sublink
->subselect
, pstate
);
1257 * Check that we got something reasonable. Many of these conditions are
1258 * impossible given restrictions of the grammar, but check 'em anyway.
1260 if (!IsA(qtree
, Query
) ||
1261 qtree
->commandType
!= CMD_SELECT
||
1262 qtree
->utilityStmt
!= NULL
)
1263 elog(ERROR
, "unexpected non-SELECT command in SubLink");
1264 if (qtree
->intoClause
)
1266 (errcode(ERRCODE_SYNTAX_ERROR
),
1267 errmsg("subquery cannot have SELECT INTO"),
1268 parser_errposition(pstate
,
1269 exprLocation((Node
*) qtree
->intoClause
))));
1271 sublink
->subselect
= (Node
*) qtree
;
1273 if (sublink
->subLinkType
== EXISTS_SUBLINK
)
1276 * EXISTS needs no test expression or combining operator. These fields
1277 * should be null already, but make sure.
1279 sublink
->testexpr
= NULL
;
1280 sublink
->operName
= NIL
;
1282 else if (sublink
->subLinkType
== EXPR_SUBLINK
||
1283 sublink
->subLinkType
== ARRAY_SUBLINK
)
1285 ListCell
*tlist_item
= list_head(qtree
->targetList
);
1288 * Make sure the subselect delivers a single column (ignoring resjunk
1291 if (tlist_item
== NULL
||
1292 ((TargetEntry
*) lfirst(tlist_item
))->resjunk
)
1294 (errcode(ERRCODE_SYNTAX_ERROR
),
1295 errmsg("subquery must return a column"),
1296 parser_errposition(pstate
, sublink
->location
)));
1297 while ((tlist_item
= lnext(tlist_item
)) != NULL
)
1299 if (!((TargetEntry
*) lfirst(tlist_item
))->resjunk
)
1301 (errcode(ERRCODE_SYNTAX_ERROR
),
1302 errmsg("subquery must return only one column"),
1303 parser_errposition(pstate
, sublink
->location
)));
1307 * EXPR and ARRAY need no test expression or combining operator. These
1308 * fields should be null already, but make sure.
1310 sublink
->testexpr
= NULL
;
1311 sublink
->operName
= NIL
;
1315 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1322 * Transform lefthand expression, and convert to a list
1324 lefthand
= transformExpr(pstate
, sublink
->testexpr
);
1325 if (lefthand
&& IsA(lefthand
, RowExpr
))
1326 left_list
= ((RowExpr
*) lefthand
)->args
;
1328 left_list
= list_make1(lefthand
);
1331 * Build a list of PARAM_SUBLINK nodes representing the output columns
1335 foreach(l
, qtree
->targetList
)
1337 TargetEntry
*tent
= (TargetEntry
*) lfirst(l
);
1343 param
= makeNode(Param
);
1344 param
->paramkind
= PARAM_SUBLINK
;
1345 param
->paramid
= tent
->resno
;
1346 param
->paramtype
= exprType((Node
*) tent
->expr
);
1347 param
->paramtypmod
= exprTypmod((Node
*) tent
->expr
);
1348 param
->location
= -1;
1350 right_list
= lappend(right_list
, param
);
1354 * We could rely on make_row_comparison_op to complain if the list
1355 * lengths differ, but we prefer to generate a more specific error
1358 if (list_length(left_list
) < list_length(right_list
))
1360 (errcode(ERRCODE_SYNTAX_ERROR
),
1361 errmsg("subquery has too many columns"),
1362 parser_errposition(pstate
, sublink
->location
)));
1363 if (list_length(left_list
) > list_length(right_list
))
1365 (errcode(ERRCODE_SYNTAX_ERROR
),
1366 errmsg("subquery has too few columns"),
1367 parser_errposition(pstate
, sublink
->location
)));
1370 * Identify the combining operator(s) and generate a suitable
1371 * row-comparison expression.
1373 sublink
->testexpr
= make_row_comparison_op(pstate
,
1384 * transformArrayExpr
1386 * If the caller specifies the target type, the resulting array will
1387 * be of exactly that type. Otherwise we try to infer a common type
1388 * for the elements using select_common_type().
1391 transformArrayExpr(ParseState
*pstate
, A_ArrayExpr
*a
,
1392 Oid array_type
, Oid element_type
, int32 typmod
)
1394 ArrayExpr
*newa
= makeNode(ArrayExpr
);
1395 List
*newelems
= NIL
;
1396 List
*newcoercedelems
= NIL
;
1402 * Transform the element expressions
1404 * Assume that the array is one-dimensional unless we find an array-type
1405 * element expression.
1407 newa
->multidims
= false;
1408 foreach(element
, a
->elements
)
1410 Node
*e
= (Node
*) lfirst(element
);
1414 * If an element is itself an A_ArrayExpr, recurse directly so that we
1415 * can pass down any target type we were given.
1417 if (IsA(e
, A_ArrayExpr
))
1419 newe
= transformArrayExpr(pstate
,
1424 /* we certainly have an array here */
1425 Assert(array_type
== InvalidOid
|| array_type
== exprType(newe
));
1426 newa
->multidims
= true;
1430 newe
= transformExpr(pstate
, e
);
1433 * Check for sub-array expressions, if we haven't already found
1436 if (!newa
->multidims
&& type_is_array(exprType(newe
)))
1437 newa
->multidims
= true;
1440 newelems
= lappend(newelems
, newe
);
1444 * Select a target type for the elements.
1446 * If we haven't been given a target array type, we must try to deduce a
1447 * common type based on the types of the individual elements present.
1449 if (OidIsValid(array_type
))
1451 /* Caller must ensure array_type matches element_type */
1452 Assert(OidIsValid(element_type
));
1453 coerce_type
= (newa
->multidims
? array_type
: element_type
);
1458 /* Can't handle an empty array without a target type */
1459 if (newelems
== NIL
)
1461 (errcode(ERRCODE_INDETERMINATE_DATATYPE
),
1462 errmsg("cannot determine type of empty array"),
1463 errhint("Explicitly cast to the desired type, "
1464 "for example ARRAY[]::integer[]."),
1465 parser_errposition(pstate
, a
->location
)));
1467 /* Select a common type for the elements */
1468 coerce_type
= select_common_type(pstate
, newelems
, "ARRAY", NULL
);
1470 if (newa
->multidims
)
1472 array_type
= coerce_type
;
1473 element_type
= get_element_type(array_type
);
1474 if (!OidIsValid(element_type
))
1476 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1477 errmsg("could not find element type for data type %s",
1478 format_type_be(array_type
)),
1479 parser_errposition(pstate
, a
->location
)));
1483 element_type
= coerce_type
;
1484 array_type
= get_array_type(element_type
);
1485 if (!OidIsValid(array_type
))
1487 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1488 errmsg("could not find array type for data type %s",
1489 format_type_be(element_type
)),
1490 parser_errposition(pstate
, a
->location
)));
1492 coerce_hard
= false;
1496 * Coerce elements to target type
1498 * If the array has been explicitly cast, then the elements are in turn
1499 * explicitly coerced.
1501 * If the array's type was merely derived from the common type of its
1502 * elements, then the elements are implicitly coerced to the common type.
1503 * This is consistent with other uses of select_common_type().
1505 foreach(element
, newelems
)
1507 Node
*e
= (Node
*) lfirst(element
);
1512 newe
= coerce_to_target_type(pstate
, e
,
1517 COERCE_EXPLICIT_CAST
,
1521 (errcode(ERRCODE_CANNOT_COERCE
),
1522 errmsg("cannot cast type %s to %s",
1523 format_type_be(exprType(e
)),
1524 format_type_be(coerce_type
)),
1525 parser_errposition(pstate
, exprLocation(e
))));
1528 newe
= coerce_to_common_type(pstate
, e
,
1531 newcoercedelems
= lappend(newcoercedelems
, newe
);
1534 newa
->array_typeid
= array_type
;
1535 newa
->element_typeid
= element_type
;
1536 newa
->elements
= newcoercedelems
;
1537 newa
->location
= a
->location
;
1539 return (Node
*) newa
;
1543 transformRowExpr(ParseState
*pstate
, RowExpr
*r
)
1545 RowExpr
*newr
= makeNode(RowExpr
);
1547 /* Transform the field expressions */
1548 newr
->args
= transformExpressionList(pstate
, r
->args
);
1550 /* Barring later casting, we consider the type RECORD */
1551 newr
->row_typeid
= RECORDOID
;
1552 newr
->row_format
= COERCE_IMPLICIT_CAST
;
1553 newr
->colnames
= NIL
; /* ROW() has anonymous columns */
1554 newr
->location
= r
->location
;
1556 return (Node
*) newr
;
1560 transformCoalesceExpr(ParseState
*pstate
, CoalesceExpr
*c
)
1562 CoalesceExpr
*newc
= makeNode(CoalesceExpr
);
1563 List
*newargs
= NIL
;
1564 List
*newcoercedargs
= NIL
;
1567 foreach(args
, c
->args
)
1569 Node
*e
= (Node
*) lfirst(args
);
1572 newe
= transformExpr(pstate
, e
);
1573 newargs
= lappend(newargs
, newe
);
1576 newc
->coalescetype
= select_common_type(pstate
, newargs
, "COALESCE", NULL
);
1578 /* Convert arguments if necessary */
1579 foreach(args
, newargs
)
1581 Node
*e
= (Node
*) lfirst(args
);
1584 newe
= coerce_to_common_type(pstate
, e
,
1587 newcoercedargs
= lappend(newcoercedargs
, newe
);
1590 newc
->args
= newcoercedargs
;
1591 newc
->location
= c
->location
;
1592 return (Node
*) newc
;
1596 transformMinMaxExpr(ParseState
*pstate
, MinMaxExpr
*m
)
1598 MinMaxExpr
*newm
= makeNode(MinMaxExpr
);
1599 List
*newargs
= NIL
;
1600 List
*newcoercedargs
= NIL
;
1601 const char *funcname
= (m
->op
== IS_GREATEST
) ? "GREATEST" : "LEAST";
1605 foreach(args
, m
->args
)
1607 Node
*e
= (Node
*) lfirst(args
);
1610 newe
= transformExpr(pstate
, e
);
1611 newargs
= lappend(newargs
, newe
);
1614 newm
->minmaxtype
= select_common_type(pstate
, newargs
, funcname
, NULL
);
1616 /* Convert arguments if necessary */
1617 foreach(args
, newargs
)
1619 Node
*e
= (Node
*) lfirst(args
);
1622 newe
= coerce_to_common_type(pstate
, e
,
1625 newcoercedargs
= lappend(newcoercedargs
, newe
);
1628 newm
->args
= newcoercedargs
;
1629 newm
->location
= m
->location
;
1630 return (Node
*) newm
;
1634 transformXmlExpr(ParseState
*pstate
, XmlExpr
*x
)
1636 XmlExpr
*newx
= makeNode(XmlExpr
);
1642 newx
->name
= map_sql_identifier_to_xml_name(x
->name
, false, false);
1645 newx
->xmloption
= x
->xmloption
;
1646 newx
->location
= x
->location
;
1649 * gram.y built the named args as a list of ResTarget. Transform each,
1650 * and break the names out as a separate list.
1652 newx
->named_args
= NIL
;
1653 newx
->arg_names
= NIL
;
1655 foreach(lc
, x
->named_args
)
1657 ResTarget
*r
= (ResTarget
*) lfirst(lc
);
1661 Assert(IsA(r
, ResTarget
));
1663 expr
= transformExpr(pstate
, r
->val
);
1666 argname
= map_sql_identifier_to_xml_name(r
->name
, false, false);
1667 else if (IsA(r
->val
, ColumnRef
))
1668 argname
= map_sql_identifier_to_xml_name(FigureColname(r
->val
),
1673 (errcode(ERRCODE_SYNTAX_ERROR
),
1674 x
->op
== IS_XMLELEMENT
1675 ? errmsg("unnamed XML attribute value must be a column reference")
1676 : errmsg("unnamed XML element value must be a column reference"),
1677 parser_errposition(pstate
, r
->location
)));
1678 argname
= NULL
; /* keep compiler quiet */
1681 /* reject duplicate argnames in XMLELEMENT only */
1682 if (x
->op
== IS_XMLELEMENT
)
1686 foreach(lc2
, newx
->arg_names
)
1688 if (strcmp(argname
, strVal(lfirst(lc2
))) == 0)
1690 (errcode(ERRCODE_SYNTAX_ERROR
),
1691 errmsg("XML attribute name \"%s\" appears more than once",
1693 parser_errposition(pstate
, r
->location
)));
1697 newx
->named_args
= lappend(newx
->named_args
, expr
);
1698 newx
->arg_names
= lappend(newx
->arg_names
, makeString(argname
));
1701 /* The other arguments are of varying types depending on the function */
1704 foreach(lc
, x
->args
)
1706 Node
*e
= (Node
*) lfirst(lc
);
1709 newe
= transformExpr(pstate
, e
);
1713 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1717 /* no coercion necessary */
1720 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1725 newe
= coerce_to_specific_type(pstate
, newe
, TEXTOID
,
1728 newe
= coerce_to_boolean(pstate
, newe
, "XMLPARSE");
1731 newe
= coerce_to_specific_type(pstate
, newe
, TEXTOID
,
1736 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1739 newe
= coerce_to_specific_type(pstate
, newe
, TEXTOID
,
1742 newe
= coerce_to_specific_type(pstate
, newe
, INT4OID
,
1745 case IS_XMLSERIALIZE
:
1746 /* not handled here */
1750 newe
= coerce_to_specific_type(pstate
, newe
, XMLOID
,
1754 newx
->args
= lappend(newx
->args
, newe
);
1758 return (Node
*) newx
;
1762 transformXmlSerialize(ParseState
*pstate
, XmlSerialize
*xs
)
1769 xexpr
= makeNode(XmlExpr
);
1770 xexpr
->op
= IS_XMLSERIALIZE
;
1771 xexpr
->args
= list_make1(coerce_to_specific_type(pstate
,
1772 transformExpr(pstate
, xs
->expr
),
1776 targetType
= typenameTypeId(pstate
, xs
->typename
, &targetTypmod
);
1778 xexpr
->xmloption
= xs
->xmloption
;
1779 xexpr
->location
= xs
->location
;
1780 /* We actually only need these to be able to parse back the expression. */
1781 xexpr
->type
= targetType
;
1782 xexpr
->typmod
= targetTypmod
;
1785 * The actual target type is determined this way. SQL allows char and
1786 * varchar as target types. We allow anything that can be cast implicitly
1787 * from text. This way, user-defined text-like data types automatically
1790 result
= coerce_to_target_type(pstate
, (Node
*) xexpr
,
1791 TEXTOID
, targetType
, targetTypmod
,
1793 COERCE_IMPLICIT_CAST
,
1797 (errcode(ERRCODE_CANNOT_COERCE
),
1798 errmsg("cannot cast XMLSERIALIZE result to %s",
1799 format_type_be(targetType
)),
1800 parser_errposition(pstate
, xexpr
->location
)));
1805 transformBooleanTest(ParseState
*pstate
, BooleanTest
*b
)
1807 const char *clausename
;
1809 switch (b
->booltesttype
)
1812 clausename
= "IS TRUE";
1815 clausename
= "IS NOT TRUE";
1818 clausename
= "IS FALSE";
1821 clausename
= "IS NOT FALSE";
1824 clausename
= "IS UNKNOWN";
1826 case IS_NOT_UNKNOWN
:
1827 clausename
= "IS NOT UNKNOWN";
1830 elog(ERROR
, "unrecognized booltesttype: %d",
1831 (int) b
->booltesttype
);
1832 clausename
= NULL
; /* keep compiler quiet */
1835 b
->arg
= (Expr
*) transformExpr(pstate
, (Node
*) b
->arg
);
1837 b
->arg
= (Expr
*) coerce_to_boolean(pstate
,
1845 transformCurrentOfExpr(ParseState
*pstate
, CurrentOfExpr
*cexpr
)
1849 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1850 Assert(pstate
->p_target_rangetblentry
!= NULL
);
1851 cexpr
->cvarno
= RTERangeTablePosn(pstate
,
1852 pstate
->p_target_rangetblentry
,
1854 Assert(sublevels_up
== 0);
1856 /* If a parameter is used, it must be of type REFCURSOR */
1857 if (cexpr
->cursor_name
== NULL
)
1859 Oid
*pptype
= find_param_type(pstate
, cexpr
->cursor_param
, -1);
1861 if (pstate
->p_variableparams
&& *pptype
== UNKNOWNOID
)
1863 /* resolve unknown param type as REFCURSOR */
1864 *pptype
= REFCURSOROID
;
1866 else if (*pptype
!= REFCURSOROID
)
1869 (errcode(ERRCODE_AMBIGUOUS_PARAMETER
),
1870 errmsg("inconsistent types deduced for parameter $%d",
1871 cexpr
->cursor_param
),
1872 errdetail("%s versus %s",
1873 format_type_be(*pptype
),
1874 format_type_be(REFCURSOROID
))));
1878 return (Node
*) cexpr
;
1882 * Construct a whole-row reference to represent the notation "relation.*".
1884 * A whole-row reference is a Var with varno set to the correct range
1885 * table entry, and varattno == 0 to signal that it references the whole
1886 * tuple. (Use of zero here is unclean, since it could easily be confused
1887 * with error cases, but it's not worth changing now.) The vartype indicates
1888 * a rowtype; either a named composite type, or RECORD.
1891 transformWholeRowRef(ParseState
*pstate
, char *schemaname
, char *relname
,
1900 /* Look up the referenced RTE, creating it if needed */
1902 rte
= refnameRangeTblEntry(pstate
, schemaname
, relname
, location
,
1906 rte
= addImplicitRTE(pstate
,
1907 makeRangeVar(schemaname
, relname
, location
));
1909 vnum
= RTERangeTablePosn(pstate
, rte
, &sublevels_up
);
1911 /* Build the appropriate referencing node */
1913 switch (rte
->rtekind
)
1916 /* relation: the rowtype is a named composite type */
1917 toid
= get_rel_type_id(rte
->relid
);
1918 if (!OidIsValid(toid
))
1919 elog(ERROR
, "could not find type OID for relation %u",
1921 result
= makeVar(vnum
,
1928 toid
= exprType(rte
->funcexpr
);
1929 if (type_is_rowtype(toid
))
1931 /* func returns composite; same as relation case */
1932 result
= makeVar(vnum
,
1941 * func returns scalar; instead of making a whole-row Var,
1942 * just reference the function's scalar output. (XXX this
1943 * seems a tad inconsistent, especially if "f.*" was
1944 * explicitly written ...)
1946 result
= makeVar(vnum
,
1955 /* returns composite; same as relation case */
1956 result
= makeVar(vnum
,
1965 * RTE is a join or subselect. We represent this as a whole-row
1966 * Var of RECORD type. (Note that in most cases the Var will be
1967 * expanded to a RowExpr during planning, but that is not our
1970 result
= makeVar(vnum
,
1978 /* location is not filled in by makeVar */
1979 result
->location
= location
;
1981 /* mark relation as requiring whole-row SELECT access */
1982 markVarForSelectPriv(pstate
, result
, rte
);
1984 return (Node
*) result
;
1988 * Handle an explicit CAST construct.
1990 * Transform the argument, then look up the type name and apply any necessary
1991 * coercion function(s).
1994 transformTypeCast(ParseState
*pstate
, TypeCast
*tc
)
1997 Node
*expr
= transformExpr(pstate
, tc
->arg
);
1998 Oid inputType
= exprType(expr
);
2003 targetType
= typenameTypeId(pstate
, tc
->typename
, &targetTypmod
);
2005 if (inputType
== InvalidOid
)
2006 return expr
; /* do nothing if NULL input */
2009 * Location of the coercion is preferentially the location of the :: or
2010 * CAST symbol, but if there is none then use the location of the type
2011 * name (this can happen in TypeName 'string' syntax, for instance).
2013 location
= tc
->location
;
2015 location
= tc
->typename
->location
;
2017 result
= coerce_to_target_type(pstate
, expr
, inputType
,
2018 targetType
, targetTypmod
,
2020 COERCE_EXPLICIT_CAST
,
2024 (errcode(ERRCODE_CANNOT_COERCE
),
2025 errmsg("cannot cast type %s to %s",
2026 format_type_be(inputType
),
2027 format_type_be(targetType
)),
2028 parser_coercion_errposition(pstate
, location
, expr
)));
2034 * Transform a "row compare-op row" construct
2036 * The inputs are lists of already-transformed expressions.
2037 * As with coerce_type, pstate may be NULL if no special unknown-Param
2038 * processing is wanted.
2040 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2041 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2042 * The AND, OR, and RowCompareExpr cases further imply things about the
2043 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2046 make_row_comparison_op(ParseState
*pstate
, List
*opname
,
2047 List
*largs
, List
*rargs
, int location
)
2049 RowCompareExpr
*rcexpr
;
2050 RowCompareType rctype
;
2056 List
**opfamily_lists
;
2057 List
**opstrat_lists
;
2062 nopers
= list_length(largs
);
2063 if (nopers
!= list_length(rargs
))
2065 (errcode(ERRCODE_SYNTAX_ERROR
),
2066 errmsg("unequal number of entries in row expressions"),
2067 parser_errposition(pstate
, location
)));
2070 * We can't compare zero-length rows because there is no principled basis
2071 * for figuring out what the operator is.
2075 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2076 errmsg("cannot compare rows of zero length"),
2077 parser_errposition(pstate
, location
)));
2080 * Identify all the pairwise operators, using make_op so that behavior is
2081 * the same as in the simple scalar case.
2084 forboth(l
, largs
, r
, rargs
)
2086 Node
*larg
= (Node
*) lfirst(l
);
2087 Node
*rarg
= (Node
*) lfirst(r
);
2090 cmp
= (OpExpr
*) make_op(pstate
, opname
, larg
, rarg
, location
);
2091 Assert(IsA(cmp
, OpExpr
));
2094 * We don't use coerce_to_boolean here because we insist on the
2095 * operator yielding boolean directly, not via coercion. If it
2096 * doesn't yield bool it won't be in any index opfamilies...
2098 if (cmp
->opresulttype
!= BOOLOID
)
2100 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2101 errmsg("row comparison operator must yield type boolean, "
2103 format_type_be(cmp
->opresulttype
)),
2104 parser_errposition(pstate
, location
)));
2105 if (expression_returns_set((Node
*) cmp
))
2107 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2108 errmsg("row comparison operator must not return a set"),
2109 parser_errposition(pstate
, location
)));
2110 opexprs
= lappend(opexprs
, cmp
);
2114 * If rows are length 1, just return the single operator. In this case we
2115 * don't insist on identifying btree semantics for the operator (but we
2116 * still require it to return boolean).
2119 return (Node
*) linitial(opexprs
);
2122 * Now we must determine which row comparison semantics (= <> < <= > >=)
2123 * apply to this set of operators. We look for btree opfamilies
2124 * containing the operators, and see which interpretations (strategy
2125 * numbers) exist for each operator.
2127 opfamily_lists
= (List
**) palloc(nopers
* sizeof(List
*));
2128 opstrat_lists
= (List
**) palloc(nopers
* sizeof(List
*));
2133 Oid opno
= ((OpExpr
*) lfirst(l
))->opno
;
2134 Bitmapset
*this_strats
;
2137 get_op_btree_interpretation(opno
,
2138 &opfamily_lists
[i
], &opstrat_lists
[i
]);
2141 * convert strategy number list to a Bitmapset to make the
2142 * intersection calculation easy.
2145 foreach(j
, opstrat_lists
[i
])
2147 this_strats
= bms_add_member(this_strats
, lfirst_int(j
));
2150 strats
= this_strats
;
2152 strats
= bms_int_members(strats
, this_strats
);
2157 * If there are multiple common interpretations, we may use any one of
2158 * them ... this coding arbitrarily picks the lowest btree strategy
2161 i
= bms_first_member(strats
);
2164 /* No common interpretation, so fail */
2166 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2167 errmsg("could not determine interpretation of row comparison operator %s",
2168 strVal(llast(opname
))),
2169 errhint("Row comparison operators must be associated with btree operator families."),
2170 parser_errposition(pstate
, location
)));
2172 rctype
= (RowCompareType
) i
;
2175 * For = and <> cases, we just combine the pairwise operators with AND or
2178 * Note: this is presently the only place where the parser generates
2179 * BoolExpr with more than two arguments. Should be OK since the rest of
2180 * the system thinks BoolExpr is N-argument anyway.
2182 if (rctype
== ROWCOMPARE_EQ
)
2183 return (Node
*) makeBoolExpr(AND_EXPR
, opexprs
, location
);
2184 if (rctype
== ROWCOMPARE_NE
)
2185 return (Node
*) makeBoolExpr(OR_EXPR
, opexprs
, location
);
2188 * Otherwise we need to choose exactly which opfamily to associate with
2192 for (i
= 0; i
< nopers
; i
++)
2194 Oid opfamily
= InvalidOid
;
2196 forboth(l
, opfamily_lists
[i
], r
, opstrat_lists
[i
])
2198 int opstrat
= lfirst_int(r
);
2200 if (opstrat
== rctype
)
2202 opfamily
= lfirst_oid(l
);
2206 if (OidIsValid(opfamily
))
2207 opfamilies
= lappend_oid(opfamilies
, opfamily
);
2208 else /* should not happen */
2210 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2211 errmsg("could not determine interpretation of row comparison operator %s",
2212 strVal(llast(opname
))),
2213 errdetail("There are multiple equally-plausible candidates."),
2214 parser_errposition(pstate
, location
)));
2218 * Now deconstruct the OpExprs and create a RowCompareExpr.
2220 * Note: can't just reuse the passed largs/rargs lists, because of
2221 * possibility that make_op inserted coercion operations.
2228 OpExpr
*cmp
= (OpExpr
*) lfirst(l
);
2230 opnos
= lappend_oid(opnos
, cmp
->opno
);
2231 largs
= lappend(largs
, linitial(cmp
->args
));
2232 rargs
= lappend(rargs
, lsecond(cmp
->args
));
2235 rcexpr
= makeNode(RowCompareExpr
);
2236 rcexpr
->rctype
= rctype
;
2237 rcexpr
->opnos
= opnos
;
2238 rcexpr
->opfamilies
= opfamilies
;
2239 rcexpr
->largs
= largs
;
2240 rcexpr
->rargs
= rargs
;
2242 return (Node
*) rcexpr
;
2246 * Transform a "row IS DISTINCT FROM row" construct
2248 * The input RowExprs are already transformed
2251 make_row_distinct_op(ParseState
*pstate
, List
*opname
,
2252 RowExpr
*lrow
, RowExpr
*rrow
,
2255 Node
*result
= NULL
;
2256 List
*largs
= lrow
->args
;
2257 List
*rargs
= rrow
->args
;
2261 if (list_length(largs
) != list_length(rargs
))
2263 (errcode(ERRCODE_SYNTAX_ERROR
),
2264 errmsg("unequal number of entries in row expressions"),
2265 parser_errposition(pstate
, location
)));
2267 forboth(l
, largs
, r
, rargs
)
2269 Node
*larg
= (Node
*) lfirst(l
);
2270 Node
*rarg
= (Node
*) lfirst(r
);
2273 cmp
= (Node
*) make_distinct_op(pstate
, opname
, larg
, rarg
, location
);
2277 result
= (Node
*) makeBoolExpr(OR_EXPR
,
2278 list_make2(result
, cmp
),
2284 /* zero-length rows? Generate constant FALSE */
2285 result
= makeBoolConst(false, false);
2292 * make the node for an IS DISTINCT FROM operator
2295 make_distinct_op(ParseState
*pstate
, List
*opname
, Node
*ltree
, Node
*rtree
,
2300 result
= make_op(pstate
, opname
, ltree
, rtree
, location
);
2301 if (((OpExpr
*) result
)->opresulttype
!= BOOLOID
)
2303 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2304 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2305 parser_errposition(pstate
, location
)));
2308 * We rely on DistinctExpr and OpExpr being same struct
2310 NodeSetTag(result
, T_DistinctExpr
);