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