1 /*-------------------------------------------------------------------------
4 * handle expressions in parser
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.69 2000/02/20 21:32:10 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "catalog/pg_operator.h"
19 #include "nodes/makefuncs.h"
20 #include "nodes/params.h"
21 #include "nodes/relation.h"
23 #include "parser/analyze.h"
24 #include "parser/gramparse.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 "utils/builtins.h"
33 static Node *parser_typecast_constant(Value *expr, TypeName *typename);
34 static Node *parser_typecast_expression(ParseState *pstate,
35 Node *expr, TypeName *typename);
36 static Node *transformAttr(ParseState *pstate, Attr *att, int precedence);
37 static Node *transformIdent(ParseState *pstate, Ident *ident, int precedence);
38 static Node *transformIndirection(ParseState *pstate, Node *basenode,
43 * analyze and transform expressions. Type checking and type casting is
44 * done here. The optimizer and the executor cannot handle the original
45 * (raw) expressions collected by the parse tree. Hence the transformation
49 transformExpr(ParseState *pstate, Node *expr, int precedence)
56 switch (nodeTag(expr))
60 result = transformAttr(pstate, (Attr *) expr, precedence);
65 A_Const *con = (A_Const *) expr;
66 Value *val = &con->val;
68 if (con->typename != NULL)
69 result = parser_typecast_constant(val, con->typename);
71 result = (Node *) make_const(val);
76 ParamNo *pno = (ParamNo *) expr;
77 int paramno = pno->number;
78 Oid toid = param_type(paramno);
81 if (!OidIsValid(toid))
82 elog(ERROR, "Parameter '$%d' is out of range", paramno);
83 param = makeNode(Param);
84 param->paramkind = PARAM_NUM;
85 param->paramid = (AttrNumber) paramno;
86 param->paramname = "<unnamed>";
87 param->paramtype = (Oid) toid;
88 param->param_tlist = (List *) NULL;
89 result = transformIndirection(pstate, (Node *) param,
91 /* XXX what about cast (typename) applied to Param ??? */
96 TypeCast *tc = (TypeCast *) expr;
97 Node *arg = transformExpr(pstate, tc->arg, precedence);
99 result = parser_typecast_expression(pstate, arg, tc->typename);
104 A_Expr *a = (A_Expr *) expr;
110 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
111 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
113 result = (Node *) make_op(a->opname, lexpr, rexpr);
118 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
120 result = ParseFuncOrColumn(pstate,
124 &pstate->p_last_resno,
130 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
132 result = ParseFuncOrColumn(pstate,
136 &pstate->p_last_resno,
142 Expr *expr = makeNode(Expr);
143 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
144 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
146 if (exprType(lexpr) != BOOLOID)
147 elog(ERROR, "left-hand side of AND is type '%s', not '%s'",
148 typeidTypeName(exprType(lexpr)), typeidTypeName(BOOLOID));
150 if (exprType(rexpr) != BOOLOID)
151 elog(ERROR, "right-hand side of AND is type '%s', not '%s'",
152 typeidTypeName(exprType(rexpr)), typeidTypeName(BOOLOID));
154 expr->typeOid = BOOLOID;
155 expr->opType = AND_EXPR;
156 expr->args = makeList(lexpr, rexpr, -1);
157 result = (Node *) expr;
162 Expr *expr = makeNode(Expr);
163 Node *lexpr = transformExpr(pstate, a->lexpr, precedence);
164 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
166 if (exprType(lexpr) != BOOLOID)
167 elog(ERROR, "left-hand side of OR is type '%s', not '%s'",
168 typeidTypeName(exprType(lexpr)), typeidTypeName(BOOLOID));
169 if (exprType(rexpr) != BOOLOID)
170 elog(ERROR, "right-hand side of OR is type '%s', not '%s'",
171 typeidTypeName(exprType(rexpr)), typeidTypeName(BOOLOID));
172 expr->typeOid = BOOLOID;
173 expr->opType = OR_EXPR;
174 expr->args = makeList(lexpr, rexpr, -1);
175 result = (Node *) expr;
180 Expr *expr = makeNode(Expr);
181 Node *rexpr = transformExpr(pstate, a->rexpr, precedence);
183 if (exprType(rexpr) != BOOLOID)
184 elog(ERROR, "argument to NOT is type '%s', not '%s'",
185 typeidTypeName(exprType(rexpr)), typeidTypeName(BOOLOID));
186 expr->typeOid = BOOLOID;
187 expr->opType = NOT_EXPR;
188 expr->args = makeList(rexpr, -1);
189 result = (Node *) expr;
197 result = transformIdent(pstate, (Ident *) expr, precedence);
202 FuncCall *fn = (FuncCall *) expr;
205 /* transform the list of arguments */
206 foreach(args, fn->args)
207 lfirst(args) = transformExpr(pstate, (Node *) lfirst(args), precedence);
208 result = ParseFuncOrColumn(pstate,
213 &pstate->p_last_resno,
219 SubLink *sublink = (SubLink *) expr;
223 pstate->p_hasSubLinks = true;
224 qtrees = parse_analyze(lcons(sublink->subselect, NIL), pstate);
225 if (length(qtrees) != 1)
226 elog(ERROR, "Bad query in subselect");
227 qtree = (Query *) lfirst(qtrees);
228 if (qtree->commandType != CMD_SELECT ||
229 qtree->resultRelation != 0)
230 elog(ERROR, "Bad query in subselect");
231 sublink->subselect = (Node *) qtree;
233 if (sublink->subLinkType == EXISTS_SUBLINK)
235 /* EXISTS needs no lefthand or combining operator.
236 * These fields should be NIL already, but make sure.
238 sublink->lefthand = NIL;
241 else if (sublink->subLinkType == EXPR_SUBLINK)
243 List *tlist = qtree->targetList;
245 /* Make sure the subselect delivers a single column
246 * (ignoring resjunk targets).
249 ((TargetEntry *) lfirst(tlist))->resdom->resjunk)
250 elog(ERROR, "Subselect must have a field");
251 while ((tlist = lnext(tlist)) != NIL)
253 if (! ((TargetEntry *) lfirst(tlist))->resdom->resjunk)
254 elog(ERROR, "Subselect must have only one field");
256 /* EXPR needs no lefthand or combining operator.
257 * These fields should be NIL already, but make sure.
259 sublink->lefthand = NIL;
264 /* ALL, ANY, or MULTIEXPR: generate operator list */
265 char *op = lfirst(sublink->oper);
266 List *left_list = sublink->lefthand;
267 List *right_list = qtree->targetList;
270 foreach(elist, left_list)
271 lfirst(elist) = transformExpr(pstate, lfirst(elist),
274 /* Combining operators other than =/<> is dubious... */
275 if (length(left_list) != 1 &&
276 strcmp(op, "=") != 0 && strcmp(op, "<>") != 0)
277 elog(ERROR, "Row comparison cannot use '%s'",
282 /* Scan subquery's targetlist to find values that will be
283 * matched against lefthand values. We need to ignore
284 * resjunk targets, so doing the outer iteration over
285 * right_list is easier than doing it over left_list.
287 while (right_list != NIL)
289 TargetEntry *tent = (TargetEntry *) lfirst(right_list);
292 Form_pg_operator opform;
295 right_list = lnext(right_list);
296 if (tent->resdom->resjunk)
299 if (left_list == NIL)
300 elog(ERROR, "Subselect has too many fields");
301 lexpr = lfirst(left_list);
302 left_list = lnext(left_list);
306 exprType(tent->expr),
308 opform = (Form_pg_operator) GETSTRUCT(optup);
310 if (opform->oprresult != BOOLOID)
311 elog(ERROR, "'%s' result type of '%s' must return '%s'"
312 " to be used with quantified predicate subquery",
313 op, typeidTypeName(opform->oprresult),
314 typeidTypeName(BOOLOID));
316 newop = makeOper(oprid(optup),/* opno */
317 InvalidOid, /* opid */
321 sublink->oper = lappend(sublink->oper, newop);
323 if (left_list != NIL)
324 elog(ERROR, "Subselect has too few fields");
326 result = (Node *) expr;
332 CaseExpr *c = (CaseExpr *) expr;
338 /* transform the list of arguments */
339 foreach(args, c->args)
344 /* shorthand form was specified, so expand... */
345 A_Expr *a = makeNode(A_Expr);
351 w->expr = (Node *) a;
353 lfirst(args) = transformExpr(pstate, (Node *) w, precedence);
357 * It's not shorthand anymore, so drop the implicit
358 * argument. This is necessary to keep the executor from
359 * seeing an untransformed expression...
363 /* transform the default clause */
364 if (c->defresult == NULL)
366 A_Const *n = makeNode(A_Const);
368 n->val.type = T_Null;
369 c->defresult = (Node *) n;
371 c->defresult = transformExpr(pstate, c->defresult, precedence);
373 /* now check types across result clauses... */
374 c->casetype = exprType(c->defresult);
376 pcategory = TypeCategory(ptype);
377 foreach(args, c->args)
382 wtype = exprType(w->result);
383 /* move on to next one if no new information... */
384 if (wtype && (wtype != UNKNOWNOID)
387 if (!ptype || ptype == UNKNOWNOID)
389 /* so far, only nulls so take anything... */
391 pcategory = TypeCategory(ptype);
393 else if ((TypeCategory(wtype) != pcategory)
394 || ((TypeCategory(wtype) == USER_TYPE)
395 && (TypeCategory(c->casetype) == USER_TYPE)))
398 * both types in different categories?
399 * then not much hope...
401 elog(ERROR, "CASE/WHEN types '%s' and '%s' not matched",
402 typeidTypeName(c->casetype), typeidTypeName(wtype));
404 else if (IsPreferredType(pcategory, wtype)
405 && can_coerce_type(1, &ptype, &wtype))
408 * new one is preferred and can convert?
412 pcategory = TypeCategory(ptype);
417 /* Convert default result clause, if necessary */
418 if (c->casetype != ptype)
420 if (!c->casetype || c->casetype == UNKNOWNOID)
423 * default clause is NULL, so assign preferred
424 * type from WHEN clauses...
428 else if (can_coerce_type(1, &c->casetype, &ptype))
430 c->defresult = coerce_type(pstate, c->defresult,
431 c->casetype, ptype, -1);
436 elog(ERROR, "CASE/ELSE unable to convert to type '%s'",
437 typeidTypeName(ptype));
441 /* Convert when clauses, if not null and if necessary */
442 foreach(args, c->args)
447 wtype = exprType(w->result);
450 * only bother with conversion if not NULL and
453 if (wtype && (wtype != UNKNOWNOID)
456 if (can_coerce_type(1, &wtype, &ptype))
458 w->result = coerce_type(pstate, w->result, wtype,
463 elog(ERROR, "CASE/WHEN unable to convert to type '%s'",
464 typeidTypeName(ptype));
475 CaseWhen *w = (CaseWhen *) expr;
477 w->expr = transformExpr(pstate, (Node *) w->expr, precedence);
478 if (exprType(w->expr) != BOOLOID)
479 elog(ERROR, "WHEN clause must have a boolean result");
482 * result is NULL for NULLIF() construct - thomas
485 if (w->result == NULL)
487 A_Const *n = makeNode(A_Const);
489 n->val.type = T_Null;
490 w->result = (Node *) n;
492 w->result = transformExpr(pstate, (Node *) w->result, precedence);
497 /* Some nodes do _not_ come from the original parse tree,
498 * but result from parser transformation in this phase.
499 * At least one construct (BETWEEN/AND) puts the same nodes
500 * into two branches of the parse tree; hence, some nodes
501 * are transformed twice.
502 * Another way it can happen is that coercion of an operator or
503 * function argument to the required type (via coerce_type())
504 * can apply transformExpr to an already-transformed subexpression.
505 * An example here is "SELECT count(*) + 1.0 FROM table".
506 * Thus, we can see node types in this routine that do not appear in the
507 * original parse tree. Assume they are already transformed, and just
509 * Do any other node types need to be accepted? For now we are taking
510 * a conservative approach, and only accepting node types that are
511 * demonstrably necessary to accept.
521 result = (Node *) expr;
525 /* should not reach here */
526 elog(ERROR, "transformExpr: does not know how to transform node %d"
527 " (internal error)", nodeTag(expr));
535 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
537 if (indirection == NIL)
539 return (Node *) transformArraySubscripts(pstate, basenode,
540 indirection, false, NULL);
544 transformAttr(ParseState *pstate, Attr *att, int precedence)
548 basenode = ParseNestedFuncOrColumn(pstate, att, &pstate->p_last_resno,
550 return transformIndirection(pstate, basenode, att->indirection);
554 transformIdent(ParseState *pstate, Ident *ident, int precedence)
559 /* try to find the ident as a relation ... but not if subscripts appear */
560 if (ident->indirection == NIL &&
561 refnameRangeTableEntry(pstate, ident->name) != NULL)
564 result = (Node *) ident;
567 if (result == NULL || precedence == EXPR_COLUMN_FIRST)
569 /* try to find the ident as a column */
570 if ((rte = colnameRangeTableEntry(pstate, ident->name)) != NULL)
572 /* Convert it to a fully qualified Attr, and transform that */
573 #ifndef DISABLE_JOIN_SYNTAX
574 Attr *att = makeAttr(rte->ref->relname, ident->name);
576 Attr *att = makeNode(Attr);
578 att->relname = rte->refname;
580 att->attrs = lcons(makeString(ident->name), NIL);
582 att->indirection = ident->indirection;
583 return transformAttr(pstate, att, precedence);
588 elog(ERROR, "Attribute '%s' not found", ident->name);
595 * returns the Oid of the type of the expression. (Used for typechecking.)
600 Oid type = (Oid) InvalidOid;
605 switch (nodeTag(expr))
608 type = ((Func *) expr)->functype;
611 type = ((Iter *) expr)->itertype;
614 type = ((Var *) expr)->vartype;
617 type = ((Expr *) expr)->typeOid;
620 type = ((Const *) expr)->consttype;
623 type = ((ArrayRef *) expr)->refelemtype;
626 type = ((Aggref *) expr)->aggtype;
629 type = ((Param *) expr)->paramtype;
632 type = ((RelabelType *) expr)->resulttype;
636 SubLink *sublink = (SubLink *) expr;
638 if (sublink->subLinkType == EXPR_SUBLINK)
640 /* get the type of the subselect's first target column */
641 Query *qtree = (Query *) sublink->subselect;
644 if (! qtree || ! IsA(qtree, Query))
645 elog(ERROR, "Cannot get type for untransformed sublink");
646 tent = (TargetEntry *) lfirst(qtree->targetList);
647 type = tent->resdom->restype;
651 /* for all other sublink types, result is boolean */
657 type = ((CaseExpr *) expr)->casetype;
660 type = exprType(((CaseWhen *) expr)->result);
667 elog(ERROR, "Do not know how to get type for %d node",
676 * returns the type-specific attrmod of the expression, if it can be
677 * determined. In most cases, it can't and we return -1.
680 exprTypmod(Node *expr)
685 switch (nodeTag(expr))
688 return ((Var *) expr)->vartypmod;
691 /* Be smart about string constants... */
692 Const *con = (Const *) expr;
693 switch (con->consttype)
696 if (! con->constisnull)
697 return VARSIZE(DatumGetPointer(con->constvalue));
705 return ((RelabelType *) expr)->resulttypmod;
714 * Produce an appropriate Const node from a constant value produced
715 * by the parser and an explicit type name to cast to.
718 parser_typecast_constant(Value *expr, TypeName *typename)
723 char *const_string = NULL;
724 bool string_palloced = false;
727 switch (nodeTag(expr))
730 const_string = DatumGetPointer(expr->val.str);
733 string_palloced = true;
734 const_string = int4out(expr->val.ival);
737 string_palloced = true;
738 const_string = float8out(&expr->val.dval);
745 "Cannot cast this expression to type '%s'",
749 if (typename->arrayBounds != NIL)
751 char type_string[NAMEDATALEN+2];
753 sprintf(type_string, "_%s", typename->name);
754 tp = (Type) typenameType(type_string);
757 tp = (Type) typenameType(typename->name);
760 datum = (Datum) NULL;
762 datum = stringTypeDatum(tp, const_string, typename->typmod);
764 con = makeConst(typeTypeId(tp),
769 false, /* not a set */
770 true /* is cast */ );
779 * Handle an explicit CAST applied to a non-constant expression.
780 * (Actually, this works for constants too, but gram.y won't generate
781 * a TypeCast node if the argument is just a constant.)
783 * The given expr has already been transformed, but we need to lookup
784 * the type name and then apply any necessary coercion function(s).
787 parser_typecast_expression(ParseState *pstate,
788 Node *expr, TypeName *typename)
790 Oid inputType = exprType(expr);
794 if (typename->arrayBounds != NIL)
796 char type_string[NAMEDATALEN+2];
798 sprintf(type_string, "_%s", typename->name);
799 tp = (Type) typenameType(type_string);
802 tp = (Type) typenameType(typename->name);
803 targetType = typeTypeId(tp);
805 if (inputType == InvalidOid)
806 return expr; /* do nothing if NULL input */
808 if (inputType != targetType)
810 expr = CoerceTargetExpr(pstate, expr, inputType,
811 targetType, typename->typmod);
813 elog(ERROR, "Cannot cast type '%s' to '%s'",
814 typeidTypeName(inputType),
815 typeidTypeName(targetType));
818 * If the target is a fixed-length type, it may need a length
819 * coercion as well as a type coercion.
821 expr = coerce_type_typmod(pstate, expr,
822 targetType, typename->typmod);