1 /*-------------------------------------------------------------------------
4 * handle expressions in parser
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.121 2002/07/06 20:16:36 momjian Exp $
13 *-------------------------------------------------------------------------
18 #include "catalog/pg_operator.h"
19 #include "catalog/pg_proc.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/params.h"
23 #include "parser/analyze.h"
24 #include "parser/gramparse.h"
25 #include "parser/parse.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_expr.h"
28 #include "parser/parse_func.h"
29 #include "parser/parse_oper.h"
30 #include "parser/parse_relation.h"
31 #include "parser/parse_target.h"
32 #include "parser/parse_type.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
38 int max_expr_depth = DEFAULT_MAX_EXPR_DEPTH;
39 static int expr_depth_counter = 0;
41 bool Transform_null_equals = false;
43 static Node *parser_typecast_constant(Value *expr, TypeName *typename);
44 static Node *parser_typecast_expression(ParseState *pstate,
45 Node *expr, TypeName *typename);
46 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
47 static Node *transformIndirection(ParseState *pstate, Node *basenode,
52 * Initialize for parsing a new query.
54 * We reset the expression depth counter here, in case it was left nonzero
55 * due to elog()'ing out of the last parsing operation.
60 expr_depth_counter = 0;
66 * Analyze and transform expressions. Type checking and type casting is
67 * done here. The optimizer and the executor cannot handle the original
68 * (raw) expressions collected by the parse tree. Hence the transformation
71 * NOTE: there are various cases in which this routine will get applied to
72 * an already-transformed expression. Some examples:
73 * 1. At least one construct (BETWEEN/AND) puts the same nodes
74 * into two branches of the parse tree; hence, some nodes
75 * are transformed twice.
76 * 2. Another way it can happen is that coercion of an operator or
77 * function argument to the required type (via coerce_type())
78 * can apply transformExpr to an already-transformed subexpression.
79 * An example here is "SELECT count(*) + 1.0 FROM table".
80 * While it might be possible to eliminate these cases, the path of
81 * least resistance so far has been to ensure that transformExpr() does
82 * no damage if applied to an already-transformed tree. This is pretty
83 * easy for cases where the transformation replaces one node type with
84 * another, such as A_Const => Const; we just do nothing when handed
85 * a Const. More care is needed for node types that are used as both
86 * input and output of transformExpr; see SubLink for example.
89 transformExpr(ParseState *pstate, Node *expr)
97 * Guard against an overly complex expression leading to coredump due
98 * to stack overflow here, or in later recursive routines that
99 * traverse expression trees. Note that this is very unlikely to
100 * happen except with pathological queries; but we don't want someone
101 * to be able to crash the backend quite that easily...
103 if (++expr_depth_counter > max_expr_depth)
104 elog(ERROR, "Expression too complex: nesting depth exceeds max_expr_depth = %d",
107 switch (nodeTag(expr))
111 result = transformColumnRef(pstate, (ColumnRef *) expr);
116 ParamRef *pref = (ParamRef *) expr;
117 int paramno = pref->number;
118 Oid paramtyp = param_type(paramno);
122 if (!OidIsValid(paramtyp))
123 elog(ERROR, "Parameter '$%d' is out of range", paramno);
124 param = makeNode(Param);
125 param->paramkind = PARAM_NUM;
126 param->paramid = (AttrNumber) paramno;
127 param->paramname = "<unnamed>";
128 param->paramtype = paramtyp;
129 result = (Node *) param;
130 /* handle qualification, if any */
131 foreach(fields, pref->fields)
133 result = ParseFuncOrColumn(pstate,
134 makeList1(lfirst(fields)),
138 /* handle subscripts, if any */
139 result = transformIndirection(pstate, result,
145 A_Const *con = (A_Const *) expr;
146 Value *val = &con->val;
148 if (con->typename != NULL)
149 result = parser_typecast_constant(val, con->typename);
151 result = (Node *) make_const(val);
154 case T_ExprFieldSelect:
156 ExprFieldSelect *efs = (ExprFieldSelect *) expr;
159 result = transformExpr(pstate, efs->arg);
160 /* handle qualification, if any */
161 foreach(fields, efs->fields)
163 result = ParseFuncOrColumn(pstate,
164 makeList1(lfirst(fields)),
168 /* handle subscripts, if any */
169 result = transformIndirection(pstate, result,
175 TypeCast *tc = (TypeCast *) expr;
176 Node *arg = transformExpr(pstate, tc->arg);
178 result = parser_typecast_expression(pstate, arg, tc->typename);
183 A_Expr *a = (A_Expr *) expr;
190 * Special-case "foo = NULL" and "NULL = foo"
191 * for compatibility with standards-broken
192 * products (like Microsoft's). Turn these
193 * into IS NULL exprs.
195 if (Transform_null_equals &&
196 length(a->name) == 1 &&
197 strcmp(strVal(lfirst(a->name)), "=") == 0 &&
198 (exprIsNullConstant(a->lexpr) ||
199 exprIsNullConstant(a->rexpr)))
201 NullTest *n = makeNode(NullTest);
203 n->nulltesttype = IS_NULL;
205 if (exprIsNullConstant(a->lexpr))
210 result = transformExpr(pstate,
215 Node *lexpr = transformExpr(pstate,
217 Node *rexpr = transformExpr(pstate,
220 result = (Node *) make_op(a->name,
228 Node *lexpr = transformExpr(pstate,
230 Node *rexpr = transformExpr(pstate,
232 Expr *expr = makeNode(Expr);
234 lexpr = coerce_to_boolean(lexpr, "AND");
235 rexpr = coerce_to_boolean(rexpr, "AND");
237 expr->typeOid = BOOLOID;
238 expr->opType = AND_EXPR;
239 expr->args = makeList2(lexpr, rexpr);
240 result = (Node *) expr;
245 Node *lexpr = transformExpr(pstate,
247 Node *rexpr = transformExpr(pstate,
249 Expr *expr = makeNode(Expr);
251 lexpr = coerce_to_boolean(lexpr, "OR");
252 rexpr = coerce_to_boolean(rexpr, "OR");
254 expr->typeOid = BOOLOID;
255 expr->opType = OR_EXPR;
256 expr->args = makeList2(lexpr, rexpr);
257 result = (Node *) expr;
262 Node *rexpr = transformExpr(pstate,
264 Expr *expr = makeNode(Expr);
266 rexpr = coerce_to_boolean(rexpr, "NOT");
268 expr->typeOid = BOOLOID;
269 expr->opType = NOT_EXPR;
270 expr->args = makeList1(rexpr);
271 result = (Node *) expr;
276 Node *lexpr = transformExpr(pstate,
278 Node *rexpr = transformExpr(pstate,
280 result = (Node *) make_op(a->name,
283 ((Expr *)result)->opType = DISTINCT_EXPR;
290 FuncCall *fn = (FuncCall *) expr;
293 /* transform the list of arguments */
294 foreach(args, fn->args)
295 lfirst(args) = transformExpr(pstate,
296 (Node *) lfirst(args));
297 result = ParseFuncOrColumn(pstate,
307 SubLink *sublink = (SubLink *) expr;
311 /* If we already transformed this node, do nothing */
312 if (IsA(sublink->subselect, Query))
317 pstate->p_hasSubLinks = true;
318 qtrees = parse_analyze(sublink->subselect, pstate);
319 if (length(qtrees) != 1)
320 elog(ERROR, "Bad query in subselect");
321 qtree = (Query *) lfirst(qtrees);
322 if (qtree->commandType != CMD_SELECT ||
323 qtree->resultRelation != 0)
324 elog(ERROR, "Bad query in subselect");
325 sublink->subselect = (Node *) qtree;
327 if (sublink->subLinkType == EXISTS_SUBLINK)
330 * EXISTS needs no lefthand or combining operator.
331 * These fields should be NIL already, but make sure.
333 sublink->lefthand = NIL;
336 else if (sublink->subLinkType == EXPR_SUBLINK)
338 List *tlist = qtree->targetList;
341 * Make sure the subselect delivers a single column
342 * (ignoring resjunk targets).
345 ((TargetEntry *) lfirst(tlist))->resdom->resjunk)
346 elog(ERROR, "Subselect must have a field");
347 while ((tlist = lnext(tlist)) != NIL)
349 if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk)
350 elog(ERROR, "Subselect must have only one field");
354 * EXPR needs no lefthand or combining operator. These
355 * fields should be NIL already, but make sure.
357 sublink->lefthand = NIL;
362 /* ALL, ANY, or MULTIEXPR: generate operator list */
363 List *left_list = sublink->lefthand;
364 List *right_list = qtree->targetList;
369 foreach(elist, left_list)
370 lfirst(elist) = transformExpr(pstate, lfirst(elist));
372 Assert(IsA(sublink->oper, A_Expr));
373 op = ((A_Expr *) sublink->oper)->name;
374 opname = strVal(llast(op));
377 /* Combining operators other than =/<> is dubious... */
378 if (length(left_list) != 1 &&
379 strcmp(opname, "=") != 0 && strcmp(opname, "<>") != 0)
380 elog(ERROR, "Row comparison cannot use operator %s",
384 * Scan subquery's targetlist to find values that will
385 * be matched against lefthand values. We need to
386 * ignore resjunk targets, so doing the outer
387 * iteration over right_list is easier than doing it
390 while (right_list != NIL)
392 TargetEntry *tent = (TargetEntry *) lfirst(right_list);
395 Form_pg_operator opform;
398 right_list = lnext(right_list);
399 if (tent->resdom->resjunk)
402 if (left_list == NIL)
403 elog(ERROR, "Subselect has too many fields");
404 lexpr = lfirst(left_list);
405 left_list = lnext(left_list);
408 * It's OK to use oper() not compatible_oper()
409 * here, because make_subplan() will insert type
410 * coercion calls if needed.
414 exprType(tent->expr),
416 opform = (Form_pg_operator) GETSTRUCT(optup);
418 if (opform->oprresult != BOOLOID)
419 elog(ERROR, "%s has result type of %s, but must return %s"
420 " to be used with quantified predicate subquery",
421 opname, format_type_be(opform->oprresult),
422 format_type_be(BOOLOID));
424 if (get_func_retset(opform->oprcode))
425 elog(ERROR, "%s must not return a set"
426 " to be used with quantified predicate subquery",
429 newop = makeOper(oprid(optup), /* opno */
430 InvalidOid, /* opid */
433 sublink->oper = lappend(sublink->oper, newop);
434 ReleaseSysCache(optup);
436 if (left_list != NIL)
437 elog(ERROR, "Subselect has too few fields");
439 result = (Node *) expr;
445 CaseExpr *c = (CaseExpr *) expr;
446 CaseExpr *newc = makeNode(CaseExpr);
453 /* transform the list of arguments */
454 foreach(args, c->args)
456 CaseWhen *w = (CaseWhen *) lfirst(args);
457 CaseWhen *neww = makeNode(CaseWhen);
460 Assert(IsA(w, CaseWhen));
465 /* shorthand form was specified, so expand... */
466 warg = (Node *) makeSimpleA_Expr(OP, "=",
469 neww->expr = transformExpr(pstate, warg);
471 neww->expr = coerce_to_boolean(neww->expr, "CASE/WHEN");
474 * result is NULL for NULLIF() construct - thomas
480 A_Const *n = makeNode(A_Const);
482 n->val.type = T_Null;
485 neww->result = transformExpr(pstate, warg);
487 newargs = lappend(newargs, neww);
488 typeids = lappendi(typeids, exprType(neww->result));
491 newc->args = newargs;
494 * It's not shorthand anymore, so drop the implicit
495 * argument. This is necessary to keep any re-application
496 * of transformExpr from doing the wrong thing.
500 /* transform the default clause */
501 defresult = c->defresult;
502 if (defresult == NULL)
504 A_Const *n = makeNode(A_Const);
506 n->val.type = T_Null;
507 defresult = (Node *) n;
509 newc->defresult = transformExpr(pstate, defresult);
512 * Note: default result is considered the most significant
513 * type in determining preferred type. This is how the
514 * code worked before, but it seems a little bogus to me
517 typeids = lconsi(exprType(newc->defresult), typeids);
519 ptype = select_common_type(typeids, "CASE");
520 newc->casetype = ptype;
522 /* Convert default result clause, if necessary */
523 newc->defresult = coerce_to_common_type(pstate,
528 /* Convert when-clause results, if necessary */
529 foreach(args, newc->args)
531 CaseWhen *w = (CaseWhen *) lfirst(args);
533 w->result = coerce_to_common_type(pstate,
539 result = (Node *) newc;
545 NullTest *n = (NullTest *) expr;
547 n->arg = transformExpr(pstate, n->arg);
548 /* the argument can be any type, so don't coerce it */
555 BooleanTest *b = (BooleanTest *) expr;
556 const char *clausename;
558 switch (b->booltesttype)
561 clausename = "IS TRUE";
564 clausename = "IS NOT TRUE";
567 clausename = "IS FALSE";
570 clausename = "IS NOT FALSE";
573 clausename = "IS UNKNOWN";
576 clausename = "IS NOT UNKNOWN";
579 elog(ERROR, "transformExpr: unexpected booltesttype %d",
580 (int) b->booltesttype);
581 clausename = NULL; /* keep compiler quiet */
584 b->arg = transformExpr(pstate, b->arg);
586 b->arg = coerce_to_boolean(b->arg, clausename);
593 * Quietly accept node types that may be presented when we are
594 * called on an already-transformed tree.
596 * Do any other node types need to be accepted? For now we are
597 * taking a conservative approach, and only accepting node
598 * types that are demonstrably necessary to accept.
609 result = (Node *) expr;
614 /* should not reach here */
615 elog(ERROR, "transformExpr: does not know how to transform node %d"
616 " (internal error)", nodeTag(expr));
620 expr_depth_counter--;
626 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
628 if (indirection == NIL)
630 return (Node *) transformArraySubscripts(pstate,
631 basenode, exprType(basenode),
632 indirection, false, NULL);
636 transformColumnRef(ParseState *pstate, ColumnRef *cref)
638 int numnames = length(cref->fields);
643 * The allowed syntaxes are:
645 * A First try to resolve as unqualified column name;
646 * if no luck, try to resolve as unqual. table name (A.*).
647 * A.B A is an unqual. table name; B is either a
648 * column or function name (trying column name first).
649 * A.B.C schema A, table B, col or func name C.
650 * A.B.C.D catalog A, schema B, table C, col or func D.
651 * A.* A is an unqual. table name; means whole-row value.
652 * A.B.* whole-row value of table B in schema A.
653 * A.B.C.* whole-row value of table C in schema B in catalog A.
655 * We do not need to cope with bare "*"; that will only be accepted by
656 * the grammar at the top level of a SELECT list, and transformTargetList
657 * will take care of it before it ever gets here.
659 * Currently, if a catalog name is given then it must equal the current
660 * database name; we check it here and then discard it.
662 * For whole-row references, the result is an untransformed RangeVar,
663 * which will work as the argument to a function call, but not in any
664 * other context at present. (We could instead coerce to a whole-row Var,
665 * but that will fail for subselect and join RTEs, because there is no
666 * pg_type entry for their rowtypes.)
673 char *name = strVal(lfirst(cref->fields));
675 /* Try to identify as an unqualified column */
676 node = colnameToVar(pstate, name);
680 * Not known as a column of any range-table entry, so
681 * try to find the name as a relation ... but not if
682 * subscripts appear. Note also that only relations
683 * already entered into the rangetable will be recognized.
687 if (cref->indirection == NIL &&
688 refnameRangeTblEntry(pstate, name, &levels_up) != NULL)
690 rv = makeNode(RangeVar);
692 rv->inhOpt = INH_DEFAULT;
696 elog(ERROR, "Attribute \"%s\" not found", name);
702 char *name1 = strVal(lfirst(cref->fields));
703 char *name2 = strVal(lsecond(cref->fields));
705 /* Whole-row reference? */
706 if (strcmp(name2, "*") == 0)
708 rv = makeNode(RangeVar);
710 rv->inhOpt = INH_DEFAULT;
715 /* Try to identify as a once-qualified column */
716 node = qualifiedNameToVar(pstate, name1, name2, true);
720 * Not known as a column of any range-table entry, so
721 * try it as a function call. Here, we will create an
722 * implicit RTE for tables not already entered.
724 rv = makeNode(RangeVar);
726 rv->inhOpt = INH_DEFAULT;
727 node = ParseFuncOrColumn(pstate,
728 makeList1(makeString(name2)),
736 char *name1 = strVal(lfirst(cref->fields));
737 char *name2 = strVal(lsecond(cref->fields));
738 char *name3 = strVal(lfirst(lnext(lnext(cref->fields))));
740 /* Whole-row reference? */
741 if (strcmp(name3, "*") == 0)
743 rv = makeNode(RangeVar);
744 rv->schemaname = name1;
746 rv->inhOpt = INH_DEFAULT;
751 /* Try to identify as a twice-qualified column */
752 /* XXX do something with schema name here */
753 node = qualifiedNameToVar(pstate, name2, name3, true);
756 /* Try it as a function call */
757 rv = makeNode(RangeVar);
758 rv->schemaname = name1;
760 rv->inhOpt = INH_DEFAULT;
761 node = ParseFuncOrColumn(pstate,
762 makeList1(makeString(name3)),
770 char *name1 = strVal(lfirst(cref->fields));
771 char *name2 = strVal(lsecond(cref->fields));
772 char *name3 = strVal(lfirst(lnext(lnext(cref->fields))));
773 char *name4 = strVal(lfirst(lnext(lnext(lnext(cref->fields)))));
776 * We check the catalog name and then ignore it.
778 if (strcmp(name1, DatabaseName) != 0)
779 elog(ERROR, "Cross-database references are not implemented");
781 /* Whole-row reference? */
782 if (strcmp(name4, "*") == 0)
784 rv = makeNode(RangeVar);
785 rv->schemaname = name2;
787 rv->inhOpt = INH_DEFAULT;
792 /* Try to identify as a twice-qualified column */
793 /* XXX do something with schema name here */
794 node = qualifiedNameToVar(pstate, name3, name4, true);
797 /* Try it as a function call */
798 rv = makeNode(RangeVar);
799 rv->schemaname = name2;
801 rv->inhOpt = INH_DEFAULT;
802 node = ParseFuncOrColumn(pstate,
803 makeList1(makeString(name4)),
810 elog(ERROR, "Invalid qualified name syntax (too many names)");
811 node = NULL; /* keep compiler quiet */
815 return transformIndirection(pstate, node, cref->indirection);
820 * returns the Oid of the type of the expression. (Used for typechecking.)
825 Oid type = (Oid) InvalidOid;
830 switch (nodeTag(expr))
833 type = ((Var *) expr)->vartype;
836 type = ((Expr *) expr)->typeOid;
839 type = ((Const *) expr)->consttype;
842 type = ((ArrayRef *) expr)->refelemtype;
845 type = ((Aggref *) expr)->aggtype;
848 type = ((Param *) expr)->paramtype;
851 type = ((FieldSelect *) expr)->resulttype;
854 type = ((RelabelType *) expr)->resulttype;
858 SubLink *sublink = (SubLink *) expr;
860 if (sublink->subLinkType == EXPR_SUBLINK)
862 /* get the type of the subselect's first target column */
863 Query *qtree = (Query *) sublink->subselect;
866 if (!qtree || !IsA(qtree, Query))
867 elog(ERROR, "exprType: Cannot get type for untransformed sublink");
868 tent = (TargetEntry *) lfirst(qtree->targetList);
869 type = tent->resdom->restype;
873 /* for all other sublink types, result is boolean */
879 type = ((CaseExpr *) expr)->casetype;
882 type = exprType(((CaseWhen *) expr)->result);
885 type = exprType(((Constraint *) expr)->raw_expr);
894 elog(ERROR, "exprType: Do not know how to get type for %d node",
903 * returns the type-specific attrmod of the expression, if it can be
904 * determined. In most cases, it can't and we return -1.
907 exprTypmod(Node *expr)
912 switch (nodeTag(expr))
915 return ((Var *) expr)->vartypmod;
918 /* Be smart about string constants... */
919 Const *con = (Const *) expr;
921 switch (con->consttype)
924 if (!con->constisnull)
925 return VARSIZE(DatumGetPointer(con->constvalue));
936 /* Be smart about length-coercion functions... */
937 if (exprIsLengthCoercion(expr, &coercedTypmod))
938 return coercedTypmod;
942 return ((FieldSelect *) expr)->resulttypmod;
945 return ((RelabelType *) expr)->resulttypmod;
950 * If all the alternatives agree on type/typmod, return
951 * that typmod, else use -1
953 CaseExpr *cexpr = (CaseExpr *) expr;
954 Oid casetype = cexpr->casetype;
958 if (!cexpr->defresult)
960 if (exprType(cexpr->defresult) != casetype)
962 typmod = exprTypmod(cexpr->defresult);
964 return -1; /* no point in trying harder */
965 foreach(arg, cexpr->args)
967 CaseWhen *w = (CaseWhen *) lfirst(arg);
969 Assert(IsA(w, CaseWhen));
970 if (exprType(w->result) != casetype)
972 if (exprTypmod(w->result) != typmod)
985 * exprIsLengthCoercion
986 * Detect whether an expression tree is an application of a datatype's
987 * typmod-coercion function. Optionally extract the result's typmod.
989 * If coercedTypmod is not NULL, the typmod is stored there if the expression
990 * is a length-coercion function, else -1 is stored there.
992 * We assume that a two-argument function named for a datatype, whose
993 * output and first argument types are that datatype, and whose second
994 * input is an int32 constant, represents a forced length coercion.
996 * XXX It'd be better if the parsetree retained some explicit indication
997 * of the coercion, so we didn't need these heuristics.
1000 exprIsLengthCoercion(Node *expr, int32 *coercedTypmod)
1004 HeapTuple procTuple;
1005 HeapTuple typeTuple;
1006 Form_pg_proc procStruct;
1007 Form_pg_type typeStruct;
1009 if (coercedTypmod != NULL)
1010 *coercedTypmod = -1; /* default result on failure */
1012 /* Is it a function-call at all? */
1015 ((Expr *) expr)->opType != FUNC_EXPR)
1017 func = (Func *) (((Expr *) expr)->oper);
1018 Assert(IsA(func, Func));
1021 * If it's not a two-argument function with the second argument being
1022 * an int4 constant, it can't have been created from a length
1025 if (length(((Expr *) expr)->args) != 2)
1027 second_arg = (Const *) lsecond(((Expr *) expr)->args);
1028 if (!IsA(second_arg, Const) ||
1029 second_arg->consttype != INT4OID ||
1030 second_arg->constisnull)
1034 * Lookup the function in pg_proc
1036 procTuple = SearchSysCache(PROCOID,
1037 ObjectIdGetDatum(func->funcid),
1039 if (!HeapTupleIsValid(procTuple))
1040 elog(ERROR, "cache lookup for proc %u failed", func->funcid);
1041 procStruct = (Form_pg_proc) GETSTRUCT(procTuple);
1044 * It must be a function with two arguments where the first is of the
1045 * same type as the return value and the second is an int4. Also, just
1046 * to be sure, check return type agrees with expr node.
1048 if (procStruct->pronargs != 2 ||
1049 procStruct->prorettype != procStruct->proargtypes[0] ||
1050 procStruct->proargtypes[1] != INT4OID ||
1051 procStruct->prorettype != ((Expr *) expr)->typeOid)
1053 ReleaseSysCache(procTuple);
1058 * Furthermore, the name and namespace of the function must be the same
1059 * as its result type's name/namespace (cf. find_coercion_function).
1061 typeTuple = SearchSysCache(TYPEOID,
1062 ObjectIdGetDatum(procStruct->prorettype),
1064 if (!HeapTupleIsValid(typeTuple))
1065 elog(ERROR, "cache lookup for type %u failed",
1066 procStruct->prorettype);
1067 typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
1068 if (strcmp(NameStr(procStruct->proname),
1069 NameStr(typeStruct->typname)) != 0 ||
1070 procStruct->pronamespace != typeStruct->typnamespace)
1072 ReleaseSysCache(procTuple);
1073 ReleaseSysCache(typeTuple);
1078 * OK, it is indeed a length-coercion function.
1080 if (coercedTypmod != NULL)
1081 *coercedTypmod = DatumGetInt32(second_arg->constvalue);
1083 ReleaseSysCache(procTuple);
1084 ReleaseSysCache(typeTuple);
1089 * Produce an appropriate Const node from a constant value produced
1090 * by the parser and an explicit type name to cast to.
1093 parser_typecast_constant(Value *expr, TypeName *typename)
1098 char *const_string = NULL;
1099 bool string_palloced = false;
1100 bool isNull = false;
1102 tp = typenameType(typename);
1104 switch (nodeTag(expr))
1107 const_string = DatumGetCString(DirectFunctionCall1(int4out,
1108 Int32GetDatum(expr->val.ival)));
1109 string_palloced = true;
1114 const_string = expr->val.str;
1120 elog(ERROR, "Cannot cast this expression to type '%s'",
1125 datum = (Datum) NULL;
1127 datum = stringTypeDatum(tp, const_string, typename->typmod);
1129 con = makeConst(typeTypeId(tp),
1134 false, /* not a set */
1135 true /* is cast */ );
1137 if (string_palloced)
1138 pfree(const_string);
1140 ReleaseSysCache(tp);
1142 return (Node *) con;
1146 * Handle an explicit CAST applied to a non-constant expression.
1147 * (Actually, this works for constants too, but gram.y won't generate
1148 * a TypeCast node if the argument is just a constant.)
1150 * The given expr has already been transformed, but we need to lookup
1151 * the type name and then apply any necessary coercion function(s).
1154 parser_typecast_expression(ParseState *pstate,
1155 Node *expr, TypeName *typename)
1157 Oid inputType = exprType(expr);
1160 targetType = typenameTypeId(typename);
1162 if (inputType == InvalidOid)
1163 return expr; /* do nothing if NULL input */
1165 if (inputType != targetType)
1167 expr = CoerceTargetExpr(pstate, expr, inputType,
1168 targetType, typename->typmod,
1169 true); /* explicit coercion */
1171 elog(ERROR, "Cannot cast type '%s' to '%s'",
1172 format_type_be(inputType),
1173 format_type_be(targetType));
1177 * If the target is a fixed-length type, it may need a length coercion
1178 * as well as a type coercion.
1180 expr = coerce_type_typmod(pstate, expr,
1181 targetType, typename->typmod);