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.68 2000/02/15 03:37:47 thomas 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.
520 result = (Node *) expr;
524 /* should not reach here */
525 elog(ERROR, "transformExpr: does not know how to transform node %d"
526 " (internal error)", nodeTag(expr));
534 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
536 if (indirection == NIL)
538 return (Node *) transformArraySubscripts(pstate, basenode,
539 indirection, false, NULL);
543 transformAttr(ParseState *pstate, Attr *att, int precedence)
547 basenode = ParseNestedFuncOrColumn(pstate, att, &pstate->p_last_resno,
549 return transformIndirection(pstate, basenode, att->indirection);
553 transformIdent(ParseState *pstate, Ident *ident, int precedence)
558 /* try to find the ident as a relation ... but not if subscripts appear */
559 if (ident->indirection == NIL &&
560 refnameRangeTableEntry(pstate, ident->name) != NULL)
563 result = (Node *) ident;
566 if (result == NULL || precedence == EXPR_COLUMN_FIRST)
568 /* try to find the ident as a column */
569 if ((rte = colnameRangeTableEntry(pstate, ident->name)) != NULL)
571 /* Convert it to a fully qualified Attr, and transform that */
572 #ifndef DISABLE_JOIN_SYNTAX
573 Attr *att = makeAttr(rte->ref->relname, ident->name);
575 Attr *att = makeNode(Attr);
577 att->relname = rte->refname;
579 att->attrs = lcons(makeString(ident->name), NIL);
581 att->indirection = ident->indirection;
582 return transformAttr(pstate, att, precedence);
587 elog(ERROR, "Attribute '%s' not found", ident->name);
594 * returns the Oid of the type of the expression. (Used for typechecking.)
599 Oid type = (Oid) InvalidOid;
604 switch (nodeTag(expr))
607 type = ((Func *) expr)->functype;
610 type = ((Iter *) expr)->itertype;
613 type = ((Var *) expr)->vartype;
616 type = ((Expr *) expr)->typeOid;
619 type = ((Const *) expr)->consttype;
622 type = ((ArrayRef *) expr)->refelemtype;
625 type = ((Aggref *) expr)->aggtype;
628 type = ((Param *) expr)->paramtype;
632 SubLink *sublink = (SubLink *) expr;
634 if (sublink->subLinkType == EXPR_SUBLINK)
636 /* get the type of the subselect's first target column */
637 Query *qtree = (Query *) sublink->subselect;
640 if (! qtree || ! IsA(qtree, Query))
641 elog(ERROR, "Cannot get type for untransformed sublink");
642 tent = (TargetEntry *) lfirst(qtree->targetList);
643 type = tent->resdom->restype;
647 /* for all other sublink types, result is boolean */
653 type = ((CaseExpr *) expr)->casetype;
656 type = exprType(((CaseWhen *) expr)->result);
663 elog(ERROR, "Do not know how to get type for %d node",
672 * returns the type-specific attrmod of the expression, if it can be
673 * determined. In most cases, it can't and we return -1.
676 exprTypmod(Node *expr)
681 switch (nodeTag(expr))
684 return ((Var *) expr)->vartypmod;
687 /* Be smart about string constants... */
688 Const *con = (Const *) expr;
689 switch (con->consttype)
692 if (! con->constisnull)
693 return VARSIZE(DatumGetPointer(con->constvalue));
707 * Produce an appropriate Const node from a constant value produced
708 * by the parser and an explicit type name to cast to.
711 parser_typecast_constant(Value *expr, TypeName *typename)
716 char *const_string = NULL;
717 bool string_palloced = false;
720 switch (nodeTag(expr))
723 const_string = DatumGetPointer(expr->val.str);
726 string_palloced = true;
727 const_string = int4out(expr->val.ival);
730 string_palloced = true;
731 const_string = float8out(&expr->val.dval);
738 "Cannot cast this expression to type '%s'",
742 if (typename->arrayBounds != NIL)
744 char type_string[NAMEDATALEN+2];
746 sprintf(type_string, "_%s", typename->name);
747 tp = (Type) typenameType(type_string);
750 tp = (Type) typenameType(typename->name);
753 datum = (Datum) NULL;
755 datum = stringTypeDatum(tp, const_string, typename->typmod);
757 con = makeConst(typeTypeId(tp),
762 false, /* not a set */
763 true /* is cast */ );
772 * Handle an explicit CAST applied to a non-constant expression.
773 * (Actually, this works for constants too, but gram.y won't generate
774 * a TypeCast node if the argument is just a constant.)
776 * The given expr has already been transformed, but we need to lookup
777 * the type name and then apply any necessary coercion function(s).
780 parser_typecast_expression(ParseState *pstate,
781 Node *expr, TypeName *typename)
783 Oid inputType = exprType(expr);
787 if (typename->arrayBounds != NIL)
789 char type_string[NAMEDATALEN+2];
791 sprintf(type_string, "_%s", typename->name);
792 tp = (Type) typenameType(type_string);
795 tp = (Type) typenameType(typename->name);
796 targetType = typeTypeId(tp);
798 if (inputType == InvalidOid)
799 return expr; /* do nothing if NULL input */
801 if (inputType != targetType)
803 expr = CoerceTargetExpr(pstate, expr, inputType,
804 targetType, typename->typmod);
806 elog(ERROR, "Cannot cast type '%s' to '%s'",
807 typeidTypeName(inputType),
808 typeidTypeName(targetType));
811 * If the target is a fixed-length type, it may need a length
812 * coercion as well as a type coercion.
814 expr = coerce_type_typmod(pstate, expr,
815 targetType, typename->typmod);