]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_expr.c
Implement feature of new FE/BE protocol whereby RowDescription identifies
[postgresql] / src / backend / parser / parse_expr.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_expr.c
4  *        handle expressions in parser
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.148 2003/04/29 22:13:10 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
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"
35
36
37 int                     max_expr_depth = DEFAULT_MAX_EXPR_DEPTH;
38 static int      expr_depth_counter = 0;
39
40 bool            Transform_null_equals = false;
41
42 static Node *typecast_expression(ParseState *pstate, Node *expr,
43                                                                  TypeName *typename);
44 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
45 static Node *transformIndirection(ParseState *pstate, Node *basenode,
46                                          List *indirection);
47
48
49 /*
50  * Initialize for parsing a new query.
51  *
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.
54  */
55 void
56 parse_expr_init(void)
57 {
58         expr_depth_counter = 0;
59 }
60
61
62 /*
63  * transformExpr -
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
67  *        here.
68  *
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.
85  */
86 Node *
87 transformExpr(ParseState *pstate, Node *expr)
88 {
89         Node       *result = NULL;
90
91         if (expr == NULL)
92                 return NULL;
93
94         /*
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...
100          */
101         if (++expr_depth_counter > max_expr_depth)
102                 elog(ERROR, "Expression too complex: nesting depth exceeds max_expr_depth = %d",
103                          max_expr_depth);
104
105         switch (nodeTag(expr))
106         {
107                 case T_ColumnRef:
108                         {
109                                 result = transformColumnRef(pstate, (ColumnRef *) expr);
110                                 break;
111                         }
112                 case T_ParamRef:
113                         {
114                                 ParamRef   *pref = (ParamRef *) expr;
115                                 int                     paramno = pref->number;
116                                 ParseState *toppstate;
117                                 Param      *param;
118                                 List       *fields;
119
120                                 /*
121                                  * Find topmost ParseState, which is where paramtype info
122                                  * lives.
123                                  */
124                                 toppstate = pstate;
125                                 while (toppstate->parentParseState != NULL)
126                                         toppstate = toppstate->parentParseState;
127
128                                 /* Check parameter number is in range */
129                                 if (paramno <= 0) /* probably can't happen? */
130                                         elog(ERROR, "Parameter '$%d' is out of range",
131                                                  paramno);
132                                 if (paramno > toppstate->p_numparams)
133                                 {
134                                         if (!toppstate->p_variableparams)
135                                                 elog(ERROR, "Parameter '$%d' is out of range",
136                                                          paramno);
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));
142                                         else
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,
147                                                    0,
148                                                    (paramno - toppstate->p_numparams) * sizeof(Oid));
149                                         toppstate->p_numparams = paramno;
150                                 }
151                                 if (toppstate->p_variableparams)
152                                 {
153                                         /* If not seen before, initialize to UNKNOWN type */
154                                         if (toppstate->p_paramtypes[paramno-1] == InvalidOid)
155                                                 toppstate->p_paramtypes[paramno-1] = UNKNOWNOID;
156                                 }
157
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;
163
164                                 /* handle qualification, if any */
165                                 foreach(fields, pref->fields)
166                                 {
167                                         result = ParseFuncOrColumn(pstate,
168                                                                                            makeList1(lfirst(fields)),
169                                                                                            makeList1(result),
170                                                                                            false, false, true);
171                                 }
172                                 /* handle subscripts, if any */
173                                 result = transformIndirection(pstate, result,
174                                                                                           pref->indirection);
175                                 break;
176                         }
177                 case T_A_Const:
178                         {
179                                 A_Const    *con = (A_Const *) expr;
180                                 Value      *val = &con->val;
181
182                                 result = (Node *) make_const(val);
183                                 if (con->typename != NULL)
184                                         result = typecast_expression(pstate, result,
185                                                                                                  con->typename);
186                                 break;
187                         }
188                 case T_ExprFieldSelect:
189                         {
190                                 ExprFieldSelect *efs = (ExprFieldSelect *) expr;
191                                 List       *fields;
192
193                                 result = transformExpr(pstate, efs->arg);
194                                 /* handle qualification, if any */
195                                 foreach(fields, efs->fields)
196                                 {
197                                         result = ParseFuncOrColumn(pstate,
198                                                                                            makeList1(lfirst(fields)),
199                                                                                            makeList1(result),
200                                                                                            false, false, true);
201                                 }
202                                 /* handle subscripts, if any */
203                                 result = transformIndirection(pstate, result,
204                                                                                           efs->indirection);
205                                 break;
206                         }
207                 case T_TypeCast:
208                         {
209                                 TypeCast   *tc = (TypeCast *) expr;
210                                 Node       *arg = transformExpr(pstate, tc->arg);
211
212                                 result = typecast_expression(pstate, arg, tc->typename);
213                                 break;
214                         }
215                 case T_A_Expr:
216                         {
217                                 A_Expr     *a = (A_Expr *) expr;
218
219                                 switch (a->kind)
220                                 {
221                                         case AEXPR_OP:
222                                                 {
223                                                         /*
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.
228                                                          */
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)))
234                                                         {
235                                                                 NullTest   *n = makeNode(NullTest);
236
237                                                                 n->nulltesttype = IS_NULL;
238
239                                                                 if (exprIsNullConstant(a->lexpr))
240                                                                         n->arg = (Expr *) a->rexpr;
241                                                                 else
242                                                                         n->arg = (Expr *) a->lexpr;
243
244                                                                 result = transformExpr(pstate,
245                                                                                                            (Node *) n);
246                                                         }
247                                                         else
248                                                         {
249                                                                 Node       *lexpr = transformExpr(pstate,
250                                                                                                                                   a->lexpr);
251                                                                 Node       *rexpr = transformExpr(pstate,
252                                                                                                                                   a->rexpr);
253
254                                                                 result = (Node *) make_op(pstate,
255                                                                                                                   a->name,
256                                                                                                                   lexpr,
257                                                                                                                   rexpr);
258                                                         }
259                                                 }
260                                                 break;
261                                         case AEXPR_AND:
262                                                 {
263                                                         Node       *lexpr = transformExpr(pstate,
264                                                                                                                           a->lexpr);
265                                                         Node       *rexpr = transformExpr(pstate,
266                                                                                                                           a->rexpr);
267
268                                                         lexpr = coerce_to_boolean(pstate, lexpr, "AND");
269                                                         rexpr = coerce_to_boolean(pstate, rexpr, "AND");
270
271                                                         result = (Node *) makeBoolExpr(AND_EXPR,
272                                                                                                                    makeList2(lexpr,
273                                                                                                                                          rexpr));
274                                                 }
275                                                 break;
276                                         case AEXPR_OR:
277                                                 {
278                                                         Node       *lexpr = transformExpr(pstate,
279                                                                                                                           a->lexpr);
280                                                         Node       *rexpr = transformExpr(pstate,
281                                                                                                                           a->rexpr);
282
283                                                         lexpr = coerce_to_boolean(pstate, lexpr, "OR");
284                                                         rexpr = coerce_to_boolean(pstate, rexpr, "OR");
285
286                                                         result = (Node *) makeBoolExpr(OR_EXPR,
287                                                                                                                    makeList2(lexpr,
288                                                                                                                                          rexpr));
289                                                 }
290                                                 break;
291                                         case AEXPR_NOT:
292                                                 {
293                                                         Node       *rexpr = transformExpr(pstate,
294                                                                                                                           a->rexpr);
295
296                                                         rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
297
298                                                         result = (Node *) makeBoolExpr(NOT_EXPR,
299                                                                                                                    makeList1(rexpr));
300                                                 }
301                                                 break;
302                                         case AEXPR_DISTINCT:
303                                                 {
304                                                         Node       *lexpr = transformExpr(pstate,
305                                                                                                                           a->lexpr);
306                                                         Node       *rexpr = transformExpr(pstate,
307                                                                                                                           a->rexpr);
308
309                                                         result = (Node *) make_op(pstate,
310                                                                                                           a->name,
311                                                                                                           lexpr,
312                                                                                                           rexpr);
313                                                         if (((OpExpr *) result)->opresulttype != BOOLOID)
314                                                                 elog(ERROR, "IS DISTINCT FROM requires = operator to yield boolean");
315                                                         /*
316                                                          * We rely on DistinctExpr and OpExpr being same struct
317                                                          */
318                                                         NodeSetTag(result, T_DistinctExpr);
319                                                 }
320                                                 break;
321                                         case AEXPR_NULLIF:
322                                                 {
323                                                         Node       *lexpr = transformExpr(pstate,
324                                                                                                                           a->lexpr);
325                                                         Node       *rexpr = transformExpr(pstate,
326                                                                                                                           a->rexpr);
327
328                                                         result = (Node *) make_op(pstate,
329                                                                                                           a->name,
330                                                                                                           lexpr,
331                                                                                                           rexpr);
332                                                         if (((OpExpr *) result)->opresulttype != BOOLOID)
333                                                                 elog(ERROR, "NULLIF requires = operator to yield boolean");
334                                                         /*
335                                                          * We rely on NullIfExpr and OpExpr being same struct
336                                                          */
337                                                         NodeSetTag(result, T_NullIfExpr);
338                                                 }
339                                                 break;
340                                         case AEXPR_OF:
341                                                 {
342                                                         /*
343                                                          * Checking an expression for match to type.
344                                                          * Will result in a boolean constant node.
345                                                          */
346                                                         List       *telem;
347                                                         A_Const    *n;
348                                                         Oid                     ltype,
349                                                                                 rtype;
350                                                         bool            matched = FALSE;
351                                                         Node       *lexpr = transformExpr(pstate,
352                                                                                                                           a->lexpr);
353
354                                                         ltype = exprType(lexpr);
355                                                         foreach(telem, (List *) a->rexpr)
356                                                         {
357                                                                 rtype = LookupTypeName(lfirst(telem));
358                                                                 matched = (rtype == ltype);
359                                                                 if (matched)
360                                                                         break;
361                                                         }
362
363                                                         /*
364                                                          * Expect two forms: equals or not equals.
365                                                          * Flip the sense of the result for not
366                                                          * equals.
367                                                          */
368                                                         if (strcmp(strVal(lfirst(a->name)), "!=") == 0)
369                                                                 matched = (!matched);
370
371                                                         n = makeNode(A_Const);
372                                                         n->val.type = T_String;
373                                                         n->val.val.str = (matched ? "t" : "f");
374                                                         n->typename = SystemTypeName("bool");
375
376                                                         result = transformExpr(pstate, (Node *) n);
377                                                 }
378                                                 break;
379                                 }
380                                 break;
381                         }
382                 case T_FuncCall:
383                         {
384                                 FuncCall   *fn = (FuncCall *) expr;
385                                 List       *targs;
386                                 List       *args;
387
388                                 /*
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.
392                                  */
393                                 targs = listCopy(fn->args);
394                                 foreach(args, targs)
395                                 {
396                                         lfirst(args) = transformExpr(pstate,
397                                                                                                  (Node *) lfirst(args));
398                                 }
399                                 result = ParseFuncOrColumn(pstate,
400                                                                                    fn->funcname,
401                                                                                    targs,
402                                                                                    fn->agg_star,
403                                                                                    fn->agg_distinct,
404                                                                                    false);
405                                 break;
406                         }
407                 case T_SubLink:
408                         {
409                                 SubLink    *sublink = (SubLink *) expr;
410                                 List       *qtrees;
411                                 Query      *qtree;
412
413                                 /* If we already transformed this node, do nothing */
414                                 if (IsA(sublink->subselect, Query))
415                                 {
416                                         result = expr;
417                                         break;
418                                 }
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;
428
429                                 if (sublink->subLinkType == EXISTS_SUBLINK)
430                                 {
431                                         /*
432                                          * EXISTS needs no lefthand or combining operator.
433                                          * These fields should be NIL already, but make sure.
434                                          */
435                                         sublink->lefthand = NIL;
436                                         sublink->operName = NIL;
437                                         sublink->operOids = NIL;
438                                         sublink->useOr = FALSE;
439                                 }
440                                 else if (sublink->subLinkType == EXPR_SUBLINK ||
441                                                  sublink->subLinkType == ARRAY_SUBLINK)
442                                 {
443                                         List       *tlist = qtree->targetList;
444
445                                         /*
446                                          * Make sure the subselect delivers a single column
447                                          * (ignoring resjunk targets).
448                                          */
449                                         if (tlist == NIL ||
450                                                 ((TargetEntry *) lfirst(tlist))->resdom->resjunk)
451                                                 elog(ERROR, "Subselect must have a field");
452                                         while ((tlist = lnext(tlist)) != NIL)
453                                         {
454                                                 if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk)
455                                                         elog(ERROR, "Subselect must have only one field");
456                                         }
457
458                                         /*
459                                          * EXPR and ARRAY need no lefthand or combining operator.
460                                          * These fields should be NIL already, but make sure.
461                                          */
462                                         sublink->lefthand = NIL;
463                                         sublink->operName = NIL;
464                                         sublink->operOids = NIL;
465                                         sublink->useOr = FALSE;
466                                 }
467                                 else
468                                 {
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));
476                                         List       *elist;
477
478                                         /* transform lefthand expressions */
479                                         foreach(elist, left_list)
480                                                 lfirst(elist) = transformExpr(pstate, lfirst(elist));
481
482                                         /*
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.
486                                          */
487                                         if (sublink->subLinkType == ALL_SUBLINK &&
488                                                 length(op) == 1 && strcmp(opname, "<>") == 0)
489                                         {
490                                                 sublink->subLinkType = ANY_SUBLINK;
491                                                 opname = pstrdup("=");
492                                                 op = makeList1(makeString(opname));
493                                                 sublink->operName = op;
494                                                 needNot = true;
495                                         }
496
497                                         /* Set useOr if op is "<>" (possibly qualified) */
498                                         if (strcmp(opname, "<>") == 0)
499                                                 sublink->useOr = TRUE;
500                                         else
501                                                 sublink->useOr = FALSE;
502
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",
508                                                          opname);
509
510                                         /*
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
516                                          * over left_list.
517                                          */
518                                         sublink->operOids = NIL;
519
520                                         while (right_list != NIL)
521                                         {
522                                                 TargetEntry *tent = (TargetEntry *) lfirst(right_list);
523                                                 Node       *lexpr;
524                                                 Operator        optup;
525                                                 Form_pg_operator opform;
526
527                                                 right_list = lnext(right_list);
528                                                 if (tent->resdom->resjunk)
529                                                         continue;
530
531                                                 if (left_list == NIL)
532                                                         elog(ERROR, "Subselect has too many fields");
533                                                 lexpr = lfirst(left_list);
534                                                 left_list = lnext(left_list);
535
536                                                 /*
537                                                  * It's OK to use oper() not compatible_oper()
538                                                  * here, because make_subplan() will insert type
539                                                  * coercion calls if needed.
540                                                  */
541                                                 optup = oper(op,
542                                                                          exprType(lexpr),
543                                                                          exprType((Node *) tent->expr),
544                                                                          false);
545                                                 opform = (Form_pg_operator) GETSTRUCT(optup);
546
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));
552
553                                                 if (get_func_retset(opform->oprcode))
554                                                         elog(ERROR, "%s must not return a set"
555                                                                  " to be used with quantified predicate subquery",
556                                                                  opname);
557
558                                                 sublink->operOids = lappendo(sublink->operOids,
559                                                                                                          oprid(optup));
560
561                                                 ReleaseSysCache(optup);
562                                         }
563                                         if (left_list != NIL)
564                                                 elog(ERROR, "Subselect has too few fields");
565
566                                         if (needNot)
567                                         {
568                                                 expr = coerce_to_boolean(pstate, expr, "NOT");
569                                                 expr = (Node *) makeBoolExpr(NOT_EXPR,
570                                                                                                          makeList1(expr));
571                                         }
572                                 }
573                                 result = (Node *) expr;
574                                 break;
575                         }
576
577                 case T_CaseExpr:
578                         {
579                                 CaseExpr   *c = (CaseExpr *) expr;
580                                 CaseExpr   *newc = makeNode(CaseExpr);
581                                 List       *newargs = NIL;
582                                 List       *typeids = NIL;
583                                 List       *args;
584                                 Node       *defresult;
585                                 Oid                     ptype;
586
587                                 /* transform the list of arguments */
588                                 foreach(args, c->args)
589                                 {
590                                         CaseWhen   *w = (CaseWhen *) lfirst(args);
591                                         CaseWhen   *neww = makeNode(CaseWhen);
592                                         Node       *warg;
593
594                                         Assert(IsA(w, CaseWhen));
595
596                                         warg = (Node *) w->expr;
597                                         if (c->arg != NULL)
598                                         {
599                                                 /* shorthand form was specified, so expand... */
600                                                 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
601                                                                                                                  (Node *) c->arg,
602                                                                                                                  warg);
603                                         }
604                                         neww->expr = (Expr *) transformExpr(pstate, warg);
605
606                                         neww->expr = (Expr *) coerce_to_boolean(pstate,
607                                                                                                                         (Node *) neww->expr,
608                                                                                                                         "CASE/WHEN");
609
610                                         /*
611                                          * result is NULL for NULLIF() construct - thomas
612                                          * 1998-11-11
613                                          */
614                                         warg = (Node *) w->result;
615                                         if (warg == NULL)
616                                         {
617                                                 A_Const    *n = makeNode(A_Const);
618
619                                                 n->val.type = T_Null;
620                                                 warg = (Node *) n;
621                                         }
622                                         neww->result = (Expr *) transformExpr(pstate, warg);
623
624                                         newargs = lappend(newargs, neww);
625                                         typeids = lappendo(typeids, exprType((Node *) neww->result));
626                                 }
627
628                                 newc->args = newargs;
629
630                                 /*
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.
634                                  */
635                                 newc->arg = NULL;
636
637                                 /* transform the default clause */
638                                 defresult = (Node *) c->defresult;
639                                 if (defresult == NULL)
640                                 {
641                                         A_Const    *n = makeNode(A_Const);
642
643                                         n->val.type = T_Null;
644                                         defresult = (Node *) n;
645                                 }
646                                 newc->defresult = (Expr *) transformExpr(pstate, defresult);
647
648                                 /*
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
652                                  * --- tgl
653                                  */
654                                 typeids = lconso(exprType((Node *) newc->defresult), typeids);
655
656                                 ptype = select_common_type(typeids, "CASE");
657                                 newc->casetype = ptype;
658
659                                 /* Convert default result clause, if necessary */
660                                 newc->defresult = (Expr *)
661                                         coerce_to_common_type(pstate,
662                                                                                   (Node *) newc->defresult,
663                                                                                   ptype,
664                                                                                   "CASE/ELSE");
665
666                                 /* Convert when-clause results, if necessary */
667                                 foreach(args, newc->args)
668                                 {
669                                         CaseWhen   *w = (CaseWhen *) lfirst(args);
670
671                                         w->result = (Expr *)
672                                                 coerce_to_common_type(pstate,
673                                                                                           (Node *) w->result,
674                                                                                           ptype,
675                                                                                           "CASE/WHEN");
676                                 }
677
678                                 result = (Node *) newc;
679                                 break;
680                         }
681
682                 case T_ArrayExpr:
683                         {
684                                 ArrayExpr  *a = (ArrayExpr *) expr;
685                                 ArrayExpr  *newa = makeNode(ArrayExpr);
686                                 List       *newelems = NIL;
687                                 List       *newcoercedelems = NIL;
688                                 List       *typeids = NIL;
689                                 List       *element;
690                                 Oid                     array_type;
691                                 Oid                     element_type;
692                                 int                     ndims;
693
694                                 /* Transform the element expressions */
695                                 foreach(element, a->elements)
696                                 {
697                                         Node *e = (Node *) lfirst(element);
698                                         Node *newe;
699
700                                         newe = transformExpr(pstate, e);
701                                         newelems = lappend(newelems, newe);
702                                         typeids = lappendo(typeids, exprType(newe));
703                                 }
704
705                                 /* Select a common type for the elements */
706                                 element_type = select_common_type(typeids, "ARRAY");
707
708                                 /* Coerce arguments to common type if necessary */
709                                 foreach(element, newelems)
710                                 {
711                                         Node *e = (Node *) lfirst(element);
712                                         Node *newe;
713
714                                         newe = coerce_to_common_type(pstate, e,
715                                                                                                  element_type,
716                                                                                                  "ARRAY");
717                                         newcoercedelems = lappend(newcoercedelems, newe);
718                                 }
719
720                                 /* Do we have an array type to use? */
721                                 array_type = get_array_type(element_type);
722                                 if (array_type != InvalidOid)
723                                 {
724                                         /* Elements are presumably of scalar type */
725                                         ndims = 1;
726                                 }
727                                 else
728                                 {
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));
735
736                                         /*
737                                          * make sure the element expressions all have the same
738                                          * number of dimensions
739                                          */
740                                         ndims = 0;
741                                         foreach(element, newcoercedelems)
742                                         {
743                                                 ArrayExpr  *e = (ArrayExpr *) lfirst(element);
744
745                                                 if (!IsA(e, ArrayExpr))
746                                                         elog(ERROR, "Multi-dimensional ARRAY[] must be built from nested array expressions");
747                                                 if (ndims == 0)
748                                                         ndims = e->ndims;
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");
755
756                                         }
757                                         /* increment the number of dimensions */
758                                         ndims++;
759
760                                         /* make sure we don't have too many dimensions now */
761                                         if (ndims > MAXDIM)
762                                                 elog(ERROR, "Number of array dimensions, %d, "
763                                                          "exceeds the maximum allowed %d",
764                                                          ndims, MAXDIM);
765                                 }
766
767                                 newa->array_typeid = array_type;
768                                 newa->element_typeid = element_type;
769                                 newa->elements = newcoercedelems;
770                                 newa->ndims = ndims;
771
772                                 result = (Node *) newa;
773                                 break;
774                         }
775
776                 case T_CoalesceExpr:
777                         {
778                                 CoalesceExpr *c = (CoalesceExpr *) expr;
779                                 CoalesceExpr *newc = makeNode(CoalesceExpr);
780                                 List *newargs = NIL;
781                                 List *newcoercedargs = NIL;
782                                 List *typeids = NIL;
783                                 List *args;
784
785                                 foreach(args, c->args)
786                                 {
787                                         Node *e = (Node *) lfirst(args);
788                                         Node *newe;
789
790                                         newe = transformExpr(pstate, e);
791                                         newargs = lappend(newargs, newe);
792                                         typeids = lappendo(typeids, exprType(newe));
793                                 }
794
795                                 newc->coalescetype = select_common_type(typeids, "COALESCE");
796
797                                 /* Convert arguments if necessary */
798                                 foreach(args, newargs)
799                                 {
800                                         Node *e = (Node *) lfirst(args);
801                                         Node *newe;
802
803                                         newe = coerce_to_common_type(pstate, e,
804                                                                                                  newc->coalescetype,
805                                                                                                  "COALESCE");
806                                         newcoercedargs = lappend(newcoercedargs, newe);
807                                 }
808
809                                 newc->args = newcoercedargs;
810                                 result = (Node *) newc;
811                                 break;
812                         }
813
814                 case T_NullTest:
815                         {
816                                 NullTest   *n = (NullTest *) expr;
817
818                                 n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
819                                 /* the argument can be any type, so don't coerce it */
820                                 result = expr;
821                                 break;
822                         }
823
824                 case T_BooleanTest:
825                         {
826                                 BooleanTest *b = (BooleanTest *) expr;
827                                 const char *clausename;
828
829                                 switch (b->booltesttype)
830                                 {
831                                         case IS_TRUE:
832                                                 clausename = "IS TRUE";
833                                                 break;
834                                         case IS_NOT_TRUE:
835                                                 clausename = "IS NOT TRUE";
836                                                 break;
837                                         case IS_FALSE:
838                                                 clausename = "IS FALSE";
839                                                 break;
840                                         case IS_NOT_FALSE:
841                                                 clausename = "IS NOT FALSE";
842                                                 break;
843                                         case IS_UNKNOWN:
844                                                 clausename = "IS UNKNOWN";
845                                                 break;
846                                         case IS_NOT_UNKNOWN:
847                                                 clausename = "IS NOT UNKNOWN";
848                                                 break;
849                                         default:
850                                                 elog(ERROR, "transformExpr: unexpected booltesttype %d",
851                                                          (int) b->booltesttype);
852                                                 clausename = NULL;              /* keep compiler quiet */
853                                 }
854
855                                 b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
856
857                                 b->arg = (Expr *) coerce_to_boolean(pstate,
858                                                                                                         (Node *) b->arg,
859                                                                                                         clausename);
860
861                                 result = expr;
862                                 break;
863                         }
864
865                         /*********************************************
866                          * Quietly accept node types that may be presented when we are
867                          * called on an already-transformed tree.
868                          *
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                          *********************************************/
873                 case T_Var:
874                 case T_Const:
875                 case T_Param:
876                 case T_Aggref:
877                 case T_ArrayRef:
878                 case T_FuncExpr:
879                 case T_OpExpr:
880                 case T_DistinctExpr:
881                 case T_NullIfExpr:
882                 case T_BoolExpr:
883                 case T_FieldSelect:
884                 case T_RelabelType:
885                 case T_CoerceToDomain:
886                 case T_CoerceToDomainValue:
887                         {
888                                 result = (Node *) expr;
889                                 break;
890                         }
891
892                 default:
893                         /* should not reach here */
894                         elog(ERROR, "transformExpr: does not know how to transform node %d"
895                                  " (internal error)", nodeTag(expr));
896                         break;
897         }
898
899         expr_depth_counter--;
900
901         return result;
902 }
903
904 static Node *
905 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
906 {
907         if (indirection == NIL)
908                 return basenode;
909         return (Node *) transformArraySubscripts(pstate,
910                                                                                          basenode,
911                                                                                          exprType(basenode),
912                                                                                          exprTypmod(basenode),
913                                                                                          indirection,
914                                                                                          false,
915                                                                                          NULL);
916 }
917
918 static Node *
919 transformColumnRef(ParseState *pstate, ColumnRef *cref)
920 {
921         int                     numnames = length(cref->fields);
922         Node       *node;
923         RangeVar   *rv;
924         int                     levels_up;
925
926         /*----------
927          * The allowed syntaxes are:
928          *
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.
938          *
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.
942          *
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.
945          *
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.)
951          *----------
952          */
953         switch (numnames)
954         {
955                 case 1:
956                         {
957                                 char       *name = strVal(lfirst(cref->fields));
958
959                                 /* Try to identify as an unqualified column */
960                                 node = colnameToVar(pstate, name);
961
962                                 if (node == NULL)
963                                 {
964                                         /*
965                                          * Not known as a column of any range-table entry.
966                                          *
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.)
971                                          */
972                                         if (pstate->p_value_substitute != NULL &&
973                                                 strcmp(name, "value") == 0)
974                                         {
975                                                 node = (Node *) copyObject(pstate->p_value_substitute);
976                                                 break;
977                                         }
978
979                                         /*
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
983                                          * recognized.
984                                          *
985                                          * This is a hack for backwards compatibility with
986                                          * PostQUEL-inspired syntax.  The preferred form now
987                                          * is "rel.*".
988                                          */
989                                         if (cref->indirection == NIL &&
990                                                 refnameRangeTblEntry(pstate, NULL, name,
991                                                                                          &levels_up) != NULL)
992                                         {
993                                                 rv = makeNode(RangeVar);
994                                                 rv->relname = name;
995                                                 rv->inhOpt = INH_DEFAULT;
996                                                 node = (Node *) rv;
997                                         }
998                                         else
999                                                 elog(ERROR, "Attribute \"%s\" not found", name);
1000                                 }
1001                                 break;
1002                         }
1003                 case 2:
1004                         {
1005                                 char       *name1 = strVal(lfirst(cref->fields));
1006                                 char       *name2 = strVal(lsecond(cref->fields));
1007
1008                                 /* Whole-row reference? */
1009                                 if (strcmp(name2, "*") == 0)
1010                                 {
1011                                         rv = makeNode(RangeVar);
1012                                         rv->relname = name1;
1013                                         rv->inhOpt = INH_DEFAULT;
1014                                         node = (Node *) rv;
1015                                         break;
1016                                 }
1017
1018                                 /* Try to identify as a once-qualified column */
1019                                 node = qualifiedNameToVar(pstate, NULL, name1, name2, true);
1020                                 if (node == NULL)
1021                                 {
1022                                         /*
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.
1026                                          */
1027                                         rv = makeNode(RangeVar);
1028                                         rv->relname = name1;
1029                                         rv->inhOpt = INH_DEFAULT;
1030                                         node = ParseFuncOrColumn(pstate,
1031                                                                                          makeList1(makeString(name2)),
1032                                                                                          makeList1(rv),
1033                                                                                          false, false, true);
1034                                 }
1035                                 break;
1036                         }
1037                 case 3:
1038                         {
1039                                 char       *name1 = strVal(lfirst(cref->fields));
1040                                 char       *name2 = strVal(lsecond(cref->fields));
1041                                 char       *name3 = strVal(lthird(cref->fields));
1042
1043                                 /* Whole-row reference? */
1044                                 if (strcmp(name3, "*") == 0)
1045                                 {
1046                                         rv = makeNode(RangeVar);
1047                                         rv->schemaname = name1;
1048                                         rv->relname = name2;
1049                                         rv->inhOpt = INH_DEFAULT;
1050                                         node = (Node *) rv;
1051                                         break;
1052                                 }
1053
1054                                 /* Try to identify as a twice-qualified column */
1055                                 node = qualifiedNameToVar(pstate, name1, name2, name3, true);
1056                                 if (node == NULL)
1057                                 {
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)),
1065                                                                                          makeList1(rv),
1066                                                                                          false, false, true);
1067                                 }
1068                                 break;
1069                         }
1070                 case 4:
1071                         {
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));
1076
1077                                 /*
1078                                  * We check the catalog name and then ignore it.
1079                                  */
1080                                 if (strcmp(name1, DatabaseName) != 0)
1081                                         elog(ERROR, "Cross-database references are not implemented");
1082
1083                                 /* Whole-row reference? */
1084                                 if (strcmp(name4, "*") == 0)
1085                                 {
1086                                         rv = makeNode(RangeVar);
1087                                         rv->schemaname = name2;
1088                                         rv->relname = name3;
1089                                         rv->inhOpt = INH_DEFAULT;
1090                                         node = (Node *) rv;
1091                                         break;
1092                                 }
1093
1094                                 /* Try to identify as a twice-qualified column */
1095                                 node = qualifiedNameToVar(pstate, name2, name3, name4, true);
1096                                 if (node == NULL)
1097                                 {
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)),
1105                                                                                          makeList1(rv),
1106                                                                                          false, false, true);
1107                                 }
1108                                 break;
1109                         }
1110                 default:
1111                         elog(ERROR, "Invalid qualified name syntax (too many names)");
1112                         node = NULL;            /* keep compiler quiet */
1113                         break;
1114         }
1115
1116         return transformIndirection(pstate, node, cref->indirection);
1117 }
1118
1119 /*
1120  *      exprType -
1121  *        returns the Oid of the type of the expression. (Used for typechecking.)
1122  */
1123 Oid
1124 exprType(Node *expr)
1125 {
1126         Oid                     type;
1127
1128         if (!expr)
1129                 return InvalidOid;
1130
1131         switch (nodeTag(expr))
1132         {
1133                 case T_Var:
1134                         type = ((Var *) expr)->vartype;
1135                         break;
1136                 case T_Const:
1137                         type = ((Const *) expr)->consttype;
1138                         break;
1139                 case T_Param:
1140                         type = ((Param *) expr)->paramtype;
1141                         break;
1142                 case T_Aggref:
1143                         type = ((Aggref *) expr)->aggtype;
1144                         break;
1145                 case T_ArrayRef:
1146                         type = ((ArrayRef *) expr)->refrestype;
1147                         break;
1148                 case T_FuncExpr:
1149                         type = ((FuncExpr *) expr)->funcresulttype;
1150                         break;
1151                 case T_OpExpr:
1152                         type = ((OpExpr *) expr)->opresulttype;
1153                         break;
1154                 case T_DistinctExpr:
1155                         type = ((DistinctExpr *) expr)->opresulttype;
1156                         break;
1157                 case T_BoolExpr:
1158                         type = BOOLOID;
1159                         break;
1160                 case T_SubLink:
1161                         {
1162                                 SubLink    *sublink = (SubLink *) expr;
1163
1164                                 if (sublink->subLinkType == EXPR_SUBLINK ||
1165                                         sublink->subLinkType == ARRAY_SUBLINK)
1166                                 {
1167                                         /* get the type of the subselect's first target column */
1168                                         Query      *qtree = (Query *) sublink->subselect;
1169                                         TargetEntry *tent;
1170
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 */
1179                                         {
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));
1184                                         }
1185                                 }
1186                                 else
1187                                 {
1188                                         /* for all other sublink types, result is boolean */
1189                                         type = BOOLOID;
1190                                 }
1191                         }
1192                         break;
1193                 case T_SubPlan:
1194                         {
1195                                 /*
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.
1199                                  */
1200                                 SubPlan    *subplan = (SubPlan *) expr;
1201
1202                                 if (subplan->subLinkType == EXPR_SUBLINK ||
1203                                         subplan->subLinkType == ARRAY_SUBLINK)
1204                                 {
1205                                         /* get the type of the subselect's first target column */
1206                                         TargetEntry *tent;
1207
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 */
1214                                         {
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));
1219                                         }
1220                                 }
1221                                 else
1222                                 {
1223                                         /* for all other subplan types, result is boolean */
1224                                         type = BOOLOID;
1225                                 }
1226                         }
1227                         break;
1228                 case T_FieldSelect:
1229                         type = ((FieldSelect *) expr)->resulttype;
1230                         break;
1231                 case T_RelabelType:
1232                         type = ((RelabelType *) expr)->resulttype;
1233                         break;
1234                 case T_CaseExpr:
1235                         type = ((CaseExpr *) expr)->casetype;
1236                         break;
1237                 case T_CaseWhen:
1238                         type = exprType((Node *) ((CaseWhen *) expr)->result);
1239                         break;
1240                 case T_ArrayExpr:
1241                         type = ((ArrayExpr *) expr)->array_typeid;
1242                         break;
1243                 case T_CoalesceExpr:
1244                         type = ((CoalesceExpr *) expr)->coalescetype;
1245                         break;
1246                 case T_NullIfExpr:
1247                         type = exprType((Node *) lfirst(((NullIfExpr *) expr)->args));
1248                         break;
1249                 case T_NullTest:
1250                         type = BOOLOID;
1251                         break;
1252                 case T_BooleanTest:
1253                         type = BOOLOID;
1254                         break;
1255                 case T_CoerceToDomain:
1256                         type = ((CoerceToDomain *) expr)->resulttype;
1257                         break;
1258                 case T_CoerceToDomainValue:
1259                         type = ((CoerceToDomainValue *) expr)->typeId;
1260                         break;
1261                 case T_RangeVar:
1262                         /*
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.
1266                          */
1267                         elog(ERROR, "Relation reference \"%s\" cannot be used in an expression",
1268                                  ((RangeVar *) expr)->relname);
1269                         type = InvalidOid;      /* keep compiler quiet */
1270                         break;
1271                 default:
1272                         elog(ERROR, "exprType: Do not know how to get type for %d node",
1273                                  nodeTag(expr));
1274                         type = InvalidOid;      /* keep compiler quiet */
1275                         break;
1276         }
1277         return type;
1278 }
1279
1280 /*
1281  *      exprTypmod -
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.
1284  */
1285 int32
1286 exprTypmod(Node *expr)
1287 {
1288         if (!expr)
1289                 return -1;
1290
1291         switch (nodeTag(expr))
1292         {
1293                 case T_Var:
1294                         return ((Var *) expr)->vartypmod;
1295                 case T_Const:
1296                         {
1297                                 /* Be smart about string constants... */
1298                                 Const      *con = (Const *) expr;
1299
1300                                 switch (con->consttype)
1301                                 {
1302                                         case BPCHAROID:
1303                                                 if (!con->constisnull)
1304                                                         return VARSIZE(DatumGetPointer(con->constvalue));
1305                                                 break;
1306                                         default:
1307                                                 break;
1308                                 }
1309                         }
1310                         break;
1311                 case T_FuncExpr:
1312                         {
1313                                 int32           coercedTypmod;
1314
1315                                 /* Be smart about length-coercion functions... */
1316                                 if (exprIsLengthCoercion(expr, &coercedTypmod))
1317                                         return coercedTypmod;
1318                         }
1319                         break;
1320                 case T_FieldSelect:
1321                         return ((FieldSelect *) expr)->resulttypmod;
1322                 case T_RelabelType:
1323                         return ((RelabelType *) expr)->resulttypmod;
1324                 case T_CaseExpr:
1325                         {
1326                                 /*
1327                                  * If all the alternatives agree on type/typmod, return
1328                                  * that typmod, else use -1
1329                                  */
1330                                 CaseExpr   *cexpr = (CaseExpr *) expr;
1331                                 Oid                     casetype = cexpr->casetype;
1332                                 int32           typmod;
1333                                 List       *arg;
1334
1335                                 if (!cexpr->defresult)
1336                                         return -1;
1337                                 if (exprType((Node *) cexpr->defresult) != casetype)
1338                                         return -1;
1339                                 typmod = exprTypmod((Node *) cexpr->defresult);
1340                                 if (typmod < 0)
1341                                         return -1;      /* no point in trying harder */
1342                                 foreach(arg, cexpr->args)
1343                                 {
1344                                         CaseWhen   *w = (CaseWhen *) lfirst(arg);
1345
1346                                         Assert(IsA(w, CaseWhen));
1347                                         if (exprType((Node *) w->result) != casetype)
1348                                                 return -1;
1349                                         if (exprTypmod((Node *) w->result) != typmod)
1350                                                 return -1;
1351                                 }
1352                                 return typmod;
1353                         }
1354                         break;
1355                 case T_CoalesceExpr:
1356                         {
1357                                 /*
1358                                  * If all the alternatives agree on type/typmod, return
1359                                  * that typmod, else use -1
1360                                  */
1361                                 CoalesceExpr *cexpr = (CoalesceExpr *) expr;
1362                                 Oid coalescetype = cexpr->coalescetype;
1363                                 int32 typmod;
1364                                 List *arg;
1365
1366                                 typmod = exprTypmod((Node *) lfirst(cexpr->args));
1367                                 foreach(arg, cexpr->args)
1368                                 {
1369                                         Node *e = (Node *) lfirst(arg);
1370
1371                                         if (exprType(e) != coalescetype)
1372                                                 return -1;
1373                                         if (exprTypmod(e) != typmod)
1374                                                 return -1;
1375                                 }
1376                                 return typmod;
1377                         }
1378                         break;
1379                 case T_NullIfExpr:
1380                         {
1381                                 NullIfExpr *nexpr = (NullIfExpr *) expr;
1382
1383                                 return exprTypmod((Node *) lfirst(nexpr->args));
1384                         }
1385                         break;
1386                 case T_CoerceToDomain:
1387                         return ((CoerceToDomain *) expr)->resulttypmod;
1388                 case T_CoerceToDomainValue:
1389                         return ((CoerceToDomainValue *) expr)->typeMod;
1390                 default:
1391                         break;
1392         }
1393         return -1;
1394 }
1395
1396 /*
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.
1400  *
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.
1403  */
1404 bool
1405 exprIsLengthCoercion(Node *expr, int32 *coercedTypmod)
1406 {
1407         FuncExpr   *func;
1408         int                     nargs;
1409         Const      *second_arg;
1410
1411         if (coercedTypmod != NULL)
1412                 *coercedTypmod = -1;    /* default result on failure */
1413
1414         /* Is it a function-call at all? */
1415         if (expr == NULL || !IsA(expr, FuncExpr))
1416                 return false;
1417         func = (FuncExpr *) expr;
1418
1419         /*
1420          * If it didn't come from a coercion context, reject.
1421          */
1422         if (func->funcformat != COERCE_EXPLICIT_CAST &&
1423                 func->funcformat != COERCE_IMPLICIT_CAST)
1424                 return false;
1425
1426         /*
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).
1430          */
1431         nargs = length(func->args);
1432         if (nargs < 2 || nargs > 3)
1433                 return false;
1434
1435         second_arg = (Const *) lsecond(func->args);
1436         if (!IsA(second_arg, Const) ||
1437                 second_arg->consttype != INT4OID ||
1438                 second_arg->constisnull)
1439                 return false;
1440
1441         /*
1442          * OK, it is indeed a length-coercion function.
1443          */
1444         if (coercedTypmod != NULL)
1445                 *coercedTypmod = DatumGetInt32(second_arg->constvalue);
1446
1447         return true;
1448 }
1449
1450 /*
1451  * Handle an explicit CAST construct.
1452  *
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).
1455  */
1456 static Node *
1457 typecast_expression(ParseState *pstate, Node *expr, TypeName *typename)
1458 {
1459         Oid                     inputType = exprType(expr);
1460         Oid                     targetType;
1461
1462         targetType = typenameTypeId(typename);
1463
1464         if (inputType == InvalidOid)
1465                 return expr;                    /* do nothing if NULL input */
1466
1467         expr = coerce_to_target_type(pstate, expr, inputType,
1468                                                                  targetType, typename->typmod,
1469                                                                  COERCION_EXPLICIT,
1470                                                                  COERCE_EXPLICIT_CAST);
1471         if (expr == NULL)
1472                 elog(ERROR, "Cannot cast type %s to %s",
1473                          format_type_be(inputType),
1474                          format_type_be(targetType));
1475
1476         return expr;
1477 }