]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_expr.c
Add an "argisrow" field to NullTest nodes, following a plan made way back in
[postgresql] / src / backend / parser / parse_expr.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_expr.c
4  *        handle expressions in parser
5  *
6  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.252 2010/01/01 23:03:10 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include "catalog/pg_type.h"
19 #include "commands/dbcommands.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/var.h"
24 #include "parser/analyze.h"
25 #include "parser/parse_coerce.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_func.h"
28 #include "parser/parse_oper.h"
29 #include "parser/parse_relation.h"
30 #include "parser/parse_target.h"
31 #include "parser/parse_type.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/xml.h"
35
36
37 bool            Transform_null_equals = false;
38
39 static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
40 static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
41 static Node *transformAExprAnd(ParseState *pstate, A_Expr *a);
42 static Node *transformAExprOr(ParseState *pstate, A_Expr *a);
43 static Node *transformAExprNot(ParseState *pstate, A_Expr *a);
44 static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
45 static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
46 static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
47 static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
48 static Node *transformAExprOf(ParseState *pstate, A_Expr *a);
49 static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
50 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
51 static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
52 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
53 static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
54                                    Oid array_type, Oid element_type, int32 typmod);
55 static Node *transformRowExpr(ParseState *pstate, RowExpr *r);
56 static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
57 static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
58 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
59 static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
60 static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
61 static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
62 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
63 static Node *transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte,
64                                                                   int location);
65 static Node *transformIndirection(ParseState *pstate, Node *basenode,
66                                          List *indirection);
67 static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
68 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
69                                            List *largs, List *rargs, int location);
70 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
71                                          RowExpr *lrow, RowExpr *rrow, int location);
72 static Expr *make_distinct_op(ParseState *pstate, List *opname,
73                                  Node *ltree, Node *rtree, int location);
74
75
76 /*
77  * transformExpr -
78  *        Analyze and transform expressions. Type checking and type casting is
79  *        done here. The optimizer and the executor cannot handle the original
80  *        (raw) expressions collected by the parse tree. Hence the transformation
81  *        here.
82  *
83  * NOTE: there are various cases in which this routine will get applied to
84  * an already-transformed expression.  Some examples:
85  *      1. At least one construct (BETWEEN/AND) puts the same nodes
86  *      into two branches of the parse tree; hence, some nodes
87  *      are transformed twice.
88  *      2. Another way it can happen is that coercion of an operator or
89  *      function argument to the required type (via coerce_type())
90  *      can apply transformExpr to an already-transformed subexpression.
91  *      An example here is "SELECT count(*) + 1.0 FROM table".
92  * While it might be possible to eliminate these cases, the path of
93  * least resistance so far has been to ensure that transformExpr() does
94  * no damage if applied to an already-transformed tree.  This is pretty
95  * easy for cases where the transformation replaces one node type with
96  * another, such as A_Const => Const; we just do nothing when handed
97  * a Const.  More care is needed for node types that are used as both
98  * input and output of transformExpr; see SubLink for example.
99  */
100 Node *
101 transformExpr(ParseState *pstate, Node *expr)
102 {
103         Node       *result = NULL;
104
105         if (expr == NULL)
106                 return NULL;
107
108         /* Guard against stack overflow due to overly complex expressions */
109         check_stack_depth();
110
111         switch (nodeTag(expr))
112         {
113                 case T_ColumnRef:
114                         result = transformColumnRef(pstate, (ColumnRef *) expr);
115                         break;
116
117                 case T_ParamRef:
118                         result = transformParamRef(pstate, (ParamRef *) expr);
119                         break;
120
121                 case T_A_Const:
122                         {
123                                 A_Const    *con = (A_Const *) expr;
124                                 Value      *val = &con->val;
125
126                                 result = (Node *) make_const(pstate, val, con->location);
127                                 break;
128                         }
129
130                 case T_A_Indirection:
131                         {
132                                 A_Indirection *ind = (A_Indirection *) expr;
133
134                                 result = transformExpr(pstate, ind->arg);
135                                 result = transformIndirection(pstate, result,
136                                                                                           ind->indirection);
137                                 break;
138                         }
139
140                 case T_A_ArrayExpr:
141                         result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
142                                                                                 InvalidOid, InvalidOid, -1);
143                         break;
144
145                 case T_TypeCast:
146                         {
147                                 TypeCast   *tc = (TypeCast *) expr;
148
149                                 /*
150                                  * If the subject of the typecast is an ARRAY[] construct and
151                                  * the target type is an array type, we invoke
152                                  * transformArrayExpr() directly so that we can pass down the
153                                  * type information.  This avoids some cases where
154                                  * transformArrayExpr() might not infer the correct type.
155                                  */
156                                 if (IsA(tc->arg, A_ArrayExpr))
157                                 {
158                                         Oid                     targetType;
159                                         Oid                     elementType;
160                                         int32           targetTypmod;
161
162                                         targetType = typenameTypeId(pstate, tc->typeName,
163                                                                                                 &targetTypmod);
164                                         elementType = get_element_type(targetType);
165                                         if (OidIsValid(elementType))
166                                         {
167                                                 /*
168                                                  * tranformArrayExpr doesn't know how to check domain
169                                                  * constraints, so ask it to return the base type
170                                                  * instead. transformTypeCast below will cast it to
171                                                  * the domain. In the usual case that the target is
172                                                  * not a domain, transformTypeCast is a no-op.
173                                                  */
174                                                 targetType = getBaseTypeAndTypmod(targetType,
175                                                                                                                  &targetTypmod);
176                                                         
177                                                 tc = copyObject(tc);
178                                                 tc->arg = transformArrayExpr(pstate,
179                                                                                                          (A_ArrayExpr *) tc->arg,
180                                                                                                          targetType,
181                                                                                                          elementType,
182                                                                                                          targetTypmod);
183                                         }
184                                 }
185
186                                 result = transformTypeCast(pstate, tc);
187                                 break;
188                         }
189
190                 case T_A_Expr:
191                         {
192                                 A_Expr     *a = (A_Expr *) expr;
193
194                                 switch (a->kind)
195                                 {
196                                         case AEXPR_OP:
197                                                 result = transformAExprOp(pstate, a);
198                                                 break;
199                                         case AEXPR_AND:
200                                                 result = transformAExprAnd(pstate, a);
201                                                 break;
202                                         case AEXPR_OR:
203                                                 result = transformAExprOr(pstate, a);
204                                                 break;
205                                         case AEXPR_NOT:
206                                                 result = transformAExprNot(pstate, a);
207                                                 break;
208                                         case AEXPR_OP_ANY:
209                                                 result = transformAExprOpAny(pstate, a);
210                                                 break;
211                                         case AEXPR_OP_ALL:
212                                                 result = transformAExprOpAll(pstate, a);
213                                                 break;
214                                         case AEXPR_DISTINCT:
215                                                 result = transformAExprDistinct(pstate, a);
216                                                 break;
217                                         case AEXPR_NULLIF:
218                                                 result = transformAExprNullIf(pstate, a);
219                                                 break;
220                                         case AEXPR_OF:
221                                                 result = transformAExprOf(pstate, a);
222                                                 break;
223                                         case AEXPR_IN:
224                                                 result = transformAExprIn(pstate, a);
225                                                 break;
226                                         default:
227                                                 elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
228                                 }
229                                 break;
230                         }
231
232                 case T_FuncCall:
233                         result = transformFuncCall(pstate, (FuncCall *) expr);
234                         break;
235
236                 case T_NamedArgExpr:
237                         {
238                                 NamedArgExpr *na = (NamedArgExpr *) expr;
239
240                                 na->arg = (Expr *) transformExpr(pstate, (Node *) na->arg);
241                                 result = expr;
242                                 break;
243                         }
244
245                 case T_SubLink:
246                         result = transformSubLink(pstate, (SubLink *) expr);
247                         break;
248
249                 case T_CaseExpr:
250                         result = transformCaseExpr(pstate, (CaseExpr *) expr);
251                         break;
252
253                 case T_RowExpr:
254                         result = transformRowExpr(pstate, (RowExpr *) expr);
255                         break;
256
257                 case T_CoalesceExpr:
258                         result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
259                         break;
260
261                 case T_MinMaxExpr:
262                         result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
263                         break;
264
265                 case T_XmlExpr:
266                         result = transformXmlExpr(pstate, (XmlExpr *) expr);
267                         break;
268
269                 case T_XmlSerialize:
270                         result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
271                         break;
272
273                 case T_NullTest:
274                         {
275                                 NullTest   *n = (NullTest *) expr;
276
277                                 n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
278                                 /* the argument can be any type, so don't coerce it */
279                                 n->argisrow = type_is_rowtype(exprType((Node *) n->arg));
280                                 result = expr;
281                                 break;
282                         }
283
284                 case T_BooleanTest:
285                         result = transformBooleanTest(pstate, (BooleanTest *) expr);
286                         break;
287
288                 case T_CurrentOfExpr:
289                         result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
290                         break;
291
292                         /*********************************************
293                          * Quietly accept node types that may be presented when we are
294                          * called on an already-transformed tree.
295                          *
296                          * Do any other node types need to be accepted?  For now we are
297                          * taking a conservative approach, and only accepting node
298                          * types that are demonstrably necessary to accept.
299                          *********************************************/
300                 case T_Var:
301                 case T_Const:
302                 case T_Param:
303                 case T_Aggref:
304                 case T_WindowFunc:
305                 case T_ArrayRef:
306                 case T_FuncExpr:
307                 case T_OpExpr:
308                 case T_DistinctExpr:
309                 case T_ScalarArrayOpExpr:
310                 case T_NullIfExpr:
311                 case T_BoolExpr:
312                 case T_FieldSelect:
313                 case T_FieldStore:
314                 case T_RelabelType:
315                 case T_CoerceViaIO:
316                 case T_ArrayCoerceExpr:
317                 case T_ConvertRowtypeExpr:
318                 case T_CaseTestExpr:
319                 case T_ArrayExpr:
320                 case T_CoerceToDomain:
321                 case T_CoerceToDomainValue:
322                 case T_SetToDefault:
323                         {
324                                 result = (Node *) expr;
325                                 break;
326                         }
327
328                 default:
329                         /* should not reach here */
330                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
331                         break;
332         }
333
334         return result;
335 }
336
337 /*
338  * helper routine for delivering "column does not exist" error message
339  *
340  * (Usually we don't have to work this hard, but the general case of field
341  * selection from an arbitrary node needs it.)
342  */
343 static void
344 unknown_attribute(ParseState *pstate, Node *relref, char *attname,
345                                   int location)
346 {
347         RangeTblEntry *rte;
348
349         if (IsA(relref, Var) &&
350                 ((Var *) relref)->varattno == InvalidAttrNumber)
351         {
352                 /* Reference the RTE by alias not by actual table name */
353                 rte = GetRTEByRangeTablePosn(pstate,
354                                                                          ((Var *) relref)->varno,
355                                                                          ((Var *) relref)->varlevelsup);
356                 ereport(ERROR,
357                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
358                                  errmsg("column %s.%s does not exist",
359                                                 rte->eref->aliasname, attname),
360                                  parser_errposition(pstate, location)));
361         }
362         else
363         {
364                 /* Have to do it by reference to the type of the expression */
365                 Oid                     relTypeId = exprType(relref);
366
367                 if (ISCOMPLEX(relTypeId))
368                         ereport(ERROR,
369                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
370                                          errmsg("column \"%s\" not found in data type %s",
371                                                         attname, format_type_be(relTypeId)),
372                                          parser_errposition(pstate, location)));
373                 else if (relTypeId == RECORDOID)
374                         ereport(ERROR,
375                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
376                            errmsg("could not identify column \"%s\" in record data type",
377                                           attname),
378                                          parser_errposition(pstate, location)));
379                 else
380                         ereport(ERROR,
381                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
382                                          errmsg("column notation .%s applied to type %s, "
383                                                         "which is not a composite type",
384                                                         attname, format_type_be(relTypeId)),
385                                          parser_errposition(pstate, location)));
386         }
387 }
388
389 static Node *
390 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
391 {
392         Node       *result = basenode;
393         List       *subscripts = NIL;
394         int                     location = exprLocation(basenode);
395         ListCell   *i;
396
397         /*
398          * We have to split any field-selection operations apart from
399          * subscripting.  Adjacent A_Indices nodes have to be treated as a single
400          * multidimensional subscript operation.
401          */
402         foreach(i, indirection)
403         {
404                 Node       *n = lfirst(i);
405
406                 if (IsA(n, A_Indices))
407                         subscripts = lappend(subscripts, n);
408                 else if (IsA(n, A_Star))
409                 {
410                         ereport(ERROR,
411                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
412                                          errmsg("row expansion via \"*\" is not supported here"),
413                                          parser_errposition(pstate, location)));
414                 }
415                 else
416                 {
417                         Node       *newresult;
418
419                         Assert(IsA(n, String));
420
421                         /* process subscripts before this field selection */
422                         if (subscripts)
423                                 result = (Node *) transformArraySubscripts(pstate,
424                                                                                                                    result,
425                                                                                                                    exprType(result),
426                                                                                                                    InvalidOid,
427                                                                                                                    exprTypmod(result),
428                                                                                                                    subscripts,
429                                                                                                                    NULL);
430                         subscripts = NIL;
431
432                         newresult = ParseFuncOrColumn(pstate,
433                                                                                   list_make1(n),
434                                                                                   list_make1(result),
435                                                                                   NIL, false, false, false,
436                                                                                   NULL, true, location);
437                         if (newresult == NULL)
438                                 unknown_attribute(pstate, result, strVal(n), location);
439                         result = newresult;
440                 }
441         }
442         /* process trailing subscripts, if any */
443         if (subscripts)
444                 result = (Node *) transformArraySubscripts(pstate,
445                                                                                                    result,
446                                                                                                    exprType(result),
447                                                                                                    InvalidOid,
448                                                                                                    exprTypmod(result),
449                                                                                                    subscripts,
450                                                                                                    NULL);
451
452         return result;
453 }
454
455 /*
456  * Transform a ColumnRef.
457  *
458  * If you find yourself changing this code, see also ExpandColumnRefStar.
459  */
460 static Node *
461 transformColumnRef(ParseState *pstate, ColumnRef *cref)
462 {
463         Node       *node = NULL;
464         char       *nspname = NULL;
465         char       *relname = NULL;
466         char       *colname = NULL;
467         RangeTblEntry *rte;
468         int                     levels_up;
469         enum {
470                 CRERR_NO_COLUMN,
471                 CRERR_NO_RTE,
472                 CRERR_WRONG_DB,
473                 CRERR_TOO_MANY
474         }                       crerr = CRERR_NO_COLUMN;
475
476         /*
477          * Give the PreParseColumnRefHook, if any, first shot.  If it returns
478          * non-null then that's all, folks.
479          */
480         if (pstate->p_pre_columnref_hook != NULL)
481         {
482                 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
483                 if (node != NULL)
484                         return node;
485         }
486
487         /*----------
488          * The allowed syntaxes are:
489          *
490          * A            First try to resolve as unqualified column name;
491          *                      if no luck, try to resolve as unqualified table name (A.*).
492          * A.B          A is an unqualified table name; B is either a
493          *                      column or function name (trying column name first).
494          * A.B.C        schema A, table B, col or func name C.
495          * A.B.C.D      catalog A, schema B, table C, col or func D.
496          * A.*          A is an unqualified table name; means whole-row value.
497          * A.B.*        whole-row value of table B in schema A.
498          * A.B.C.*      whole-row value of table C in schema B in catalog A.
499          *
500          * We do not need to cope with bare "*"; that will only be accepted by
501          * the grammar at the top level of a SELECT list, and transformTargetList
502          * will take care of it before it ever gets here.  Also, "A.*" etc will
503          * be expanded by transformTargetList if they appear at SELECT top level,
504          * so here we are only going to see them as function or operator inputs.
505          *
506          * Currently, if a catalog name is given then it must equal the current
507          * database name; we check it here and then discard it.
508          *----------
509          */
510         switch (list_length(cref->fields))
511         {
512                 case 1:
513                         {
514                                 Node       *field1 = (Node *) linitial(cref->fields);
515
516                                 Assert(IsA(field1, String));
517                                 colname = strVal(field1);
518
519                                 /* Try to identify as an unqualified column */
520                                 node = colNameToVar(pstate, colname, false, cref->location);
521
522                                 if (node == NULL)
523                                 {
524                                         /*
525                                          * Not known as a column of any range-table entry.
526                                          *
527                                          * Consider the possibility that it's VALUE in a domain
528                                          * check expression.  (We handle VALUE as a name, not a
529                                          * keyword, to avoid breaking a lot of applications that
530                                          * have used VALUE as a column name in the past.)
531                                          */
532                                         if (pstate->p_value_substitute != NULL &&
533                                                 strcmp(colname, "value") == 0)
534                                         {
535                                                 node = (Node *) copyObject(pstate->p_value_substitute);
536
537                                                 /*
538                                                  * Try to propagate location knowledge.  This should
539                                                  * be extended if p_value_substitute can ever take on
540                                                  * other node types.
541                                                  */
542                                                 if (IsA(node, CoerceToDomainValue))
543                                                         ((CoerceToDomainValue *) node)->location = cref->location;
544                                                 break;
545                                         }
546
547                                         /*
548                                          * Try to find the name as a relation.  Note that only
549                                          * relations already entered into the rangetable will be
550                                          * recognized.
551                                          *
552                                          * This is a hack for backwards compatibility with
553                                          * PostQUEL-inspired syntax.  The preferred form now is
554                                          * "rel.*".
555                                          */
556                                         rte = refnameRangeTblEntry(pstate, NULL, colname,
557                                                                                            cref->location,
558                                                                                            &levels_up);
559                                         if (rte)
560                                                 node = transformWholeRowRef(pstate, rte,
561                                                                                                         cref->location);
562                                 }
563                                 break;
564                         }
565                 case 2:
566                         {
567                                 Node       *field1 = (Node *) linitial(cref->fields);
568                                 Node       *field2 = (Node *) lsecond(cref->fields);
569
570                                 Assert(IsA(field1, String));
571                                 relname = strVal(field1);
572
573                                 /* Locate the referenced RTE */
574                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
575                                                                                    cref->location,
576                                                                                    &levels_up);
577                                 if (rte == NULL)
578                                 {
579                                         crerr = CRERR_NO_RTE;
580                                         break;
581                                 }
582
583                                 /* Whole-row reference? */
584                                 if (IsA(field2, A_Star))
585                                 {
586                                         node = transformWholeRowRef(pstate, rte, cref->location);
587                                         break;
588                                 }
589
590                                 Assert(IsA(field2, String));
591                                 colname = strVal(field2);
592
593                                 /* Try to identify as a column of the RTE */
594                                 node = scanRTEForColumn(pstate, rte, colname, cref->location);
595                                 if (node == NULL)
596                                 {
597                                         /* Try it as a function call on the whole row */
598                                         node = transformWholeRowRef(pstate, rte, cref->location);
599                                         node = ParseFuncOrColumn(pstate,
600                                                                                          list_make1(makeString(colname)),
601                                                                                          list_make1(node),
602                                                                                          NIL, false, false, false,
603                                                                                          NULL, true, cref->location);
604                                 }
605                                 break;
606                         }
607                 case 3:
608                         {
609                                 Node       *field1 = (Node *) linitial(cref->fields);
610                                 Node       *field2 = (Node *) lsecond(cref->fields);
611                                 Node       *field3 = (Node *) lthird(cref->fields);
612
613                                 Assert(IsA(field1, String));
614                                 nspname = strVal(field1);
615                                 Assert(IsA(field2, String));
616                                 relname = strVal(field2);
617
618                                 /* Locate the referenced RTE */
619                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
620                                                                                    cref->location,
621                                                                                    &levels_up);
622                                 if (rte == NULL)
623                                 {
624                                         crerr = CRERR_NO_RTE;
625                                         break;
626                                 }
627
628                                 /* Whole-row reference? */
629                                 if (IsA(field3, A_Star))
630                                 {
631                                         node = transformWholeRowRef(pstate, rte, cref->location);
632                                         break;
633                                 }
634
635                                 Assert(IsA(field3, String));
636                                 colname = strVal(field3);
637
638                                 /* Try to identify as a column of the RTE */
639                                 node = scanRTEForColumn(pstate, rte, colname, cref->location);
640                                 if (node == NULL)
641                                 {
642                                         /* Try it as a function call on the whole row */
643                                         node = transformWholeRowRef(pstate, rte, cref->location);
644                                         node = ParseFuncOrColumn(pstate,
645                                                                                          list_make1(makeString(colname)),
646                                                                                          list_make1(node),
647                                                                                          NIL, false, false, false,
648                                                                                          NULL, true, cref->location);
649                                 }
650                                 break;
651                         }
652                 case 4:
653                         {
654                                 Node       *field1 = (Node *) linitial(cref->fields);
655                                 Node       *field2 = (Node *) lsecond(cref->fields);
656                                 Node       *field3 = (Node *) lthird(cref->fields);
657                                 Node       *field4 = (Node *) lfourth(cref->fields);
658                                 char       *catname;
659
660                                 Assert(IsA(field1, String));
661                                 catname = strVal(field1);
662                                 Assert(IsA(field2, String));
663                                 nspname = strVal(field2);
664                                 Assert(IsA(field3, String));
665                                 relname = strVal(field3);
666
667                                 /*
668                                  * We check the catalog name and then ignore it.
669                                  */
670                                 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
671                                 {
672                                         crerr = CRERR_WRONG_DB;
673                                         break;
674                                 }
675
676                                 /* Locate the referenced RTE */
677                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
678                                                                                    cref->location,
679                                                                                    &levels_up);
680                                 if (rte == NULL)
681                                 {
682                                         crerr = CRERR_NO_RTE;
683                                         break;
684                                 }
685
686                                 /* Whole-row reference? */
687                                 if (IsA(field4, A_Star))
688                                 {
689                                         node = transformWholeRowRef(pstate, rte, cref->location);
690                                         break;
691                                 }
692
693                                 Assert(IsA(field4, String));
694                                 colname = strVal(field4);
695
696                                 /* Try to identify as a column of the RTE */
697                                 node = scanRTEForColumn(pstate, rte, colname, cref->location);
698                                 if (node == NULL)
699                                 {
700                                         /* Try it as a function call on the whole row */
701                                         node = transformWholeRowRef(pstate, rte, cref->location);
702                                         node = ParseFuncOrColumn(pstate,
703                                                                                          list_make1(makeString(colname)),
704                                                                                          list_make1(node),
705                                                                                          NIL, false, false, false,
706                                                                                          NULL, true, cref->location);
707                                 }
708                                 break;
709                         }
710                 default:
711                         crerr = CRERR_TOO_MANY;                 /* too many dotted names */
712                         break;
713         }
714
715         /*
716          * Now give the PostParseColumnRefHook, if any, a chance.  We pass the
717          * translation-so-far so that it can throw an error if it wishes in the
718          * case that it has a conflicting interpretation of the ColumnRef.
719          * (If it just translates anyway, we'll throw an error, because we can't
720          * undo whatever effects the preceding steps may have had on the pstate.)
721          * If it returns NULL, use the standard translation, or throw a suitable
722          * error if there is none.
723          */
724         if (pstate->p_post_columnref_hook != NULL)
725         {
726                 Node   *hookresult;
727
728                 hookresult = (*pstate->p_post_columnref_hook) (pstate, cref, node);
729                 if (node == NULL)
730                         node = hookresult;
731                 else if (hookresult != NULL)
732                         ereport(ERROR,
733                                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
734                                          errmsg("column reference \"%s\" is ambiguous",
735                                                         NameListToString(cref->fields)),
736                                          parser_errposition(pstate, cref->location)));
737         }
738
739         /*
740          * Throw error if no translation found.
741          */
742         if (node == NULL)
743         {
744                 switch (crerr)
745                 {
746                         case CRERR_NO_COLUMN:
747                                 if (relname)
748                                         ereport(ERROR,
749                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
750                                                          errmsg("column %s.%s does not exist",
751                                                                         relname, colname),
752                                                          parser_errposition(pstate, cref->location)));
753
754                                 else
755                                         ereport(ERROR,
756                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
757                                                          errmsg("column \"%s\" does not exist",
758                                                                         colname),
759                                                          parser_errposition(pstate, cref->location)));
760                                 break;
761                         case CRERR_NO_RTE:
762                                 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
763                                                                                                          cref->location));
764                                 break;
765                         case CRERR_WRONG_DB:
766                                 ereport(ERROR,
767                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768                                                  errmsg("cross-database references are not implemented: %s",
769                                                                 NameListToString(cref->fields)),
770                                                  parser_errposition(pstate, cref->location)));
771                                 break;
772                         case CRERR_TOO_MANY:
773                                 ereport(ERROR,
774                                                 (errcode(ERRCODE_SYNTAX_ERROR),
775                                                  errmsg("improper qualified name (too many dotted names): %s",
776                                                                 NameListToString(cref->fields)),
777                                                  parser_errposition(pstate, cref->location)));
778                                 break;
779                 }
780         }
781
782         return node;
783 }
784
785 static Node *
786 transformParamRef(ParseState *pstate, ParamRef *pref)
787 {
788         Node       *result;
789
790         /*
791          * The core parser knows nothing about Params.  If a hook is supplied,
792          * call it.  If not, or if the hook returns NULL, throw a generic error.
793          */
794         if (pstate->p_paramref_hook != NULL)
795                 result = (*pstate->p_paramref_hook) (pstate, pref);
796         else
797                 result = NULL;
798
799         if (result == NULL)
800                 ereport(ERROR,
801                                 (errcode(ERRCODE_UNDEFINED_PARAMETER),
802                                  errmsg("there is no parameter $%d", pref->number),
803                                  parser_errposition(pstate, pref->location)));
804
805         return result;
806 }
807
808 /* Test whether an a_expr is a plain NULL constant or not */
809 static bool
810 exprIsNullConstant(Node *arg)
811 {
812         if (arg && IsA(arg, A_Const))
813         {
814                 A_Const    *con = (A_Const *) arg;
815
816                 if (con->val.type == T_Null)
817                         return true;
818         }
819         return false;
820 }
821
822 static Node *
823 transformAExprOp(ParseState *pstate, A_Expr *a)
824 {
825         Node       *lexpr = a->lexpr;
826         Node       *rexpr = a->rexpr;
827         Node       *result;
828
829         /*
830          * Special-case "foo = NULL" and "NULL = foo" for compatibility with
831          * standards-broken products (like Microsoft's).  Turn these into IS NULL
832          * exprs.
833          */
834         if (Transform_null_equals &&
835                 list_length(a->name) == 1 &&
836                 strcmp(strVal(linitial(a->name)), "=") == 0 &&
837                 (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)))
838         {
839                 NullTest   *n = makeNode(NullTest);
840
841                 n->nulltesttype = IS_NULL;
842
843                 if (exprIsNullConstant(lexpr))
844                         n->arg = (Expr *) rexpr;
845                 else
846                         n->arg = (Expr *) lexpr;
847
848                 result = transformExpr(pstate, (Node *) n);
849         }
850         else if (lexpr && IsA(lexpr, RowExpr) &&
851                          rexpr && IsA(rexpr, SubLink) &&
852                          ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
853         {
854                 /*
855                  * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
856                  * grammar did this, but now that a row construct is allowed anywhere
857                  * in expressions, it's easier to do it here.
858                  */
859                 SubLink    *s = (SubLink *) rexpr;
860
861                 s->subLinkType = ROWCOMPARE_SUBLINK;
862                 s->testexpr = lexpr;
863                 s->operName = a->name;
864                 s->location = a->location;
865                 result = transformExpr(pstate, (Node *) s);
866         }
867         else if (lexpr && IsA(lexpr, RowExpr) &&
868                          rexpr && IsA(rexpr, RowExpr))
869         {
870                 /* "row op row" */
871                 lexpr = transformExpr(pstate, lexpr);
872                 rexpr = transformExpr(pstate, rexpr);
873                 Assert(IsA(lexpr, RowExpr));
874                 Assert(IsA(rexpr, RowExpr));
875
876                 result = make_row_comparison_op(pstate,
877                                                                                 a->name,
878                                                                                 ((RowExpr *) lexpr)->args,
879                                                                                 ((RowExpr *) rexpr)->args,
880                                                                                 a->location);
881         }
882         else
883         {
884                 /* Ordinary scalar operator */
885                 lexpr = transformExpr(pstate, lexpr);
886                 rexpr = transformExpr(pstate, rexpr);
887
888                 result = (Node *) make_op(pstate,
889                                                                   a->name,
890                                                                   lexpr,
891                                                                   rexpr,
892                                                                   a->location);
893         }
894
895         return result;
896 }
897
898 static Node *
899 transformAExprAnd(ParseState *pstate, A_Expr *a)
900 {
901         Node       *lexpr = transformExpr(pstate, a->lexpr);
902         Node       *rexpr = transformExpr(pstate, a->rexpr);
903
904         lexpr = coerce_to_boolean(pstate, lexpr, "AND");
905         rexpr = coerce_to_boolean(pstate, rexpr, "AND");
906
907         return (Node *) makeBoolExpr(AND_EXPR,
908                                                                  list_make2(lexpr, rexpr),
909                                                                  a->location);
910 }
911
912 static Node *
913 transformAExprOr(ParseState *pstate, A_Expr *a)
914 {
915         Node       *lexpr = transformExpr(pstate, a->lexpr);
916         Node       *rexpr = transformExpr(pstate, a->rexpr);
917
918         lexpr = coerce_to_boolean(pstate, lexpr, "OR");
919         rexpr = coerce_to_boolean(pstate, rexpr, "OR");
920
921         return (Node *) makeBoolExpr(OR_EXPR,
922                                                                  list_make2(lexpr, rexpr),
923                                                                  a->location);
924 }
925
926 static Node *
927 transformAExprNot(ParseState *pstate, A_Expr *a)
928 {
929         Node       *rexpr = transformExpr(pstate, a->rexpr);
930
931         rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
932
933         return (Node *) makeBoolExpr(NOT_EXPR,
934                                                                  list_make1(rexpr),
935                                                                  a->location);
936 }
937
938 static Node *
939 transformAExprOpAny(ParseState *pstate, A_Expr *a)
940 {
941         Node       *lexpr = transformExpr(pstate, a->lexpr);
942         Node       *rexpr = transformExpr(pstate, a->rexpr);
943
944         return (Node *) make_scalar_array_op(pstate,
945                                                                                  a->name,
946                                                                                  true,
947                                                                                  lexpr,
948                                                                                  rexpr,
949                                                                                  a->location);
950 }
951
952 static Node *
953 transformAExprOpAll(ParseState *pstate, A_Expr *a)
954 {
955         Node       *lexpr = transformExpr(pstate, a->lexpr);
956         Node       *rexpr = transformExpr(pstate, a->rexpr);
957
958         return (Node *) make_scalar_array_op(pstate,
959                                                                                  a->name,
960                                                                                  false,
961                                                                                  lexpr,
962                                                                                  rexpr,
963                                                                                  a->location);
964 }
965
966 static Node *
967 transformAExprDistinct(ParseState *pstate, A_Expr *a)
968 {
969         Node       *lexpr = transformExpr(pstate, a->lexpr);
970         Node       *rexpr = transformExpr(pstate, a->rexpr);
971
972         if (lexpr && IsA(lexpr, RowExpr) &&
973                 rexpr && IsA(rexpr, RowExpr))
974         {
975                 /* "row op row" */
976                 return make_row_distinct_op(pstate, a->name,
977                                                                         (RowExpr *) lexpr,
978                                                                         (RowExpr *) rexpr,
979                                                                         a->location);
980         }
981         else
982         {
983                 /* Ordinary scalar operator */
984                 return (Node *) make_distinct_op(pstate,
985                                                                                  a->name,
986                                                                                  lexpr,
987                                                                                  rexpr,
988                                                                                  a->location);
989         }
990 }
991
992 static Node *
993 transformAExprNullIf(ParseState *pstate, A_Expr *a)
994 {
995         Node       *lexpr = transformExpr(pstate, a->lexpr);
996         Node       *rexpr = transformExpr(pstate, a->rexpr);
997         Node       *result;
998
999         result = (Node *) make_op(pstate,
1000                                                           a->name,
1001                                                           lexpr,
1002                                                           rexpr,
1003                                                           a->location);
1004         if (((OpExpr *) result)->opresulttype != BOOLOID)
1005                 ereport(ERROR,
1006                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1007                                  errmsg("NULLIF requires = operator to yield boolean"),
1008                                  parser_errposition(pstate, a->location)));
1009
1010         /*
1011          * We rely on NullIfExpr and OpExpr being the same struct
1012          */
1013         NodeSetTag(result, T_NullIfExpr);
1014
1015         return result;
1016 }
1017
1018 static Node *
1019 transformAExprOf(ParseState *pstate, A_Expr *a)
1020 {
1021         /*
1022          * Checking an expression for match to a list of type names. Will result
1023          * in a boolean constant node.
1024          */
1025         Node       *lexpr = transformExpr(pstate, a->lexpr);
1026         Const      *result;
1027         ListCell   *telem;
1028         Oid                     ltype,
1029                                 rtype;
1030         bool            matched = false;
1031
1032         ltype = exprType(lexpr);
1033         foreach(telem, (List *) a->rexpr)
1034         {
1035                 rtype = typenameTypeId(pstate, lfirst(telem), NULL);
1036                 matched = (rtype == ltype);
1037                 if (matched)
1038                         break;
1039         }
1040
1041         /*
1042          * We have two forms: equals or not equals. Flip the sense of the result
1043          * for not equals.
1044          */
1045         if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1046                 matched = (!matched);
1047
1048         result = (Const *) makeBoolConst(matched, false);
1049
1050         /* Make the result have the original input's parse location */
1051         result->location = exprLocation((Node *) a);
1052
1053         return (Node *) result;
1054 }
1055
1056 static Node *
1057 transformAExprIn(ParseState *pstate, A_Expr *a)
1058 {
1059         Node       *result = NULL;
1060         Node       *lexpr;
1061         List       *rexprs;
1062         List       *rvars;
1063         List       *rnonvars;
1064         bool            useOr;
1065         bool            haveRowExpr;
1066         ListCell   *l;
1067
1068         /*
1069          * If the operator is <>, combine with AND not OR.
1070          */
1071         if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1072                 useOr = false;
1073         else
1074                 useOr = true;
1075
1076         /*
1077          * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
1078          * possible if the inputs are all scalars (no RowExprs) and there is a
1079          * suitable array type available.  If not, we fall back to a boolean
1080          * condition tree with multiple copies of the lefthand expression. Also,
1081          * any IN-list items that contain Vars are handled as separate boolean
1082          * conditions, because that gives the planner more scope for optimization
1083          * on such clauses.
1084          *
1085          * First step: transform all the inputs, and detect whether any are
1086          * RowExprs or contain Vars.
1087          */
1088         lexpr = transformExpr(pstate, a->lexpr);
1089         haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
1090         rexprs = rvars = rnonvars = NIL;
1091         foreach(l, (List *) a->rexpr)
1092         {
1093                 Node       *rexpr = transformExpr(pstate, lfirst(l));
1094
1095                 haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
1096                 rexprs = lappend(rexprs, rexpr);
1097                 if (contain_vars_of_level(rexpr, 0))
1098                         rvars = lappend(rvars, rexpr);
1099                 else
1100                         rnonvars = lappend(rnonvars, rexpr);
1101         }
1102
1103         /*
1104          * ScalarArrayOpExpr is only going to be useful if there's more than one
1105          * non-Var righthand item.      Also, it won't work for RowExprs.
1106          */
1107         if (!haveRowExpr && list_length(rnonvars) > 1)
1108         {
1109                 List       *allexprs;
1110                 Oid                     scalar_type;
1111                 Oid                     array_type;
1112
1113                 /*
1114                  * Try to select a common type for the array elements.  Note that
1115                  * since the LHS' type is first in the list, it will be preferred when
1116                  * there is doubt (eg, when all the RHS items are unknown literals).
1117                  *
1118                  * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1119                  */
1120                 allexprs = list_concat(list_make1(lexpr), rnonvars);
1121                 scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1122
1123                 /* Do we have an array type to use? */
1124                 if (OidIsValid(scalar_type))
1125                         array_type = get_array_type(scalar_type);
1126                 else
1127                         array_type = InvalidOid;
1128                 if (array_type != InvalidOid)
1129                 {
1130                         /*
1131                          * OK: coerce all the right-hand non-Var inputs to the common type
1132                          * and build an ArrayExpr for them.
1133                          */
1134                         List       *aexprs;
1135                         ArrayExpr  *newa;
1136
1137                         aexprs = NIL;
1138                         foreach(l, rnonvars)
1139                         {
1140                                 Node       *rexpr = (Node *) lfirst(l);
1141
1142                                 rexpr = coerce_to_common_type(pstate, rexpr,
1143                                                                                           scalar_type,
1144                                                                                           "IN");
1145                                 aexprs = lappend(aexprs, rexpr);
1146                         }
1147                         newa = makeNode(ArrayExpr);
1148                         newa->array_typeid = array_type;
1149                         newa->element_typeid = scalar_type;
1150                         newa->elements = aexprs;
1151                         newa->multidims = false;
1152                         newa->location = -1;
1153
1154                         result = (Node *) make_scalar_array_op(pstate,
1155                                                                                                    a->name,
1156                                                                                                    useOr,
1157                                                                                                    lexpr,
1158                                                                                                    (Node *) newa,
1159                                                                                                    a->location);
1160
1161                         /* Consider only the Vars (if any) in the loop below */
1162                         rexprs = rvars;
1163                 }
1164         }
1165
1166         /*
1167          * Must do it the hard way, ie, with a boolean expression tree.
1168          */
1169         foreach(l, rexprs)
1170         {
1171                 Node       *rexpr = (Node *) lfirst(l);
1172                 Node       *cmp;
1173
1174                 if (haveRowExpr)
1175                 {
1176                         if (!IsA(lexpr, RowExpr) ||
1177                                 !IsA(rexpr, RowExpr))
1178                                 ereport(ERROR,
1179                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1180                                    errmsg("arguments of row IN must all be row expressions"),
1181                                                  parser_errposition(pstate, a->location)));
1182                         cmp = make_row_comparison_op(pstate,
1183                                                                                  a->name,
1184                                                           (List *) copyObject(((RowExpr *) lexpr)->args),
1185                                                                                  ((RowExpr *) rexpr)->args,
1186                                                                                  a->location);
1187                 }
1188                 else
1189                         cmp = (Node *) make_op(pstate,
1190                                                                    a->name,
1191                                                                    copyObject(lexpr),
1192                                                                    rexpr,
1193                                                                    a->location);
1194
1195                 cmp = coerce_to_boolean(pstate, cmp, "IN");
1196                 if (result == NULL)
1197                         result = cmp;
1198                 else
1199                         result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1200                                                                                    list_make2(result, cmp),
1201                                                                                    a->location);
1202         }
1203
1204         return result;
1205 }
1206
1207 static Node *
1208 transformFuncCall(ParseState *pstate, FuncCall *fn)
1209 {
1210         List       *targs;
1211         ListCell   *args;
1212
1213         /* Transform the list of arguments ... */
1214         targs = NIL;
1215         foreach(args, fn->args)
1216         {
1217                 targs = lappend(targs, transformExpr(pstate,
1218                                                                                          (Node *) lfirst(args)));
1219         }
1220
1221         /* ... and hand off to ParseFuncOrColumn */
1222         return ParseFuncOrColumn(pstate,
1223                                                          fn->funcname,
1224                                                          targs,
1225                                                          fn->agg_order,
1226                                                          fn->agg_star,
1227                                                          fn->agg_distinct,
1228                                                          fn->func_variadic,
1229                                                          fn->over,
1230                                                          false,
1231                                                          fn->location);
1232 }
1233
1234 static Node *
1235 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1236 {
1237         CaseExpr   *newc;
1238         Node       *arg;
1239         CaseTestExpr *placeholder;
1240         List       *newargs;
1241         List       *resultexprs;
1242         ListCell   *l;
1243         Node       *defresult;
1244         Oid                     ptype;
1245
1246         /* If we already transformed this node, do nothing */
1247         if (OidIsValid(c->casetype))
1248                 return (Node *) c;
1249
1250         newc = makeNode(CaseExpr);
1251
1252         /* transform the test expression, if any */
1253         arg = transformExpr(pstate, (Node *) c->arg);
1254
1255         /* generate placeholder for test expression */
1256         if (arg)
1257         {
1258                 /*
1259                  * If test expression is an untyped literal, force it to text. We have
1260                  * to do something now because we won't be able to do this coercion on
1261                  * the placeholder.  This is not as flexible as what was done in 7.4
1262                  * and before, but it's good enough to handle the sort of silly coding
1263                  * commonly seen.
1264                  */
1265                 if (exprType(arg) == UNKNOWNOID)
1266                         arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1267
1268                 placeholder = makeNode(CaseTestExpr);
1269                 placeholder->typeId = exprType(arg);
1270                 placeholder->typeMod = exprTypmod(arg);
1271         }
1272         else
1273                 placeholder = NULL;
1274
1275         newc->arg = (Expr *) arg;
1276
1277         /* transform the list of arguments */
1278         newargs = NIL;
1279         resultexprs = NIL;
1280         foreach(l, c->args)
1281         {
1282                 CaseWhen   *w = (CaseWhen *) lfirst(l);
1283                 CaseWhen   *neww = makeNode(CaseWhen);
1284                 Node       *warg;
1285
1286                 Assert(IsA(w, CaseWhen));
1287
1288                 warg = (Node *) w->expr;
1289                 if (placeholder)
1290                 {
1291                         /* shorthand form was specified, so expand... */
1292                         warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1293                                                                                          (Node *) placeholder,
1294                                                                                          warg,
1295                                                                                          w->location);
1296                 }
1297                 neww->expr = (Expr *) transformExpr(pstate, warg);
1298
1299                 neww->expr = (Expr *) coerce_to_boolean(pstate,
1300                                                                                                 (Node *) neww->expr,
1301                                                                                                 "CASE/WHEN");
1302
1303                 warg = (Node *) w->result;
1304                 neww->result = (Expr *) transformExpr(pstate, warg);
1305                 neww->location = w->location;
1306
1307                 newargs = lappend(newargs, neww);
1308                 resultexprs = lappend(resultexprs, neww->result);
1309         }
1310
1311         newc->args = newargs;
1312
1313         /* transform the default clause */
1314         defresult = (Node *) c->defresult;
1315         if (defresult == NULL)
1316         {
1317                 A_Const    *n = makeNode(A_Const);
1318
1319                 n->val.type = T_Null;
1320                 n->location = -1;
1321                 defresult = (Node *) n;
1322         }
1323         newc->defresult = (Expr *) transformExpr(pstate, defresult);
1324
1325         /*
1326          * Note: default result is considered the most significant type in
1327          * determining preferred type. This is how the code worked before, but it
1328          * seems a little bogus to me --- tgl
1329          */
1330         resultexprs = lcons(newc->defresult, resultexprs);
1331
1332         ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1333         Assert(OidIsValid(ptype));
1334         newc->casetype = ptype;
1335
1336         /* Convert default result clause, if necessary */
1337         newc->defresult = (Expr *)
1338                 coerce_to_common_type(pstate,
1339                                                           (Node *) newc->defresult,
1340                                                           ptype,
1341                                                           "CASE/ELSE");
1342
1343         /* Convert when-clause results, if necessary */
1344         foreach(l, newc->args)
1345         {
1346                 CaseWhen   *w = (CaseWhen *) lfirst(l);
1347
1348                 w->result = (Expr *)
1349                         coerce_to_common_type(pstate,
1350                                                                   (Node *) w->result,
1351                                                                   ptype,
1352                                                                   "CASE/WHEN");
1353         }
1354
1355         newc->location = c->location;
1356
1357         return (Node *) newc;
1358 }
1359
1360 static Node *
1361 transformSubLink(ParseState *pstate, SubLink *sublink)
1362 {
1363         Node       *result = (Node *) sublink;
1364         Query      *qtree;
1365
1366         /* If we already transformed this node, do nothing */
1367         if (IsA(sublink->subselect, Query))
1368                 return result;
1369
1370         pstate->p_hasSubLinks = true;
1371         qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false);
1372
1373         /*
1374          * Check that we got something reasonable.      Many of these conditions are
1375          * impossible given restrictions of the grammar, but check 'em anyway.
1376          */
1377         if (!IsA(qtree, Query) ||
1378                 qtree->commandType != CMD_SELECT ||
1379                 qtree->utilityStmt != NULL)
1380                 elog(ERROR, "unexpected non-SELECT command in SubLink");
1381         if (qtree->intoClause)
1382                 ereport(ERROR,
1383                                 (errcode(ERRCODE_SYNTAX_ERROR),
1384                                  errmsg("subquery cannot have SELECT INTO"),
1385                                  parser_errposition(pstate,
1386                                                                  exprLocation((Node *) qtree->intoClause))));
1387
1388         sublink->subselect = (Node *) qtree;
1389
1390         if (sublink->subLinkType == EXISTS_SUBLINK)
1391         {
1392                 /*
1393                  * EXISTS needs no test expression or combining operator. These fields
1394                  * should be null already, but make sure.
1395                  */
1396                 sublink->testexpr = NULL;
1397                 sublink->operName = NIL;
1398         }
1399         else if (sublink->subLinkType == EXPR_SUBLINK ||
1400                          sublink->subLinkType == ARRAY_SUBLINK)
1401         {
1402                 ListCell   *tlist_item = list_head(qtree->targetList);
1403
1404                 /*
1405                  * Make sure the subselect delivers a single column (ignoring resjunk
1406                  * targets).
1407                  */
1408                 if (tlist_item == NULL ||
1409                         ((TargetEntry *) lfirst(tlist_item))->resjunk)
1410                         ereport(ERROR,
1411                                         (errcode(ERRCODE_SYNTAX_ERROR),
1412                                          errmsg("subquery must return a column"),
1413                                          parser_errposition(pstate, sublink->location)));
1414                 while ((tlist_item = lnext(tlist_item)) != NULL)
1415                 {
1416                         if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1417                                 ereport(ERROR,
1418                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1419                                                  errmsg("subquery must return only one column"),
1420                                                  parser_errposition(pstate, sublink->location)));
1421                 }
1422
1423                 /*
1424                  * EXPR and ARRAY need no test expression or combining operator. These
1425                  * fields should be null already, but make sure.
1426                  */
1427                 sublink->testexpr = NULL;
1428                 sublink->operName = NIL;
1429         }
1430         else
1431         {
1432                 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1433                 Node       *lefthand;
1434                 List       *left_list;
1435                 List       *right_list;
1436                 ListCell   *l;
1437
1438                 /*
1439                  * Transform lefthand expression, and convert to a list
1440                  */
1441                 lefthand = transformExpr(pstate, sublink->testexpr);
1442                 if (lefthand && IsA(lefthand, RowExpr))
1443                         left_list = ((RowExpr *) lefthand)->args;
1444                 else
1445                         left_list = list_make1(lefthand);
1446
1447                 /*
1448                  * Build a list of PARAM_SUBLINK nodes representing the output columns
1449                  * of the subquery.
1450                  */
1451                 right_list = NIL;
1452                 foreach(l, qtree->targetList)
1453                 {
1454                         TargetEntry *tent = (TargetEntry *) lfirst(l);
1455                         Param      *param;
1456
1457                         if (tent->resjunk)
1458                                 continue;
1459
1460                         param = makeNode(Param);
1461                         param->paramkind = PARAM_SUBLINK;
1462                         param->paramid = tent->resno;
1463                         param->paramtype = exprType((Node *) tent->expr);
1464                         param->paramtypmod = exprTypmod((Node *) tent->expr);
1465                         param->location = -1;
1466
1467                         right_list = lappend(right_list, param);
1468                 }
1469
1470                 /*
1471                  * We could rely on make_row_comparison_op to complain if the list
1472                  * lengths differ, but we prefer to generate a more specific error
1473                  * message.
1474                  */
1475                 if (list_length(left_list) < list_length(right_list))
1476                         ereport(ERROR,
1477                                         (errcode(ERRCODE_SYNTAX_ERROR),
1478                                          errmsg("subquery has too many columns"),
1479                                          parser_errposition(pstate, sublink->location)));
1480                 if (list_length(left_list) > list_length(right_list))
1481                         ereport(ERROR,
1482                                         (errcode(ERRCODE_SYNTAX_ERROR),
1483                                          errmsg("subquery has too few columns"),
1484                                          parser_errposition(pstate, sublink->location)));
1485
1486                 /*
1487                  * Identify the combining operator(s) and generate a suitable
1488                  * row-comparison expression.
1489                  */
1490                 sublink->testexpr = make_row_comparison_op(pstate,
1491                                                                                                    sublink->operName,
1492                                                                                                    left_list,
1493                                                                                                    right_list,
1494                                                                                                    sublink->location);
1495         }
1496
1497         return result;
1498 }
1499
1500 /*
1501  * transformArrayExpr
1502  *
1503  * If the caller specifies the target type, the resulting array will
1504  * be of exactly that type.  Otherwise we try to infer a common type
1505  * for the elements using select_common_type().
1506  */
1507 static Node *
1508 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
1509                                    Oid array_type, Oid element_type, int32 typmod)
1510 {
1511         ArrayExpr  *newa = makeNode(ArrayExpr);
1512         List       *newelems = NIL;
1513         List       *newcoercedelems = NIL;
1514         ListCell   *element;
1515         Oid                     coerce_type;
1516         bool            coerce_hard;
1517
1518         /*
1519          * Transform the element expressions
1520          *
1521          * Assume that the array is one-dimensional unless we find an array-type
1522          * element expression.
1523          */
1524         newa->multidims = false;
1525         foreach(element, a->elements)
1526         {
1527                 Node       *e = (Node *) lfirst(element);
1528                 Node       *newe;
1529
1530                 /*
1531                  * If an element is itself an A_ArrayExpr, recurse directly so that we
1532                  * can pass down any target type we were given.
1533                  */
1534                 if (IsA(e, A_ArrayExpr))
1535                 {
1536                         newe = transformArrayExpr(pstate,
1537                                                                           (A_ArrayExpr *) e,
1538                                                                           array_type,
1539                                                                           element_type,
1540                                                                           typmod);
1541                         /* we certainly have an array here */
1542                         Assert(array_type == InvalidOid || array_type == exprType(newe));
1543                         newa->multidims = true;
1544                 }
1545                 else
1546                 {
1547                         newe = transformExpr(pstate, e);
1548
1549                         /*
1550                          * Check for sub-array expressions, if we haven't already found
1551                          * one.
1552                          */
1553                         if (!newa->multidims && type_is_array(exprType(newe)))
1554                                 newa->multidims = true;
1555                 }
1556
1557                 newelems = lappend(newelems, newe);
1558         }
1559
1560         /*
1561          * Select a target type for the elements.
1562          *
1563          * If we haven't been given a target array type, we must try to deduce a
1564          * common type based on the types of the individual elements present.
1565          */
1566         if (OidIsValid(array_type))
1567         {
1568                 /* Caller must ensure array_type matches element_type */
1569                 Assert(OidIsValid(element_type));
1570                 coerce_type = (newa->multidims ? array_type : element_type);
1571                 coerce_hard = true;
1572         }
1573         else
1574         {
1575                 /* Can't handle an empty array without a target type */
1576                 if (newelems == NIL)
1577                         ereport(ERROR,
1578                                         (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1579                                          errmsg("cannot determine type of empty array"),
1580                                          errhint("Explicitly cast to the desired type, "
1581                                                          "for example ARRAY[]::integer[]."),
1582                                          parser_errposition(pstate, a->location)));
1583
1584                 /* Select a common type for the elements */
1585                 coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1586
1587                 if (newa->multidims)
1588                 {
1589                         array_type = coerce_type;
1590                         element_type = get_element_type(array_type);
1591                         if (!OidIsValid(element_type))
1592                                 ereport(ERROR,
1593                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1594                                            errmsg("could not find element type for data type %s",
1595                                                           format_type_be(array_type)),
1596                                                  parser_errposition(pstate, a->location)));
1597                 }
1598                 else
1599                 {
1600                         element_type = coerce_type;
1601                         array_type = get_array_type(element_type);
1602                         if (!OidIsValid(array_type))
1603                                 ereport(ERROR,
1604                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1605                                                  errmsg("could not find array type for data type %s",
1606                                                                 format_type_be(element_type)),
1607                                                  parser_errposition(pstate, a->location)));
1608                 }
1609                 coerce_hard = false;
1610         }
1611
1612         /*
1613          * Coerce elements to target type
1614          *
1615          * If the array has been explicitly cast, then the elements are in turn
1616          * explicitly coerced.
1617          *
1618          * If the array's type was merely derived from the common type of its
1619          * elements, then the elements are implicitly coerced to the common type.
1620          * This is consistent with other uses of select_common_type().
1621          */
1622         foreach(element, newelems)
1623         {
1624                 Node       *e = (Node *) lfirst(element);
1625                 Node       *newe;
1626
1627                 if (coerce_hard)
1628                 {
1629                         newe = coerce_to_target_type(pstate, e,
1630                                                                                  exprType(e),
1631                                                                                  coerce_type,
1632                                                                                  typmod,
1633                                                                                  COERCION_EXPLICIT,
1634                                                                                  COERCE_EXPLICIT_CAST,
1635                                                                                  -1);
1636                         if (newe == NULL)
1637                                 ereport(ERROR,
1638                                                 (errcode(ERRCODE_CANNOT_COERCE),
1639                                                  errmsg("cannot cast type %s to %s",
1640                                                                 format_type_be(exprType(e)),
1641                                                                 format_type_be(coerce_type)),
1642                                                  parser_errposition(pstate, exprLocation(e))));
1643                 }
1644                 else
1645                         newe = coerce_to_common_type(pstate, e,
1646                                                                                  coerce_type,
1647                                                                                  "ARRAY");
1648                 newcoercedelems = lappend(newcoercedelems, newe);
1649         }
1650
1651         newa->array_typeid = array_type;
1652         newa->element_typeid = element_type;
1653         newa->elements = newcoercedelems;
1654         newa->location = a->location;
1655
1656         return (Node *) newa;
1657 }
1658
1659 static Node *
1660 transformRowExpr(ParseState *pstate, RowExpr *r)
1661 {
1662         RowExpr    *newr = makeNode(RowExpr);
1663
1664         /* Transform the field expressions */
1665         newr->args = transformExpressionList(pstate, r->args);
1666
1667         /* Barring later casting, we consider the type RECORD */
1668         newr->row_typeid = RECORDOID;
1669         newr->row_format = COERCE_IMPLICIT_CAST;
1670         newr->colnames = NIL;           /* ROW() has anonymous columns */
1671         newr->location = r->location;
1672
1673         return (Node *) newr;
1674 }
1675
1676 static Node *
1677 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
1678 {
1679         CoalesceExpr *newc = makeNode(CoalesceExpr);
1680         List       *newargs = NIL;
1681         List       *newcoercedargs = NIL;
1682         ListCell   *args;
1683
1684         foreach(args, c->args)
1685         {
1686                 Node       *e = (Node *) lfirst(args);
1687                 Node       *newe;
1688
1689                 newe = transformExpr(pstate, e);
1690                 newargs = lappend(newargs, newe);
1691         }
1692
1693         newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1694
1695         /* Convert arguments if necessary */
1696         foreach(args, newargs)
1697         {
1698                 Node       *e = (Node *) lfirst(args);
1699                 Node       *newe;
1700
1701                 newe = coerce_to_common_type(pstate, e,
1702                                                                          newc->coalescetype,
1703                                                                          "COALESCE");
1704                 newcoercedargs = lappend(newcoercedargs, newe);
1705         }
1706
1707         newc->args = newcoercedargs;
1708         newc->location = c->location;
1709         return (Node *) newc;
1710 }
1711
1712 static Node *
1713 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
1714 {
1715         MinMaxExpr *newm = makeNode(MinMaxExpr);
1716         List       *newargs = NIL;
1717         List       *newcoercedargs = NIL;
1718         const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1719         ListCell   *args;
1720
1721         newm->op = m->op;
1722         foreach(args, m->args)
1723         {
1724                 Node       *e = (Node *) lfirst(args);
1725                 Node       *newe;
1726
1727                 newe = transformExpr(pstate, e);
1728                 newargs = lappend(newargs, newe);
1729         }
1730
1731         newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1732
1733         /* Convert arguments if necessary */
1734         foreach(args, newargs)
1735         {
1736                 Node       *e = (Node *) lfirst(args);
1737                 Node       *newe;
1738
1739                 newe = coerce_to_common_type(pstate, e,
1740                                                                          newm->minmaxtype,
1741                                                                          funcname);
1742                 newcoercedargs = lappend(newcoercedargs, newe);
1743         }
1744
1745         newm->args = newcoercedargs;
1746         newm->location = m->location;
1747         return (Node *) newm;
1748 }
1749
1750 static Node *
1751 transformXmlExpr(ParseState *pstate, XmlExpr *x)
1752 {
1753         XmlExpr    *newx = makeNode(XmlExpr);
1754         ListCell   *lc;
1755         int                     i;
1756
1757         newx->op = x->op;
1758         if (x->name)
1759                 newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1760         else
1761                 newx->name = NULL;
1762         newx->xmloption = x->xmloption;
1763         newx->location = x->location;
1764
1765         /*
1766          * gram.y built the named args as a list of ResTarget.  Transform each,
1767          * and break the names out as a separate list.
1768          */
1769         newx->named_args = NIL;
1770         newx->arg_names = NIL;
1771
1772         foreach(lc, x->named_args)
1773         {
1774                 ResTarget  *r = (ResTarget *) lfirst(lc);
1775                 Node       *expr;
1776                 char       *argname;
1777
1778                 Assert(IsA(r, ResTarget));
1779
1780                 expr = transformExpr(pstate, r->val);
1781
1782                 if (r->name)
1783                         argname = map_sql_identifier_to_xml_name(r->name, false, false);
1784                 else if (IsA(r->val, ColumnRef))
1785                         argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1786                                                                                                          true, false);
1787                 else
1788                 {
1789                         ereport(ERROR,
1790                                         (errcode(ERRCODE_SYNTAX_ERROR),
1791                                          x->op == IS_XMLELEMENT
1792                         ? errmsg("unnamed XML attribute value must be a column reference")
1793                         : errmsg("unnamed XML element value must be a column reference"),
1794                                          parser_errposition(pstate, r->location)));
1795                         argname = NULL;         /* keep compiler quiet */
1796                 }
1797
1798                 /* reject duplicate argnames in XMLELEMENT only */
1799                 if (x->op == IS_XMLELEMENT)
1800                 {
1801                         ListCell   *lc2;
1802
1803                         foreach(lc2, newx->arg_names)
1804                         {
1805                                 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1806                                         ereport(ERROR,
1807                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1808                                         errmsg("XML attribute name \"%s\" appears more than once",
1809                                                    argname),
1810                                                          parser_errposition(pstate, r->location)));
1811                         }
1812                 }
1813
1814                 newx->named_args = lappend(newx->named_args, expr);
1815                 newx->arg_names = lappend(newx->arg_names, makeString(argname));
1816         }
1817
1818         /* The other arguments are of varying types depending on the function */
1819         newx->args = NIL;
1820         i = 0;
1821         foreach(lc, x->args)
1822         {
1823                 Node       *e = (Node *) lfirst(lc);
1824                 Node       *newe;
1825
1826                 newe = transformExpr(pstate, e);
1827                 switch (x->op)
1828                 {
1829                         case IS_XMLCONCAT:
1830                                 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1831                                                                                            "XMLCONCAT");
1832                                 break;
1833                         case IS_XMLELEMENT:
1834                                 /* no coercion necessary */
1835                                 break;
1836                         case IS_XMLFOREST:
1837                                 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1838                                                                                            "XMLFOREST");
1839                                 break;
1840                         case IS_XMLPARSE:
1841                                 if (i == 0)
1842                                         newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1843                                                                                                    "XMLPARSE");
1844                                 else
1845                                         newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
1846                                 break;
1847                         case IS_XMLPI:
1848                                 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1849                                                                                            "XMLPI");
1850                                 break;
1851                         case IS_XMLROOT:
1852                                 if (i == 0)
1853                                         newe = coerce_to_specific_type(pstate, newe, XMLOID,
1854                                                                                                    "XMLROOT");
1855                                 else if (i == 1)
1856                                         newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1857                                                                                                    "XMLROOT");
1858                                 else
1859                                         newe = coerce_to_specific_type(pstate, newe, INT4OID,
1860                                                                                                    "XMLROOT");
1861                                 break;
1862                         case IS_XMLSERIALIZE:
1863                                 /* not handled here */
1864                                 Assert(false);
1865                                 break;
1866                         case IS_DOCUMENT:
1867                                 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1868                                                                                            "IS DOCUMENT");
1869                                 break;
1870                 }
1871                 newx->args = lappend(newx->args, newe);
1872                 i++;
1873         }
1874
1875         return (Node *) newx;
1876 }
1877
1878 static Node *
1879 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1880 {
1881         Node       *result;
1882         XmlExpr    *xexpr;
1883         Oid                     targetType;
1884         int32           targetTypmod;
1885
1886         xexpr = makeNode(XmlExpr);
1887         xexpr->op = IS_XMLSERIALIZE;
1888         xexpr->args = list_make1(coerce_to_specific_type(pstate,
1889                                                                                          transformExpr(pstate, xs->expr),
1890                                                                                                          XMLOID,
1891                                                                                                          "XMLSERIALIZE"));
1892
1893         targetType = typenameTypeId(pstate, xs->typeName, &targetTypmod);
1894
1895         xexpr->xmloption = xs->xmloption;
1896         xexpr->location = xs->location;
1897         /* We actually only need these to be able to parse back the expression. */
1898         xexpr->type = targetType;
1899         xexpr->typmod = targetTypmod;
1900
1901         /*
1902          * The actual target type is determined this way.  SQL allows char and
1903          * varchar as target types.  We allow anything that can be cast implicitly
1904          * from text.  This way, user-defined text-like data types automatically
1905          * fit in.
1906          */
1907         result = coerce_to_target_type(pstate, (Node *) xexpr,
1908                                                                    TEXTOID, targetType, targetTypmod,
1909                                                                    COERCION_IMPLICIT,
1910                                                                    COERCE_IMPLICIT_CAST,
1911                                                                    -1);
1912         if (result == NULL)
1913                 ereport(ERROR,
1914                                 (errcode(ERRCODE_CANNOT_COERCE),
1915                                  errmsg("cannot cast XMLSERIALIZE result to %s",
1916                                                 format_type_be(targetType)),
1917                                  parser_errposition(pstate, xexpr->location)));
1918         return result;
1919 }
1920
1921 static Node *
1922 transformBooleanTest(ParseState *pstate, BooleanTest *b)
1923 {
1924         const char *clausename;
1925
1926         switch (b->booltesttype)
1927         {
1928                 case IS_TRUE:
1929                         clausename = "IS TRUE";
1930                         break;
1931                 case IS_NOT_TRUE:
1932                         clausename = "IS NOT TRUE";
1933                         break;
1934                 case IS_FALSE:
1935                         clausename = "IS FALSE";
1936                         break;
1937                 case IS_NOT_FALSE:
1938                         clausename = "IS NOT FALSE";
1939                         break;
1940                 case IS_UNKNOWN:
1941                         clausename = "IS UNKNOWN";
1942                         break;
1943                 case IS_NOT_UNKNOWN:
1944                         clausename = "IS NOT UNKNOWN";
1945                         break;
1946                 default:
1947                         elog(ERROR, "unrecognized booltesttype: %d",
1948                                  (int) b->booltesttype);
1949                         clausename = NULL;      /* keep compiler quiet */
1950         }
1951
1952         b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
1953
1954         b->arg = (Expr *) coerce_to_boolean(pstate,
1955                                                                                 (Node *) b->arg,
1956                                                                                 clausename);
1957
1958         return (Node *) b;
1959 }
1960
1961 static Node *
1962 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1963 {
1964         int                     sublevels_up;
1965
1966         /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1967         Assert(pstate->p_target_rangetblentry != NULL);
1968         cexpr->cvarno = RTERangeTablePosn(pstate,
1969                                                                           pstate->p_target_rangetblentry,
1970                                                                           &sublevels_up);
1971         Assert(sublevels_up == 0);
1972
1973         /*
1974          * Check to see if the cursor name matches a parameter of type REFCURSOR.
1975          * If so, replace the raw name reference with a parameter reference.
1976          * (This is a hack for the convenience of plpgsql.)
1977          */
1978         if (cexpr->cursor_name != NULL)                 /* in case already transformed */
1979         {
1980                 ColumnRef  *cref = makeNode(ColumnRef);
1981                 Node       *node = NULL;
1982
1983                 /* Build an unqualified ColumnRef with the given name */
1984                 cref->fields = list_make1(makeString(cexpr->cursor_name));
1985                 cref->location = -1;
1986
1987                 /* See if there is a translation available from a parser hook */
1988                 if (pstate->p_pre_columnref_hook != NULL)
1989                         node = (*pstate->p_pre_columnref_hook) (pstate, cref);
1990                 if (node == NULL && pstate->p_post_columnref_hook != NULL)
1991                         node = (*pstate->p_post_columnref_hook) (pstate, cref, NULL);
1992
1993                 /*
1994                  * XXX Should we throw an error if we get a translation that isn't
1995                  * a refcursor Param?  For now it seems best to silently ignore
1996                  * false matches.
1997                  */
1998                 if (node != NULL && IsA(node, Param))
1999                 {
2000                         Param  *p = (Param *) node;
2001
2002                         if (p->paramkind == PARAM_EXTERN &&
2003                                 p->paramtype == REFCURSOROID)
2004                         {
2005                                 /* Matches, so convert CURRENT OF to a param reference */
2006                                 cexpr->cursor_name = NULL;
2007                                 cexpr->cursor_param = p->paramid;
2008                         }
2009                 }
2010         }
2011
2012         return (Node *) cexpr;
2013 }
2014
2015 /*
2016  * Construct a whole-row reference to represent the notation "relation.*".
2017  *
2018  * A whole-row reference is a Var with varno set to the correct range
2019  * table entry, and varattno == 0 to signal that it references the whole
2020  * tuple.  (Use of zero here is unclean, since it could easily be confused
2021  * with error cases, but it's not worth changing now.)  The vartype indicates
2022  * a rowtype; either a named composite type, or RECORD.
2023  */
2024 static Node *
2025 transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte, int location)
2026 {
2027         Var                *result;
2028         int                     vnum;
2029         int                     sublevels_up;
2030         Oid                     toid;
2031
2032         /* Find the RTE's rangetable location */
2033
2034         vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
2035
2036         /* Build the appropriate referencing node */
2037
2038         switch (rte->rtekind)
2039         {
2040                 case RTE_RELATION:
2041                         /* relation: the rowtype is a named composite type */
2042                         toid = get_rel_type_id(rte->relid);
2043                         if (!OidIsValid(toid))
2044                                 elog(ERROR, "could not find type OID for relation %u",
2045                                          rte->relid);
2046                         result = makeVar(vnum,
2047                                                          InvalidAttrNumber,
2048                                                          toid,
2049                                                          -1,
2050                                                          sublevels_up);
2051                         break;
2052                 case RTE_FUNCTION:
2053                         toid = exprType(rte->funcexpr);
2054                         if (type_is_rowtype(toid))
2055                         {
2056                                 /* func returns composite; same as relation case */
2057                                 result = makeVar(vnum,
2058                                                                  InvalidAttrNumber,
2059                                                                  toid,
2060                                                                  -1,
2061                                                                  sublevels_up);
2062                         }
2063                         else
2064                         {
2065                                 /*
2066                                  * func returns scalar; instead of making a whole-row Var,
2067                                  * just reference the function's scalar output.  (XXX this
2068                                  * seems a tad inconsistent, especially if "f.*" was
2069                                  * explicitly written ...)
2070                                  */
2071                                 result = makeVar(vnum,
2072                                                                  1,
2073                                                                  toid,
2074                                                                  -1,
2075                                                                  sublevels_up);
2076                         }
2077                         break;
2078                 case RTE_VALUES:
2079                         toid = RECORDOID;
2080                         /* returns composite; same as relation case */
2081                         result = makeVar(vnum,
2082                                                          InvalidAttrNumber,
2083                                                          toid,
2084                                                          -1,
2085                                                          sublevels_up);
2086                         break;
2087                 default:
2088
2089                         /*
2090                          * RTE is a join or subselect.  We represent this as a whole-row
2091                          * Var of RECORD type.  (Note that in most cases the Var will be
2092                          * expanded to a RowExpr during planning, but that is not our
2093                          * concern here.)
2094                          */
2095                         result = makeVar(vnum,
2096                                                          InvalidAttrNumber,
2097                                                          RECORDOID,
2098                                                          -1,
2099                                                          sublevels_up);
2100                         break;
2101         }
2102
2103         /* location is not filled in by makeVar */
2104         result->location = location;
2105
2106         /* mark relation as requiring whole-row SELECT access */
2107         markVarForSelectPriv(pstate, result, rte);
2108
2109         return (Node *) result;
2110 }
2111
2112 /*
2113  * Handle an explicit CAST construct.
2114  *
2115  * Transform the argument, then look up the type name and apply any necessary
2116  * coercion function(s).
2117  */
2118 static Node *
2119 transformTypeCast(ParseState *pstate, TypeCast *tc)
2120 {
2121         Node       *result;
2122         Node       *expr = transformExpr(pstate, tc->arg);
2123         Oid                     inputType = exprType(expr);
2124         Oid                     targetType;
2125         int32           targetTypmod;
2126         int                     location;
2127
2128         targetType = typenameTypeId(pstate, tc->typeName, &targetTypmod);
2129
2130         if (inputType == InvalidOid)
2131                 return expr;                    /* do nothing if NULL input */
2132
2133         /*
2134          * Location of the coercion is preferentially the location of the :: or
2135          * CAST symbol, but if there is none then use the location of the type
2136          * name (this can happen in TypeName 'string' syntax, for instance).
2137          */
2138         location = tc->location;
2139         if (location < 0)
2140                 location = tc->typeName->location;
2141
2142         result = coerce_to_target_type(pstate, expr, inputType,
2143                                                                    targetType, targetTypmod,
2144                                                                    COERCION_EXPLICIT,
2145                                                                    COERCE_EXPLICIT_CAST,
2146                                                                    location);
2147         if (result == NULL)
2148                 ereport(ERROR,
2149                                 (errcode(ERRCODE_CANNOT_COERCE),
2150                                  errmsg("cannot cast type %s to %s",
2151                                                 format_type_be(inputType),
2152                                                 format_type_be(targetType)),
2153                                  parser_coercion_errposition(pstate, location, expr)));
2154
2155         return result;
2156 }
2157
2158 /*
2159  * Transform a "row compare-op row" construct
2160  *
2161  * The inputs are lists of already-transformed expressions.
2162  * As with coerce_type, pstate may be NULL if no special unknown-Param
2163  * processing is wanted.
2164  *
2165  * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2166  * or a RowCompareExpr.  In all cases it is guaranteed to return boolean.
2167  * The AND, OR, and RowCompareExpr cases further imply things about the
2168  * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2169  */
2170 static Node *
2171 make_row_comparison_op(ParseState *pstate, List *opname,
2172                                            List *largs, List *rargs, int location)
2173 {
2174         RowCompareExpr *rcexpr;
2175         RowCompareType rctype;
2176         List       *opexprs;
2177         List       *opnos;
2178         List       *opfamilies;
2179         ListCell   *l,
2180                            *r;
2181         List      **opfamily_lists;
2182         List      **opstrat_lists;
2183         Bitmapset  *strats;
2184         int                     nopers;
2185         int                     i;
2186
2187         nopers = list_length(largs);
2188         if (nopers != list_length(rargs))
2189                 ereport(ERROR,
2190                                 (errcode(ERRCODE_SYNTAX_ERROR),
2191                                  errmsg("unequal number of entries in row expressions"),
2192                                  parser_errposition(pstate, location)));
2193
2194         /*
2195          * We can't compare zero-length rows because there is no principled basis
2196          * for figuring out what the operator is.
2197          */
2198         if (nopers == 0)
2199                 ereport(ERROR,
2200                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2201                                  errmsg("cannot compare rows of zero length"),
2202                                  parser_errposition(pstate, location)));
2203
2204         /*
2205          * Identify all the pairwise operators, using make_op so that behavior is
2206          * the same as in the simple scalar case.
2207          */
2208         opexprs = NIL;
2209         forboth(l, largs, r, rargs)
2210         {
2211                 Node       *larg = (Node *) lfirst(l);
2212                 Node       *rarg = (Node *) lfirst(r);
2213                 OpExpr     *cmp;
2214
2215                 cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2216                 Assert(IsA(cmp, OpExpr));
2217
2218                 /*
2219                  * We don't use coerce_to_boolean here because we insist on the
2220                  * operator yielding boolean directly, not via coercion.  If it
2221                  * doesn't yield bool it won't be in any index opfamilies...
2222                  */
2223                 if (cmp->opresulttype != BOOLOID)
2224                         ereport(ERROR,
2225                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2226                                    errmsg("row comparison operator must yield type boolean, "
2227                                                   "not type %s",
2228                                                   format_type_be(cmp->opresulttype)),
2229                                          parser_errposition(pstate, location)));
2230                 if (expression_returns_set((Node *) cmp))
2231                         ereport(ERROR,
2232                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2233                                          errmsg("row comparison operator must not return a set"),
2234                                          parser_errposition(pstate, location)));
2235                 opexprs = lappend(opexprs, cmp);
2236         }
2237
2238         /*
2239          * If rows are length 1, just return the single operator.  In this case we
2240          * don't insist on identifying btree semantics for the operator (but we
2241          * still require it to return boolean).
2242          */
2243         if (nopers == 1)
2244                 return (Node *) linitial(opexprs);
2245
2246         /*
2247          * Now we must determine which row comparison semantics (= <> < <= > >=)
2248          * apply to this set of operators.      We look for btree opfamilies
2249          * containing the operators, and see which interpretations (strategy
2250          * numbers) exist for each operator.
2251          */
2252         opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2253         opstrat_lists = (List **) palloc(nopers * sizeof(List *));
2254         strats = NULL;
2255         i = 0;
2256         foreach(l, opexprs)
2257         {
2258                 Oid                     opno = ((OpExpr *) lfirst(l))->opno;
2259                 Bitmapset  *this_strats;
2260                 ListCell   *j;
2261
2262                 get_op_btree_interpretation(opno,
2263                                                                         &opfamily_lists[i], &opstrat_lists[i]);
2264
2265                 /*
2266                  * convert strategy number list to a Bitmapset to make the
2267                  * intersection calculation easy.
2268                  */
2269                 this_strats = NULL;
2270                 foreach(j, opstrat_lists[i])
2271                 {
2272                         this_strats = bms_add_member(this_strats, lfirst_int(j));
2273                 }
2274                 if (i == 0)
2275                         strats = this_strats;
2276                 else
2277                         strats = bms_int_members(strats, this_strats);
2278                 i++;
2279         }
2280
2281         /*
2282          * If there are multiple common interpretations, we may use any one of
2283          * them ... this coding arbitrarily picks the lowest btree strategy
2284          * number.
2285          */
2286         i = bms_first_member(strats);
2287         if (i < 0)
2288         {
2289                 /* No common interpretation, so fail */
2290                 ereport(ERROR,
2291                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2292                                  errmsg("could not determine interpretation of row comparison operator %s",
2293                                                 strVal(llast(opname))),
2294                                  errhint("Row comparison operators must be associated with btree operator families."),
2295                                  parser_errposition(pstate, location)));
2296         }
2297         rctype = (RowCompareType) i;
2298
2299         /*
2300          * For = and <> cases, we just combine the pairwise operators with AND or
2301          * OR respectively.
2302          *
2303          * Note: this is presently the only place where the parser generates
2304          * BoolExpr with more than two arguments.  Should be OK since the rest of
2305          * the system thinks BoolExpr is N-argument anyway.
2306          */
2307         if (rctype == ROWCOMPARE_EQ)
2308                 return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2309         if (rctype == ROWCOMPARE_NE)
2310                 return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2311
2312         /*
2313          * Otherwise we need to choose exactly which opfamily to associate with
2314          * each operator.
2315          */
2316         opfamilies = NIL;
2317         for (i = 0; i < nopers; i++)
2318         {
2319                 Oid                     opfamily = InvalidOid;
2320
2321                 forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2322                 {
2323                         int                     opstrat = lfirst_int(r);
2324
2325                         if (opstrat == rctype)
2326                         {
2327                                 opfamily = lfirst_oid(l);
2328                                 break;
2329                         }
2330                 }
2331                 if (OidIsValid(opfamily))
2332                         opfamilies = lappend_oid(opfamilies, opfamily);
2333                 else    /* should not happen */
2334                         ereport(ERROR,
2335                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2336                                          errmsg("could not determine interpretation of row comparison operator %s",
2337                                                         strVal(llast(opname))),
2338                            errdetail("There are multiple equally-plausible candidates."),
2339                                          parser_errposition(pstate, location)));
2340         }
2341
2342         /*
2343          * Now deconstruct the OpExprs and create a RowCompareExpr.
2344          *
2345          * Note: can't just reuse the passed largs/rargs lists, because of
2346          * possibility that make_op inserted coercion operations.
2347          */
2348         opnos = NIL;
2349         largs = NIL;
2350         rargs = NIL;
2351         foreach(l, opexprs)
2352         {
2353                 OpExpr     *cmp = (OpExpr *) lfirst(l);
2354
2355                 opnos = lappend_oid(opnos, cmp->opno);
2356                 largs = lappend(largs, linitial(cmp->args));
2357                 rargs = lappend(rargs, lsecond(cmp->args));
2358         }
2359
2360         rcexpr = makeNode(RowCompareExpr);
2361         rcexpr->rctype = rctype;
2362         rcexpr->opnos = opnos;
2363         rcexpr->opfamilies = opfamilies;
2364         rcexpr->largs = largs;
2365         rcexpr->rargs = rargs;
2366
2367         return (Node *) rcexpr;
2368 }
2369
2370 /*
2371  * Transform a "row IS DISTINCT FROM row" construct
2372  *
2373  * The input RowExprs are already transformed
2374  */
2375 static Node *
2376 make_row_distinct_op(ParseState *pstate, List *opname,
2377                                          RowExpr *lrow, RowExpr *rrow,
2378                                          int location)
2379 {
2380         Node       *result = NULL;
2381         List       *largs = lrow->args;
2382         List       *rargs = rrow->args;
2383         ListCell   *l,
2384                            *r;
2385
2386         if (list_length(largs) != list_length(rargs))
2387                 ereport(ERROR,
2388                                 (errcode(ERRCODE_SYNTAX_ERROR),
2389                                  errmsg("unequal number of entries in row expressions"),
2390                                  parser_errposition(pstate, location)));
2391
2392         forboth(l, largs, r, rargs)
2393         {
2394                 Node       *larg = (Node *) lfirst(l);
2395                 Node       *rarg = (Node *) lfirst(r);
2396                 Node       *cmp;
2397
2398                 cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2399                 if (result == NULL)
2400                         result = cmp;
2401                 else
2402                         result = (Node *) makeBoolExpr(OR_EXPR,
2403                                                                                    list_make2(result, cmp),
2404                                                                                    location);
2405         }
2406
2407         if (result == NULL)
2408         {
2409                 /* zero-length rows?  Generate constant FALSE */
2410                 result = makeBoolConst(false, false);
2411         }
2412
2413         return result;
2414 }
2415
2416 /*
2417  * make the node for an IS DISTINCT FROM operator
2418  */
2419 static Expr *
2420 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
2421                                  int location)
2422 {
2423         Expr       *result;
2424
2425         result = make_op(pstate, opname, ltree, rtree, location);
2426         if (((OpExpr *) result)->opresulttype != BOOLOID)
2427                 ereport(ERROR,
2428                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2429                          errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2430                                  parser_errposition(pstate, location)));
2431
2432         /*
2433          * We rely on DistinctExpr and OpExpr being same struct
2434          */
2435         NodeSetTag(result, T_DistinctExpr);
2436
2437         return result;
2438 }