Fix oversight in previous error-reporting patch; mustn't pfree path string
[PostgreSQL.git] / src / backend / parser / parse_expr.c
blobf9aa98f291b89f7cae3ade5fad0025dc33a6b0f4
1 /*-------------------------------------------------------------------------
3 * parse_expr.c
4 * handle expressions in parser
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
16 #include "postgres.h"
18 #include "catalog/pg_type.h"
19 #include "commands/dbcommands.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/var.h"
24 #include "parser/analyze.h"
25 #include "parser/parse_coerce.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_func.h"
28 #include "parser/parse_oper.h"
29 #include "parser/parse_relation.h"
30 #include "parser/parse_target.h"
31 #include "parser/parse_type.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/xml.h"
37 bool Transform_null_equals = false;
39 static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
40 static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
41 static Node *transformAExprAnd(ParseState *pstate, A_Expr *a);
42 static Node *transformAExprOr(ParseState *pstate, A_Expr *a);
43 static Node *transformAExprNot(ParseState *pstate, A_Expr *a);
44 static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
45 static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
46 static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
47 static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
48 static Node *transformAExprOf(ParseState *pstate, A_Expr *a);
49 static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
50 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
51 static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
52 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
53 static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
54 Oid array_type, Oid element_type, int32 typmod);
55 static Node *transformRowExpr(ParseState *pstate, RowExpr *r);
56 static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
57 static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
58 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
59 static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
60 static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
61 static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
62 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
63 static Node *transformWholeRowRef(ParseState *pstate, char *schemaname,
64 char *relname, int location);
65 static Node *transformIndirection(ParseState *pstate, Node *basenode,
66 List *indirection);
67 static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
68 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
69 List *largs, List *rargs, int location);
70 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
71 RowExpr *lrow, RowExpr *rrow, int location);
72 static Expr *make_distinct_op(ParseState *pstate, List *opname,
73 Node *ltree, Node *rtree, int location);
77 * transformExpr -
78 * Analyze and transform expressions. Type checking and type casting is
79 * done here. The optimizer and the executor cannot handle the original
80 * (raw) expressions collected by the parse tree. Hence the transformation
81 * here.
83 * NOTE: there are various cases in which this routine will get applied to
84 * an already-transformed expression. Some examples:
85 * 1. At least one construct (BETWEEN/AND) puts the same nodes
86 * into two branches of the parse tree; hence, some nodes
87 * are transformed twice.
88 * 2. Another way it can happen is that coercion of an operator or
89 * function argument to the required type (via coerce_type())
90 * can apply transformExpr to an already-transformed subexpression.
91 * An example here is "SELECT count(*) + 1.0 FROM table".
92 * While it might be possible to eliminate these cases, the path of
93 * least resistance so far has been to ensure that transformExpr() does
94 * no damage if applied to an already-transformed tree. This is pretty
95 * easy for cases where the transformation replaces one node type with
96 * another, such as A_Const => Const; we just do nothing when handed
97 * a Const. More care is needed for node types that are used as both
98 * input and output of transformExpr; see SubLink for example.
100 Node *
101 transformExpr(ParseState *pstate, Node *expr)
103 Node *result = NULL;
105 if (expr == NULL)
106 return NULL;
108 /* Guard against stack overflow due to overly complex expressions */
109 check_stack_depth();
111 switch (nodeTag(expr))
113 case T_ColumnRef:
114 result = transformColumnRef(pstate, (ColumnRef *) expr);
115 break;
117 case T_ParamRef:
118 result = transformParamRef(pstate, (ParamRef *) expr);
119 break;
121 case T_A_Const:
123 A_Const *con = (A_Const *) expr;
124 Value *val = &con->val;
126 result = (Node *) make_const(pstate, val, con->location);
127 break;
130 case T_A_Indirection:
132 A_Indirection *ind = (A_Indirection *) expr;
134 result = transformExpr(pstate, ind->arg);
135 result = transformIndirection(pstate, result,
136 ind->indirection);
137 break;
140 case T_A_ArrayExpr:
141 result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
142 InvalidOid, InvalidOid, -1);
143 break;
145 case T_TypeCast:
147 TypeCast *tc = (TypeCast *) expr;
150 * If the subject of the typecast is an ARRAY[] construct
151 * and the target type is an array type, we invoke
152 * transformArrayExpr() directly so that we can pass down
153 * the type information. This avoids some cases where
154 * transformArrayExpr() might not infer the correct type.
156 if (IsA(tc->arg, A_ArrayExpr))
158 Oid targetType;
159 Oid elementType;
160 int32 targetTypmod;
162 targetType = typenameTypeId(pstate, tc->typename,
163 &targetTypmod);
164 elementType = get_element_type(targetType);
165 if (OidIsValid(elementType))
167 result = transformArrayExpr(pstate,
168 (A_ArrayExpr *) tc->arg,
169 targetType,
170 elementType,
171 targetTypmod);
172 break;
176 * Corner case: ARRAY[] cast to a non-array type.
177 * Fall through to do it the standard way.
181 result = transformTypeCast(pstate, tc);
182 break;
185 case T_A_Expr:
187 A_Expr *a = (A_Expr *) expr;
189 switch (a->kind)
191 case AEXPR_OP:
192 result = transformAExprOp(pstate, a);
193 break;
194 case AEXPR_AND:
195 result = transformAExprAnd(pstate, a);
196 break;
197 case AEXPR_OR:
198 result = transformAExprOr(pstate, a);
199 break;
200 case AEXPR_NOT:
201 result = transformAExprNot(pstate, a);
202 break;
203 case AEXPR_OP_ANY:
204 result = transformAExprOpAny(pstate, a);
205 break;
206 case AEXPR_OP_ALL:
207 result = transformAExprOpAll(pstate, a);
208 break;
209 case AEXPR_DISTINCT:
210 result = transformAExprDistinct(pstate, a);
211 break;
212 case AEXPR_NULLIF:
213 result = transformAExprNullIf(pstate, a);
214 break;
215 case AEXPR_OF:
216 result = transformAExprOf(pstate, a);
217 break;
218 case AEXPR_IN:
219 result = transformAExprIn(pstate, a);
220 break;
221 default:
222 elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
224 break;
227 case T_FuncCall:
228 result = transformFuncCall(pstate, (FuncCall *) expr);
229 break;
231 case T_SubLink:
232 result = transformSubLink(pstate, (SubLink *) expr);
233 break;
235 case T_CaseExpr:
236 result = transformCaseExpr(pstate, (CaseExpr *) expr);
237 break;
239 case T_RowExpr:
240 result = transformRowExpr(pstate, (RowExpr *) expr);
241 break;
243 case T_CoalesceExpr:
244 result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
245 break;
247 case T_MinMaxExpr:
248 result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
249 break;
251 case T_XmlExpr:
252 result = transformXmlExpr(pstate, (XmlExpr *) expr);
253 break;
255 case T_XmlSerialize:
256 result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
257 break;
259 case T_NullTest:
261 NullTest *n = (NullTest *) expr;
263 n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
264 /* the argument can be any type, so don't coerce it */
265 result = expr;
266 break;
269 case T_BooleanTest:
270 result = transformBooleanTest(pstate, (BooleanTest *) expr);
271 break;
273 case T_CurrentOfExpr:
274 result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
275 break;
277 /*********************************************
278 * Quietly accept node types that may be presented when we are
279 * called on an already-transformed tree.
281 * Do any other node types need to be accepted? For now we are
282 * taking a conservative approach, and only accepting node
283 * types that are demonstrably necessary to accept.
284 *********************************************/
285 case T_Var:
286 case T_Const:
287 case T_Param:
288 case T_Aggref:
289 case T_ArrayRef:
290 case T_FuncExpr:
291 case T_OpExpr:
292 case T_DistinctExpr:
293 case T_ScalarArrayOpExpr:
294 case T_NullIfExpr:
295 case T_BoolExpr:
296 case T_FieldSelect:
297 case T_FieldStore:
298 case T_RelabelType:
299 case T_CoerceViaIO:
300 case T_ArrayCoerceExpr:
301 case T_ConvertRowtypeExpr:
302 case T_CaseTestExpr:
303 case T_CoerceToDomain:
304 case T_CoerceToDomainValue:
305 case T_SetToDefault:
307 result = (Node *) expr;
308 break;
311 default:
312 /* should not reach here */
313 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
314 break;
317 return result;
320 static Node *
321 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
323 Node *result = basenode;
324 List *subscripts = NIL;
325 ListCell *i;
328 * We have to split any field-selection operations apart from
329 * subscripting. Adjacent A_Indices nodes have to be treated as a single
330 * multidimensional subscript operation.
332 foreach(i, indirection)
334 Node *n = lfirst(i);
336 if (IsA(n, A_Indices))
337 subscripts = lappend(subscripts, n);
338 else if (IsA(n, A_Star))
340 ereport(ERROR,
341 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
342 errmsg("row expansion via \"*\" is not supported here"),
343 parser_errposition(pstate, exprLocation(basenode))));
345 else
347 Assert(IsA(n, String));
349 /* process subscripts before this field selection */
350 if (subscripts)
351 result = (Node *) transformArraySubscripts(pstate,
352 result,
353 exprType(result),
354 InvalidOid,
355 exprTypmod(result),
356 subscripts,
357 NULL);
358 subscripts = NIL;
360 result = ParseFuncOrColumn(pstate,
361 list_make1(n),
362 list_make1(result),
363 false, false, false,
364 true, -1);
367 /* process trailing subscripts, if any */
368 if (subscripts)
369 result = (Node *) transformArraySubscripts(pstate,
370 result,
371 exprType(result),
372 InvalidOid,
373 exprTypmod(result),
374 subscripts,
375 NULL);
377 return result;
380 static Node *
381 transformColumnRef(ParseState *pstate, ColumnRef *cref)
383 int numnames = list_length(cref->fields);
384 Node *node;
385 int levels_up;
387 /*----------
388 * The allowed syntaxes are:
390 * A First try to resolve as unqualified column name;
391 * if no luck, try to resolve as unqualified table name (A.*).
392 * A.B A is an unqualified table name; B is either a
393 * column or function name (trying column name first).
394 * A.B.C schema A, table B, col or func name C.
395 * A.B.C.D catalog A, schema B, table C, col or func D.
396 * A.* A is an unqualified table name; means whole-row value.
397 * A.B.* whole-row value of table B in schema A.
398 * A.B.C.* whole-row value of table C in schema B in catalog A.
400 * We do not need to cope with bare "*"; that will only be accepted by
401 * the grammar at the top level of a SELECT list, and transformTargetList
402 * will take care of it before it ever gets here. Also, "A.*" etc will
403 * be expanded by transformTargetList if they appear at SELECT top level,
404 * so here we are only going to see them as function or operator inputs.
406 * Currently, if a catalog name is given then it must equal the current
407 * database name; we check it here and then discard it.
408 *----------
410 switch (numnames)
412 case 1:
414 Node *field1 = (Node *) linitial(cref->fields);
415 char *name1;
417 Assert(IsA(field1, String));
418 name1 = strVal(field1);
420 /* Try to identify as an unqualified column */
421 node = colNameToVar(pstate, name1, false, cref->location);
423 if (node == NULL)
426 * Not known as a column of any range-table entry.
428 * Consider the possibility that it's VALUE in a domain
429 * check expression. (We handle VALUE as a name, not a
430 * keyword, to avoid breaking a lot of applications that
431 * have used VALUE as a column name in the past.)
433 if (pstate->p_value_substitute != NULL &&
434 strcmp(name1, "value") == 0)
436 node = (Node *) copyObject(pstate->p_value_substitute);
439 * Try to propagate location knowledge. This should
440 * be extended if p_value_substitute can ever take on
441 * other node types.
443 if (IsA(node, CoerceToDomainValue))
444 ((CoerceToDomainValue *) node)->location = cref->location;
445 break;
449 * Try to find the name as a relation. Note that only
450 * relations already entered into the rangetable will be
451 * recognized.
453 * This is a hack for backwards compatibility with
454 * PostQUEL-inspired syntax. The preferred form now is
455 * "rel.*".
457 if (refnameRangeTblEntry(pstate, NULL, name1,
458 cref->location,
459 &levels_up) != NULL)
460 node = transformWholeRowRef(pstate, NULL, name1,
461 cref->location);
462 else
463 ereport(ERROR,
464 (errcode(ERRCODE_UNDEFINED_COLUMN),
465 errmsg("column \"%s\" does not exist",
466 name1),
467 parser_errposition(pstate, cref->location)));
469 break;
471 case 2:
473 Node *field1 = (Node *) linitial(cref->fields);
474 Node *field2 = (Node *) lsecond(cref->fields);
475 char *name1;
476 char *name2;
478 Assert(IsA(field1, String));
479 name1 = strVal(field1);
481 /* Whole-row reference? */
482 if (IsA(field2, A_Star))
484 node = transformWholeRowRef(pstate, NULL, name1,
485 cref->location);
486 break;
489 Assert(IsA(field2, String));
490 name2 = strVal(field2);
492 /* Try to identify as a once-qualified column */
493 node = qualifiedNameToVar(pstate, NULL, name1, name2, true,
494 cref->location);
495 if (node == NULL)
498 * Not known as a column of any range-table entry, so try
499 * it as a function call. Here, we will create an
500 * implicit RTE for tables not already entered.
502 node = transformWholeRowRef(pstate, NULL, name1,
503 cref->location);
504 node = ParseFuncOrColumn(pstate,
505 list_make1(makeString(name2)),
506 list_make1(node),
507 false, false, false,
508 true, cref->location);
510 break;
512 case 3:
514 Node *field1 = (Node *) linitial(cref->fields);
515 Node *field2 = (Node *) lsecond(cref->fields);
516 Node *field3 = (Node *) lthird(cref->fields);
517 char *name1;
518 char *name2;
519 char *name3;
521 Assert(IsA(field1, String));
522 name1 = strVal(field1);
523 Assert(IsA(field2, String));
524 name2 = strVal(field2);
526 /* Whole-row reference? */
527 if (IsA(field3, A_Star))
529 node = transformWholeRowRef(pstate, name1, name2,
530 cref->location);
531 break;
534 Assert(IsA(field3, String));
535 name3 = strVal(field3);
537 /* Try to identify as a twice-qualified column */
538 node = qualifiedNameToVar(pstate, name1, name2, name3, true,
539 cref->location);
540 if (node == NULL)
542 /* Try it as a function call */
543 node = transformWholeRowRef(pstate, name1, name2,
544 cref->location);
545 node = ParseFuncOrColumn(pstate,
546 list_make1(makeString(name3)),
547 list_make1(node),
548 false, false, false,
549 true, cref->location);
551 break;
553 case 4:
555 Node *field1 = (Node *) linitial(cref->fields);
556 Node *field2 = (Node *) lsecond(cref->fields);
557 Node *field3 = (Node *) lthird(cref->fields);
558 Node *field4 = (Node *) lfourth(cref->fields);
559 char *name1;
560 char *name2;
561 char *name3;
562 char *name4;
564 Assert(IsA(field1, String));
565 name1 = strVal(field1);
566 Assert(IsA(field2, String));
567 name2 = strVal(field2);
568 Assert(IsA(field3, String));
569 name3 = strVal(field3);
572 * We check the catalog name and then ignore it.
574 if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
575 ereport(ERROR,
576 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
577 errmsg("cross-database references are not implemented: %s",
578 NameListToString(cref->fields)),
579 parser_errposition(pstate, cref->location)));
581 /* Whole-row reference? */
582 if (IsA(field4, A_Star))
584 node = transformWholeRowRef(pstate, name2, name3,
585 cref->location);
586 break;
589 Assert(IsA(field4, String));
590 name4 = strVal(field4);
592 /* Try to identify as a twice-qualified column */
593 node = qualifiedNameToVar(pstate, name2, name3, name4, true,
594 cref->location);
595 if (node == NULL)
597 /* Try it as a function call */
598 node = transformWholeRowRef(pstate, name2, name3,
599 cref->location);
600 node = ParseFuncOrColumn(pstate,
601 list_make1(makeString(name4)),
602 list_make1(node),
603 false, false, false,
604 true, cref->location);
606 break;
608 default:
609 ereport(ERROR,
610 (errcode(ERRCODE_SYNTAX_ERROR),
611 errmsg("improper qualified name (too many dotted names): %s",
612 NameListToString(cref->fields)),
613 parser_errposition(pstate, cref->location)));
614 node = NULL; /* keep compiler quiet */
615 break;
618 return node;
622 * Locate the parameter type info for the given parameter number, and
623 * return a pointer to it.
625 static Oid *
626 find_param_type(ParseState *pstate, int paramno, int location)
628 Oid *result;
631 * Find topmost ParseState, which is where paramtype info lives.
633 while (pstate->parentParseState != NULL)
634 pstate = pstate->parentParseState;
636 /* Check parameter number is in range */
637 if (paramno <= 0) /* probably can't happen? */
638 ereport(ERROR,
639 (errcode(ERRCODE_UNDEFINED_PARAMETER),
640 errmsg("there is no parameter $%d", paramno),
641 parser_errposition(pstate, location)));
642 if (paramno > pstate->p_numparams)
644 if (!pstate->p_variableparams)
645 ereport(ERROR,
646 (errcode(ERRCODE_UNDEFINED_PARAMETER),
647 errmsg("there is no parameter $%d", paramno),
648 parser_errposition(pstate, location)));
649 /* Okay to enlarge param array */
650 if (pstate->p_paramtypes)
651 pstate->p_paramtypes = (Oid *) repalloc(pstate->p_paramtypes,
652 paramno * sizeof(Oid));
653 else
654 pstate->p_paramtypes = (Oid *) palloc(paramno * sizeof(Oid));
655 /* Zero out the previously-unreferenced slots */
656 MemSet(pstate->p_paramtypes + pstate->p_numparams,
658 (paramno - pstate->p_numparams) * sizeof(Oid));
659 pstate->p_numparams = paramno;
662 result = &pstate->p_paramtypes[paramno - 1];
664 if (pstate->p_variableparams)
666 /* If not seen before, initialize to UNKNOWN type */
667 if (*result == InvalidOid)
668 *result = UNKNOWNOID;
671 return result;
674 static Node *
675 transformParamRef(ParseState *pstate, ParamRef *pref)
677 int paramno = pref->number;
678 Oid *pptype = find_param_type(pstate, paramno, pref->location);
679 Param *param;
681 param = makeNode(Param);
682 param->paramkind = PARAM_EXTERN;
683 param->paramid = paramno;
684 param->paramtype = *pptype;
685 param->paramtypmod = -1;
686 param->location = pref->location;
688 return (Node *) param;
691 /* Test whether an a_expr is a plain NULL constant or not */
692 static bool
693 exprIsNullConstant(Node *arg)
695 if (arg && IsA(arg, A_Const))
697 A_Const *con = (A_Const *) arg;
699 if (con->val.type == T_Null)
700 return true;
702 return false;
705 static Node *
706 transformAExprOp(ParseState *pstate, A_Expr *a)
708 Node *lexpr = a->lexpr;
709 Node *rexpr = a->rexpr;
710 Node *result;
713 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
714 * standards-broken products (like Microsoft's). Turn these into IS NULL
715 * exprs.
717 if (Transform_null_equals &&
718 list_length(a->name) == 1 &&
719 strcmp(strVal(linitial(a->name)), "=") == 0 &&
720 (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)))
722 NullTest *n = makeNode(NullTest);
724 n->nulltesttype = IS_NULL;
726 if (exprIsNullConstant(lexpr))
727 n->arg = (Expr *) rexpr;
728 else
729 n->arg = (Expr *) lexpr;
731 result = transformExpr(pstate, (Node *) n);
733 else if (lexpr && IsA(lexpr, RowExpr) &&
734 rexpr && IsA(rexpr, SubLink) &&
735 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
738 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
739 * grammar did this, but now that a row construct is allowed anywhere
740 * in expressions, it's easier to do it here.
742 SubLink *s = (SubLink *) rexpr;
744 s->subLinkType = ROWCOMPARE_SUBLINK;
745 s->testexpr = lexpr;
746 s->operName = a->name;
747 s->location = a->location;
748 result = transformExpr(pstate, (Node *) s);
750 else if (lexpr && IsA(lexpr, RowExpr) &&
751 rexpr && IsA(rexpr, RowExpr))
753 /* "row op row" */
754 lexpr = transformExpr(pstate, lexpr);
755 rexpr = transformExpr(pstate, rexpr);
756 Assert(IsA(lexpr, RowExpr));
757 Assert(IsA(rexpr, RowExpr));
759 result = make_row_comparison_op(pstate,
760 a->name,
761 ((RowExpr *) lexpr)->args,
762 ((RowExpr *) rexpr)->args,
763 a->location);
765 else
767 /* Ordinary scalar operator */
768 lexpr = transformExpr(pstate, lexpr);
769 rexpr = transformExpr(pstate, rexpr);
771 result = (Node *) make_op(pstate,
772 a->name,
773 lexpr,
774 rexpr,
775 a->location);
778 return result;
781 static Node *
782 transformAExprAnd(ParseState *pstate, A_Expr *a)
784 Node *lexpr = transformExpr(pstate, a->lexpr);
785 Node *rexpr = transformExpr(pstate, a->rexpr);
787 lexpr = coerce_to_boolean(pstate, lexpr, "AND");
788 rexpr = coerce_to_boolean(pstate, rexpr, "AND");
790 return (Node *) makeBoolExpr(AND_EXPR,
791 list_make2(lexpr, rexpr),
792 a->location);
795 static Node *
796 transformAExprOr(ParseState *pstate, A_Expr *a)
798 Node *lexpr = transformExpr(pstate, a->lexpr);
799 Node *rexpr = transformExpr(pstate, a->rexpr);
801 lexpr = coerce_to_boolean(pstate, lexpr, "OR");
802 rexpr = coerce_to_boolean(pstate, rexpr, "OR");
804 return (Node *) makeBoolExpr(OR_EXPR,
805 list_make2(lexpr, rexpr),
806 a->location);
809 static Node *
810 transformAExprNot(ParseState *pstate, A_Expr *a)
812 Node *rexpr = transformExpr(pstate, a->rexpr);
814 rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
816 return (Node *) makeBoolExpr(NOT_EXPR,
817 list_make1(rexpr),
818 a->location);
821 static Node *
822 transformAExprOpAny(ParseState *pstate, A_Expr *a)
824 Node *lexpr = transformExpr(pstate, a->lexpr);
825 Node *rexpr = transformExpr(pstate, a->rexpr);
827 return (Node *) make_scalar_array_op(pstate,
828 a->name,
829 true,
830 lexpr,
831 rexpr,
832 a->location);
835 static Node *
836 transformAExprOpAll(ParseState *pstate, A_Expr *a)
838 Node *lexpr = transformExpr(pstate, a->lexpr);
839 Node *rexpr = transformExpr(pstate, a->rexpr);
841 return (Node *) make_scalar_array_op(pstate,
842 a->name,
843 false,
844 lexpr,
845 rexpr,
846 a->location);
849 static Node *
850 transformAExprDistinct(ParseState *pstate, A_Expr *a)
852 Node *lexpr = transformExpr(pstate, a->lexpr);
853 Node *rexpr = transformExpr(pstate, a->rexpr);
855 if (lexpr && IsA(lexpr, RowExpr) &&
856 rexpr && IsA(rexpr, RowExpr))
858 /* "row op row" */
859 return make_row_distinct_op(pstate, a->name,
860 (RowExpr *) lexpr,
861 (RowExpr *) rexpr,
862 a->location);
864 else
866 /* Ordinary scalar operator */
867 return (Node *) make_distinct_op(pstate,
868 a->name,
869 lexpr,
870 rexpr,
871 a->location);
875 static Node *
876 transformAExprNullIf(ParseState *pstate, A_Expr *a)
878 Node *lexpr = transformExpr(pstate, a->lexpr);
879 Node *rexpr = transformExpr(pstate, a->rexpr);
880 Node *result;
882 result = (Node *) make_op(pstate,
883 a->name,
884 lexpr,
885 rexpr,
886 a->location);
887 if (((OpExpr *) result)->opresulttype != BOOLOID)
888 ereport(ERROR,
889 (errcode(ERRCODE_DATATYPE_MISMATCH),
890 errmsg("NULLIF requires = operator to yield boolean"),
891 parser_errposition(pstate, a->location)));
894 * We rely on NullIfExpr and OpExpr being the same struct
896 NodeSetTag(result, T_NullIfExpr);
898 return result;
901 static Node *
902 transformAExprOf(ParseState *pstate, A_Expr *a)
905 * Checking an expression for match to a list of type names. Will result
906 * in a boolean constant node.
908 Node *lexpr = transformExpr(pstate, a->lexpr);
909 Const *result;
910 ListCell *telem;
911 Oid ltype,
912 rtype;
913 bool matched = false;
915 ltype = exprType(lexpr);
916 foreach(telem, (List *) a->rexpr)
918 rtype = typenameTypeId(pstate, lfirst(telem), NULL);
919 matched = (rtype == ltype);
920 if (matched)
921 break;
925 * We have two forms: equals or not equals. Flip the sense of the result
926 * for not equals.
928 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
929 matched = (!matched);
931 result = (Const *) makeBoolConst(matched, false);
933 /* Make the result have the original input's parse location */
934 result->location = exprLocation((Node *) a);
936 return (Node *) result;
939 static Node *
940 transformAExprIn(ParseState *pstate, A_Expr *a)
942 Node *result = NULL;
943 Node *lexpr;
944 List *rexprs;
945 List *rvars;
946 List *rnonvars;
947 bool useOr;
948 bool haveRowExpr;
949 ListCell *l;
952 * If the operator is <>, combine with AND not OR.
954 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
955 useOr = false;
956 else
957 useOr = true;
960 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
961 * possible if the inputs are all scalars (no RowExprs) and there is a
962 * suitable array type available. If not, we fall back to a boolean
963 * condition tree with multiple copies of the lefthand expression.
964 * Also, any IN-list items that contain Vars are handled as separate
965 * boolean conditions, because that gives the planner more scope for
966 * optimization on such clauses.
968 * First step: transform all the inputs, and detect whether any are
969 * RowExprs or contain Vars.
971 lexpr = transformExpr(pstate, a->lexpr);
972 haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
973 rexprs = rvars = rnonvars = NIL;
974 foreach(l, (List *) a->rexpr)
976 Node *rexpr = transformExpr(pstate, lfirst(l));
978 haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
979 rexprs = lappend(rexprs, rexpr);
980 if (contain_vars_of_level(rexpr, 0))
981 rvars = lappend(rvars, rexpr);
982 else
983 rnonvars = lappend(rnonvars, rexpr);
987 * ScalarArrayOpExpr is only going to be useful if there's more than
988 * one non-Var righthand item. Also, it won't work for RowExprs.
990 if (!haveRowExpr && list_length(rnonvars) > 1)
992 List *allexprs;
993 Oid scalar_type;
994 Oid array_type;
997 * Try to select a common type for the array elements. Note that
998 * since the LHS' type is first in the list, it will be preferred when
999 * there is doubt (eg, when all the RHS items are unknown literals).
1001 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1003 allexprs = list_concat(list_make1(lexpr), rnonvars);
1004 scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1006 /* Do we have an array type to use? */
1007 if (OidIsValid(scalar_type))
1008 array_type = get_array_type(scalar_type);
1009 else
1010 array_type = InvalidOid;
1011 if (array_type != InvalidOid)
1014 * OK: coerce all the right-hand non-Var inputs to the common type
1015 * and build an ArrayExpr for them.
1017 List *aexprs;
1018 ArrayExpr *newa;
1020 aexprs = NIL;
1021 foreach(l, rnonvars)
1023 Node *rexpr = (Node *) lfirst(l);
1025 rexpr = coerce_to_common_type(pstate, rexpr,
1026 scalar_type,
1027 "IN");
1028 aexprs = lappend(aexprs, rexpr);
1030 newa = makeNode(ArrayExpr);
1031 newa->array_typeid = array_type;
1032 newa->element_typeid = scalar_type;
1033 newa->elements = aexprs;
1034 newa->multidims = false;
1035 newa->location = -1;
1037 result = (Node *) make_scalar_array_op(pstate,
1038 a->name,
1039 useOr,
1040 lexpr,
1041 (Node *) newa,
1042 a->location);
1044 /* Consider only the Vars (if any) in the loop below */
1045 rexprs = rvars;
1050 * Must do it the hard way, ie, with a boolean expression tree.
1052 foreach(l, rexprs)
1054 Node *rexpr = (Node *) lfirst(l);
1055 Node *cmp;
1057 if (haveRowExpr)
1059 if (!IsA(lexpr, RowExpr) ||
1060 !IsA(rexpr, RowExpr))
1061 ereport(ERROR,
1062 (errcode(ERRCODE_SYNTAX_ERROR),
1063 errmsg("arguments of row IN must all be row expressions"),
1064 parser_errposition(pstate, a->location)));
1065 cmp = make_row_comparison_op(pstate,
1066 a->name,
1067 (List *) copyObject(((RowExpr *) lexpr)->args),
1068 ((RowExpr *) rexpr)->args,
1069 a->location);
1071 else
1072 cmp = (Node *) make_op(pstate,
1073 a->name,
1074 copyObject(lexpr),
1075 rexpr,
1076 a->location);
1078 cmp = coerce_to_boolean(pstate, cmp, "IN");
1079 if (result == NULL)
1080 result = cmp;
1081 else
1082 result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1083 list_make2(result, cmp),
1084 a->location);
1087 return result;
1090 static Node *
1091 transformFuncCall(ParseState *pstate, FuncCall *fn)
1093 List *targs;
1094 ListCell *args;
1096 /* Transform the list of arguments ... */
1097 targs = NIL;
1098 foreach(args, fn->args)
1100 targs = lappend(targs, transformExpr(pstate,
1101 (Node *) lfirst(args)));
1104 /* ... and hand off to ParseFuncOrColumn */
1105 return ParseFuncOrColumn(pstate,
1106 fn->funcname,
1107 targs,
1108 fn->agg_star,
1109 fn->agg_distinct,
1110 fn->func_variadic,
1111 false,
1112 fn->location);
1115 static Node *
1116 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1118 CaseExpr *newc;
1119 Node *arg;
1120 CaseTestExpr *placeholder;
1121 List *newargs;
1122 List *resultexprs;
1123 ListCell *l;
1124 Node *defresult;
1125 Oid ptype;
1127 /* If we already transformed this node, do nothing */
1128 if (OidIsValid(c->casetype))
1129 return (Node *) c;
1131 newc = makeNode(CaseExpr);
1133 /* transform the test expression, if any */
1134 arg = transformExpr(pstate, (Node *) c->arg);
1136 /* generate placeholder for test expression */
1137 if (arg)
1140 * If test expression is an untyped literal, force it to text. We have
1141 * to do something now because we won't be able to do this coercion on
1142 * the placeholder. This is not as flexible as what was done in 7.4
1143 * and before, but it's good enough to handle the sort of silly coding
1144 * commonly seen.
1146 if (exprType(arg) == UNKNOWNOID)
1147 arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1149 placeholder = makeNode(CaseTestExpr);
1150 placeholder->typeId = exprType(arg);
1151 placeholder->typeMod = exprTypmod(arg);
1153 else
1154 placeholder = NULL;
1156 newc->arg = (Expr *) arg;
1158 /* transform the list of arguments */
1159 newargs = NIL;
1160 resultexprs = NIL;
1161 foreach(l, c->args)
1163 CaseWhen *w = (CaseWhen *) lfirst(l);
1164 CaseWhen *neww = makeNode(CaseWhen);
1165 Node *warg;
1167 Assert(IsA(w, CaseWhen));
1169 warg = (Node *) w->expr;
1170 if (placeholder)
1172 /* shorthand form was specified, so expand... */
1173 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1174 (Node *) placeholder,
1175 warg,
1176 w->location);
1178 neww->expr = (Expr *) transformExpr(pstate, warg);
1180 neww->expr = (Expr *) coerce_to_boolean(pstate,
1181 (Node *) neww->expr,
1182 "CASE/WHEN");
1184 warg = (Node *) w->result;
1185 neww->result = (Expr *) transformExpr(pstate, warg);
1186 neww->location = w->location;
1188 newargs = lappend(newargs, neww);
1189 resultexprs = lappend(resultexprs, neww->result);
1192 newc->args = newargs;
1194 /* transform the default clause */
1195 defresult = (Node *) c->defresult;
1196 if (defresult == NULL)
1198 A_Const *n = makeNode(A_Const);
1200 n->val.type = T_Null;
1201 n->location = -1;
1202 defresult = (Node *) n;
1204 newc->defresult = (Expr *) transformExpr(pstate, defresult);
1207 * Note: default result is considered the most significant type in
1208 * determining preferred type. This is how the code worked before, but it
1209 * seems a little bogus to me --- tgl
1211 resultexprs = lcons(newc->defresult, resultexprs);
1213 ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1214 Assert(OidIsValid(ptype));
1215 newc->casetype = ptype;
1217 /* Convert default result clause, if necessary */
1218 newc->defresult = (Expr *)
1219 coerce_to_common_type(pstate,
1220 (Node *) newc->defresult,
1221 ptype,
1222 "CASE/ELSE");
1224 /* Convert when-clause results, if necessary */
1225 foreach(l, newc->args)
1227 CaseWhen *w = (CaseWhen *) lfirst(l);
1229 w->result = (Expr *)
1230 coerce_to_common_type(pstate,
1231 (Node *) w->result,
1232 ptype,
1233 "CASE/WHEN");
1236 newc->location = c->location;
1238 return (Node *) newc;
1241 static Node *
1242 transformSubLink(ParseState *pstate, SubLink *sublink)
1244 Node *result = (Node *) sublink;
1245 Query *qtree;
1247 /* If we already transformed this node, do nothing */
1248 if (IsA(sublink->subselect, Query))
1249 return result;
1251 pstate->p_hasSubLinks = true;
1252 qtree = parse_sub_analyze(sublink->subselect, pstate);
1255 * Check that we got something reasonable. Many of these conditions are
1256 * impossible given restrictions of the grammar, but check 'em anyway.
1258 if (!IsA(qtree, Query) ||
1259 qtree->commandType != CMD_SELECT ||
1260 qtree->utilityStmt != NULL)
1261 elog(ERROR, "unexpected non-SELECT command in SubLink");
1262 if (qtree->intoClause)
1263 ereport(ERROR,
1264 (errcode(ERRCODE_SYNTAX_ERROR),
1265 errmsg("subquery cannot have SELECT INTO"),
1266 parser_errposition(pstate,
1267 exprLocation((Node *) qtree->intoClause))));
1269 sublink->subselect = (Node *) qtree;
1271 if (sublink->subLinkType == EXISTS_SUBLINK)
1274 * EXISTS needs no test expression or combining operator. These fields
1275 * should be null already, but make sure.
1277 sublink->testexpr = NULL;
1278 sublink->operName = NIL;
1280 else if (sublink->subLinkType == EXPR_SUBLINK ||
1281 sublink->subLinkType == ARRAY_SUBLINK)
1283 ListCell *tlist_item = list_head(qtree->targetList);
1286 * Make sure the subselect delivers a single column (ignoring resjunk
1287 * targets).
1289 if (tlist_item == NULL ||
1290 ((TargetEntry *) lfirst(tlist_item))->resjunk)
1291 ereport(ERROR,
1292 (errcode(ERRCODE_SYNTAX_ERROR),
1293 errmsg("subquery must return a column"),
1294 parser_errposition(pstate, sublink->location)));
1295 while ((tlist_item = lnext(tlist_item)) != NULL)
1297 if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1298 ereport(ERROR,
1299 (errcode(ERRCODE_SYNTAX_ERROR),
1300 errmsg("subquery must return only one column"),
1301 parser_errposition(pstate, sublink->location)));
1305 * EXPR and ARRAY need no test expression or combining operator. These
1306 * fields should be null already, but make sure.
1308 sublink->testexpr = NULL;
1309 sublink->operName = NIL;
1311 else
1313 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1314 Node *lefthand;
1315 List *left_list;
1316 List *right_list;
1317 ListCell *l;
1320 * Transform lefthand expression, and convert to a list
1322 lefthand = transformExpr(pstate, sublink->testexpr);
1323 if (lefthand && IsA(lefthand, RowExpr))
1324 left_list = ((RowExpr *) lefthand)->args;
1325 else
1326 left_list = list_make1(lefthand);
1329 * Build a list of PARAM_SUBLINK nodes representing the output columns
1330 * of the subquery.
1332 right_list = NIL;
1333 foreach(l, qtree->targetList)
1335 TargetEntry *tent = (TargetEntry *) lfirst(l);
1336 Param *param;
1338 if (tent->resjunk)
1339 continue;
1341 param = makeNode(Param);
1342 param->paramkind = PARAM_SUBLINK;
1343 param->paramid = tent->resno;
1344 param->paramtype = exprType((Node *) tent->expr);
1345 param->paramtypmod = exprTypmod((Node *) tent->expr);
1346 param->location = -1;
1348 right_list = lappend(right_list, param);
1352 * We could rely on make_row_comparison_op to complain if the list
1353 * lengths differ, but we prefer to generate a more specific error
1354 * message.
1356 if (list_length(left_list) < list_length(right_list))
1357 ereport(ERROR,
1358 (errcode(ERRCODE_SYNTAX_ERROR),
1359 errmsg("subquery has too many columns"),
1360 parser_errposition(pstate, sublink->location)));
1361 if (list_length(left_list) > list_length(right_list))
1362 ereport(ERROR,
1363 (errcode(ERRCODE_SYNTAX_ERROR),
1364 errmsg("subquery has too few columns"),
1365 parser_errposition(pstate, sublink->location)));
1368 * Identify the combining operator(s) and generate a suitable
1369 * row-comparison expression.
1371 sublink->testexpr = make_row_comparison_op(pstate,
1372 sublink->operName,
1373 left_list,
1374 right_list,
1375 sublink->location);
1378 return result;
1382 * transformArrayExpr
1384 * If the caller specifies the target type, the resulting array will
1385 * be of exactly that type. Otherwise we try to infer a common type
1386 * for the elements using select_common_type().
1388 static Node *
1389 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
1390 Oid array_type, Oid element_type, int32 typmod)
1392 ArrayExpr *newa = makeNode(ArrayExpr);
1393 List *newelems = NIL;
1394 List *newcoercedelems = NIL;
1395 ListCell *element;
1396 Oid coerce_type;
1397 bool coerce_hard;
1400 * Transform the element expressions
1402 * Assume that the array is one-dimensional unless we find an
1403 * array-type element expression.
1405 newa->multidims = false;
1406 foreach(element, a->elements)
1408 Node *e = (Node *) lfirst(element);
1409 Node *newe;
1412 * If an element is itself an A_ArrayExpr, recurse directly so that
1413 * we can pass down any target type we were given.
1415 if (IsA(e, A_ArrayExpr))
1417 newe = transformArrayExpr(pstate,
1418 (A_ArrayExpr *) e,
1419 array_type,
1420 element_type,
1421 typmod);
1422 /* we certainly have an array here */
1423 Assert(array_type == InvalidOid || array_type == exprType(newe));
1424 newa->multidims = true;
1426 else
1428 newe = transformExpr(pstate, e);
1430 * Check for sub-array expressions, if we haven't already
1431 * found one.
1433 if (!newa->multidims && type_is_array(exprType(newe)))
1434 newa->multidims = true;
1437 newelems = lappend(newelems, newe);
1441 * Select a target type for the elements.
1443 * If we haven't been given a target array type, we must try to deduce a
1444 * common type based on the types of the individual elements present.
1446 if (OidIsValid(array_type))
1448 /* Caller must ensure array_type matches element_type */
1449 Assert(OidIsValid(element_type));
1450 coerce_type = (newa->multidims ? array_type : element_type);
1451 coerce_hard = true;
1453 else
1455 /* Can't handle an empty array without a target type */
1456 if (newelems == NIL)
1457 ereport(ERROR,
1458 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1459 errmsg("cannot determine type of empty array"),
1460 errhint("Explicitly cast to the desired type, "
1461 "for example ARRAY[]::integer[]."),
1462 parser_errposition(pstate, a->location)));
1464 /* Select a common type for the elements */
1465 coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1467 if (newa->multidims)
1469 array_type = coerce_type;
1470 element_type = get_element_type(array_type);
1471 if (!OidIsValid(element_type))
1472 ereport(ERROR,
1473 (errcode(ERRCODE_UNDEFINED_OBJECT),
1474 errmsg("could not find element type for data type %s",
1475 format_type_be(array_type)),
1476 parser_errposition(pstate, a->location)));
1478 else
1480 element_type = coerce_type;
1481 array_type = get_array_type(element_type);
1482 if (!OidIsValid(array_type))
1483 ereport(ERROR,
1484 (errcode(ERRCODE_UNDEFINED_OBJECT),
1485 errmsg("could not find array type for data type %s",
1486 format_type_be(element_type)),
1487 parser_errposition(pstate, a->location)));
1489 coerce_hard = false;
1493 * Coerce elements to target type
1495 * If the array has been explicitly cast, then the elements are in turn
1496 * explicitly coerced.
1498 * If the array's type was merely derived from the common type of its
1499 * elements, then the elements are implicitly coerced to the common type.
1500 * This is consistent with other uses of select_common_type().
1502 foreach(element, newelems)
1504 Node *e = (Node *) lfirst(element);
1505 Node *newe;
1507 if (coerce_hard)
1509 newe = coerce_to_target_type(pstate, e,
1510 exprType(e),
1511 coerce_type,
1512 typmod,
1513 COERCION_EXPLICIT,
1514 COERCE_EXPLICIT_CAST,
1515 -1);
1516 if (newe == NULL)
1517 ereport(ERROR,
1518 (errcode(ERRCODE_CANNOT_COERCE),
1519 errmsg("cannot cast type %s to %s",
1520 format_type_be(exprType(e)),
1521 format_type_be(coerce_type)),
1522 parser_errposition(pstate, exprLocation(e))));
1524 else
1525 newe = coerce_to_common_type(pstate, e,
1526 coerce_type,
1527 "ARRAY");
1528 newcoercedelems = lappend(newcoercedelems, newe);
1531 newa->array_typeid = array_type;
1532 newa->element_typeid = element_type;
1533 newa->elements = newcoercedelems;
1534 newa->location = a->location;
1536 return (Node *) newa;
1539 static Node *
1540 transformRowExpr(ParseState *pstate, RowExpr *r)
1542 RowExpr *newr = makeNode(RowExpr);
1544 /* Transform the field expressions */
1545 newr->args = transformExpressionList(pstate, r->args);
1547 /* Barring later casting, we consider the type RECORD */
1548 newr->row_typeid = RECORDOID;
1549 newr->row_format = COERCE_IMPLICIT_CAST;
1550 newr->colnames = NIL; /* ROW() has anonymous columns */
1551 newr->location = r->location;
1553 return (Node *) newr;
1556 static Node *
1557 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
1559 CoalesceExpr *newc = makeNode(CoalesceExpr);
1560 List *newargs = NIL;
1561 List *newcoercedargs = NIL;
1562 ListCell *args;
1564 foreach(args, c->args)
1566 Node *e = (Node *) lfirst(args);
1567 Node *newe;
1569 newe = transformExpr(pstate, e);
1570 newargs = lappend(newargs, newe);
1573 newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1575 /* Convert arguments if necessary */
1576 foreach(args, newargs)
1578 Node *e = (Node *) lfirst(args);
1579 Node *newe;
1581 newe = coerce_to_common_type(pstate, e,
1582 newc->coalescetype,
1583 "COALESCE");
1584 newcoercedargs = lappend(newcoercedargs, newe);
1587 newc->args = newcoercedargs;
1588 newc->location = c->location;
1589 return (Node *) newc;
1592 static Node *
1593 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
1595 MinMaxExpr *newm = makeNode(MinMaxExpr);
1596 List *newargs = NIL;
1597 List *newcoercedargs = NIL;
1598 const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1599 ListCell *args;
1601 newm->op = m->op;
1602 foreach(args, m->args)
1604 Node *e = (Node *) lfirst(args);
1605 Node *newe;
1607 newe = transformExpr(pstate, e);
1608 newargs = lappend(newargs, newe);
1611 newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1613 /* Convert arguments if necessary */
1614 foreach(args, newargs)
1616 Node *e = (Node *) lfirst(args);
1617 Node *newe;
1619 newe = coerce_to_common_type(pstate, e,
1620 newm->minmaxtype,
1621 funcname);
1622 newcoercedargs = lappend(newcoercedargs, newe);
1625 newm->args = newcoercedargs;
1626 newm->location = m->location;
1627 return (Node *) newm;
1630 static Node *
1631 transformXmlExpr(ParseState *pstate, XmlExpr *x)
1633 XmlExpr *newx = makeNode(XmlExpr);
1634 ListCell *lc;
1635 int i;
1637 newx->op = x->op;
1638 if (x->name)
1639 newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1640 else
1641 newx->name = NULL;
1642 newx->xmloption = x->xmloption;
1643 newx->location = x->location;
1646 * gram.y built the named args as a list of ResTarget. Transform each,
1647 * and break the names out as a separate list.
1649 newx->named_args = NIL;
1650 newx->arg_names = NIL;
1652 foreach(lc, x->named_args)
1654 ResTarget *r = (ResTarget *) lfirst(lc);
1655 Node *expr;
1656 char *argname;
1658 Assert(IsA(r, ResTarget));
1660 expr = transformExpr(pstate, r->val);
1662 if (r->name)
1663 argname = map_sql_identifier_to_xml_name(r->name, false, false);
1664 else if (IsA(r->val, ColumnRef))
1665 argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1666 true, false);
1667 else
1669 ereport(ERROR,
1670 (errcode(ERRCODE_SYNTAX_ERROR),
1671 x->op == IS_XMLELEMENT
1672 ? errmsg("unnamed XML attribute value must be a column reference")
1673 : errmsg("unnamed XML element value must be a column reference"),
1674 parser_errposition(pstate, r->location)));
1675 argname = NULL; /* keep compiler quiet */
1678 /* reject duplicate argnames in XMLELEMENT only */
1679 if (x->op == IS_XMLELEMENT)
1681 ListCell *lc2;
1683 foreach(lc2, newx->arg_names)
1685 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1686 ereport(ERROR,
1687 (errcode(ERRCODE_SYNTAX_ERROR),
1688 errmsg("XML attribute name \"%s\" appears more than once",
1689 argname),
1690 parser_errposition(pstate, r->location)));
1694 newx->named_args = lappend(newx->named_args, expr);
1695 newx->arg_names = lappend(newx->arg_names, makeString(argname));
1698 /* The other arguments are of varying types depending on the function */
1699 newx->args = NIL;
1700 i = 0;
1701 foreach(lc, x->args)
1703 Node *e = (Node *) lfirst(lc);
1704 Node *newe;
1706 newe = transformExpr(pstate, e);
1707 switch (x->op)
1709 case IS_XMLCONCAT:
1710 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1711 "XMLCONCAT");
1712 break;
1713 case IS_XMLELEMENT:
1714 /* no coercion necessary */
1715 break;
1716 case IS_XMLFOREST:
1717 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1718 "XMLFOREST");
1719 break;
1720 case IS_XMLPARSE:
1721 if (i == 0)
1722 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1723 "XMLPARSE");
1724 else
1725 newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
1726 break;
1727 case IS_XMLPI:
1728 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1729 "XMLPI");
1730 break;
1731 case IS_XMLROOT:
1732 if (i == 0)
1733 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1734 "XMLROOT");
1735 else if (i == 1)
1736 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1737 "XMLROOT");
1738 else
1739 newe = coerce_to_specific_type(pstate, newe, INT4OID,
1740 "XMLROOT");
1741 break;
1742 case IS_XMLSERIALIZE:
1743 /* not handled here */
1744 Assert(false);
1745 break;
1746 case IS_DOCUMENT:
1747 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1748 "IS DOCUMENT");
1749 break;
1751 newx->args = lappend(newx->args, newe);
1752 i++;
1755 return (Node *) newx;
1758 static Node *
1759 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1761 Node *result;
1762 XmlExpr *xexpr;
1763 Oid targetType;
1764 int32 targetTypmod;
1766 xexpr = makeNode(XmlExpr);
1767 xexpr->op = IS_XMLSERIALIZE;
1768 xexpr->args = list_make1(coerce_to_specific_type(pstate,
1769 transformExpr(pstate, xs->expr),
1770 XMLOID,
1771 "XMLSERIALIZE"));
1773 targetType = typenameTypeId(pstate, xs->typename, &targetTypmod);
1775 xexpr->xmloption = xs->xmloption;
1776 xexpr->location = xs->location;
1777 /* We actually only need these to be able to parse back the expression. */
1778 xexpr->type = targetType;
1779 xexpr->typmod = targetTypmod;
1782 * The actual target type is determined this way. SQL allows char and
1783 * varchar as target types. We allow anything that can be cast implicitly
1784 * from text. This way, user-defined text-like data types automatically
1785 * fit in.
1787 result = coerce_to_target_type(pstate, (Node *) xexpr,
1788 TEXTOID, targetType, targetTypmod,
1789 COERCION_IMPLICIT,
1790 COERCE_IMPLICIT_CAST,
1791 -1);
1792 if (result == NULL)
1793 ereport(ERROR,
1794 (errcode(ERRCODE_CANNOT_COERCE),
1795 errmsg("cannot cast XMLSERIALIZE result to %s",
1796 format_type_be(targetType)),
1797 parser_errposition(pstate, xexpr->location)));
1798 return result;
1801 static Node *
1802 transformBooleanTest(ParseState *pstate, BooleanTest *b)
1804 const char *clausename;
1806 switch (b->booltesttype)
1808 case IS_TRUE:
1809 clausename = "IS TRUE";
1810 break;
1811 case IS_NOT_TRUE:
1812 clausename = "IS NOT TRUE";
1813 break;
1814 case IS_FALSE:
1815 clausename = "IS FALSE";
1816 break;
1817 case IS_NOT_FALSE:
1818 clausename = "IS NOT FALSE";
1819 break;
1820 case IS_UNKNOWN:
1821 clausename = "IS UNKNOWN";
1822 break;
1823 case IS_NOT_UNKNOWN:
1824 clausename = "IS NOT UNKNOWN";
1825 break;
1826 default:
1827 elog(ERROR, "unrecognized booltesttype: %d",
1828 (int) b->booltesttype);
1829 clausename = NULL; /* keep compiler quiet */
1832 b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
1834 b->arg = (Expr *) coerce_to_boolean(pstate,
1835 (Node *) b->arg,
1836 clausename);
1838 return (Node *) b;
1841 static Node *
1842 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1844 int sublevels_up;
1846 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1847 Assert(pstate->p_target_rangetblentry != NULL);
1848 cexpr->cvarno = RTERangeTablePosn(pstate,
1849 pstate->p_target_rangetblentry,
1850 &sublevels_up);
1851 Assert(sublevels_up == 0);
1853 /* If a parameter is used, it must be of type REFCURSOR */
1854 if (cexpr->cursor_name == NULL)
1856 Oid *pptype = find_param_type(pstate, cexpr->cursor_param, -1);
1858 if (pstate->p_variableparams && *pptype == UNKNOWNOID)
1860 /* resolve unknown param type as REFCURSOR */
1861 *pptype = REFCURSOROID;
1863 else if (*pptype != REFCURSOROID)
1865 ereport(ERROR,
1866 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
1867 errmsg("inconsistent types deduced for parameter $%d",
1868 cexpr->cursor_param),
1869 errdetail("%s versus %s",
1870 format_type_be(*pptype),
1871 format_type_be(REFCURSOROID))));
1875 return (Node *) cexpr;
1879 * Construct a whole-row reference to represent the notation "relation.*".
1881 * A whole-row reference is a Var with varno set to the correct range
1882 * table entry, and varattno == 0 to signal that it references the whole
1883 * tuple. (Use of zero here is unclean, since it could easily be confused
1884 * with error cases, but it's not worth changing now.) The vartype indicates
1885 * a rowtype; either a named composite type, or RECORD.
1887 static Node *
1888 transformWholeRowRef(ParseState *pstate, char *schemaname, char *relname,
1889 int location)
1891 Var *result;
1892 RangeTblEntry *rte;
1893 int vnum;
1894 int sublevels_up;
1895 Oid toid;
1897 /* Look up the referenced RTE, creating it if needed */
1899 rte = refnameRangeTblEntry(pstate, schemaname, relname, location,
1900 &sublevels_up);
1902 if (rte == NULL)
1903 rte = addImplicitRTE(pstate,
1904 makeRangeVar(schemaname, relname, location));
1906 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
1908 /* Build the appropriate referencing node */
1910 switch (rte->rtekind)
1912 case RTE_RELATION:
1913 /* relation: the rowtype is a named composite type */
1914 toid = get_rel_type_id(rte->relid);
1915 if (!OidIsValid(toid))
1916 elog(ERROR, "could not find type OID for relation %u",
1917 rte->relid);
1918 result = makeVar(vnum,
1919 InvalidAttrNumber,
1920 toid,
1922 sublevels_up);
1923 break;
1924 case RTE_FUNCTION:
1925 toid = exprType(rte->funcexpr);
1926 if (type_is_rowtype(toid))
1928 /* func returns composite; same as relation case */
1929 result = makeVar(vnum,
1930 InvalidAttrNumber,
1931 toid,
1933 sublevels_up);
1935 else
1938 * func returns scalar; instead of making a whole-row Var,
1939 * just reference the function's scalar output. (XXX this
1940 * seems a tad inconsistent, especially if "f.*" was
1941 * explicitly written ...)
1943 result = makeVar(vnum,
1945 toid,
1947 sublevels_up);
1949 break;
1950 case RTE_VALUES:
1951 toid = RECORDOID;
1952 /* returns composite; same as relation case */
1953 result = makeVar(vnum,
1954 InvalidAttrNumber,
1955 toid,
1957 sublevels_up);
1958 break;
1959 default:
1962 * RTE is a join or subselect. We represent this as a whole-row
1963 * Var of RECORD type. (Note that in most cases the Var will be
1964 * expanded to a RowExpr during planning, but that is not our
1965 * concern here.)
1967 result = makeVar(vnum,
1968 InvalidAttrNumber,
1969 RECORDOID,
1971 sublevels_up);
1972 break;
1975 /* location is not filled in by makeVar */
1976 result->location = location;
1978 return (Node *) result;
1982 * Handle an explicit CAST construct.
1984 * Transform the argument, then look up the type name and apply any necessary
1985 * coercion function(s).
1987 static Node *
1988 transformTypeCast(ParseState *pstate, TypeCast *tc)
1990 Node *result;
1991 Node *expr = transformExpr(pstate, tc->arg);
1992 Oid inputType = exprType(expr);
1993 Oid targetType;
1994 int32 targetTypmod;
1995 int location;
1997 targetType = typenameTypeId(pstate, tc->typename, &targetTypmod);
1999 if (inputType == InvalidOid)
2000 return expr; /* do nothing if NULL input */
2003 * Location of the coercion is preferentially the location of the :: or
2004 * CAST symbol, but if there is none then use the location of the type
2005 * name (this can happen in TypeName 'string' syntax, for instance).
2007 location = tc->location;
2008 if (location < 0)
2009 location = tc->typename->location;
2011 result = coerce_to_target_type(pstate, expr, inputType,
2012 targetType, targetTypmod,
2013 COERCION_EXPLICIT,
2014 COERCE_EXPLICIT_CAST,
2015 location);
2016 if (result == NULL)
2017 ereport(ERROR,
2018 (errcode(ERRCODE_CANNOT_COERCE),
2019 errmsg("cannot cast type %s to %s",
2020 format_type_be(inputType),
2021 format_type_be(targetType)),
2022 parser_coercion_errposition(pstate, location, expr)));
2024 return result;
2028 * Transform a "row compare-op row" construct
2030 * The inputs are lists of already-transformed expressions.
2031 * As with coerce_type, pstate may be NULL if no special unknown-Param
2032 * processing is wanted.
2034 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2035 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2036 * The AND, OR, and RowCompareExpr cases further imply things about the
2037 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2039 static Node *
2040 make_row_comparison_op(ParseState *pstate, List *opname,
2041 List *largs, List *rargs, int location)
2043 RowCompareExpr *rcexpr;
2044 RowCompareType rctype;
2045 List *opexprs;
2046 List *opnos;
2047 List *opfamilies;
2048 ListCell *l,
2050 List **opfamily_lists;
2051 List **opstrat_lists;
2052 Bitmapset *strats;
2053 int nopers;
2054 int i;
2056 nopers = list_length(largs);
2057 if (nopers != list_length(rargs))
2058 ereport(ERROR,
2059 (errcode(ERRCODE_SYNTAX_ERROR),
2060 errmsg("unequal number of entries in row expressions"),
2061 parser_errposition(pstate, location)));
2064 * We can't compare zero-length rows because there is no principled basis
2065 * for figuring out what the operator is.
2067 if (nopers == 0)
2068 ereport(ERROR,
2069 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2070 errmsg("cannot compare rows of zero length"),
2071 parser_errposition(pstate, location)));
2074 * Identify all the pairwise operators, using make_op so that behavior is
2075 * the same as in the simple scalar case.
2077 opexprs = NIL;
2078 forboth(l, largs, r, rargs)
2080 Node *larg = (Node *) lfirst(l);
2081 Node *rarg = (Node *) lfirst(r);
2082 OpExpr *cmp;
2084 cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2085 Assert(IsA(cmp, OpExpr));
2088 * We don't use coerce_to_boolean here because we insist on the
2089 * operator yielding boolean directly, not via coercion. If it
2090 * doesn't yield bool it won't be in any index opfamilies...
2092 if (cmp->opresulttype != BOOLOID)
2093 ereport(ERROR,
2094 (errcode(ERRCODE_DATATYPE_MISMATCH),
2095 errmsg("row comparison operator must yield type boolean, "
2096 "not type %s",
2097 format_type_be(cmp->opresulttype)),
2098 parser_errposition(pstate, location)));
2099 if (expression_returns_set((Node *) cmp))
2100 ereport(ERROR,
2101 (errcode(ERRCODE_DATATYPE_MISMATCH),
2102 errmsg("row comparison operator must not return a set"),
2103 parser_errposition(pstate, location)));
2104 opexprs = lappend(opexprs, cmp);
2108 * If rows are length 1, just return the single operator. In this case we
2109 * don't insist on identifying btree semantics for the operator (but we
2110 * still require it to return boolean).
2112 if (nopers == 1)
2113 return (Node *) linitial(opexprs);
2116 * Now we must determine which row comparison semantics (= <> < <= > >=)
2117 * apply to this set of operators. We look for btree opfamilies
2118 * containing the operators, and see which interpretations (strategy
2119 * numbers) exist for each operator.
2121 opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2122 opstrat_lists = (List **) palloc(nopers * sizeof(List *));
2123 strats = NULL;
2124 i = 0;
2125 foreach(l, opexprs)
2127 Oid opno = ((OpExpr *) lfirst(l))->opno;
2128 Bitmapset *this_strats;
2129 ListCell *j;
2131 get_op_btree_interpretation(opno,
2132 &opfamily_lists[i], &opstrat_lists[i]);
2135 * convert strategy number list to a Bitmapset to make the
2136 * intersection calculation easy.
2138 this_strats = NULL;
2139 foreach(j, opstrat_lists[i])
2141 this_strats = bms_add_member(this_strats, lfirst_int(j));
2143 if (i == 0)
2144 strats = this_strats;
2145 else
2146 strats = bms_int_members(strats, this_strats);
2147 i++;
2151 * If there are multiple common interpretations, we may use any one of
2152 * them ... this coding arbitrarily picks the lowest btree strategy
2153 * number.
2155 i = bms_first_member(strats);
2156 if (i < 0)
2158 /* No common interpretation, so fail */
2159 ereport(ERROR,
2160 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2161 errmsg("could not determine interpretation of row comparison operator %s",
2162 strVal(llast(opname))),
2163 errhint("Row comparison operators must be associated with btree operator families."),
2164 parser_errposition(pstate, location)));
2166 rctype = (RowCompareType) i;
2169 * For = and <> cases, we just combine the pairwise operators with AND or
2170 * OR respectively.
2172 * Note: this is presently the only place where the parser generates
2173 * BoolExpr with more than two arguments. Should be OK since the rest of
2174 * the system thinks BoolExpr is N-argument anyway.
2176 if (rctype == ROWCOMPARE_EQ)
2177 return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2178 if (rctype == ROWCOMPARE_NE)
2179 return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2182 * Otherwise we need to choose exactly which opfamily to associate with
2183 * each operator.
2185 opfamilies = NIL;
2186 for (i = 0; i < nopers; i++)
2188 Oid opfamily = InvalidOid;
2190 forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2192 int opstrat = lfirst_int(r);
2194 if (opstrat == rctype)
2196 opfamily = lfirst_oid(l);
2197 break;
2200 if (OidIsValid(opfamily))
2201 opfamilies = lappend_oid(opfamilies, opfamily);
2202 else /* should not happen */
2203 ereport(ERROR,
2204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2205 errmsg("could not determine interpretation of row comparison operator %s",
2206 strVal(llast(opname))),
2207 errdetail("There are multiple equally-plausible candidates."),
2208 parser_errposition(pstate, location)));
2212 * Now deconstruct the OpExprs and create a RowCompareExpr.
2214 * Note: can't just reuse the passed largs/rargs lists, because of
2215 * possibility that make_op inserted coercion operations.
2217 opnos = NIL;
2218 largs = NIL;
2219 rargs = NIL;
2220 foreach(l, opexprs)
2222 OpExpr *cmp = (OpExpr *) lfirst(l);
2224 opnos = lappend_oid(opnos, cmp->opno);
2225 largs = lappend(largs, linitial(cmp->args));
2226 rargs = lappend(rargs, lsecond(cmp->args));
2229 rcexpr = makeNode(RowCompareExpr);
2230 rcexpr->rctype = rctype;
2231 rcexpr->opnos = opnos;
2232 rcexpr->opfamilies = opfamilies;
2233 rcexpr->largs = largs;
2234 rcexpr->rargs = rargs;
2236 return (Node *) rcexpr;
2240 * Transform a "row IS DISTINCT FROM row" construct
2242 * The input RowExprs are already transformed
2244 static Node *
2245 make_row_distinct_op(ParseState *pstate, List *opname,
2246 RowExpr *lrow, RowExpr *rrow,
2247 int location)
2249 Node *result = NULL;
2250 List *largs = lrow->args;
2251 List *rargs = rrow->args;
2252 ListCell *l,
2255 if (list_length(largs) != list_length(rargs))
2256 ereport(ERROR,
2257 (errcode(ERRCODE_SYNTAX_ERROR),
2258 errmsg("unequal number of entries in row expressions"),
2259 parser_errposition(pstate, location)));
2261 forboth(l, largs, r, rargs)
2263 Node *larg = (Node *) lfirst(l);
2264 Node *rarg = (Node *) lfirst(r);
2265 Node *cmp;
2267 cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2268 if (result == NULL)
2269 result = cmp;
2270 else
2271 result = (Node *) makeBoolExpr(OR_EXPR,
2272 list_make2(result, cmp),
2273 location);
2276 if (result == NULL)
2278 /* zero-length rows? Generate constant FALSE */
2279 result = makeBoolConst(false, false);
2282 return result;
2286 * make the node for an IS DISTINCT FROM operator
2288 static Expr *
2289 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
2290 int location)
2292 Expr *result;
2294 result = make_op(pstate, opname, ltree, rtree, location);
2295 if (((OpExpr *) result)->opresulttype != BOOLOID)
2296 ereport(ERROR,
2297 (errcode(ERRCODE_DATATYPE_MISMATCH),
2298 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2299 parser_errposition(pstate, location)));
2302 * We rely on DistinctExpr and OpExpr being same struct
2304 NodeSetTag(result, T_DistinctExpr);
2306 return result;