Make to_timestamp and friends skip leading spaces before an integer field,
[PostgreSQL.git] / src / backend / parser / parse_expr.c
blob46fecd23a325adaf011b7dc68bf3d615c91b80ad
1 /*-------------------------------------------------------------------------
3 * parse_expr.c
4 * handle expressions in parser
6 * Portions Copyright (c) 1996-2009, 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 and
151 * the target type is an array type, we invoke
152 * transformArrayExpr() directly so that we can pass down the
153 * type information. This avoids some cases where
154 * transformArrayExpr() might not infer the correct type.
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. Fall
177 * 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_WindowFunc:
290 case T_ArrayRef:
291 case T_FuncExpr:
292 case T_OpExpr:
293 case T_DistinctExpr:
294 case T_ScalarArrayOpExpr:
295 case T_NullIfExpr:
296 case T_BoolExpr:
297 case T_FieldSelect:
298 case T_FieldStore:
299 case T_RelabelType:
300 case T_CoerceViaIO:
301 case T_ArrayCoerceExpr:
302 case T_ConvertRowtypeExpr:
303 case T_CaseTestExpr:
304 case T_CoerceToDomain:
305 case T_CoerceToDomainValue:
306 case T_SetToDefault:
308 result = (Node *) expr;
309 break;
312 default:
313 /* should not reach here */
314 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
315 break;
318 return result;
321 static Node *
322 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
324 Node *result = basenode;
325 List *subscripts = NIL;
326 ListCell *i;
329 * We have to split any field-selection operations apart from
330 * subscripting. Adjacent A_Indices nodes have to be treated as a single
331 * multidimensional subscript operation.
333 foreach(i, indirection)
335 Node *n = lfirst(i);
337 if (IsA(n, A_Indices))
338 subscripts = lappend(subscripts, n);
339 else if (IsA(n, A_Star))
341 ereport(ERROR,
342 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
343 errmsg("row expansion via \"*\" is not supported here"),
344 parser_errposition(pstate, exprLocation(basenode))));
346 else
348 Assert(IsA(n, String));
350 /* process subscripts before this field selection */
351 if (subscripts)
352 result = (Node *) transformArraySubscripts(pstate,
353 result,
354 exprType(result),
355 InvalidOid,
356 exprTypmod(result),
357 subscripts,
358 NULL);
359 subscripts = NIL;
361 result = ParseFuncOrColumn(pstate,
362 list_make1(n),
363 list_make1(result),
364 false, false, false,
365 NULL, true, -1);
368 /* process trailing subscripts, if any */
369 if (subscripts)
370 result = (Node *) transformArraySubscripts(pstate,
371 result,
372 exprType(result),
373 InvalidOid,
374 exprTypmod(result),
375 subscripts,
376 NULL);
378 return result;
381 static Node *
382 transformColumnRef(ParseState *pstate, ColumnRef *cref)
384 int numnames = list_length(cref->fields);
385 Node *node;
386 int levels_up;
388 /*----------
389 * The allowed syntaxes are:
391 * A First try to resolve as unqualified column name;
392 * if no luck, try to resolve as unqualified table name (A.*).
393 * A.B A is an unqualified table name; B is either a
394 * column or function name (trying column name first).
395 * A.B.C schema A, table B, col or func name C.
396 * A.B.C.D catalog A, schema B, table C, col or func D.
397 * A.* A is an unqualified table name; means whole-row value.
398 * A.B.* whole-row value of table B in schema A.
399 * A.B.C.* whole-row value of table C in schema B in catalog A.
401 * We do not need to cope with bare "*"; that will only be accepted by
402 * the grammar at the top level of a SELECT list, and transformTargetList
403 * will take care of it before it ever gets here. Also, "A.*" etc will
404 * be expanded by transformTargetList if they appear at SELECT top level,
405 * so here we are only going to see them as function or operator inputs.
407 * Currently, if a catalog name is given then it must equal the current
408 * database name; we check it here and then discard it.
409 *----------
411 switch (numnames)
413 case 1:
415 Node *field1 = (Node *) linitial(cref->fields);
416 char *name1;
418 Assert(IsA(field1, String));
419 name1 = strVal(field1);
421 /* Try to identify as an unqualified column */
422 node = colNameToVar(pstate, name1, false, cref->location);
424 if (node == NULL)
427 * Not known as a column of any range-table entry.
429 * Consider the possibility that it's VALUE in a domain
430 * check expression. (We handle VALUE as a name, not a
431 * keyword, to avoid breaking a lot of applications that
432 * have used VALUE as a column name in the past.)
434 if (pstate->p_value_substitute != NULL &&
435 strcmp(name1, "value") == 0)
437 node = (Node *) copyObject(pstate->p_value_substitute);
440 * Try to propagate location knowledge. This should
441 * be extended if p_value_substitute can ever take on
442 * other node types.
444 if (IsA(node, CoerceToDomainValue))
445 ((CoerceToDomainValue *) node)->location = cref->location;
446 break;
450 * Try to find the name as a relation. Note that only
451 * relations already entered into the rangetable will be
452 * recognized.
454 * This is a hack for backwards compatibility with
455 * PostQUEL-inspired syntax. The preferred form now is
456 * "rel.*".
458 if (refnameRangeTblEntry(pstate, NULL, name1,
459 cref->location,
460 &levels_up) != NULL)
461 node = transformWholeRowRef(pstate, NULL, name1,
462 cref->location);
463 else
464 ereport(ERROR,
465 (errcode(ERRCODE_UNDEFINED_COLUMN),
466 errmsg("column \"%s\" does not exist",
467 name1),
468 parser_errposition(pstate, cref->location)));
470 break;
472 case 2:
474 Node *field1 = (Node *) linitial(cref->fields);
475 Node *field2 = (Node *) lsecond(cref->fields);
476 char *name1;
477 char *name2;
479 Assert(IsA(field1, String));
480 name1 = strVal(field1);
482 /* Whole-row reference? */
483 if (IsA(field2, A_Star))
485 node = transformWholeRowRef(pstate, NULL, name1,
486 cref->location);
487 break;
490 Assert(IsA(field2, String));
491 name2 = strVal(field2);
493 /* Try to identify as a once-qualified column */
494 node = qualifiedNameToVar(pstate, NULL, name1, name2, true,
495 cref->location);
496 if (node == NULL)
499 * Not known as a column of any range-table entry, so try
500 * it as a function call. Here, we will create an
501 * implicit RTE for tables not already entered.
503 node = transformWholeRowRef(pstate, NULL, name1,
504 cref->location);
505 node = ParseFuncOrColumn(pstate,
506 list_make1(makeString(name2)),
507 list_make1(node),
508 false, false, false,
509 NULL, true, cref->location);
511 break;
513 case 3:
515 Node *field1 = (Node *) linitial(cref->fields);
516 Node *field2 = (Node *) lsecond(cref->fields);
517 Node *field3 = (Node *) lthird(cref->fields);
518 char *name1;
519 char *name2;
520 char *name3;
522 Assert(IsA(field1, String));
523 name1 = strVal(field1);
524 Assert(IsA(field2, String));
525 name2 = strVal(field2);
527 /* Whole-row reference? */
528 if (IsA(field3, A_Star))
530 node = transformWholeRowRef(pstate, name1, name2,
531 cref->location);
532 break;
535 Assert(IsA(field3, String));
536 name3 = strVal(field3);
538 /* Try to identify as a twice-qualified column */
539 node = qualifiedNameToVar(pstate, name1, name2, name3, true,
540 cref->location);
541 if (node == NULL)
543 /* Try it as a function call */
544 node = transformWholeRowRef(pstate, name1, name2,
545 cref->location);
546 node = ParseFuncOrColumn(pstate,
547 list_make1(makeString(name3)),
548 list_make1(node),
549 false, false, false,
550 NULL, true, cref->location);
552 break;
554 case 4:
556 Node *field1 = (Node *) linitial(cref->fields);
557 Node *field2 = (Node *) lsecond(cref->fields);
558 Node *field3 = (Node *) lthird(cref->fields);
559 Node *field4 = (Node *) lfourth(cref->fields);
560 char *name1;
561 char *name2;
562 char *name3;
563 char *name4;
565 Assert(IsA(field1, String));
566 name1 = strVal(field1);
567 Assert(IsA(field2, String));
568 name2 = strVal(field2);
569 Assert(IsA(field3, String));
570 name3 = strVal(field3);
573 * We check the catalog name and then ignore it.
575 if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
576 ereport(ERROR,
577 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
578 errmsg("cross-database references are not implemented: %s",
579 NameListToString(cref->fields)),
580 parser_errposition(pstate, cref->location)));
582 /* Whole-row reference? */
583 if (IsA(field4, A_Star))
585 node = transformWholeRowRef(pstate, name2, name3,
586 cref->location);
587 break;
590 Assert(IsA(field4, String));
591 name4 = strVal(field4);
593 /* Try to identify as a twice-qualified column */
594 node = qualifiedNameToVar(pstate, name2, name3, name4, true,
595 cref->location);
596 if (node == NULL)
598 /* Try it as a function call */
599 node = transformWholeRowRef(pstate, name2, name3,
600 cref->location);
601 node = ParseFuncOrColumn(pstate,
602 list_make1(makeString(name4)),
603 list_make1(node),
604 false, false, false,
605 NULL, true, cref->location);
607 break;
609 default:
610 ereport(ERROR,
611 (errcode(ERRCODE_SYNTAX_ERROR),
612 errmsg("improper qualified name (too many dotted names): %s",
613 NameListToString(cref->fields)),
614 parser_errposition(pstate, cref->location)));
615 node = NULL; /* keep compiler quiet */
616 break;
619 return node;
623 * Locate the parameter type info for the given parameter number, and
624 * return a pointer to it.
626 static Oid *
627 find_param_type(ParseState *pstate, int paramno, int location)
629 Oid *result;
632 * Find topmost ParseState, which is where paramtype info lives.
634 while (pstate->parentParseState != NULL)
635 pstate = pstate->parentParseState;
637 /* Check parameter number is in range */
638 if (paramno <= 0) /* probably can't happen? */
639 ereport(ERROR,
640 (errcode(ERRCODE_UNDEFINED_PARAMETER),
641 errmsg("there is no parameter $%d", paramno),
642 parser_errposition(pstate, location)));
643 if (paramno > pstate->p_numparams)
645 if (!pstate->p_variableparams)
646 ereport(ERROR,
647 (errcode(ERRCODE_UNDEFINED_PARAMETER),
648 errmsg("there is no parameter $%d", paramno),
649 parser_errposition(pstate, location)));
650 /* Okay to enlarge param array */
651 if (pstate->p_paramtypes)
652 pstate->p_paramtypes = (Oid *) repalloc(pstate->p_paramtypes,
653 paramno * sizeof(Oid));
654 else
655 pstate->p_paramtypes = (Oid *) palloc(paramno * sizeof(Oid));
656 /* Zero out the previously-unreferenced slots */
657 MemSet(pstate->p_paramtypes + pstate->p_numparams,
659 (paramno - pstate->p_numparams) * sizeof(Oid));
660 pstate->p_numparams = paramno;
663 result = &pstate->p_paramtypes[paramno - 1];
665 if (pstate->p_variableparams)
667 /* If not seen before, initialize to UNKNOWN type */
668 if (*result == InvalidOid)
669 *result = UNKNOWNOID;
672 return result;
675 static Node *
676 transformParamRef(ParseState *pstate, ParamRef *pref)
678 int paramno = pref->number;
679 Oid *pptype = find_param_type(pstate, paramno, pref->location);
680 Param *param;
682 param = makeNode(Param);
683 param->paramkind = PARAM_EXTERN;
684 param->paramid = paramno;
685 param->paramtype = *pptype;
686 param->paramtypmod = -1;
687 param->location = pref->location;
689 return (Node *) param;
692 /* Test whether an a_expr is a plain NULL constant or not */
693 static bool
694 exprIsNullConstant(Node *arg)
696 if (arg && IsA(arg, A_Const))
698 A_Const *con = (A_Const *) arg;
700 if (con->val.type == T_Null)
701 return true;
703 return false;
706 static Node *
707 transformAExprOp(ParseState *pstate, A_Expr *a)
709 Node *lexpr = a->lexpr;
710 Node *rexpr = a->rexpr;
711 Node *result;
714 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
715 * standards-broken products (like Microsoft's). Turn these into IS NULL
716 * exprs.
718 if (Transform_null_equals &&
719 list_length(a->name) == 1 &&
720 strcmp(strVal(linitial(a->name)), "=") == 0 &&
721 (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)))
723 NullTest *n = makeNode(NullTest);
725 n->nulltesttype = IS_NULL;
727 if (exprIsNullConstant(lexpr))
728 n->arg = (Expr *) rexpr;
729 else
730 n->arg = (Expr *) lexpr;
732 result = transformExpr(pstate, (Node *) n);
734 else if (lexpr && IsA(lexpr, RowExpr) &&
735 rexpr && IsA(rexpr, SubLink) &&
736 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
739 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
740 * grammar did this, but now that a row construct is allowed anywhere
741 * in expressions, it's easier to do it here.
743 SubLink *s = (SubLink *) rexpr;
745 s->subLinkType = ROWCOMPARE_SUBLINK;
746 s->testexpr = lexpr;
747 s->operName = a->name;
748 s->location = a->location;
749 result = transformExpr(pstate, (Node *) s);
751 else if (lexpr && IsA(lexpr, RowExpr) &&
752 rexpr && IsA(rexpr, RowExpr))
754 /* "row op row" */
755 lexpr = transformExpr(pstate, lexpr);
756 rexpr = transformExpr(pstate, rexpr);
757 Assert(IsA(lexpr, RowExpr));
758 Assert(IsA(rexpr, RowExpr));
760 result = make_row_comparison_op(pstate,
761 a->name,
762 ((RowExpr *) lexpr)->args,
763 ((RowExpr *) rexpr)->args,
764 a->location);
766 else
768 /* Ordinary scalar operator */
769 lexpr = transformExpr(pstate, lexpr);
770 rexpr = transformExpr(pstate, rexpr);
772 result = (Node *) make_op(pstate,
773 a->name,
774 lexpr,
775 rexpr,
776 a->location);
779 return result;
782 static Node *
783 transformAExprAnd(ParseState *pstate, A_Expr *a)
785 Node *lexpr = transformExpr(pstate, a->lexpr);
786 Node *rexpr = transformExpr(pstate, a->rexpr);
788 lexpr = coerce_to_boolean(pstate, lexpr, "AND");
789 rexpr = coerce_to_boolean(pstate, rexpr, "AND");
791 return (Node *) makeBoolExpr(AND_EXPR,
792 list_make2(lexpr, rexpr),
793 a->location);
796 static Node *
797 transformAExprOr(ParseState *pstate, A_Expr *a)
799 Node *lexpr = transformExpr(pstate, a->lexpr);
800 Node *rexpr = transformExpr(pstate, a->rexpr);
802 lexpr = coerce_to_boolean(pstate, lexpr, "OR");
803 rexpr = coerce_to_boolean(pstate, rexpr, "OR");
805 return (Node *) makeBoolExpr(OR_EXPR,
806 list_make2(lexpr, rexpr),
807 a->location);
810 static Node *
811 transformAExprNot(ParseState *pstate, A_Expr *a)
813 Node *rexpr = transformExpr(pstate, a->rexpr);
815 rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
817 return (Node *) makeBoolExpr(NOT_EXPR,
818 list_make1(rexpr),
819 a->location);
822 static Node *
823 transformAExprOpAny(ParseState *pstate, A_Expr *a)
825 Node *lexpr = transformExpr(pstate, a->lexpr);
826 Node *rexpr = transformExpr(pstate, a->rexpr);
828 return (Node *) make_scalar_array_op(pstate,
829 a->name,
830 true,
831 lexpr,
832 rexpr,
833 a->location);
836 static Node *
837 transformAExprOpAll(ParseState *pstate, A_Expr *a)
839 Node *lexpr = transformExpr(pstate, a->lexpr);
840 Node *rexpr = transformExpr(pstate, a->rexpr);
842 return (Node *) make_scalar_array_op(pstate,
843 a->name,
844 false,
845 lexpr,
846 rexpr,
847 a->location);
850 static Node *
851 transformAExprDistinct(ParseState *pstate, A_Expr *a)
853 Node *lexpr = transformExpr(pstate, a->lexpr);
854 Node *rexpr = transformExpr(pstate, a->rexpr);
856 if (lexpr && IsA(lexpr, RowExpr) &&
857 rexpr && IsA(rexpr, RowExpr))
859 /* "row op row" */
860 return make_row_distinct_op(pstate, a->name,
861 (RowExpr *) lexpr,
862 (RowExpr *) rexpr,
863 a->location);
865 else
867 /* Ordinary scalar operator */
868 return (Node *) make_distinct_op(pstate,
869 a->name,
870 lexpr,
871 rexpr,
872 a->location);
876 static Node *
877 transformAExprNullIf(ParseState *pstate, A_Expr *a)
879 Node *lexpr = transformExpr(pstate, a->lexpr);
880 Node *rexpr = transformExpr(pstate, a->rexpr);
881 Node *result;
883 result = (Node *) make_op(pstate,
884 a->name,
885 lexpr,
886 rexpr,
887 a->location);
888 if (((OpExpr *) result)->opresulttype != BOOLOID)
889 ereport(ERROR,
890 (errcode(ERRCODE_DATATYPE_MISMATCH),
891 errmsg("NULLIF requires = operator to yield boolean"),
892 parser_errposition(pstate, a->location)));
895 * We rely on NullIfExpr and OpExpr being the same struct
897 NodeSetTag(result, T_NullIfExpr);
899 return result;
902 static Node *
903 transformAExprOf(ParseState *pstate, A_Expr *a)
906 * Checking an expression for match to a list of type names. Will result
907 * in a boolean constant node.
909 Node *lexpr = transformExpr(pstate, a->lexpr);
910 Const *result;
911 ListCell *telem;
912 Oid ltype,
913 rtype;
914 bool matched = false;
916 ltype = exprType(lexpr);
917 foreach(telem, (List *) a->rexpr)
919 rtype = typenameTypeId(pstate, lfirst(telem), NULL);
920 matched = (rtype == ltype);
921 if (matched)
922 break;
926 * We have two forms: equals or not equals. Flip the sense of the result
927 * for not equals.
929 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
930 matched = (!matched);
932 result = (Const *) makeBoolConst(matched, false);
934 /* Make the result have the original input's parse location */
935 result->location = exprLocation((Node *) a);
937 return (Node *) result;
940 static Node *
941 transformAExprIn(ParseState *pstate, A_Expr *a)
943 Node *result = NULL;
944 Node *lexpr;
945 List *rexprs;
946 List *rvars;
947 List *rnonvars;
948 bool useOr;
949 bool haveRowExpr;
950 ListCell *l;
953 * If the operator is <>, combine with AND not OR.
955 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
956 useOr = false;
957 else
958 useOr = true;
961 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
962 * possible if the inputs are all scalars (no RowExprs) and there is a
963 * suitable array type available. If not, we fall back to a boolean
964 * condition tree with multiple copies of the lefthand expression. Also,
965 * any IN-list items that contain Vars are handled as separate boolean
966 * conditions, because that gives the planner more scope for optimization
967 * on such clauses.
969 * First step: transform all the inputs, and detect whether any are
970 * RowExprs or contain Vars.
972 lexpr = transformExpr(pstate, a->lexpr);
973 haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
974 rexprs = rvars = rnonvars = NIL;
975 foreach(l, (List *) a->rexpr)
977 Node *rexpr = transformExpr(pstate, lfirst(l));
979 haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
980 rexprs = lappend(rexprs, rexpr);
981 if (contain_vars_of_level(rexpr, 0))
982 rvars = lappend(rvars, rexpr);
983 else
984 rnonvars = lappend(rnonvars, rexpr);
988 * ScalarArrayOpExpr is only going to be useful if there's more than one
989 * non-Var righthand item. Also, it won't work for RowExprs.
991 if (!haveRowExpr && list_length(rnonvars) > 1)
993 List *allexprs;
994 Oid scalar_type;
995 Oid array_type;
998 * Try to select a common type for the array elements. Note that
999 * since the LHS' type is first in the list, it will be preferred when
1000 * there is doubt (eg, when all the RHS items are unknown literals).
1002 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1004 allexprs = list_concat(list_make1(lexpr), rnonvars);
1005 scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1007 /* Do we have an array type to use? */
1008 if (OidIsValid(scalar_type))
1009 array_type = get_array_type(scalar_type);
1010 else
1011 array_type = InvalidOid;
1012 if (array_type != InvalidOid)
1015 * OK: coerce all the right-hand non-Var inputs to the common type
1016 * and build an ArrayExpr for them.
1018 List *aexprs;
1019 ArrayExpr *newa;
1021 aexprs = NIL;
1022 foreach(l, rnonvars)
1024 Node *rexpr = (Node *) lfirst(l);
1026 rexpr = coerce_to_common_type(pstate, rexpr,
1027 scalar_type,
1028 "IN");
1029 aexprs = lappend(aexprs, rexpr);
1031 newa = makeNode(ArrayExpr);
1032 newa->array_typeid = array_type;
1033 newa->element_typeid = scalar_type;
1034 newa->elements = aexprs;
1035 newa->multidims = false;
1036 newa->location = -1;
1038 result = (Node *) make_scalar_array_op(pstate,
1039 a->name,
1040 useOr,
1041 lexpr,
1042 (Node *) newa,
1043 a->location);
1045 /* Consider only the Vars (if any) in the loop below */
1046 rexprs = rvars;
1051 * Must do it the hard way, ie, with a boolean expression tree.
1053 foreach(l, rexprs)
1055 Node *rexpr = (Node *) lfirst(l);
1056 Node *cmp;
1058 if (haveRowExpr)
1060 if (!IsA(lexpr, RowExpr) ||
1061 !IsA(rexpr, RowExpr))
1062 ereport(ERROR,
1063 (errcode(ERRCODE_SYNTAX_ERROR),
1064 errmsg("arguments of row IN must all be row expressions"),
1065 parser_errposition(pstate, a->location)));
1066 cmp = make_row_comparison_op(pstate,
1067 a->name,
1068 (List *) copyObject(((RowExpr *) lexpr)->args),
1069 ((RowExpr *) rexpr)->args,
1070 a->location);
1072 else
1073 cmp = (Node *) make_op(pstate,
1074 a->name,
1075 copyObject(lexpr),
1076 rexpr,
1077 a->location);
1079 cmp = coerce_to_boolean(pstate, cmp, "IN");
1080 if (result == NULL)
1081 result = cmp;
1082 else
1083 result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1084 list_make2(result, cmp),
1085 a->location);
1088 return result;
1091 static Node *
1092 transformFuncCall(ParseState *pstate, FuncCall *fn)
1094 List *targs;
1095 ListCell *args;
1097 /* Transform the list of arguments ... */
1098 targs = NIL;
1099 foreach(args, fn->args)
1101 targs = lappend(targs, transformExpr(pstate,
1102 (Node *) lfirst(args)));
1105 /* ... and hand off to ParseFuncOrColumn */
1106 return ParseFuncOrColumn(pstate,
1107 fn->funcname,
1108 targs,
1109 fn->agg_star,
1110 fn->agg_distinct,
1111 fn->func_variadic,
1112 fn->over,
1113 false,
1114 fn->location);
1117 static Node *
1118 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1120 CaseExpr *newc;
1121 Node *arg;
1122 CaseTestExpr *placeholder;
1123 List *newargs;
1124 List *resultexprs;
1125 ListCell *l;
1126 Node *defresult;
1127 Oid ptype;
1129 /* If we already transformed this node, do nothing */
1130 if (OidIsValid(c->casetype))
1131 return (Node *) c;
1133 newc = makeNode(CaseExpr);
1135 /* transform the test expression, if any */
1136 arg = transformExpr(pstate, (Node *) c->arg);
1138 /* generate placeholder for test expression */
1139 if (arg)
1142 * If test expression is an untyped literal, force it to text. We have
1143 * to do something now because we won't be able to do this coercion on
1144 * the placeholder. This is not as flexible as what was done in 7.4
1145 * and before, but it's good enough to handle the sort of silly coding
1146 * commonly seen.
1148 if (exprType(arg) == UNKNOWNOID)
1149 arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1151 placeholder = makeNode(CaseTestExpr);
1152 placeholder->typeId = exprType(arg);
1153 placeholder->typeMod = exprTypmod(arg);
1155 else
1156 placeholder = NULL;
1158 newc->arg = (Expr *) arg;
1160 /* transform the list of arguments */
1161 newargs = NIL;
1162 resultexprs = NIL;
1163 foreach(l, c->args)
1165 CaseWhen *w = (CaseWhen *) lfirst(l);
1166 CaseWhen *neww = makeNode(CaseWhen);
1167 Node *warg;
1169 Assert(IsA(w, CaseWhen));
1171 warg = (Node *) w->expr;
1172 if (placeholder)
1174 /* shorthand form was specified, so expand... */
1175 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1176 (Node *) placeholder,
1177 warg,
1178 w->location);
1180 neww->expr = (Expr *) transformExpr(pstate, warg);
1182 neww->expr = (Expr *) coerce_to_boolean(pstate,
1183 (Node *) neww->expr,
1184 "CASE/WHEN");
1186 warg = (Node *) w->result;
1187 neww->result = (Expr *) transformExpr(pstate, warg);
1188 neww->location = w->location;
1190 newargs = lappend(newargs, neww);
1191 resultexprs = lappend(resultexprs, neww->result);
1194 newc->args = newargs;
1196 /* transform the default clause */
1197 defresult = (Node *) c->defresult;
1198 if (defresult == NULL)
1200 A_Const *n = makeNode(A_Const);
1202 n->val.type = T_Null;
1203 n->location = -1;
1204 defresult = (Node *) n;
1206 newc->defresult = (Expr *) transformExpr(pstate, defresult);
1209 * Note: default result is considered the most significant type in
1210 * determining preferred type. This is how the code worked before, but it
1211 * seems a little bogus to me --- tgl
1213 resultexprs = lcons(newc->defresult, resultexprs);
1215 ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1216 Assert(OidIsValid(ptype));
1217 newc->casetype = ptype;
1219 /* Convert default result clause, if necessary */
1220 newc->defresult = (Expr *)
1221 coerce_to_common_type(pstate,
1222 (Node *) newc->defresult,
1223 ptype,
1224 "CASE/ELSE");
1226 /* Convert when-clause results, if necessary */
1227 foreach(l, newc->args)
1229 CaseWhen *w = (CaseWhen *) lfirst(l);
1231 w->result = (Expr *)
1232 coerce_to_common_type(pstate,
1233 (Node *) w->result,
1234 ptype,
1235 "CASE/WHEN");
1238 newc->location = c->location;
1240 return (Node *) newc;
1243 static Node *
1244 transformSubLink(ParseState *pstate, SubLink *sublink)
1246 Node *result = (Node *) sublink;
1247 Query *qtree;
1249 /* If we already transformed this node, do nothing */
1250 if (IsA(sublink->subselect, Query))
1251 return result;
1253 pstate->p_hasSubLinks = true;
1254 qtree = parse_sub_analyze(sublink->subselect, pstate);
1257 * Check that we got something reasonable. Many of these conditions are
1258 * impossible given restrictions of the grammar, but check 'em anyway.
1260 if (!IsA(qtree, Query) ||
1261 qtree->commandType != CMD_SELECT ||
1262 qtree->utilityStmt != NULL)
1263 elog(ERROR, "unexpected non-SELECT command in SubLink");
1264 if (qtree->intoClause)
1265 ereport(ERROR,
1266 (errcode(ERRCODE_SYNTAX_ERROR),
1267 errmsg("subquery cannot have SELECT INTO"),
1268 parser_errposition(pstate,
1269 exprLocation((Node *) qtree->intoClause))));
1271 sublink->subselect = (Node *) qtree;
1273 if (sublink->subLinkType == EXISTS_SUBLINK)
1276 * EXISTS needs no test expression or combining operator. These fields
1277 * should be null already, but make sure.
1279 sublink->testexpr = NULL;
1280 sublink->operName = NIL;
1282 else if (sublink->subLinkType == EXPR_SUBLINK ||
1283 sublink->subLinkType == ARRAY_SUBLINK)
1285 ListCell *tlist_item = list_head(qtree->targetList);
1288 * Make sure the subselect delivers a single column (ignoring resjunk
1289 * targets).
1291 if (tlist_item == NULL ||
1292 ((TargetEntry *) lfirst(tlist_item))->resjunk)
1293 ereport(ERROR,
1294 (errcode(ERRCODE_SYNTAX_ERROR),
1295 errmsg("subquery must return a column"),
1296 parser_errposition(pstate, sublink->location)));
1297 while ((tlist_item = lnext(tlist_item)) != NULL)
1299 if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1300 ereport(ERROR,
1301 (errcode(ERRCODE_SYNTAX_ERROR),
1302 errmsg("subquery must return only one column"),
1303 parser_errposition(pstate, sublink->location)));
1307 * EXPR and ARRAY need no test expression or combining operator. These
1308 * fields should be null already, but make sure.
1310 sublink->testexpr = NULL;
1311 sublink->operName = NIL;
1313 else
1315 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1316 Node *lefthand;
1317 List *left_list;
1318 List *right_list;
1319 ListCell *l;
1322 * Transform lefthand expression, and convert to a list
1324 lefthand = transformExpr(pstate, sublink->testexpr);
1325 if (lefthand && IsA(lefthand, RowExpr))
1326 left_list = ((RowExpr *) lefthand)->args;
1327 else
1328 left_list = list_make1(lefthand);
1331 * Build a list of PARAM_SUBLINK nodes representing the output columns
1332 * of the subquery.
1334 right_list = NIL;
1335 foreach(l, qtree->targetList)
1337 TargetEntry *tent = (TargetEntry *) lfirst(l);
1338 Param *param;
1340 if (tent->resjunk)
1341 continue;
1343 param = makeNode(Param);
1344 param->paramkind = PARAM_SUBLINK;
1345 param->paramid = tent->resno;
1346 param->paramtype = exprType((Node *) tent->expr);
1347 param->paramtypmod = exprTypmod((Node *) tent->expr);
1348 param->location = -1;
1350 right_list = lappend(right_list, param);
1354 * We could rely on make_row_comparison_op to complain if the list
1355 * lengths differ, but we prefer to generate a more specific error
1356 * message.
1358 if (list_length(left_list) < list_length(right_list))
1359 ereport(ERROR,
1360 (errcode(ERRCODE_SYNTAX_ERROR),
1361 errmsg("subquery has too many columns"),
1362 parser_errposition(pstate, sublink->location)));
1363 if (list_length(left_list) > list_length(right_list))
1364 ereport(ERROR,
1365 (errcode(ERRCODE_SYNTAX_ERROR),
1366 errmsg("subquery has too few columns"),
1367 parser_errposition(pstate, sublink->location)));
1370 * Identify the combining operator(s) and generate a suitable
1371 * row-comparison expression.
1373 sublink->testexpr = make_row_comparison_op(pstate,
1374 sublink->operName,
1375 left_list,
1376 right_list,
1377 sublink->location);
1380 return result;
1384 * transformArrayExpr
1386 * If the caller specifies the target type, the resulting array will
1387 * be of exactly that type. Otherwise we try to infer a common type
1388 * for the elements using select_common_type().
1390 static Node *
1391 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
1392 Oid array_type, Oid element_type, int32 typmod)
1394 ArrayExpr *newa = makeNode(ArrayExpr);
1395 List *newelems = NIL;
1396 List *newcoercedelems = NIL;
1397 ListCell *element;
1398 Oid coerce_type;
1399 bool coerce_hard;
1402 * Transform the element expressions
1404 * Assume that the array is one-dimensional unless we find an array-type
1405 * element expression.
1407 newa->multidims = false;
1408 foreach(element, a->elements)
1410 Node *e = (Node *) lfirst(element);
1411 Node *newe;
1414 * If an element is itself an A_ArrayExpr, recurse directly so that we
1415 * can pass down any target type we were given.
1417 if (IsA(e, A_ArrayExpr))
1419 newe = transformArrayExpr(pstate,
1420 (A_ArrayExpr *) e,
1421 array_type,
1422 element_type,
1423 typmod);
1424 /* we certainly have an array here */
1425 Assert(array_type == InvalidOid || array_type == exprType(newe));
1426 newa->multidims = true;
1428 else
1430 newe = transformExpr(pstate, e);
1433 * Check for sub-array expressions, if we haven't already found
1434 * one.
1436 if (!newa->multidims && type_is_array(exprType(newe)))
1437 newa->multidims = true;
1440 newelems = lappend(newelems, newe);
1444 * Select a target type for the elements.
1446 * If we haven't been given a target array type, we must try to deduce a
1447 * common type based on the types of the individual elements present.
1449 if (OidIsValid(array_type))
1451 /* Caller must ensure array_type matches element_type */
1452 Assert(OidIsValid(element_type));
1453 coerce_type = (newa->multidims ? array_type : element_type);
1454 coerce_hard = true;
1456 else
1458 /* Can't handle an empty array without a target type */
1459 if (newelems == NIL)
1460 ereport(ERROR,
1461 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1462 errmsg("cannot determine type of empty array"),
1463 errhint("Explicitly cast to the desired type, "
1464 "for example ARRAY[]::integer[]."),
1465 parser_errposition(pstate, a->location)));
1467 /* Select a common type for the elements */
1468 coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1470 if (newa->multidims)
1472 array_type = coerce_type;
1473 element_type = get_element_type(array_type);
1474 if (!OidIsValid(element_type))
1475 ereport(ERROR,
1476 (errcode(ERRCODE_UNDEFINED_OBJECT),
1477 errmsg("could not find element type for data type %s",
1478 format_type_be(array_type)),
1479 parser_errposition(pstate, a->location)));
1481 else
1483 element_type = coerce_type;
1484 array_type = get_array_type(element_type);
1485 if (!OidIsValid(array_type))
1486 ereport(ERROR,
1487 (errcode(ERRCODE_UNDEFINED_OBJECT),
1488 errmsg("could not find array type for data type %s",
1489 format_type_be(element_type)),
1490 parser_errposition(pstate, a->location)));
1492 coerce_hard = false;
1496 * Coerce elements to target type
1498 * If the array has been explicitly cast, then the elements are in turn
1499 * explicitly coerced.
1501 * If the array's type was merely derived from the common type of its
1502 * elements, then the elements are implicitly coerced to the common type.
1503 * This is consistent with other uses of select_common_type().
1505 foreach(element, newelems)
1507 Node *e = (Node *) lfirst(element);
1508 Node *newe;
1510 if (coerce_hard)
1512 newe = coerce_to_target_type(pstate, e,
1513 exprType(e),
1514 coerce_type,
1515 typmod,
1516 COERCION_EXPLICIT,
1517 COERCE_EXPLICIT_CAST,
1518 -1);
1519 if (newe == NULL)
1520 ereport(ERROR,
1521 (errcode(ERRCODE_CANNOT_COERCE),
1522 errmsg("cannot cast type %s to %s",
1523 format_type_be(exprType(e)),
1524 format_type_be(coerce_type)),
1525 parser_errposition(pstate, exprLocation(e))));
1527 else
1528 newe = coerce_to_common_type(pstate, e,
1529 coerce_type,
1530 "ARRAY");
1531 newcoercedelems = lappend(newcoercedelems, newe);
1534 newa->array_typeid = array_type;
1535 newa->element_typeid = element_type;
1536 newa->elements = newcoercedelems;
1537 newa->location = a->location;
1539 return (Node *) newa;
1542 static Node *
1543 transformRowExpr(ParseState *pstate, RowExpr *r)
1545 RowExpr *newr = makeNode(RowExpr);
1547 /* Transform the field expressions */
1548 newr->args = transformExpressionList(pstate, r->args);
1550 /* Barring later casting, we consider the type RECORD */
1551 newr->row_typeid = RECORDOID;
1552 newr->row_format = COERCE_IMPLICIT_CAST;
1553 newr->colnames = NIL; /* ROW() has anonymous columns */
1554 newr->location = r->location;
1556 return (Node *) newr;
1559 static Node *
1560 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
1562 CoalesceExpr *newc = makeNode(CoalesceExpr);
1563 List *newargs = NIL;
1564 List *newcoercedargs = NIL;
1565 ListCell *args;
1567 foreach(args, c->args)
1569 Node *e = (Node *) lfirst(args);
1570 Node *newe;
1572 newe = transformExpr(pstate, e);
1573 newargs = lappend(newargs, newe);
1576 newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1578 /* Convert arguments if necessary */
1579 foreach(args, newargs)
1581 Node *e = (Node *) lfirst(args);
1582 Node *newe;
1584 newe = coerce_to_common_type(pstate, e,
1585 newc->coalescetype,
1586 "COALESCE");
1587 newcoercedargs = lappend(newcoercedargs, newe);
1590 newc->args = newcoercedargs;
1591 newc->location = c->location;
1592 return (Node *) newc;
1595 static Node *
1596 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
1598 MinMaxExpr *newm = makeNode(MinMaxExpr);
1599 List *newargs = NIL;
1600 List *newcoercedargs = NIL;
1601 const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1602 ListCell *args;
1604 newm->op = m->op;
1605 foreach(args, m->args)
1607 Node *e = (Node *) lfirst(args);
1608 Node *newe;
1610 newe = transformExpr(pstate, e);
1611 newargs = lappend(newargs, newe);
1614 newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1616 /* Convert arguments if necessary */
1617 foreach(args, newargs)
1619 Node *e = (Node *) lfirst(args);
1620 Node *newe;
1622 newe = coerce_to_common_type(pstate, e,
1623 newm->minmaxtype,
1624 funcname);
1625 newcoercedargs = lappend(newcoercedargs, newe);
1628 newm->args = newcoercedargs;
1629 newm->location = m->location;
1630 return (Node *) newm;
1633 static Node *
1634 transformXmlExpr(ParseState *pstate, XmlExpr *x)
1636 XmlExpr *newx = makeNode(XmlExpr);
1637 ListCell *lc;
1638 int i;
1640 newx->op = x->op;
1641 if (x->name)
1642 newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1643 else
1644 newx->name = NULL;
1645 newx->xmloption = x->xmloption;
1646 newx->location = x->location;
1649 * gram.y built the named args as a list of ResTarget. Transform each,
1650 * and break the names out as a separate list.
1652 newx->named_args = NIL;
1653 newx->arg_names = NIL;
1655 foreach(lc, x->named_args)
1657 ResTarget *r = (ResTarget *) lfirst(lc);
1658 Node *expr;
1659 char *argname;
1661 Assert(IsA(r, ResTarget));
1663 expr = transformExpr(pstate, r->val);
1665 if (r->name)
1666 argname = map_sql_identifier_to_xml_name(r->name, false, false);
1667 else if (IsA(r->val, ColumnRef))
1668 argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1669 true, false);
1670 else
1672 ereport(ERROR,
1673 (errcode(ERRCODE_SYNTAX_ERROR),
1674 x->op == IS_XMLELEMENT
1675 ? errmsg("unnamed XML attribute value must be a column reference")
1676 : errmsg("unnamed XML element value must be a column reference"),
1677 parser_errposition(pstate, r->location)));
1678 argname = NULL; /* keep compiler quiet */
1681 /* reject duplicate argnames in XMLELEMENT only */
1682 if (x->op == IS_XMLELEMENT)
1684 ListCell *lc2;
1686 foreach(lc2, newx->arg_names)
1688 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1689 ereport(ERROR,
1690 (errcode(ERRCODE_SYNTAX_ERROR),
1691 errmsg("XML attribute name \"%s\" appears more than once",
1692 argname),
1693 parser_errposition(pstate, r->location)));
1697 newx->named_args = lappend(newx->named_args, expr);
1698 newx->arg_names = lappend(newx->arg_names, makeString(argname));
1701 /* The other arguments are of varying types depending on the function */
1702 newx->args = NIL;
1703 i = 0;
1704 foreach(lc, x->args)
1706 Node *e = (Node *) lfirst(lc);
1707 Node *newe;
1709 newe = transformExpr(pstate, e);
1710 switch (x->op)
1712 case IS_XMLCONCAT:
1713 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1714 "XMLCONCAT");
1715 break;
1716 case IS_XMLELEMENT:
1717 /* no coercion necessary */
1718 break;
1719 case IS_XMLFOREST:
1720 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1721 "XMLFOREST");
1722 break;
1723 case IS_XMLPARSE:
1724 if (i == 0)
1725 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1726 "XMLPARSE");
1727 else
1728 newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
1729 break;
1730 case IS_XMLPI:
1731 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1732 "XMLPI");
1733 break;
1734 case IS_XMLROOT:
1735 if (i == 0)
1736 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1737 "XMLROOT");
1738 else if (i == 1)
1739 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1740 "XMLROOT");
1741 else
1742 newe = coerce_to_specific_type(pstate, newe, INT4OID,
1743 "XMLROOT");
1744 break;
1745 case IS_XMLSERIALIZE:
1746 /* not handled here */
1747 Assert(false);
1748 break;
1749 case IS_DOCUMENT:
1750 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1751 "IS DOCUMENT");
1752 break;
1754 newx->args = lappend(newx->args, newe);
1755 i++;
1758 return (Node *) newx;
1761 static Node *
1762 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1764 Node *result;
1765 XmlExpr *xexpr;
1766 Oid targetType;
1767 int32 targetTypmod;
1769 xexpr = makeNode(XmlExpr);
1770 xexpr->op = IS_XMLSERIALIZE;
1771 xexpr->args = list_make1(coerce_to_specific_type(pstate,
1772 transformExpr(pstate, xs->expr),
1773 XMLOID,
1774 "XMLSERIALIZE"));
1776 targetType = typenameTypeId(pstate, xs->typename, &targetTypmod);
1778 xexpr->xmloption = xs->xmloption;
1779 xexpr->location = xs->location;
1780 /* We actually only need these to be able to parse back the expression. */
1781 xexpr->type = targetType;
1782 xexpr->typmod = targetTypmod;
1785 * The actual target type is determined this way. SQL allows char and
1786 * varchar as target types. We allow anything that can be cast implicitly
1787 * from text. This way, user-defined text-like data types automatically
1788 * fit in.
1790 result = coerce_to_target_type(pstate, (Node *) xexpr,
1791 TEXTOID, targetType, targetTypmod,
1792 COERCION_IMPLICIT,
1793 COERCE_IMPLICIT_CAST,
1794 -1);
1795 if (result == NULL)
1796 ereport(ERROR,
1797 (errcode(ERRCODE_CANNOT_COERCE),
1798 errmsg("cannot cast XMLSERIALIZE result to %s",
1799 format_type_be(targetType)),
1800 parser_errposition(pstate, xexpr->location)));
1801 return result;
1804 static Node *
1805 transformBooleanTest(ParseState *pstate, BooleanTest *b)
1807 const char *clausename;
1809 switch (b->booltesttype)
1811 case IS_TRUE:
1812 clausename = "IS TRUE";
1813 break;
1814 case IS_NOT_TRUE:
1815 clausename = "IS NOT TRUE";
1816 break;
1817 case IS_FALSE:
1818 clausename = "IS FALSE";
1819 break;
1820 case IS_NOT_FALSE:
1821 clausename = "IS NOT FALSE";
1822 break;
1823 case IS_UNKNOWN:
1824 clausename = "IS UNKNOWN";
1825 break;
1826 case IS_NOT_UNKNOWN:
1827 clausename = "IS NOT UNKNOWN";
1828 break;
1829 default:
1830 elog(ERROR, "unrecognized booltesttype: %d",
1831 (int) b->booltesttype);
1832 clausename = NULL; /* keep compiler quiet */
1835 b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
1837 b->arg = (Expr *) coerce_to_boolean(pstate,
1838 (Node *) b->arg,
1839 clausename);
1841 return (Node *) b;
1844 static Node *
1845 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1847 int sublevels_up;
1849 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1850 Assert(pstate->p_target_rangetblentry != NULL);
1851 cexpr->cvarno = RTERangeTablePosn(pstate,
1852 pstate->p_target_rangetblentry,
1853 &sublevels_up);
1854 Assert(sublevels_up == 0);
1856 /* If a parameter is used, it must be of type REFCURSOR */
1857 if (cexpr->cursor_name == NULL)
1859 Oid *pptype = find_param_type(pstate, cexpr->cursor_param, -1);
1861 if (pstate->p_variableparams && *pptype == UNKNOWNOID)
1863 /* resolve unknown param type as REFCURSOR */
1864 *pptype = REFCURSOROID;
1866 else if (*pptype != REFCURSOROID)
1868 ereport(ERROR,
1869 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
1870 errmsg("inconsistent types deduced for parameter $%d",
1871 cexpr->cursor_param),
1872 errdetail("%s versus %s",
1873 format_type_be(*pptype),
1874 format_type_be(REFCURSOROID))));
1878 return (Node *) cexpr;
1882 * Construct a whole-row reference to represent the notation "relation.*".
1884 * A whole-row reference is a Var with varno set to the correct range
1885 * table entry, and varattno == 0 to signal that it references the whole
1886 * tuple. (Use of zero here is unclean, since it could easily be confused
1887 * with error cases, but it's not worth changing now.) The vartype indicates
1888 * a rowtype; either a named composite type, or RECORD.
1890 static Node *
1891 transformWholeRowRef(ParseState *pstate, char *schemaname, char *relname,
1892 int location)
1894 Var *result;
1895 RangeTblEntry *rte;
1896 int vnum;
1897 int sublevels_up;
1898 Oid toid;
1900 /* Look up the referenced RTE, creating it if needed */
1902 rte = refnameRangeTblEntry(pstate, schemaname, relname, location,
1903 &sublevels_up);
1905 if (rte == NULL)
1906 rte = addImplicitRTE(pstate,
1907 makeRangeVar(schemaname, relname, location));
1909 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
1911 /* Build the appropriate referencing node */
1913 switch (rte->rtekind)
1915 case RTE_RELATION:
1916 /* relation: the rowtype is a named composite type */
1917 toid = get_rel_type_id(rte->relid);
1918 if (!OidIsValid(toid))
1919 elog(ERROR, "could not find type OID for relation %u",
1920 rte->relid);
1921 result = makeVar(vnum,
1922 InvalidAttrNumber,
1923 toid,
1925 sublevels_up);
1926 break;
1927 case RTE_FUNCTION:
1928 toid = exprType(rte->funcexpr);
1929 if (type_is_rowtype(toid))
1931 /* func returns composite; same as relation case */
1932 result = makeVar(vnum,
1933 InvalidAttrNumber,
1934 toid,
1936 sublevels_up);
1938 else
1941 * func returns scalar; instead of making a whole-row Var,
1942 * just reference the function's scalar output. (XXX this
1943 * seems a tad inconsistent, especially if "f.*" was
1944 * explicitly written ...)
1946 result = makeVar(vnum,
1948 toid,
1950 sublevels_up);
1952 break;
1953 case RTE_VALUES:
1954 toid = RECORDOID;
1955 /* returns composite; same as relation case */
1956 result = makeVar(vnum,
1957 InvalidAttrNumber,
1958 toid,
1960 sublevels_up);
1961 break;
1962 default:
1965 * RTE is a join or subselect. We represent this as a whole-row
1966 * Var of RECORD type. (Note that in most cases the Var will be
1967 * expanded to a RowExpr during planning, but that is not our
1968 * concern here.)
1970 result = makeVar(vnum,
1971 InvalidAttrNumber,
1972 RECORDOID,
1974 sublevels_up);
1975 break;
1978 /* location is not filled in by makeVar */
1979 result->location = location;
1981 /* mark relation as requiring whole-row SELECT access */
1982 markVarForSelectPriv(pstate, result, rte);
1984 return (Node *) result;
1988 * Handle an explicit CAST construct.
1990 * Transform the argument, then look up the type name and apply any necessary
1991 * coercion function(s).
1993 static Node *
1994 transformTypeCast(ParseState *pstate, TypeCast *tc)
1996 Node *result;
1997 Node *expr = transformExpr(pstate, tc->arg);
1998 Oid inputType = exprType(expr);
1999 Oid targetType;
2000 int32 targetTypmod;
2001 int location;
2003 targetType = typenameTypeId(pstate, tc->typename, &targetTypmod);
2005 if (inputType == InvalidOid)
2006 return expr; /* do nothing if NULL input */
2009 * Location of the coercion is preferentially the location of the :: or
2010 * CAST symbol, but if there is none then use the location of the type
2011 * name (this can happen in TypeName 'string' syntax, for instance).
2013 location = tc->location;
2014 if (location < 0)
2015 location = tc->typename->location;
2017 result = coerce_to_target_type(pstate, expr, inputType,
2018 targetType, targetTypmod,
2019 COERCION_EXPLICIT,
2020 COERCE_EXPLICIT_CAST,
2021 location);
2022 if (result == NULL)
2023 ereport(ERROR,
2024 (errcode(ERRCODE_CANNOT_COERCE),
2025 errmsg("cannot cast type %s to %s",
2026 format_type_be(inputType),
2027 format_type_be(targetType)),
2028 parser_coercion_errposition(pstate, location, expr)));
2030 return result;
2034 * Transform a "row compare-op row" construct
2036 * The inputs are lists of already-transformed expressions.
2037 * As with coerce_type, pstate may be NULL if no special unknown-Param
2038 * processing is wanted.
2040 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2041 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2042 * The AND, OR, and RowCompareExpr cases further imply things about the
2043 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2045 static Node *
2046 make_row_comparison_op(ParseState *pstate, List *opname,
2047 List *largs, List *rargs, int location)
2049 RowCompareExpr *rcexpr;
2050 RowCompareType rctype;
2051 List *opexprs;
2052 List *opnos;
2053 List *opfamilies;
2054 ListCell *l,
2056 List **opfamily_lists;
2057 List **opstrat_lists;
2058 Bitmapset *strats;
2059 int nopers;
2060 int i;
2062 nopers = list_length(largs);
2063 if (nopers != list_length(rargs))
2064 ereport(ERROR,
2065 (errcode(ERRCODE_SYNTAX_ERROR),
2066 errmsg("unequal number of entries in row expressions"),
2067 parser_errposition(pstate, location)));
2070 * We can't compare zero-length rows because there is no principled basis
2071 * for figuring out what the operator is.
2073 if (nopers == 0)
2074 ereport(ERROR,
2075 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2076 errmsg("cannot compare rows of zero length"),
2077 parser_errposition(pstate, location)));
2080 * Identify all the pairwise operators, using make_op so that behavior is
2081 * the same as in the simple scalar case.
2083 opexprs = NIL;
2084 forboth(l, largs, r, rargs)
2086 Node *larg = (Node *) lfirst(l);
2087 Node *rarg = (Node *) lfirst(r);
2088 OpExpr *cmp;
2090 cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2091 Assert(IsA(cmp, OpExpr));
2094 * We don't use coerce_to_boolean here because we insist on the
2095 * operator yielding boolean directly, not via coercion. If it
2096 * doesn't yield bool it won't be in any index opfamilies...
2098 if (cmp->opresulttype != BOOLOID)
2099 ereport(ERROR,
2100 (errcode(ERRCODE_DATATYPE_MISMATCH),
2101 errmsg("row comparison operator must yield type boolean, "
2102 "not type %s",
2103 format_type_be(cmp->opresulttype)),
2104 parser_errposition(pstate, location)));
2105 if (expression_returns_set((Node *) cmp))
2106 ereport(ERROR,
2107 (errcode(ERRCODE_DATATYPE_MISMATCH),
2108 errmsg("row comparison operator must not return a set"),
2109 parser_errposition(pstate, location)));
2110 opexprs = lappend(opexprs, cmp);
2114 * If rows are length 1, just return the single operator. In this case we
2115 * don't insist on identifying btree semantics for the operator (but we
2116 * still require it to return boolean).
2118 if (nopers == 1)
2119 return (Node *) linitial(opexprs);
2122 * Now we must determine which row comparison semantics (= <> < <= > >=)
2123 * apply to this set of operators. We look for btree opfamilies
2124 * containing the operators, and see which interpretations (strategy
2125 * numbers) exist for each operator.
2127 opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2128 opstrat_lists = (List **) palloc(nopers * sizeof(List *));
2129 strats = NULL;
2130 i = 0;
2131 foreach(l, opexprs)
2133 Oid opno = ((OpExpr *) lfirst(l))->opno;
2134 Bitmapset *this_strats;
2135 ListCell *j;
2137 get_op_btree_interpretation(opno,
2138 &opfamily_lists[i], &opstrat_lists[i]);
2141 * convert strategy number list to a Bitmapset to make the
2142 * intersection calculation easy.
2144 this_strats = NULL;
2145 foreach(j, opstrat_lists[i])
2147 this_strats = bms_add_member(this_strats, lfirst_int(j));
2149 if (i == 0)
2150 strats = this_strats;
2151 else
2152 strats = bms_int_members(strats, this_strats);
2153 i++;
2157 * If there are multiple common interpretations, we may use any one of
2158 * them ... this coding arbitrarily picks the lowest btree strategy
2159 * number.
2161 i = bms_first_member(strats);
2162 if (i < 0)
2164 /* No common interpretation, so fail */
2165 ereport(ERROR,
2166 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2167 errmsg("could not determine interpretation of row comparison operator %s",
2168 strVal(llast(opname))),
2169 errhint("Row comparison operators must be associated with btree operator families."),
2170 parser_errposition(pstate, location)));
2172 rctype = (RowCompareType) i;
2175 * For = and <> cases, we just combine the pairwise operators with AND or
2176 * OR respectively.
2178 * Note: this is presently the only place where the parser generates
2179 * BoolExpr with more than two arguments. Should be OK since the rest of
2180 * the system thinks BoolExpr is N-argument anyway.
2182 if (rctype == ROWCOMPARE_EQ)
2183 return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2184 if (rctype == ROWCOMPARE_NE)
2185 return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2188 * Otherwise we need to choose exactly which opfamily to associate with
2189 * each operator.
2191 opfamilies = NIL;
2192 for (i = 0; i < nopers; i++)
2194 Oid opfamily = InvalidOid;
2196 forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2198 int opstrat = lfirst_int(r);
2200 if (opstrat == rctype)
2202 opfamily = lfirst_oid(l);
2203 break;
2206 if (OidIsValid(opfamily))
2207 opfamilies = lappend_oid(opfamilies, opfamily);
2208 else /* should not happen */
2209 ereport(ERROR,
2210 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2211 errmsg("could not determine interpretation of row comparison operator %s",
2212 strVal(llast(opname))),
2213 errdetail("There are multiple equally-plausible candidates."),
2214 parser_errposition(pstate, location)));
2218 * Now deconstruct the OpExprs and create a RowCompareExpr.
2220 * Note: can't just reuse the passed largs/rargs lists, because of
2221 * possibility that make_op inserted coercion operations.
2223 opnos = NIL;
2224 largs = NIL;
2225 rargs = NIL;
2226 foreach(l, opexprs)
2228 OpExpr *cmp = (OpExpr *) lfirst(l);
2230 opnos = lappend_oid(opnos, cmp->opno);
2231 largs = lappend(largs, linitial(cmp->args));
2232 rargs = lappend(rargs, lsecond(cmp->args));
2235 rcexpr = makeNode(RowCompareExpr);
2236 rcexpr->rctype = rctype;
2237 rcexpr->opnos = opnos;
2238 rcexpr->opfamilies = opfamilies;
2239 rcexpr->largs = largs;
2240 rcexpr->rargs = rargs;
2242 return (Node *) rcexpr;
2246 * Transform a "row IS DISTINCT FROM row" construct
2248 * The input RowExprs are already transformed
2250 static Node *
2251 make_row_distinct_op(ParseState *pstate, List *opname,
2252 RowExpr *lrow, RowExpr *rrow,
2253 int location)
2255 Node *result = NULL;
2256 List *largs = lrow->args;
2257 List *rargs = rrow->args;
2258 ListCell *l,
2261 if (list_length(largs) != list_length(rargs))
2262 ereport(ERROR,
2263 (errcode(ERRCODE_SYNTAX_ERROR),
2264 errmsg("unequal number of entries in row expressions"),
2265 parser_errposition(pstate, location)));
2267 forboth(l, largs, r, rargs)
2269 Node *larg = (Node *) lfirst(l);
2270 Node *rarg = (Node *) lfirst(r);
2271 Node *cmp;
2273 cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2274 if (result == NULL)
2275 result = cmp;
2276 else
2277 result = (Node *) makeBoolExpr(OR_EXPR,
2278 list_make2(result, cmp),
2279 location);
2282 if (result == NULL)
2284 /* zero-length rows? Generate constant FALSE */
2285 result = makeBoolConst(false, false);
2288 return result;
2292 * make the node for an IS DISTINCT FROM operator
2294 static Expr *
2295 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
2296 int location)
2298 Expr *result;
2300 result = make_op(pstate, opname, ltree, rtree, location);
2301 if (((OpExpr *) result)->opresulttype != BOOLOID)
2302 ereport(ERROR,
2303 (errcode(ERRCODE_DATATYPE_MISMATCH),
2304 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2305 parser_errposition(pstate, location)));
2308 * We rely on DistinctExpr and OpExpr being same struct
2310 NodeSetTag(result, T_DistinctExpr);
2312 return result;