]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_expr.c
I've fixed up the way domain constraints (not null and type length)
[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.121 2002/07/06 20:16:36 momjian 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 "parser/analyze.h"
24 #include "parser/gramparse.h"
25 #include "parser/parse.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_expr.h"
28 #include "parser/parse_func.h"
29 #include "parser/parse_oper.h"
30 #include "parser/parse_relation.h"
31 #include "parser/parse_target.h"
32 #include "parser/parse_type.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
36
37
38 int                     max_expr_depth = DEFAULT_MAX_EXPR_DEPTH;
39 static int      expr_depth_counter = 0;
40
41 bool            Transform_null_equals = false;
42
43 static Node *parser_typecast_constant(Value *expr, TypeName *typename);
44 static Node *parser_typecast_expression(ParseState *pstate,
45                                                    Node *expr, TypeName *typename);
46 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
47 static Node *transformIndirection(ParseState *pstate, Node *basenode,
48                                          List *indirection);
49
50
51 /*
52  * Initialize for parsing a new query.
53  *
54  * We reset the expression depth counter here, in case it was left nonzero
55  * due to elog()'ing out of the last parsing operation.
56  */
57 void
58 parse_expr_init(void)
59 {
60         expr_depth_counter = 0;
61 }
62
63
64 /*
65  * transformExpr -
66  *        Analyze and transform expressions. Type checking and type casting is
67  *        done here. The optimizer and the executor cannot handle the original
68  *        (raw) expressions collected by the parse tree. Hence the transformation
69  *        here.
70  *
71  * NOTE: there are various cases in which this routine will get applied to
72  * an already-transformed expression.  Some examples:
73  *      1. At least one construct (BETWEEN/AND) puts the same nodes
74  *      into two branches of the parse tree; hence, some nodes
75  *      are transformed twice.
76  *      2. Another way it can happen is that coercion of an operator or
77  *      function argument to the required type (via coerce_type())
78  *      can apply transformExpr to an already-transformed subexpression.
79  *      An example here is "SELECT count(*) + 1.0 FROM table".
80  * While it might be possible to eliminate these cases, the path of
81  * least resistance so far has been to ensure that transformExpr() does
82  * no damage if applied to an already-transformed tree.  This is pretty
83  * easy for cases where the transformation replaces one node type with
84  * another, such as A_Const => Const; we just do nothing when handed
85  * a Const.  More care is needed for node types that are used as both
86  * input and output of transformExpr; see SubLink for example.
87  */
88 Node *
89 transformExpr(ParseState *pstate, Node *expr)
90 {
91         Node       *result = NULL;
92
93         if (expr == NULL)
94                 return NULL;
95
96         /*
97          * Guard against an overly complex expression leading to coredump due
98          * to stack overflow here, or in later recursive routines that
99          * traverse expression trees.  Note that this is very unlikely to
100          * happen except with pathological queries; but we don't want someone
101          * to be able to crash the backend quite that easily...
102          */
103         if (++expr_depth_counter > max_expr_depth)
104                 elog(ERROR, "Expression too complex: nesting depth exceeds max_expr_depth = %d",
105                          max_expr_depth);
106
107         switch (nodeTag(expr))
108         {
109                 case T_ColumnRef:
110                         {
111                                 result = transformColumnRef(pstate, (ColumnRef *) expr);
112                                 break;
113                         }
114                 case T_ParamRef:
115                         {
116                                 ParamRef   *pref = (ParamRef *) expr;
117                                 int                     paramno = pref->number;
118                                 Oid                     paramtyp = param_type(paramno);
119                                 Param      *param;
120                                 List       *fields;
121
122                                 if (!OidIsValid(paramtyp))
123                                         elog(ERROR, "Parameter '$%d' is out of range", paramno);
124                                 param = makeNode(Param);
125                                 param->paramkind = PARAM_NUM;
126                                 param->paramid = (AttrNumber) paramno;
127                                 param->paramname = "<unnamed>";
128                                 param->paramtype = paramtyp;
129                                 result = (Node *) param;
130                                 /* handle qualification, if any */
131                                 foreach(fields, pref->fields)
132                                 {
133                                         result = ParseFuncOrColumn(pstate,
134                                                                                            makeList1(lfirst(fields)),
135                                                                                            makeList1(result),
136                                                                                            false, false, true);
137                                 }
138                                 /* handle subscripts, if any */
139                                 result = transformIndirection(pstate, result,
140                                                                                           pref->indirection);
141                                 break;
142                         }
143                 case T_A_Const:
144                         {
145                                 A_Const    *con = (A_Const *) expr;
146                                 Value      *val = &con->val;
147
148                                 if (con->typename != NULL)
149                                         result = parser_typecast_constant(val, con->typename);
150                                 else
151                                         result = (Node *) make_const(val);
152                                 break;
153                         }
154                 case T_ExprFieldSelect:
155                         {
156                                 ExprFieldSelect *efs = (ExprFieldSelect *) expr;
157                                 List       *fields;
158
159                                 result = transformExpr(pstate, efs->arg);
160                                 /* handle qualification, if any */
161                                 foreach(fields, efs->fields)
162                                 {
163                                         result = ParseFuncOrColumn(pstate,
164                                                                                            makeList1(lfirst(fields)),
165                                                                                            makeList1(result),
166                                                                                            false, false, true);
167                                 }
168                                 /* handle subscripts, if any */
169                                 result = transformIndirection(pstate, result,
170                                                                                           efs->indirection);
171                                 break;
172                         }
173                 case T_TypeCast:
174                         {
175                                 TypeCast   *tc = (TypeCast *) expr;
176                                 Node       *arg = transformExpr(pstate, tc->arg);
177
178                                 result = parser_typecast_expression(pstate, arg, tc->typename);
179                                 break;
180                         }
181                 case T_A_Expr:
182                         {
183                                 A_Expr     *a = (A_Expr *) expr;
184
185                                 switch (a->oper)
186                                 {
187                                         case OP:
188                                                 {
189                                                         /*
190                                                          * Special-case "foo = NULL" and "NULL = foo"
191                                                          * for compatibility with standards-broken
192                                                          * products (like Microsoft's).  Turn these
193                                                          * into IS NULL exprs.
194                                                          */
195                                                         if (Transform_null_equals &&
196                                                                 length(a->name) == 1 &&
197                                                                 strcmp(strVal(lfirst(a->name)), "=") == 0 &&
198                                                                 (exprIsNullConstant(a->lexpr) ||
199                                                                  exprIsNullConstant(a->rexpr)))
200                                                         {
201                                                                 NullTest   *n = makeNode(NullTest);
202
203                                                                 n->nulltesttype = IS_NULL;
204
205                                                                 if (exprIsNullConstant(a->lexpr))
206                                                                         n->arg = a->rexpr;
207                                                                 else
208                                                                         n->arg = a->lexpr;
209
210                                                                 result = transformExpr(pstate,
211                                                                                                            (Node *) n);
212                                                         }
213                                                         else
214                                                         {
215                                                                 Node       *lexpr = transformExpr(pstate,
216                                                                                                                                 a->lexpr);
217                                                                 Node       *rexpr = transformExpr(pstate,
218                                                                                                                                 a->rexpr);
219
220                                                                 result = (Node *) make_op(a->name,
221                                                                                                                   lexpr,
222                                                                                                                   rexpr);
223                                                         }
224                                                 }
225                                                 break;
226                                         case AND:
227                                                 {
228                                                         Node       *lexpr = transformExpr(pstate,
229                                                                                                                           a->lexpr);
230                                                         Node       *rexpr = transformExpr(pstate,
231                                                                                                                           a->rexpr);
232                                                         Expr       *expr = makeNode(Expr);
233
234                                                         lexpr = coerce_to_boolean(lexpr, "AND");
235                                                         rexpr = coerce_to_boolean(rexpr, "AND");
236
237                                                         expr->typeOid = BOOLOID;
238                                                         expr->opType = AND_EXPR;
239                                                         expr->args = makeList2(lexpr, rexpr);
240                                                         result = (Node *) expr;
241                                                 }
242                                                 break;
243                                         case OR:
244                                                 {
245                                                         Node       *lexpr = transformExpr(pstate,
246                                                                                                                           a->lexpr);
247                                                         Node       *rexpr = transformExpr(pstate,
248                                                                                                                           a->rexpr);
249                                                         Expr       *expr = makeNode(Expr);
250
251                                                         lexpr = coerce_to_boolean(lexpr, "OR");
252                                                         rexpr = coerce_to_boolean(rexpr, "OR");
253
254                                                         expr->typeOid = BOOLOID;
255                                                         expr->opType = OR_EXPR;
256                                                         expr->args = makeList2(lexpr, rexpr);
257                                                         result = (Node *) expr;
258                                                 }
259                                                 break;
260                                         case NOT:
261                                                 {
262                                                         Node       *rexpr = transformExpr(pstate,
263                                                                                                                           a->rexpr);
264                                                         Expr       *expr = makeNode(Expr);
265
266                                                         rexpr = coerce_to_boolean(rexpr, "NOT");
267
268                                                         expr->typeOid = BOOLOID;
269                                                         expr->opType = NOT_EXPR;
270                                                         expr->args = makeList1(rexpr);
271                                                         result = (Node *) expr;
272                                                 }
273                                                 break;
274                                         case DISTINCT:
275                                                 {
276                                                         Node       *lexpr = transformExpr(pstate,
277                                                                                                                           a->lexpr);
278                                                         Node       *rexpr = transformExpr(pstate,
279                                                                                                                           a->rexpr);
280                                                         result = (Node *) make_op(a->name,
281                                                                                                           lexpr,
282                                                                                                           rexpr);
283                                                         ((Expr *)result)->opType = DISTINCT_EXPR;
284                                                 }
285                                 }
286                                 break;
287                         }
288                 case T_FuncCall:
289                         {
290                                 FuncCall   *fn = (FuncCall *) expr;
291                                 List       *args;
292
293                                 /* transform the list of arguments */
294                                 foreach(args, fn->args)
295                                         lfirst(args) = transformExpr(pstate,
296                                                                                                  (Node *) lfirst(args));
297                                 result = ParseFuncOrColumn(pstate,
298                                                                                    fn->funcname,
299                                                                                    fn->args,
300                                                                                    fn->agg_star,
301                                                                                    fn->agg_distinct,
302                                                                                    false);
303                                 break;
304                         }
305                 case T_SubLink:
306                         {
307                                 SubLink    *sublink = (SubLink *) expr;
308                                 List       *qtrees;
309                                 Query      *qtree;
310
311                                 /* If we already transformed this node, do nothing */
312                                 if (IsA(sublink->subselect, Query))
313                                 {
314                                         result = expr;
315                                         break;
316                                 }
317                                 pstate->p_hasSubLinks = true;
318                                 qtrees = parse_analyze(sublink->subselect, pstate);
319                                 if (length(qtrees) != 1)
320                                         elog(ERROR, "Bad query in subselect");
321                                 qtree = (Query *) lfirst(qtrees);
322                                 if (qtree->commandType != CMD_SELECT ||
323                                         qtree->resultRelation != 0)
324                                         elog(ERROR, "Bad query in subselect");
325                                 sublink->subselect = (Node *) qtree;
326
327                                 if (sublink->subLinkType == EXISTS_SUBLINK)
328                                 {
329                                         /*
330                                          * EXISTS needs no lefthand or combining operator.
331                                          * These fields should be NIL already, but make sure.
332                                          */
333                                         sublink->lefthand = NIL;
334                                         sublink->oper = NIL;
335                                 }
336                                 else if (sublink->subLinkType == EXPR_SUBLINK)
337                                 {
338                                         List       *tlist = qtree->targetList;
339
340                                         /*
341                                          * Make sure the subselect delivers a single column
342                                          * (ignoring resjunk targets).
343                                          */
344                                         if (tlist == NIL ||
345                                                 ((TargetEntry *) lfirst(tlist))->resdom->resjunk)
346                                                 elog(ERROR, "Subselect must have a field");
347                                         while ((tlist = lnext(tlist)) != NIL)
348                                         {
349                                                 if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk)
350                                                         elog(ERROR, "Subselect must have only one field");
351                                         }
352
353                                         /*
354                                          * EXPR needs no lefthand or combining operator. These
355                                          * fields should be NIL already, but make sure.
356                                          */
357                                         sublink->lefthand = NIL;
358                                         sublink->oper = NIL;
359                                 }
360                                 else
361                                 {
362                                         /* ALL, ANY, or MULTIEXPR: generate operator list */
363                                         List       *left_list = sublink->lefthand;
364                                         List       *right_list = qtree->targetList;
365                                         List       *op;
366                                         char       *opname;
367                                         List       *elist;
368
369                                         foreach(elist, left_list)
370                                                 lfirst(elist) = transformExpr(pstate, lfirst(elist));
371
372                                         Assert(IsA(sublink->oper, A_Expr));
373                                         op = ((A_Expr *) sublink->oper)->name;
374                                         opname = strVal(llast(op));
375                                         sublink->oper = NIL;
376
377                                         /* Combining operators other than =/<> is dubious... */
378                                         if (length(left_list) != 1 &&
379                                                 strcmp(opname, "=") != 0 && strcmp(opname, "<>") != 0)
380                                                 elog(ERROR, "Row comparison cannot use operator %s",
381                                                          opname);
382
383                                         /*
384                                          * Scan subquery's targetlist to find values that will
385                                          * be matched against lefthand values.  We need to
386                                          * ignore resjunk targets, so doing the outer
387                                          * iteration over right_list is easier than doing it
388                                          * over left_list.
389                                          */
390                                         while (right_list != NIL)
391                                         {
392                                                 TargetEntry *tent = (TargetEntry *) lfirst(right_list);
393                                                 Node       *lexpr;
394                                                 Operator        optup;
395                                                 Form_pg_operator opform;
396                                                 Oper       *newop;
397
398                                                 right_list = lnext(right_list);
399                                                 if (tent->resdom->resjunk)
400                                                         continue;
401
402                                                 if (left_list == NIL)
403                                                         elog(ERROR, "Subselect has too many fields");
404                                                 lexpr = lfirst(left_list);
405                                                 left_list = lnext(left_list);
406
407                                                 /*
408                                                  * It's OK to use oper() not compatible_oper()
409                                                  * here, because make_subplan() will insert type
410                                                  * coercion calls if needed.
411                                                  */
412                                                 optup = oper(op,
413                                                                          exprType(lexpr),
414                                                                          exprType(tent->expr),
415                                                                          false);
416                                                 opform = (Form_pg_operator) GETSTRUCT(optup);
417
418                                                 if (opform->oprresult != BOOLOID)
419                                                         elog(ERROR, "%s has result type of %s, but must return %s"
420                                                                  " to be used with quantified predicate subquery",
421                                                                  opname, format_type_be(opform->oprresult),
422                                                                  format_type_be(BOOLOID));
423
424                                                 if (get_func_retset(opform->oprcode))
425                                                         elog(ERROR, "%s must not return a set"
426                                                                  " to be used with quantified predicate subquery",
427                                                                  opname);
428
429                                                 newop = makeOper(oprid(optup),  /* opno */
430                                                                                  InvalidOid,    /* opid */
431                                                                                  opform->oprresult,
432                                                                                  false);
433                                                 sublink->oper = lappend(sublink->oper, newop);
434                                                 ReleaseSysCache(optup);
435                                         }
436                                         if (left_list != NIL)
437                                                 elog(ERROR, "Subselect has too few fields");
438                                 }
439                                 result = (Node *) expr;
440                                 break;
441                         }
442
443                 case T_CaseExpr:
444                         {
445                                 CaseExpr   *c = (CaseExpr *) expr;
446                                 CaseExpr   *newc = makeNode(CaseExpr);
447                                 List       *newargs = NIL;
448                                 List       *typeids = NIL;
449                                 List       *args;
450                                 Node       *defresult;
451                                 Oid                     ptype;
452
453                                 /* transform the list of arguments */
454                                 foreach(args, c->args)
455                                 {
456                                         CaseWhen   *w = (CaseWhen *) lfirst(args);
457                                         CaseWhen   *neww = makeNode(CaseWhen);
458                                         Node       *warg;
459
460                                         Assert(IsA(w, CaseWhen));
461
462                                         warg = w->expr;
463                                         if (c->arg != NULL)
464                                         {
465                                                 /* shorthand form was specified, so expand... */
466                                                 warg = (Node *) makeSimpleA_Expr(OP, "=",
467                                                                                                                  c->arg, warg);
468                                         }
469                                         neww->expr = transformExpr(pstate, warg);
470
471                                         neww->expr = coerce_to_boolean(neww->expr, "CASE/WHEN");
472
473                                         /*
474                                          * result is NULL for NULLIF() construct - thomas
475                                          * 1998-11-11
476                                          */
477                                         warg = w->result;
478                                         if (warg == NULL)
479                                         {
480                                                 A_Const    *n = makeNode(A_Const);
481
482                                                 n->val.type = T_Null;
483                                                 warg = (Node *) n;
484                                         }
485                                         neww->result = transformExpr(pstate, warg);
486
487                                         newargs = lappend(newargs, neww);
488                                         typeids = lappendi(typeids, exprType(neww->result));
489                                 }
490
491                                 newc->args = newargs;
492
493                                 /*
494                                  * It's not shorthand anymore, so drop the implicit
495                                  * argument. This is necessary to keep any re-application
496                                  * of transformExpr from doing the wrong thing.
497                                  */
498                                 newc->arg = NULL;
499
500                                 /* transform the default clause */
501                                 defresult = c->defresult;
502                                 if (defresult == NULL)
503                                 {
504                                         A_Const    *n = makeNode(A_Const);
505
506                                         n->val.type = T_Null;
507                                         defresult = (Node *) n;
508                                 }
509                                 newc->defresult = transformExpr(pstate, defresult);
510
511                                 /*
512                                  * Note: default result is considered the most significant
513                                  * type in determining preferred type.  This is how the
514                                  * code worked before, but it seems a little bogus to me
515                                  * --- tgl
516                                  */
517                                 typeids = lconsi(exprType(newc->defresult), typeids);
518
519                                 ptype = select_common_type(typeids, "CASE");
520                                 newc->casetype = ptype;
521
522                                 /* Convert default result clause, if necessary */
523                                 newc->defresult = coerce_to_common_type(pstate,
524                                                                                                                 newc->defresult,
525                                                                                                                 ptype,
526                                                                                                                 "CASE/ELSE");
527
528                                 /* Convert when-clause results, if necessary */
529                                 foreach(args, newc->args)
530                                 {
531                                         CaseWhen   *w = (CaseWhen *) lfirst(args);
532
533                                         w->result = coerce_to_common_type(pstate,
534                                                                                                           w->result,
535                                                                                                           ptype,
536                                                                                                           "CASE/WHEN");
537                                 }
538
539                                 result = (Node *) newc;
540                                 break;
541                         }
542
543                 case T_NullTest:
544                         {
545                                 NullTest   *n = (NullTest *) expr;
546
547                                 n->arg = transformExpr(pstate, n->arg);
548                                 /* the argument can be any type, so don't coerce it */
549                                 result = expr;
550                                 break;
551                         }
552
553                 case T_BooleanTest:
554                         {
555                                 BooleanTest *b = (BooleanTest *) expr;
556                                 const char *clausename;
557
558                                 switch (b->booltesttype)
559                                 {
560                                         case IS_TRUE:
561                                                 clausename = "IS TRUE";
562                                                 break;
563                                         case IS_NOT_TRUE:
564                                                 clausename = "IS NOT TRUE";
565                                                 break;
566                                         case IS_FALSE:
567                                                 clausename = "IS FALSE";
568                                                 break;
569                                         case IS_NOT_FALSE:
570                                                 clausename = "IS NOT FALSE";
571                                                 break;
572                                         case IS_UNKNOWN:
573                                                 clausename = "IS UNKNOWN";
574                                                 break;
575                                         case IS_NOT_UNKNOWN:
576                                                 clausename = "IS NOT UNKNOWN";
577                                                 break;
578                                         default:
579                                                 elog(ERROR, "transformExpr: unexpected booltesttype %d",
580                                                          (int) b->booltesttype);
581                                                 clausename = NULL;      /* keep compiler quiet */
582                                 }
583
584                                 b->arg = transformExpr(pstate, b->arg);
585
586                                 b->arg = coerce_to_boolean(b->arg, clausename);
587
588                                 result = expr;
589                                 break;
590                         }
591
592                         /*
593                          * Quietly accept node types that may be presented when we are
594                          * called on an already-transformed tree.
595                          *
596                          * Do any other node types need to be accepted?  For now we are
597                          * taking a conservative approach, and only accepting node
598                          * types that are demonstrably necessary to accept.
599                          */
600                 case T_Expr:
601                 case T_Var:
602                 case T_Const:
603                 case T_Param:
604                 case T_Aggref:
605                 case T_ArrayRef:
606                 case T_FieldSelect:
607                 case T_RelabelType:
608                         {
609                                 result = (Node *) expr;
610                                 break;
611                         }
612
613                 default:
614                         /* should not reach here */
615                         elog(ERROR, "transformExpr: does not know how to transform node %d"
616                                  " (internal error)", nodeTag(expr));
617                         break;
618         }
619
620         expr_depth_counter--;
621
622         return result;
623 }
624
625 static Node *
626 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
627 {
628         if (indirection == NIL)
629                 return basenode;
630         return (Node *) transformArraySubscripts(pstate,
631                                                                                          basenode, exprType(basenode),
632                                                                                          indirection, false, NULL);
633 }
634
635 static Node *
636 transformColumnRef(ParseState *pstate, ColumnRef *cref)
637 {
638         int                     numnames = length(cref->fields);
639         Node       *node;
640         RangeVar   *rv;
641
642         /*----------
643          * The allowed syntaxes are:
644          *
645          * A            First try to resolve as unqualified column name;
646          *                      if no luck, try to resolve as unqual. table name (A.*).
647          * A.B          A is an unqual. table name; B is either a
648          *                      column or function name (trying column name first).
649          * A.B.C        schema A, table B, col or func name C.
650          * A.B.C.D      catalog A, schema B, table C, col or func D.
651          * A.*          A is an unqual. table name; means whole-row value.
652          * A.B.*        whole-row value of table B in schema A.
653          * A.B.C.*      whole-row value of table C in schema B in catalog A.
654          *
655          * We do not need to cope with bare "*"; that will only be accepted by
656          * the grammar at the top level of a SELECT list, and transformTargetList
657          * will take care of it before it ever gets here.
658          *
659          * Currently, if a catalog name is given then it must equal the current
660          * database name; we check it here and then discard it.
661          *
662          * For whole-row references, the result is an untransformed RangeVar,
663          * which will work as the argument to a function call, but not in any
664          * other context at present.  (We could instead coerce to a whole-row Var,
665          * but that will fail for subselect and join RTEs, because there is no
666          * pg_type entry for their rowtypes.)
667          *----------
668          */
669         switch (numnames)
670         {
671                 case 1:
672                 {
673                         char   *name = strVal(lfirst(cref->fields));
674
675                         /* Try to identify as an unqualified column */
676                         node = colnameToVar(pstate, name);
677                         if (node == NULL)
678                         {
679                                 /*
680                                  * Not known as a column of any range-table entry, so
681                                  * try to find the name as a relation ... but not if
682                                  * subscripts appear.  Note also that only relations
683                                  * already entered into the rangetable will be recognized.
684                                  */
685                                 int             levels_up;
686
687                                 if (cref->indirection == NIL &&
688                                         refnameRangeTblEntry(pstate, name, &levels_up) != NULL)
689                                 {
690                                         rv = makeNode(RangeVar);
691                                         rv->relname = name;
692                                         rv->inhOpt = INH_DEFAULT;
693                                         node = (Node *) rv;
694                                 }
695                                 else
696                                         elog(ERROR, "Attribute \"%s\" not found", name);
697                         }
698                         break;
699                 }
700                 case 2:
701                 {
702                         char   *name1 = strVal(lfirst(cref->fields));
703                         char   *name2 = strVal(lsecond(cref->fields));
704
705                         /* Whole-row reference? */
706                         if (strcmp(name2, "*") == 0)
707                         {
708                                 rv = makeNode(RangeVar);
709                                 rv->relname = name1;
710                                 rv->inhOpt = INH_DEFAULT;
711                                 node = (Node *) rv;
712                                 break;
713                         }
714
715                         /* Try to identify as a once-qualified column */
716                         node = qualifiedNameToVar(pstate, name1, name2, true);
717                         if (node == NULL)
718                         {
719                                 /*
720                                  * Not known as a column of any range-table entry, so
721                                  * try it as a function call.  Here, we will create an
722                                  * implicit RTE for tables not already entered.
723                                  */
724                                 rv = makeNode(RangeVar);
725                                 rv->relname = name1;
726                                 rv->inhOpt = INH_DEFAULT;
727                                 node = ParseFuncOrColumn(pstate,
728                                                                                  makeList1(makeString(name2)),
729                                                                                  makeList1(rv),
730                                                                                  false, false, true);
731                         }
732                         break;
733                 }
734                 case 3:
735                 {
736                         char   *name1 = strVal(lfirst(cref->fields));
737                         char   *name2 = strVal(lsecond(cref->fields));
738                         char   *name3 = strVal(lfirst(lnext(lnext(cref->fields))));
739
740                         /* Whole-row reference? */
741                         if (strcmp(name3, "*") == 0)
742                         {
743                                 rv = makeNode(RangeVar);
744                                 rv->schemaname = name1;
745                                 rv->relname = name2;
746                                 rv->inhOpt = INH_DEFAULT;
747                                 node = (Node *) rv;
748                                 break;
749                         }
750
751                         /* Try to identify as a twice-qualified column */
752                         /* XXX do something with schema name here */
753                         node = qualifiedNameToVar(pstate, name2, name3, true);
754                         if (node == NULL)
755                         {
756                                 /* Try it as a function call */
757                                 rv = makeNode(RangeVar);
758                                 rv->schemaname = name1;
759                                 rv->relname = name2;
760                                 rv->inhOpt = INH_DEFAULT;
761                                 node = ParseFuncOrColumn(pstate,
762                                                                                  makeList1(makeString(name3)),
763                                                                                  makeList1(rv),
764                                                                                  false, false, true);
765                         }
766                         break;
767                 }
768                 case 4:
769                 {
770                         char   *name1 = strVal(lfirst(cref->fields));
771                         char   *name2 = strVal(lsecond(cref->fields));
772                         char   *name3 = strVal(lfirst(lnext(lnext(cref->fields))));
773                         char   *name4 = strVal(lfirst(lnext(lnext(lnext(cref->fields)))));
774
775                         /*
776                          * We check the catalog name and then ignore it.
777                          */
778                         if (strcmp(name1, DatabaseName) != 0)
779                                 elog(ERROR, "Cross-database references are not implemented");
780
781                         /* Whole-row reference? */
782                         if (strcmp(name4, "*") == 0)
783                         {
784                                 rv = makeNode(RangeVar);
785                                 rv->schemaname = name2;
786                                 rv->relname = name3;
787                                 rv->inhOpt = INH_DEFAULT;
788                                 node = (Node *) rv;
789                                 break;
790                         }
791
792                         /* Try to identify as a twice-qualified column */
793                         /* XXX do something with schema name here */
794                         node = qualifiedNameToVar(pstate, name3, name4, true);
795                         if (node == NULL)
796                         {
797                                 /* Try it as a function call */
798                                 rv = makeNode(RangeVar);
799                                 rv->schemaname = name2;
800                                 rv->relname = name3;
801                                 rv->inhOpt = INH_DEFAULT;
802                                 node = ParseFuncOrColumn(pstate,
803                                                                                  makeList1(makeString(name4)),
804                                                                                  makeList1(rv),
805                                                                                  false, false, true);
806                         }
807                         break;
808                 }
809                 default:
810                         elog(ERROR, "Invalid qualified name syntax (too many names)");
811                         node = NULL;            /* keep compiler quiet */
812                         break;
813         }
814
815         return transformIndirection(pstate, node, cref->indirection);
816 }
817
818 /*
819  *      exprType -
820  *        returns the Oid of the type of the expression. (Used for typechecking.)
821  */
822 Oid
823 exprType(Node *expr)
824 {
825         Oid                     type = (Oid) InvalidOid;
826
827         if (!expr)
828                 return type;
829
830         switch (nodeTag(expr))
831         {
832                 case T_Var:
833                         type = ((Var *) expr)->vartype;
834                         break;
835                 case T_Expr:
836                         type = ((Expr *) expr)->typeOid;
837                         break;
838                 case T_Const:
839                         type = ((Const *) expr)->consttype;
840                         break;
841                 case T_ArrayRef:
842                         type = ((ArrayRef *) expr)->refelemtype;
843                         break;
844                 case T_Aggref:
845                         type = ((Aggref *) expr)->aggtype;
846                         break;
847                 case T_Param:
848                         type = ((Param *) expr)->paramtype;
849                         break;
850                 case T_FieldSelect:
851                         type = ((FieldSelect *) expr)->resulttype;
852                         break;
853                 case T_RelabelType:
854                         type = ((RelabelType *) expr)->resulttype;
855                         break;
856                 case T_SubLink:
857                         {
858                                 SubLink    *sublink = (SubLink *) expr;
859
860                                 if (sublink->subLinkType == EXPR_SUBLINK)
861                                 {
862                                         /* get the type of the subselect's first target column */
863                                         Query      *qtree = (Query *) sublink->subselect;
864                                         TargetEntry *tent;
865
866                                         if (!qtree || !IsA(qtree, Query))
867                                                 elog(ERROR, "exprType: Cannot get type for untransformed sublink");
868                                         tent = (TargetEntry *) lfirst(qtree->targetList);
869                                         type = tent->resdom->restype;
870                                 }
871                                 else
872                                 {
873                                         /* for all other sublink types, result is boolean */
874                                         type = BOOLOID;
875                                 }
876                         }
877                         break;
878                 case T_CaseExpr:
879                         type = ((CaseExpr *) expr)->casetype;
880                         break;
881                 case T_CaseWhen:
882                         type = exprType(((CaseWhen *) expr)->result);
883                         break;
884                 case T_Constraint:
885                         type = exprType(((Constraint *) expr)->raw_expr);
886                         break;
887                 case T_NullTest:
888                         type = BOOLOID;
889                         break;
890                 case T_BooleanTest:
891                         type = BOOLOID;
892                         break;
893                 default:
894                         elog(ERROR, "exprType: Do not know how to get type for %d node",
895                                  nodeTag(expr));
896                         break;
897         }
898         return type;
899 }
900
901 /*
902  *      exprTypmod -
903  *        returns the type-specific attrmod of the expression, if it can be
904  *        determined.  In most cases, it can't and we return -1.
905  */
906 int32
907 exprTypmod(Node *expr)
908 {
909         if (!expr)
910                 return -1;
911
912         switch (nodeTag(expr))
913         {
914                 case T_Var:
915                         return ((Var *) expr)->vartypmod;
916                 case T_Const:
917                         {
918                                 /* Be smart about string constants... */
919                                 Const      *con = (Const *) expr;
920
921                                 switch (con->consttype)
922                                 {
923                                         case BPCHAROID:
924                                                 if (!con->constisnull)
925                                                         return VARSIZE(DatumGetPointer(con->constvalue));
926                                                 break;
927                                         default:
928                                                 break;
929                                 }
930                         }
931                         break;
932                 case T_Expr:
933                         {
934                                 int32           coercedTypmod;
935
936                                 /* Be smart about length-coercion functions... */
937                                 if (exprIsLengthCoercion(expr, &coercedTypmod))
938                                         return coercedTypmod;
939                         }
940                         break;
941                 case T_FieldSelect:
942                         return ((FieldSelect *) expr)->resulttypmod;
943                         break;
944                 case T_RelabelType:
945                         return ((RelabelType *) expr)->resulttypmod;
946                         break;
947                 case T_CaseExpr:
948                         {
949                                 /*
950                                  * If all the alternatives agree on type/typmod, return
951                                  * that typmod, else use -1
952                                  */
953                                 CaseExpr   *cexpr = (CaseExpr *) expr;
954                                 Oid                     casetype = cexpr->casetype;
955                                 int32           typmod;
956                                 List       *arg;
957
958                                 if (!cexpr->defresult)
959                                         return -1;
960                                 if (exprType(cexpr->defresult) != casetype)
961                                         return -1;
962                                 typmod = exprTypmod(cexpr->defresult);
963                                 if (typmod < 0)
964                                         return -1;      /* no point in trying harder */
965                                 foreach(arg, cexpr->args)
966                                 {
967                                         CaseWhen   *w = (CaseWhen *) lfirst(arg);
968
969                                         Assert(IsA(w, CaseWhen));
970                                         if (exprType(w->result) != casetype)
971                                                 return -1;
972                                         if (exprTypmod(w->result) != typmod)
973                                                 return -1;
974                                 }
975                                 return typmod;
976                         }
977                         break;
978                 default:
979                         break;
980         }
981         return -1;
982 }
983
984 /*
985  * exprIsLengthCoercion
986  *              Detect whether an expression tree is an application of a datatype's
987  *              typmod-coercion function.  Optionally extract the result's typmod.
988  *
989  * If coercedTypmod is not NULL, the typmod is stored there if the expression
990  * is a length-coercion function, else -1 is stored there.
991  *
992  * We assume that a two-argument function named for a datatype, whose
993  * output and first argument types are that datatype, and whose second
994  * input is an int32 constant, represents a forced length coercion.
995  *
996  * XXX It'd be better if the parsetree retained some explicit indication
997  * of the coercion, so we didn't need these heuristics.
998  */
999 bool
1000 exprIsLengthCoercion(Node *expr, int32 *coercedTypmod)
1001 {
1002         Func       *func;
1003         Const      *second_arg;
1004         HeapTuple       procTuple;
1005         HeapTuple       typeTuple;
1006         Form_pg_proc procStruct;
1007         Form_pg_type typeStruct;
1008
1009         if (coercedTypmod != NULL)
1010                 *coercedTypmod = -1;    /* default result on failure */
1011
1012         /* Is it a function-call at all? */
1013         if (expr == NULL ||
1014                 !IsA(expr, Expr) ||
1015                 ((Expr *) expr)->opType != FUNC_EXPR)
1016                 return false;
1017         func = (Func *) (((Expr *) expr)->oper);
1018         Assert(IsA(func, Func));
1019
1020         /*
1021          * If it's not a two-argument function with the second argument being
1022          * an int4 constant, it can't have been created from a length
1023          * coercion.
1024          */
1025         if (length(((Expr *) expr)->args) != 2)
1026                 return false;
1027         second_arg = (Const *) lsecond(((Expr *) expr)->args);
1028         if (!IsA(second_arg, Const) ||
1029                 second_arg->consttype != INT4OID ||
1030                 second_arg->constisnull)
1031                 return false;
1032
1033         /*
1034          * Lookup the function in pg_proc
1035          */
1036         procTuple = SearchSysCache(PROCOID,
1037                                                            ObjectIdGetDatum(func->funcid),
1038                                                            0, 0, 0);
1039         if (!HeapTupleIsValid(procTuple))
1040                 elog(ERROR, "cache lookup for proc %u failed", func->funcid);
1041         procStruct = (Form_pg_proc) GETSTRUCT(procTuple);
1042
1043         /*
1044          * It must be a function with two arguments where the first is of the
1045          * same type as the return value and the second is an int4. Also, just
1046          * to be sure, check return type agrees with expr node.
1047          */
1048         if (procStruct->pronargs != 2 ||
1049                 procStruct->prorettype != procStruct->proargtypes[0] ||
1050                 procStruct->proargtypes[1] != INT4OID ||
1051                 procStruct->prorettype != ((Expr *) expr)->typeOid)
1052         {
1053                 ReleaseSysCache(procTuple);
1054                 return false;
1055         }
1056
1057         /*
1058          * Furthermore, the name and namespace of the function must be the same
1059          * as its result type's name/namespace (cf. find_coercion_function).
1060          */
1061         typeTuple = SearchSysCache(TYPEOID,
1062                                                            ObjectIdGetDatum(procStruct->prorettype),
1063                                                            0, 0, 0);
1064         if (!HeapTupleIsValid(typeTuple))
1065                 elog(ERROR, "cache lookup for type %u failed",
1066                          procStruct->prorettype);
1067         typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
1068         if (strcmp(NameStr(procStruct->proname),
1069                            NameStr(typeStruct->typname)) != 0 ||
1070                 procStruct->pronamespace != typeStruct->typnamespace)
1071         {
1072                 ReleaseSysCache(procTuple);
1073                 ReleaseSysCache(typeTuple);
1074                 return false;
1075         }
1076
1077         /*
1078          * OK, it is indeed a length-coercion function.
1079          */
1080         if (coercedTypmod != NULL)
1081                 *coercedTypmod = DatumGetInt32(second_arg->constvalue);
1082
1083         ReleaseSysCache(procTuple);
1084         ReleaseSysCache(typeTuple);
1085         return true;
1086 }
1087
1088 /*
1089  * Produce an appropriate Const node from a constant value produced
1090  * by the parser and an explicit type name to cast to.
1091  */
1092 static Node *
1093 parser_typecast_constant(Value *expr, TypeName *typename)
1094 {
1095         Type            tp;
1096         Datum           datum;
1097         Const      *con;
1098         char       *const_string = NULL;
1099         bool            string_palloced = false;
1100         bool            isNull = false;
1101
1102         tp = typenameType(typename);
1103
1104         switch (nodeTag(expr))
1105         {
1106                 case T_Integer:
1107                         const_string = DatumGetCString(DirectFunctionCall1(int4out,
1108                                                                                  Int32GetDatum(expr->val.ival)));
1109                         string_palloced = true;
1110                         break;
1111                 case T_Float:
1112                 case T_String:
1113                 case T_BitString:
1114                         const_string = expr->val.str;
1115                         break;
1116                 case T_Null:
1117                         isNull = true;
1118                         break;
1119                 default:
1120                         elog(ERROR, "Cannot cast this expression to type '%s'",
1121                                  typeTypeName(tp));
1122         }
1123
1124         if (isNull)
1125                 datum = (Datum) NULL;
1126         else
1127                 datum = stringTypeDatum(tp, const_string, typename->typmod);
1128
1129         con = makeConst(typeTypeId(tp),
1130                                         typeLen(tp),
1131                                         datum,
1132                                         isNull,
1133                                         typeByVal(tp),
1134                                         false,          /* not a set */
1135                                         true /* is cast */ );
1136
1137         if (string_palloced)
1138                 pfree(const_string);
1139
1140         ReleaseSysCache(tp);
1141
1142         return (Node *) con;
1143 }
1144
1145 /*
1146  * Handle an explicit CAST applied to a non-constant expression.
1147  * (Actually, this works for constants too, but gram.y won't generate
1148  * a TypeCast node if the argument is just a constant.)
1149  *
1150  * The given expr has already been transformed, but we need to lookup
1151  * the type name and then apply any necessary coercion function(s).
1152  */
1153 static Node *
1154 parser_typecast_expression(ParseState *pstate,
1155                                                    Node *expr, TypeName *typename)
1156 {
1157         Oid                     inputType = exprType(expr);
1158         Oid                     targetType;
1159
1160         targetType = typenameTypeId(typename);
1161
1162         if (inputType == InvalidOid)
1163                 return expr;                    /* do nothing if NULL input */
1164
1165         if (inputType != targetType)
1166         {
1167                 expr = CoerceTargetExpr(pstate, expr, inputType,
1168                                                                 targetType, typename->typmod,
1169                                                                 true); /* explicit coercion */
1170                 if (expr == NULL)
1171                         elog(ERROR, "Cannot cast type '%s' to '%s'",
1172                                  format_type_be(inputType),
1173                                  format_type_be(targetType));
1174         }
1175
1176         /*
1177          * If the target is a fixed-length type, it may need a length coercion
1178          * as well as a type coercion.
1179          */
1180         expr = coerce_type_typmod(pstate, expr,
1181                                                           targetType, typename->typmod);
1182
1183         return expr;
1184 }