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.148 2003/04/29 22:13:10 tgl 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 "nodes/plannodes.h"
24 #include "parser/analyze.h"
25 #include "parser/gramparse.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_type.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/syscache.h"
37 int max_expr_depth = DEFAULT_MAX_EXPR_DEPTH;
38 static int expr_depth_counter = 0;
40 bool Transform_null_equals = false;
42 static Node *typecast_expression(ParseState *pstate, Node *expr,
44 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
45 static Node *transformIndirection(ParseState *pstate, Node *basenode,
50 * Initialize for parsing a new query.
52 * We reset the expression depth counter here, in case it was left nonzero
53 * due to elog()'ing out of the last parsing operation.
58 expr_depth_counter = 0;
64 * Analyze and transform expressions. Type checking and type casting is
65 * done here. The optimizer and the executor cannot handle the original
66 * (raw) expressions collected by the parse tree. Hence the transformation
69 * NOTE: there are various cases in which this routine will get applied to
70 * an already-transformed expression. Some examples:
71 * 1. At least one construct (BETWEEN/AND) puts the same nodes
72 * into two branches of the parse tree; hence, some nodes
73 * are transformed twice.
74 * 2. Another way it can happen is that coercion of an operator or
75 * function argument to the required type (via coerce_type())
76 * can apply transformExpr to an already-transformed subexpression.
77 * An example here is "SELECT count(*) + 1.0 FROM table".
78 * While it might be possible to eliminate these cases, the path of
79 * least resistance so far has been to ensure that transformExpr() does
80 * no damage if applied to an already-transformed tree. This is pretty
81 * easy for cases where the transformation replaces one node type with
82 * another, such as A_Const => Const; we just do nothing when handed
83 * a Const. More care is needed for node types that are used as both
84 * input and output of transformExpr; see SubLink for example.
87 transformExpr(ParseState *pstate, Node *expr)
95 * Guard against an overly complex expression leading to coredump due
96 * to stack overflow here, or in later recursive routines that
97 * traverse expression trees. Note that this is very unlikely to
98 * happen except with pathological queries; but we don't want someone
99 * to be able to crash the backend quite that easily...
101 if (++expr_depth_counter > max_expr_depth)
102 elog(ERROR, "Expression too complex: nesting depth exceeds max_expr_depth = %d",
105 switch (nodeTag(expr))
109 result = transformColumnRef(pstate, (ColumnRef *) expr);
114 ParamRef *pref = (ParamRef *) expr;
115 int paramno = pref->number;
116 ParseState *toppstate;
121 * Find topmost ParseState, which is where paramtype info
125 while (toppstate->parentParseState != NULL)
126 toppstate = toppstate->parentParseState;
128 /* Check parameter number is in range */
129 if (paramno <= 0) /* probably can't happen? */
130 elog(ERROR, "Parameter '$%d' is out of range",
132 if (paramno > toppstate->p_numparams)
134 if (!toppstate->p_variableparams)
135 elog(ERROR, "Parameter '$%d' is out of range",
137 /* Okay to enlarge param array */
138 if (toppstate->p_paramtypes)
139 toppstate->p_paramtypes =
140 (Oid *) repalloc(toppstate->p_paramtypes,
141 paramno * sizeof(Oid));
143 toppstate->p_paramtypes =
144 (Oid *) palloc(paramno * sizeof(Oid));
145 /* Zero out the previously-unreferenced slots */
146 MemSet(toppstate->p_paramtypes + toppstate->p_numparams,
148 (paramno - toppstate->p_numparams) * sizeof(Oid));
149 toppstate->p_numparams = paramno;
151 if (toppstate->p_variableparams)
153 /* If not seen before, initialize to UNKNOWN type */
154 if (toppstate->p_paramtypes[paramno-1] == InvalidOid)
155 toppstate->p_paramtypes[paramno-1] = UNKNOWNOID;
158 param = makeNode(Param);
159 param->paramkind = PARAM_NUM;
160 param->paramid = (AttrNumber) paramno;
161 param->paramtype = toppstate->p_paramtypes[paramno-1];
162 result = (Node *) param;
164 /* handle qualification, if any */
165 foreach(fields, pref->fields)
167 result = ParseFuncOrColumn(pstate,
168 makeList1(lfirst(fields)),
172 /* handle subscripts, if any */
173 result = transformIndirection(pstate, result,
179 A_Const *con = (A_Const *) expr;
180 Value *val = &con->val;
182 result = (Node *) make_const(val);
183 if (con->typename != NULL)
184 result = typecast_expression(pstate, result,
188 case T_ExprFieldSelect:
190 ExprFieldSelect *efs = (ExprFieldSelect *) expr;
193 result = transformExpr(pstate, efs->arg);
194 /* handle qualification, if any */
195 foreach(fields, efs->fields)
197 result = ParseFuncOrColumn(pstate,
198 makeList1(lfirst(fields)),
202 /* handle subscripts, if any */
203 result = transformIndirection(pstate, result,
209 TypeCast *tc = (TypeCast *) expr;
210 Node *arg = transformExpr(pstate, tc->arg);
212 result = typecast_expression(pstate, arg, tc->typename);
217 A_Expr *a = (A_Expr *) expr;
224 * Special-case "foo = NULL" and "NULL = foo"
225 * for compatibility with standards-broken
226 * products (like Microsoft's). Turn these
227 * into IS NULL exprs.
229 if (Transform_null_equals &&
230 length(a->name) == 1 &&
231 strcmp(strVal(lfirst(a->name)), "=") == 0 &&
232 (exprIsNullConstant(a->lexpr) ||
233 exprIsNullConstant(a->rexpr)))
235 NullTest *n = makeNode(NullTest);
237 n->nulltesttype = IS_NULL;
239 if (exprIsNullConstant(a->lexpr))
240 n->arg = (Expr *) a->rexpr;
242 n->arg = (Expr *) a->lexpr;
244 result = transformExpr(pstate,
249 Node *lexpr = transformExpr(pstate,
251 Node *rexpr = transformExpr(pstate,
254 result = (Node *) make_op(pstate,
263 Node *lexpr = transformExpr(pstate,
265 Node *rexpr = transformExpr(pstate,
268 lexpr = coerce_to_boolean(pstate, lexpr, "AND");
269 rexpr = coerce_to_boolean(pstate, rexpr, "AND");
271 result = (Node *) makeBoolExpr(AND_EXPR,
278 Node *lexpr = transformExpr(pstate,
280 Node *rexpr = transformExpr(pstate,
283 lexpr = coerce_to_boolean(pstate, lexpr, "OR");
284 rexpr = coerce_to_boolean(pstate, rexpr, "OR");
286 result = (Node *) makeBoolExpr(OR_EXPR,
293 Node *rexpr = transformExpr(pstate,
296 rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
298 result = (Node *) makeBoolExpr(NOT_EXPR,
304 Node *lexpr = transformExpr(pstate,
306 Node *rexpr = transformExpr(pstate,
309 result = (Node *) make_op(pstate,
313 if (((OpExpr *) result)->opresulttype != BOOLOID)
314 elog(ERROR, "IS DISTINCT FROM requires = operator to yield boolean");
316 * We rely on DistinctExpr and OpExpr being same struct
318 NodeSetTag(result, T_DistinctExpr);
323 Node *lexpr = transformExpr(pstate,
325 Node *rexpr = transformExpr(pstate,
328 result = (Node *) make_op(pstate,
332 if (((OpExpr *) result)->opresulttype != BOOLOID)
333 elog(ERROR, "NULLIF requires = operator to yield boolean");
335 * We rely on NullIfExpr and OpExpr being same struct
337 NodeSetTag(result, T_NullIfExpr);
343 * Checking an expression for match to type.
344 * Will result in a boolean constant node.
350 bool matched = FALSE;
351 Node *lexpr = transformExpr(pstate,
354 ltype = exprType(lexpr);
355 foreach(telem, (List *) a->rexpr)
357 rtype = LookupTypeName(lfirst(telem));
358 matched = (rtype == ltype);
364 * Expect two forms: equals or not equals.
365 * Flip the sense of the result for not
368 if (strcmp(strVal(lfirst(a->name)), "!=") == 0)
369 matched = (!matched);
371 n = makeNode(A_Const);
372 n->val.type = T_String;
373 n->val.val.str = (matched ? "t" : "f");
374 n->typename = SystemTypeName("bool");
376 result = transformExpr(pstate, (Node *) n);
384 FuncCall *fn = (FuncCall *) expr;
389 * Transform the list of arguments. We use a shallow
390 * list copy and then transform-in-place to avoid O(N^2)
391 * behavior from repeated lappend's.
393 targs = listCopy(fn->args);
396 lfirst(args) = transformExpr(pstate,
397 (Node *) lfirst(args));
399 result = ParseFuncOrColumn(pstate,
409 SubLink *sublink = (SubLink *) expr;
413 /* If we already transformed this node, do nothing */
414 if (IsA(sublink->subselect, Query))
419 pstate->p_hasSubLinks = true;
420 qtrees = parse_sub_analyze(sublink->subselect, pstate);
421 if (length(qtrees) != 1)
422 elog(ERROR, "Bad query in subselect");
423 qtree = (Query *) lfirst(qtrees);
424 if (qtree->commandType != CMD_SELECT ||
425 qtree->resultRelation != 0)
426 elog(ERROR, "Bad query in subselect");
427 sublink->subselect = (Node *) qtree;
429 if (sublink->subLinkType == EXISTS_SUBLINK)
432 * EXISTS needs no lefthand or combining operator.
433 * These fields should be NIL already, but make sure.
435 sublink->lefthand = NIL;
436 sublink->operName = NIL;
437 sublink->operOids = NIL;
438 sublink->useOr = FALSE;
440 else if (sublink->subLinkType == EXPR_SUBLINK ||
441 sublink->subLinkType == ARRAY_SUBLINK)
443 List *tlist = qtree->targetList;
446 * Make sure the subselect delivers a single column
447 * (ignoring resjunk targets).
450 ((TargetEntry *) lfirst(tlist))->resdom->resjunk)
451 elog(ERROR, "Subselect must have a field");
452 while ((tlist = lnext(tlist)) != NIL)
454 if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk)
455 elog(ERROR, "Subselect must have only one field");
459 * EXPR and ARRAY need no lefthand or combining operator.
460 * These fields should be NIL already, but make sure.
462 sublink->lefthand = NIL;
463 sublink->operName = NIL;
464 sublink->operOids = NIL;
465 sublink->useOr = FALSE;
469 /* ALL, ANY, or MULTIEXPR: generate operator list */
470 List *left_list = sublink->lefthand;
471 List *right_list = qtree->targetList;
472 int row_length = length(left_list);
473 bool needNot = false;
474 List *op = sublink->operName;
475 char *opname = strVal(llast(op));
478 /* transform lefthand expressions */
479 foreach(elist, left_list)
480 lfirst(elist) = transformExpr(pstate, lfirst(elist));
483 * If the expression is "<> ALL" (with unqualified opname)
484 * then convert it to "NOT IN". This is a hack to improve
485 * efficiency of expressions output by pre-7.4 Postgres.
487 if (sublink->subLinkType == ALL_SUBLINK &&
488 length(op) == 1 && strcmp(opname, "<>") == 0)
490 sublink->subLinkType = ANY_SUBLINK;
491 opname = pstrdup("=");
492 op = makeList1(makeString(opname));
493 sublink->operName = op;
497 /* Set useOr if op is "<>" (possibly qualified) */
498 if (strcmp(opname, "<>") == 0)
499 sublink->useOr = TRUE;
501 sublink->useOr = FALSE;
503 /* Combining operators other than =/<> is dubious... */
504 if (row_length != 1 &&
505 strcmp(opname, "=") != 0 &&
506 strcmp(opname, "<>") != 0)
507 elog(ERROR, "Row comparison cannot use operator %s",
511 * To build the list of combining operator OIDs, we must
512 * scan subquery's targetlist to find values that will
513 * be matched against lefthand values. We need to
514 * ignore resjunk targets, so doing the outer
515 * iteration over right_list is easier than doing it
518 sublink->operOids = NIL;
520 while (right_list != NIL)
522 TargetEntry *tent = (TargetEntry *) lfirst(right_list);
525 Form_pg_operator opform;
527 right_list = lnext(right_list);
528 if (tent->resdom->resjunk)
531 if (left_list == NIL)
532 elog(ERROR, "Subselect has too many fields");
533 lexpr = lfirst(left_list);
534 left_list = lnext(left_list);
537 * It's OK to use oper() not compatible_oper()
538 * here, because make_subplan() will insert type
539 * coercion calls if needed.
543 exprType((Node *) tent->expr),
545 opform = (Form_pg_operator) GETSTRUCT(optup);
547 if (opform->oprresult != BOOLOID)
548 elog(ERROR, "%s has result type of %s, but must return %s"
549 " to be used with quantified predicate subquery",
550 opname, format_type_be(opform->oprresult),
551 format_type_be(BOOLOID));
553 if (get_func_retset(opform->oprcode))
554 elog(ERROR, "%s must not return a set"
555 " to be used with quantified predicate subquery",
558 sublink->operOids = lappendo(sublink->operOids,
561 ReleaseSysCache(optup);
563 if (left_list != NIL)
564 elog(ERROR, "Subselect has too few fields");
568 expr = coerce_to_boolean(pstate, expr, "NOT");
569 expr = (Node *) makeBoolExpr(NOT_EXPR,
573 result = (Node *) expr;
579 CaseExpr *c = (CaseExpr *) expr;
580 CaseExpr *newc = makeNode(CaseExpr);
587 /* transform the list of arguments */
588 foreach(args, c->args)
590 CaseWhen *w = (CaseWhen *) lfirst(args);
591 CaseWhen *neww = makeNode(CaseWhen);
594 Assert(IsA(w, CaseWhen));
596 warg = (Node *) w->expr;
599 /* shorthand form was specified, so expand... */
600 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
604 neww->expr = (Expr *) transformExpr(pstate, warg);
606 neww->expr = (Expr *) coerce_to_boolean(pstate,
611 * result is NULL for NULLIF() construct - thomas
614 warg = (Node *) w->result;
617 A_Const *n = makeNode(A_Const);
619 n->val.type = T_Null;
622 neww->result = (Expr *) transformExpr(pstate, warg);
624 newargs = lappend(newargs, neww);
625 typeids = lappendo(typeids, exprType((Node *) neww->result));
628 newc->args = newargs;
631 * It's not shorthand anymore, so drop the implicit
632 * argument. This is necessary to keep any re-application
633 * of transformExpr from doing the wrong thing.
637 /* transform the default clause */
638 defresult = (Node *) c->defresult;
639 if (defresult == NULL)
641 A_Const *n = makeNode(A_Const);
643 n->val.type = T_Null;
644 defresult = (Node *) n;
646 newc->defresult = (Expr *) transformExpr(pstate, defresult);
649 * Note: default result is considered the most significant
650 * type in determining preferred type. This is how the
651 * code worked before, but it seems a little bogus to me
654 typeids = lconso(exprType((Node *) newc->defresult), typeids);
656 ptype = select_common_type(typeids, "CASE");
657 newc->casetype = ptype;
659 /* Convert default result clause, if necessary */
660 newc->defresult = (Expr *)
661 coerce_to_common_type(pstate,
662 (Node *) newc->defresult,
666 /* Convert when-clause results, if necessary */
667 foreach(args, newc->args)
669 CaseWhen *w = (CaseWhen *) lfirst(args);
672 coerce_to_common_type(pstate,
678 result = (Node *) newc;
684 ArrayExpr *a = (ArrayExpr *) expr;
685 ArrayExpr *newa = makeNode(ArrayExpr);
686 List *newelems = NIL;
687 List *newcoercedelems = NIL;
694 /* Transform the element expressions */
695 foreach(element, a->elements)
697 Node *e = (Node *) lfirst(element);
700 newe = transformExpr(pstate, e);
701 newelems = lappend(newelems, newe);
702 typeids = lappendo(typeids, exprType(newe));
705 /* Select a common type for the elements */
706 element_type = select_common_type(typeids, "ARRAY");
708 /* Coerce arguments to common type if necessary */
709 foreach(element, newelems)
711 Node *e = (Node *) lfirst(element);
714 newe = coerce_to_common_type(pstate, e,
717 newcoercedelems = lappend(newcoercedelems, newe);
720 /* Do we have an array type to use? */
721 array_type = get_array_type(element_type);
722 if (array_type != InvalidOid)
724 /* Elements are presumably of scalar type */
729 /* Must be nested array expressions */
730 array_type = element_type;
731 element_type = get_element_type(array_type);
732 if (!OidIsValid(element_type))
733 elog(ERROR, "Cannot find array type for datatype %s",
734 format_type_be(array_type));
737 * make sure the element expressions all have the same
738 * number of dimensions
741 foreach(element, newcoercedelems)
743 ArrayExpr *e = (ArrayExpr *) lfirst(element);
745 if (!IsA(e, ArrayExpr))
746 elog(ERROR, "Multi-dimensional ARRAY[] must be built from nested array expressions");
749 else if (e->ndims != ndims)
750 elog(ERROR, "Nested array expressions must have "
751 "common number of dimensions");
752 if (e->element_typeid != element_type)
753 elog(ERROR, "Nested array expressions must have "
754 "common element type");
757 /* increment the number of dimensions */
760 /* make sure we don't have too many dimensions now */
762 elog(ERROR, "Number of array dimensions, %d, "
763 "exceeds the maximum allowed %d",
767 newa->array_typeid = array_type;
768 newa->element_typeid = element_type;
769 newa->elements = newcoercedelems;
772 result = (Node *) newa;
778 CoalesceExpr *c = (CoalesceExpr *) expr;
779 CoalesceExpr *newc = makeNode(CoalesceExpr);
781 List *newcoercedargs = NIL;
785 foreach(args, c->args)
787 Node *e = (Node *) lfirst(args);
790 newe = transformExpr(pstate, e);
791 newargs = lappend(newargs, newe);
792 typeids = lappendo(typeids, exprType(newe));
795 newc->coalescetype = select_common_type(typeids, "COALESCE");
797 /* Convert arguments if necessary */
798 foreach(args, newargs)
800 Node *e = (Node *) lfirst(args);
803 newe = coerce_to_common_type(pstate, e,
806 newcoercedargs = lappend(newcoercedargs, newe);
809 newc->args = newcoercedargs;
810 result = (Node *) newc;
816 NullTest *n = (NullTest *) expr;
818 n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
819 /* the argument can be any type, so don't coerce it */
826 BooleanTest *b = (BooleanTest *) expr;
827 const char *clausename;
829 switch (b->booltesttype)
832 clausename = "IS TRUE";
835 clausename = "IS NOT TRUE";
838 clausename = "IS FALSE";
841 clausename = "IS NOT FALSE";
844 clausename = "IS UNKNOWN";
847 clausename = "IS NOT UNKNOWN";
850 elog(ERROR, "transformExpr: unexpected booltesttype %d",
851 (int) b->booltesttype);
852 clausename = NULL; /* keep compiler quiet */
855 b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
857 b->arg = (Expr *) coerce_to_boolean(pstate,
865 /*********************************************
866 * Quietly accept node types that may be presented when we are
867 * called on an already-transformed tree.
869 * Do any other node types need to be accepted? For now we are
870 * taking a conservative approach, and only accepting node
871 * types that are demonstrably necessary to accept.
872 *********************************************/
885 case T_CoerceToDomain:
886 case T_CoerceToDomainValue:
888 result = (Node *) expr;
893 /* should not reach here */
894 elog(ERROR, "transformExpr: does not know how to transform node %d"
895 " (internal error)", nodeTag(expr));
899 expr_depth_counter--;
905 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
907 if (indirection == NIL)
909 return (Node *) transformArraySubscripts(pstate,
912 exprTypmod(basenode),
919 transformColumnRef(ParseState *pstate, ColumnRef *cref)
921 int numnames = length(cref->fields);
927 * The allowed syntaxes are:
929 * A First try to resolve as unqualified column name;
930 * if no luck, try to resolve as unqual. table name (A.*).
931 * A.B A is an unqual. table name; B is either a
932 * column or function name (trying column name first).
933 * A.B.C schema A, table B, col or func name C.
934 * A.B.C.D catalog A, schema B, table C, col or func D.
935 * A.* A is an unqual. table name; means whole-row value.
936 * A.B.* whole-row value of table B in schema A.
937 * A.B.C.* whole-row value of table C in schema B in catalog A.
939 * We do not need to cope with bare "*"; that will only be accepted by
940 * the grammar at the top level of a SELECT list, and transformTargetList
941 * will take care of it before it ever gets here.
943 * Currently, if a catalog name is given then it must equal the current
944 * database name; we check it here and then discard it.
946 * For whole-row references, the result is an untransformed RangeVar,
947 * which will work as the argument to a function call, but not in any
948 * other context at present. (We could instead coerce to a whole-row Var,
949 * but that will fail for subselect and join RTEs, because there is no
950 * pg_type entry for their rowtypes.)
957 char *name = strVal(lfirst(cref->fields));
959 /* Try to identify as an unqualified column */
960 node = colnameToVar(pstate, name);
965 * Not known as a column of any range-table entry.
967 * Consider the possibility that it's VALUE in a domain
968 * check expression. (We handle VALUE as a name, not a
969 * keyword, to avoid breaking a lot of applications that
970 * have used VALUE as a column name in the past.)
972 if (pstate->p_value_substitute != NULL &&
973 strcmp(name, "value") == 0)
975 node = (Node *) copyObject(pstate->p_value_substitute);
980 * Try to find the name as a relation ... but not if
981 * subscripts appear. Note also that only relations
982 * already entered into the rangetable will be
985 * This is a hack for backwards compatibility with
986 * PostQUEL-inspired syntax. The preferred form now
989 if (cref->indirection == NIL &&
990 refnameRangeTblEntry(pstate, NULL, name,
993 rv = makeNode(RangeVar);
995 rv->inhOpt = INH_DEFAULT;
999 elog(ERROR, "Attribute \"%s\" not found", name);
1005 char *name1 = strVal(lfirst(cref->fields));
1006 char *name2 = strVal(lsecond(cref->fields));
1008 /* Whole-row reference? */
1009 if (strcmp(name2, "*") == 0)
1011 rv = makeNode(RangeVar);
1012 rv->relname = name1;
1013 rv->inhOpt = INH_DEFAULT;
1018 /* Try to identify as a once-qualified column */
1019 node = qualifiedNameToVar(pstate, NULL, name1, name2, true);
1023 * Not known as a column of any range-table entry, so
1024 * try it as a function call. Here, we will create an
1025 * implicit RTE for tables not already entered.
1027 rv = makeNode(RangeVar);
1028 rv->relname = name1;
1029 rv->inhOpt = INH_DEFAULT;
1030 node = ParseFuncOrColumn(pstate,
1031 makeList1(makeString(name2)),
1033 false, false, true);
1039 char *name1 = strVal(lfirst(cref->fields));
1040 char *name2 = strVal(lsecond(cref->fields));
1041 char *name3 = strVal(lthird(cref->fields));
1043 /* Whole-row reference? */
1044 if (strcmp(name3, "*") == 0)
1046 rv = makeNode(RangeVar);
1047 rv->schemaname = name1;
1048 rv->relname = name2;
1049 rv->inhOpt = INH_DEFAULT;
1054 /* Try to identify as a twice-qualified column */
1055 node = qualifiedNameToVar(pstate, name1, name2, name3, true);
1058 /* Try it as a function call */
1059 rv = makeNode(RangeVar);
1060 rv->schemaname = name1;
1061 rv->relname = name2;
1062 rv->inhOpt = INH_DEFAULT;
1063 node = ParseFuncOrColumn(pstate,
1064 makeList1(makeString(name3)),
1066 false, false, true);
1072 char *name1 = strVal(lfirst(cref->fields));
1073 char *name2 = strVal(lsecond(cref->fields));
1074 char *name3 = strVal(lthird(cref->fields));
1075 char *name4 = strVal(lfourth(cref->fields));
1078 * We check the catalog name and then ignore it.
1080 if (strcmp(name1, DatabaseName) != 0)
1081 elog(ERROR, "Cross-database references are not implemented");
1083 /* Whole-row reference? */
1084 if (strcmp(name4, "*") == 0)
1086 rv = makeNode(RangeVar);
1087 rv->schemaname = name2;
1088 rv->relname = name3;
1089 rv->inhOpt = INH_DEFAULT;
1094 /* Try to identify as a twice-qualified column */
1095 node = qualifiedNameToVar(pstate, name2, name3, name4, true);
1098 /* Try it as a function call */
1099 rv = makeNode(RangeVar);
1100 rv->schemaname = name2;
1101 rv->relname = name3;
1102 rv->inhOpt = INH_DEFAULT;
1103 node = ParseFuncOrColumn(pstate,
1104 makeList1(makeString(name4)),
1106 false, false, true);
1111 elog(ERROR, "Invalid qualified name syntax (too many names)");
1112 node = NULL; /* keep compiler quiet */
1116 return transformIndirection(pstate, node, cref->indirection);
1121 * returns the Oid of the type of the expression. (Used for typechecking.)
1124 exprType(Node *expr)
1131 switch (nodeTag(expr))
1134 type = ((Var *) expr)->vartype;
1137 type = ((Const *) expr)->consttype;
1140 type = ((Param *) expr)->paramtype;
1143 type = ((Aggref *) expr)->aggtype;
1146 type = ((ArrayRef *) expr)->refrestype;
1149 type = ((FuncExpr *) expr)->funcresulttype;
1152 type = ((OpExpr *) expr)->opresulttype;
1154 case T_DistinctExpr:
1155 type = ((DistinctExpr *) expr)->opresulttype;
1162 SubLink *sublink = (SubLink *) expr;
1164 if (sublink->subLinkType == EXPR_SUBLINK ||
1165 sublink->subLinkType == ARRAY_SUBLINK)
1167 /* get the type of the subselect's first target column */
1168 Query *qtree = (Query *) sublink->subselect;
1171 if (!qtree || !IsA(qtree, Query))
1172 elog(ERROR, "exprType: Cannot get type for untransformed sublink");
1173 tent = (TargetEntry *) lfirst(qtree->targetList);
1174 Assert(IsA(tent, TargetEntry));
1175 Assert(!tent->resdom->resjunk);
1176 if (sublink->subLinkType == EXPR_SUBLINK)
1177 type = tent->resdom->restype;
1178 else /* ARRAY_SUBLINK */
1180 type = get_array_type(tent->resdom->restype);
1181 if (!OidIsValid(type))
1182 elog(ERROR, "Cannot find array type for datatype %s",
1183 format_type_be(tent->resdom->restype));
1188 /* for all other sublink types, result is boolean */
1196 * Although the parser does not ever deal with already-planned
1197 * expression trees, we support SubPlan nodes in this routine
1198 * for the convenience of ruleutils.c.
1200 SubPlan *subplan = (SubPlan *) expr;
1202 if (subplan->subLinkType == EXPR_SUBLINK ||
1203 subplan->subLinkType == ARRAY_SUBLINK)
1205 /* get the type of the subselect's first target column */
1208 tent = (TargetEntry *) lfirst(subplan->plan->targetlist);
1209 Assert(IsA(tent, TargetEntry));
1210 Assert(!tent->resdom->resjunk);
1211 if (subplan->subLinkType == EXPR_SUBLINK)
1212 type = tent->resdom->restype;
1213 else /* ARRAY_SUBLINK */
1215 type = get_array_type(tent->resdom->restype);
1216 if (!OidIsValid(type))
1217 elog(ERROR, "Cannot find array type for datatype %s",
1218 format_type_be(tent->resdom->restype));
1223 /* for all other subplan types, result is boolean */
1229 type = ((FieldSelect *) expr)->resulttype;
1232 type = ((RelabelType *) expr)->resulttype;
1235 type = ((CaseExpr *) expr)->casetype;
1238 type = exprType((Node *) ((CaseWhen *) expr)->result);
1241 type = ((ArrayExpr *) expr)->array_typeid;
1243 case T_CoalesceExpr:
1244 type = ((CoalesceExpr *) expr)->coalescetype;
1247 type = exprType((Node *) lfirst(((NullIfExpr *) expr)->args));
1255 case T_CoerceToDomain:
1256 type = ((CoerceToDomain *) expr)->resulttype;
1258 case T_CoerceToDomainValue:
1259 type = ((CoerceToDomainValue *) expr)->typeId;
1263 * If someone uses a bare relation name in an expression,
1264 * we will likely first notice a problem here (see comments in
1265 * transformColumnRef()). Issue an appropriate error message.
1267 elog(ERROR, "Relation reference \"%s\" cannot be used in an expression",
1268 ((RangeVar *) expr)->relname);
1269 type = InvalidOid; /* keep compiler quiet */
1272 elog(ERROR, "exprType: Do not know how to get type for %d node",
1274 type = InvalidOid; /* keep compiler quiet */
1282 * returns the type-specific attrmod of the expression, if it can be
1283 * determined. In most cases, it can't and we return -1.
1286 exprTypmod(Node *expr)
1291 switch (nodeTag(expr))
1294 return ((Var *) expr)->vartypmod;
1297 /* Be smart about string constants... */
1298 Const *con = (Const *) expr;
1300 switch (con->consttype)
1303 if (!con->constisnull)
1304 return VARSIZE(DatumGetPointer(con->constvalue));
1313 int32 coercedTypmod;
1315 /* Be smart about length-coercion functions... */
1316 if (exprIsLengthCoercion(expr, &coercedTypmod))
1317 return coercedTypmod;
1321 return ((FieldSelect *) expr)->resulttypmod;
1323 return ((RelabelType *) expr)->resulttypmod;
1327 * If all the alternatives agree on type/typmod, return
1328 * that typmod, else use -1
1330 CaseExpr *cexpr = (CaseExpr *) expr;
1331 Oid casetype = cexpr->casetype;
1335 if (!cexpr->defresult)
1337 if (exprType((Node *) cexpr->defresult) != casetype)
1339 typmod = exprTypmod((Node *) cexpr->defresult);
1341 return -1; /* no point in trying harder */
1342 foreach(arg, cexpr->args)
1344 CaseWhen *w = (CaseWhen *) lfirst(arg);
1346 Assert(IsA(w, CaseWhen));
1347 if (exprType((Node *) w->result) != casetype)
1349 if (exprTypmod((Node *) w->result) != typmod)
1355 case T_CoalesceExpr:
1358 * If all the alternatives agree on type/typmod, return
1359 * that typmod, else use -1
1361 CoalesceExpr *cexpr = (CoalesceExpr *) expr;
1362 Oid coalescetype = cexpr->coalescetype;
1366 typmod = exprTypmod((Node *) lfirst(cexpr->args));
1367 foreach(arg, cexpr->args)
1369 Node *e = (Node *) lfirst(arg);
1371 if (exprType(e) != coalescetype)
1373 if (exprTypmod(e) != typmod)
1381 NullIfExpr *nexpr = (NullIfExpr *) expr;
1383 return exprTypmod((Node *) lfirst(nexpr->args));
1386 case T_CoerceToDomain:
1387 return ((CoerceToDomain *) expr)->resulttypmod;
1388 case T_CoerceToDomainValue:
1389 return ((CoerceToDomainValue *) expr)->typeMod;
1397 * exprIsLengthCoercion
1398 * Detect whether an expression tree is an application of a datatype's
1399 * typmod-coercion function. Optionally extract the result's typmod.
1401 * If coercedTypmod is not NULL, the typmod is stored there if the expression
1402 * is a length-coercion function, else -1 is stored there.
1405 exprIsLengthCoercion(Node *expr, int32 *coercedTypmod)
1411 if (coercedTypmod != NULL)
1412 *coercedTypmod = -1; /* default result on failure */
1414 /* Is it a function-call at all? */
1415 if (expr == NULL || !IsA(expr, FuncExpr))
1417 func = (FuncExpr *) expr;
1420 * If it didn't come from a coercion context, reject.
1422 if (func->funcformat != COERCE_EXPLICIT_CAST &&
1423 func->funcformat != COERCE_IMPLICIT_CAST)
1427 * If it's not a two-argument or three-argument function with the second
1428 * argument being an int4 constant, it can't have been created from a
1429 * length coercion (it must be a type coercion, instead).
1431 nargs = length(func->args);
1432 if (nargs < 2 || nargs > 3)
1435 second_arg = (Const *) lsecond(func->args);
1436 if (!IsA(second_arg, Const) ||
1437 second_arg->consttype != INT4OID ||
1438 second_arg->constisnull)
1442 * OK, it is indeed a length-coercion function.
1444 if (coercedTypmod != NULL)
1445 *coercedTypmod = DatumGetInt32(second_arg->constvalue);
1451 * Handle an explicit CAST construct.
1453 * The given expr has already been transformed, but we need to lookup
1454 * the type name and then apply any necessary coercion function(s).
1457 typecast_expression(ParseState *pstate, Node *expr, TypeName *typename)
1459 Oid inputType = exprType(expr);
1462 targetType = typenameTypeId(typename);
1464 if (inputType == InvalidOid)
1465 return expr; /* do nothing if NULL input */
1467 expr = coerce_to_target_type(pstate, expr, inputType,
1468 targetType, typename->typmod,
1470 COERCE_EXPLICIT_CAST);
1472 elog(ERROR, "Cannot cast type %s to %s",
1473 format_type_be(inputType),
1474 format_type_be(targetType));