1 /*-------------------------------------------------------------------------
4 * handle expressions in parser
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_expr.c
13 *-------------------------------------------------------------------------
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/tlist.h"
24 #include "optimizer/var.h"
25 #include "parser/analyze.h"
26 #include "parser/parse_clause.h"
27 #include "parser/parse_coerce.h"
28 #include "parser/parse_collate.h"
29 #include "parser/parse_expr.h"
30 #include "parser/parse_func.h"
31 #include "parser/parse_oper.h"
32 #include "parser/parse_relation.h"
33 #include "parser/parse_target.h"
34 #include "parser/parse_type.h"
35 #include "parser/parse_agg.h"
36 #include "utils/builtins.h"
37 #include "utils/date.h"
38 #include "utils/lsyscache.h"
39 #include "utils/timestamp.h"
40 #include "utils/xml.h"
44 bool operator_precedence_warning = false;
45 bool Transform_null_equals = false;
48 * Node-type groups for operator precedence warnings
49 * We use zero for everything not otherwise classified
51 #define PREC_GROUP_POSTFIX_IS 1 /* postfix IS tests (NullTest, etc) */
52 #define PREC_GROUP_INFIX_IS 2 /* infix IS (IS DISTINCT FROM, etc) */
53 #define PREC_GROUP_LESS 3 /* < > */
54 #define PREC_GROUP_EQUAL 4 /* = */
55 #define PREC_GROUP_LESS_EQUAL 5 /* <= >= <> */
56 #define PREC_GROUP_LIKE 6 /* LIKE ILIKE SIMILAR */
57 #define PREC_GROUP_BETWEEN 7 /* BETWEEN */
58 #define PREC_GROUP_IN 8 /* IN */
59 #define PREC_GROUP_NOT_LIKE 9 /* NOT LIKE/ILIKE/SIMILAR */
60 #define PREC_GROUP_NOT_BETWEEN 10 /* NOT BETWEEN */
61 #define PREC_GROUP_NOT_IN 11 /* NOT IN */
62 #define PREC_GROUP_POSTFIX_OP 12 /* generic postfix operators */
63 #define PREC_GROUP_INFIX_OP 13 /* generic infix operators */
64 #define PREC_GROUP_PREFIX_OP 14 /* generic prefix operators */
67 * Map precedence groupings to old precedence ordering
69 * Old precedence order:
73 * 4. LIKE ILIKE SIMILAR
76 * 7. generic postfix Op
77 * 8. generic Op, including <= => <>
78 * 9. generic prefix Op
79 * 10. IS tests (NullTest, BooleanTest, etc)
81 * NOT BETWEEN etc map to BETWEEN etc when considered as being on the left,
82 * but to NOT when considered as being on the right, because of the buggy
83 * precedence handling of those productions in the old grammar.
85 static const int oldprecedence_l[] = {
86 0, 10, 10, 3, 2, 8, 4, 5, 6, 4, 5, 6, 7, 8, 9
88 static const int oldprecedence_r[] = {
89 0, 10, 10, 3, 2, 8, 4, 5, 6, 1, 1, 1, 7, 8, 9
92 static Node *transformExprRecurse(ParseState *pstate, Node *expr);
93 static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
94 static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
95 static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
96 static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
97 static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
98 static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
99 static Node *transformAExprOf(ParseState *pstate, A_Expr *a);
100 static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
101 static Node *transformAExprBetween(ParseState *pstate, A_Expr *a);
102 static Node *transformBoolExpr(ParseState *pstate, BoolExpr *a);
103 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
104 static Node *transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref);
105 static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
106 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
107 static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
108 Oid array_type, Oid element_type, int32 typmod);
109 static Node *transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault);
110 static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
111 static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
112 static Node *transformSQLValueFunction(ParseState *pstate,
113 SQLValueFunction *svf);
114 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
115 static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
116 static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
117 static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
118 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
119 static Node *transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte,
121 static Node *transformIndirection(ParseState *pstate, A_Indirection *ind);
122 static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
123 static Node *transformCollateClause(ParseState *pstate, CollateClause *c);
124 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
125 List *largs, List *rargs, int location);
126 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
127 RowExpr *lrow, RowExpr *rrow, int location);
128 static Expr *make_distinct_op(ParseState *pstate, List *opname,
129 Node *ltree, Node *rtree, int location);
130 static Node *make_nulltest_from_distinct(ParseState *pstate,
131 A_Expr *distincta, Node *arg);
132 static int operator_precedence_group(Node *node, const char **nodename);
133 static void emit_precedence_warnings(ParseState *pstate,
134 int opgroup, const char *opname,
135 Node *lchild, Node *rchild,
141 * Analyze and transform expressions. Type checking and type casting is
142 * done here. This processing converts the raw grammar output into
143 * expression trees with fully determined semantics.
146 transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
149 ParseExprKind sv_expr_kind;
151 /* Save and restore identity of expression type we're parsing */
152 Assert(exprKind != EXPR_KIND_NONE);
153 sv_expr_kind = pstate->p_expr_kind;
154 pstate->p_expr_kind = exprKind;
156 result = transformExprRecurse(pstate, expr);
158 pstate->p_expr_kind = sv_expr_kind;
164 transformExprRecurse(ParseState *pstate, Node *expr)
171 /* Guard against stack overflow due to overly complex expressions */
174 switch (nodeTag(expr))
177 result = transformColumnRef(pstate, (ColumnRef *) expr);
181 result = transformParamRef(pstate, (ParamRef *) expr);
186 A_Const *con = (A_Const *) expr;
187 Value *val = &con->val;
189 result = (Node *) make_const(pstate, val, con->location);
193 case T_A_Indirection:
194 result = transformIndirection(pstate, (A_Indirection *) expr);
198 result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
199 InvalidOid, InvalidOid, -1);
203 result = transformTypeCast(pstate, (TypeCast *) expr);
206 case T_CollateClause:
207 result = transformCollateClause(pstate, (CollateClause *) expr);
212 A_Expr *a = (A_Expr *) expr;
217 result = transformAExprOp(pstate, a);
220 result = transformAExprOpAny(pstate, a);
223 result = transformAExprOpAll(pstate, a);
226 case AEXPR_NOT_DISTINCT:
227 result = transformAExprDistinct(pstate, a);
230 result = transformAExprNullIf(pstate, a);
233 result = transformAExprOf(pstate, a);
236 result = transformAExprIn(pstate, a);
241 /* we can transform these just like AEXPR_OP */
242 result = transformAExprOp(pstate, a);
245 case AEXPR_NOT_BETWEEN:
246 case AEXPR_BETWEEN_SYM:
247 case AEXPR_NOT_BETWEEN_SYM:
248 result = transformAExprBetween(pstate, a);
251 result = transformExprRecurse(pstate, a->lexpr);
254 elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
255 result = NULL; /* keep compiler quiet */
262 result = transformBoolExpr(pstate, (BoolExpr *) expr);
266 result = transformFuncCall(pstate, (FuncCall *) expr);
269 case T_MultiAssignRef:
270 result = transformMultiAssignRef(pstate, (MultiAssignRef *) expr);
274 result = transformGroupingFunc(pstate, (GroupingFunc *) expr);
279 NamedArgExpr *na = (NamedArgExpr *) expr;
281 na->arg = (Expr *) transformExprRecurse(pstate, (Node *) na->arg);
287 result = transformSubLink(pstate, (SubLink *) expr);
291 result = transformCaseExpr(pstate, (CaseExpr *) expr);
295 result = transformRowExpr(pstate, (RowExpr *) expr, false);
299 result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
303 result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
306 case T_SQLValueFunction:
307 result = transformSQLValueFunction(pstate,
308 (SQLValueFunction *) expr);
312 result = transformXmlExpr(pstate, (XmlExpr *) expr);
316 result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
321 NullTest *n = (NullTest *) expr;
323 if (operator_precedence_warning)
324 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
325 (Node *) n->arg, NULL,
328 n->arg = (Expr *) transformExprRecurse(pstate, (Node *) n->arg);
329 /* the argument can be any type, so don't coerce it */
330 n->argisrow = type_is_rowtype(exprType((Node *) n->arg));
336 result = transformBooleanTest(pstate, (BooleanTest *) expr);
339 case T_CurrentOfExpr:
340 result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
344 * In all places where DEFAULT is legal, the caller should have
345 * processed it rather than passing it to transformExpr().
349 (errcode(ERRCODE_SYNTAX_ERROR),
350 errmsg("DEFAULT is not allowed in this context"),
351 parser_errposition(pstate,
352 ((SetToDefault *) expr)->location)));
356 * CaseTestExpr doesn't require any processing; it is only
357 * injected into parse trees in a fully-formed state.
359 * Ordinarily we should not see a Var here, but it is convenient
360 * for transformJoinUsingClause() to create untransformed operator
361 * trees containing already-transformed Vars. The best
362 * alternative would be to deconstruct and reconstruct column
363 * references, which seems expensively pointless. So allow it.
368 result = (Node *) expr;
373 /* should not reach here */
374 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
375 result = NULL; /* keep compiler quiet */
383 * helper routine for delivering "column does not exist" error message
385 * (Usually we don't have to work this hard, but the general case of field
386 * selection from an arbitrary node needs it.)
389 unknown_attribute(ParseState *pstate, Node *relref, char *attname,
394 if (IsA(relref, Var) &&
395 ((Var *) relref)->varattno == InvalidAttrNumber)
397 /* Reference the RTE by alias not by actual table name */
398 rte = GetRTEByRangeTablePosn(pstate,
399 ((Var *) relref)->varno,
400 ((Var *) relref)->varlevelsup);
402 (errcode(ERRCODE_UNDEFINED_COLUMN),
403 errmsg("column %s.%s does not exist",
404 rte->eref->aliasname, attname),
405 parser_errposition(pstate, location)));
409 /* Have to do it by reference to the type of the expression */
410 Oid relTypeId = exprType(relref);
412 if (ISCOMPLEX(relTypeId))
414 (errcode(ERRCODE_UNDEFINED_COLUMN),
415 errmsg("column \"%s\" not found in data type %s",
416 attname, format_type_be(relTypeId)),
417 parser_errposition(pstate, location)));
418 else if (relTypeId == RECORDOID)
420 (errcode(ERRCODE_UNDEFINED_COLUMN),
421 errmsg("could not identify column \"%s\" in record data type",
423 parser_errposition(pstate, location)));
426 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
427 errmsg("column notation .%s applied to type %s, "
428 "which is not a composite type",
429 attname, format_type_be(relTypeId)),
430 parser_errposition(pstate, location)));
435 transformIndirection(ParseState *pstate, A_Indirection *ind)
437 Node *last_srf = pstate->p_last_srf;
438 Node *result = transformExprRecurse(pstate, ind->arg);
439 List *subscripts = NIL;
440 int location = exprLocation(result);
444 * We have to split any field-selection operations apart from
445 * subscripting. Adjacent A_Indices nodes have to be treated as a single
446 * multidimensional subscript operation.
448 foreach(i, ind->indirection)
452 if (IsA(n, A_Indices))
453 subscripts = lappend(subscripts, n);
454 else if (IsA(n, A_Star))
457 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
458 errmsg("row expansion via \"*\" is not supported here"),
459 parser_errposition(pstate, location)));
465 Assert(IsA(n, String));
467 /* process subscripts before this field selection */
469 result = (Node *) transformArraySubscripts(pstate,
478 newresult = ParseFuncOrColumn(pstate,
484 if (newresult == NULL)
485 unknown_attribute(pstate, result, strVal(n), location);
489 /* process trailing subscripts, if any */
491 result = (Node *) transformArraySubscripts(pstate,
503 * Transform a ColumnRef.
505 * If you find yourself changing this code, see also ExpandColumnRefStar.
508 transformColumnRef(ParseState *pstate, ColumnRef *cref)
511 char *nspname = NULL;
512 char *relname = NULL;
513 char *colname = NULL;
522 } crerr = CRERR_NO_COLUMN;
525 * Give the PreParseColumnRefHook, if any, first shot. If it returns
526 * non-null then that's all, folks.
528 if (pstate->p_pre_columnref_hook != NULL)
530 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
536 * The allowed syntaxes are:
538 * A First try to resolve as unqualified column name;
539 * if no luck, try to resolve as unqualified table name (A.*).
540 * A.B A is an unqualified table name; B is either a
541 * column or function name (trying column name first).
542 * A.B.C schema A, table B, col or func name C.
543 * A.B.C.D catalog A, schema B, table C, col or func D.
544 * A.* A is an unqualified table name; means whole-row value.
545 * A.B.* whole-row value of table B in schema A.
546 * A.B.C.* whole-row value of table C in schema B in catalog A.
548 * We do not need to cope with bare "*"; that will only be accepted by
549 * the grammar at the top level of a SELECT list, and transformTargetList
550 * will take care of it before it ever gets here. Also, "A.*" etc will
551 * be expanded by transformTargetList if they appear at SELECT top level,
552 * so here we are only going to see them as function or operator inputs.
554 * Currently, if a catalog name is given then it must equal the current
555 * database name; we check it here and then discard it.
558 switch (list_length(cref->fields))
562 Node *field1 = (Node *) linitial(cref->fields);
564 Assert(IsA(field1, String));
565 colname = strVal(field1);
567 /* Try to identify as an unqualified column */
568 node = colNameToVar(pstate, colname, false, cref->location);
573 * Not known as a column of any range-table entry.
575 * Try to find the name as a relation. Note that only
576 * relations already entered into the rangetable will be
579 * This is a hack for backwards compatibility with
580 * PostQUEL-inspired syntax. The preferred form now is
583 rte = refnameRangeTblEntry(pstate, NULL, colname,
587 node = transformWholeRowRef(pstate, rte,
594 Node *field1 = (Node *) linitial(cref->fields);
595 Node *field2 = (Node *) lsecond(cref->fields);
597 Assert(IsA(field1, String));
598 relname = strVal(field1);
600 /* Locate the referenced RTE */
601 rte = refnameRangeTblEntry(pstate, nspname, relname,
606 crerr = CRERR_NO_RTE;
610 /* Whole-row reference? */
611 if (IsA(field2, A_Star))
613 node = transformWholeRowRef(pstate, rte, cref->location);
617 Assert(IsA(field2, String));
618 colname = strVal(field2);
620 /* Try to identify as a column of the RTE */
621 node = scanRTEForColumn(pstate, rte, colname, cref->location,
625 /* Try it as a function call on the whole row */
626 node = transformWholeRowRef(pstate, rte, cref->location);
627 node = ParseFuncOrColumn(pstate,
628 list_make1(makeString(colname)),
638 Node *field1 = (Node *) linitial(cref->fields);
639 Node *field2 = (Node *) lsecond(cref->fields);
640 Node *field3 = (Node *) lthird(cref->fields);
642 Assert(IsA(field1, String));
643 nspname = strVal(field1);
644 Assert(IsA(field2, String));
645 relname = strVal(field2);
647 /* Locate the referenced RTE */
648 rte = refnameRangeTblEntry(pstate, nspname, relname,
653 crerr = CRERR_NO_RTE;
657 /* Whole-row reference? */
658 if (IsA(field3, A_Star))
660 node = transformWholeRowRef(pstate, rte, cref->location);
664 Assert(IsA(field3, String));
665 colname = strVal(field3);
667 /* Try to identify as a column of the RTE */
668 node = scanRTEForColumn(pstate, rte, colname, cref->location,
672 /* Try it as a function call on the whole row */
673 node = transformWholeRowRef(pstate, rte, cref->location);
674 node = ParseFuncOrColumn(pstate,
675 list_make1(makeString(colname)),
685 Node *field1 = (Node *) linitial(cref->fields);
686 Node *field2 = (Node *) lsecond(cref->fields);
687 Node *field3 = (Node *) lthird(cref->fields);
688 Node *field4 = (Node *) lfourth(cref->fields);
691 Assert(IsA(field1, String));
692 catname = strVal(field1);
693 Assert(IsA(field2, String));
694 nspname = strVal(field2);
695 Assert(IsA(field3, String));
696 relname = strVal(field3);
699 * We check the catalog name and then ignore it.
701 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
703 crerr = CRERR_WRONG_DB;
707 /* Locate the referenced RTE */
708 rte = refnameRangeTblEntry(pstate, nspname, relname,
713 crerr = CRERR_NO_RTE;
717 /* Whole-row reference? */
718 if (IsA(field4, A_Star))
720 node = transformWholeRowRef(pstate, rte, cref->location);
724 Assert(IsA(field4, String));
725 colname = strVal(field4);
727 /* Try to identify as a column of the RTE */
728 node = scanRTEForColumn(pstate, rte, colname, cref->location,
732 /* Try it as a function call on the whole row */
733 node = transformWholeRowRef(pstate, rte, cref->location);
734 node = ParseFuncOrColumn(pstate,
735 list_make1(makeString(colname)),
744 crerr = CRERR_TOO_MANY; /* too many dotted names */
749 * Now give the PostParseColumnRefHook, if any, a chance. We pass the
750 * translation-so-far so that it can throw an error if it wishes in the
751 * case that it has a conflicting interpretation of the ColumnRef. (If it
752 * just translates anyway, we'll throw an error, because we can't undo
753 * whatever effects the preceding steps may have had on the pstate.) If it
754 * returns NULL, use the standard translation, or throw a suitable error
757 if (pstate->p_post_columnref_hook != NULL)
761 hookresult = (*pstate->p_post_columnref_hook) (pstate, cref, node);
764 else if (hookresult != NULL)
766 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
767 errmsg("column reference \"%s\" is ambiguous",
768 NameListToString(cref->fields)),
769 parser_errposition(pstate, cref->location)));
773 * Throw error if no translation found.
779 case CRERR_NO_COLUMN:
780 errorMissingColumn(pstate, relname, colname, cref->location);
783 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
788 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
789 errmsg("cross-database references are not implemented: %s",
790 NameListToString(cref->fields)),
791 parser_errposition(pstate, cref->location)));
795 (errcode(ERRCODE_SYNTAX_ERROR),
796 errmsg("improper qualified name (too many dotted names): %s",
797 NameListToString(cref->fields)),
798 parser_errposition(pstate, cref->location)));
807 transformParamRef(ParseState *pstate, ParamRef *pref)
812 * The core parser knows nothing about Params. If a hook is supplied,
813 * call it. If not, or if the hook returns NULL, throw a generic error.
815 if (pstate->p_paramref_hook != NULL)
816 result = (*pstate->p_paramref_hook) (pstate, pref);
822 (errcode(ERRCODE_UNDEFINED_PARAMETER),
823 errmsg("there is no parameter $%d", pref->number),
824 parser_errposition(pstate, pref->location)));
829 /* Test whether an a_expr is a plain NULL constant or not */
831 exprIsNullConstant(Node *arg)
833 if (arg && IsA(arg, A_Const))
835 A_Const *con = (A_Const *) arg;
837 if (con->val.type == T_Null)
844 transformAExprOp(ParseState *pstate, A_Expr *a)
846 Node *lexpr = a->lexpr;
847 Node *rexpr = a->rexpr;
850 if (operator_precedence_warning)
855 opgroup = operator_precedence_group((Node *) a, &opname);
857 emit_precedence_warnings(pstate, opgroup, opname,
861 /* Look through AEXPR_PAREN nodes so they don't affect tests below */
862 while (lexpr && IsA(lexpr, A_Expr) &&
863 ((A_Expr *) lexpr)->kind == AEXPR_PAREN)
864 lexpr = ((A_Expr *) lexpr)->lexpr;
865 while (rexpr && IsA(rexpr, A_Expr) &&
866 ((A_Expr *) rexpr)->kind == AEXPR_PAREN)
867 rexpr = ((A_Expr *) rexpr)->lexpr;
871 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
872 * standards-broken products (like Microsoft's). Turn these into IS NULL
873 * exprs. (If either side is a CaseTestExpr, then the expression was
874 * generated internally from a CASE-WHEN expression, and
875 * transform_null_equals does not apply.)
877 if (Transform_null_equals &&
878 list_length(a->name) == 1 &&
879 strcmp(strVal(linitial(a->name)), "=") == 0 &&
880 (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)) &&
881 (!IsA(lexpr, CaseTestExpr) &&!IsA(rexpr, CaseTestExpr)))
883 NullTest *n = makeNode(NullTest);
885 n->nulltesttype = IS_NULL;
886 n->location = a->location;
888 if (exprIsNullConstant(lexpr))
889 n->arg = (Expr *) rexpr;
891 n->arg = (Expr *) lexpr;
893 result = transformExprRecurse(pstate, (Node *) n);
895 else if (lexpr && IsA(lexpr, RowExpr) &&
896 rexpr && IsA(rexpr, SubLink) &&
897 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
900 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
901 * grammar did this, but now that a row construct is allowed anywhere
902 * in expressions, it's easier to do it here.
904 SubLink *s = (SubLink *) rexpr;
906 s->subLinkType = ROWCOMPARE_SUBLINK;
908 s->operName = a->name;
909 s->location = a->location;
910 result = transformExprRecurse(pstate, (Node *) s);
912 else if (lexpr && IsA(lexpr, RowExpr) &&
913 rexpr && IsA(rexpr, RowExpr))
915 /* ROW() op ROW() is handled specially */
916 lexpr = transformExprRecurse(pstate, lexpr);
917 rexpr = transformExprRecurse(pstate, rexpr);
919 result = make_row_comparison_op(pstate,
921 castNode(RowExpr, lexpr)->args,
922 castNode(RowExpr, rexpr)->args,
927 /* Ordinary scalar operator */
928 Node *last_srf = pstate->p_last_srf;
930 lexpr = transformExprRecurse(pstate, lexpr);
931 rexpr = transformExprRecurse(pstate, rexpr);
933 result = (Node *) make_op(pstate,
945 transformAExprOpAny(ParseState *pstate, A_Expr *a)
947 Node *lexpr = a->lexpr;
948 Node *rexpr = a->rexpr;
950 if (operator_precedence_warning)
951 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_OP,
952 strVal(llast(a->name)),
956 lexpr = transformExprRecurse(pstate, lexpr);
957 rexpr = transformExprRecurse(pstate, rexpr);
959 return (Node *) make_scalar_array_op(pstate,
968 transformAExprOpAll(ParseState *pstate, A_Expr *a)
970 Node *lexpr = a->lexpr;
971 Node *rexpr = a->rexpr;
973 if (operator_precedence_warning)
974 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_OP,
975 strVal(llast(a->name)),
979 lexpr = transformExprRecurse(pstate, lexpr);
980 rexpr = transformExprRecurse(pstate, rexpr);
982 return (Node *) make_scalar_array_op(pstate,
991 transformAExprDistinct(ParseState *pstate, A_Expr *a)
993 Node *lexpr = a->lexpr;
994 Node *rexpr = a->rexpr;
997 if (operator_precedence_warning)
998 emit_precedence_warnings(pstate, PREC_GROUP_INFIX_IS, "IS",
1003 * If either input is an undecorated NULL literal, transform to a NullTest
1004 * on the other input. That's simpler to process than a full DistinctExpr,
1005 * and it avoids needing to require that the datatype have an = operator.
1007 if (exprIsNullConstant(rexpr))
1008 return make_nulltest_from_distinct(pstate, a, lexpr);
1009 if (exprIsNullConstant(lexpr))
1010 return make_nulltest_from_distinct(pstate, a, rexpr);
1012 lexpr = transformExprRecurse(pstate, lexpr);
1013 rexpr = transformExprRecurse(pstate, rexpr);
1015 if (lexpr && IsA(lexpr, RowExpr) &&
1016 rexpr && IsA(rexpr, RowExpr))
1018 /* ROW() op ROW() is handled specially */
1019 result = make_row_distinct_op(pstate, a->name,
1026 /* Ordinary scalar operator */
1027 result = (Node *) make_distinct_op(pstate,
1035 * If it's NOT DISTINCT, we first build a DistinctExpr and then stick a
1038 if (a->kind == AEXPR_NOT_DISTINCT)
1039 result = (Node *) makeBoolExpr(NOT_EXPR,
1047 transformAExprNullIf(ParseState *pstate, A_Expr *a)
1049 Node *lexpr = transformExprRecurse(pstate, a->lexpr);
1050 Node *rexpr = transformExprRecurse(pstate, a->rexpr);
1053 result = (OpExpr *) make_op(pstate,
1061 * The comparison operator itself should yield boolean ...
1063 if (result->opresulttype != BOOLOID)
1065 (errcode(ERRCODE_DATATYPE_MISMATCH),
1066 errmsg("NULLIF requires = operator to yield boolean"),
1067 parser_errposition(pstate, a->location)));
1068 if (result->opretset)
1070 (errcode(ERRCODE_DATATYPE_MISMATCH),
1071 /* translator: %s is name of a SQL construct, eg NULLIF */
1072 errmsg("%s must not return a set", "NULLIF"),
1073 parser_errposition(pstate, a->location)));
1076 * ... but the NullIfExpr will yield the first operand's type.
1078 result->opresulttype = exprType((Node *) linitial(result->args));
1081 * We rely on NullIfExpr and OpExpr being the same struct
1083 NodeSetTag(result, T_NullIfExpr);
1085 return (Node *) result;
1089 * Checking an expression for match to a list of type names. Will result
1090 * in a boolean constant node.
1093 transformAExprOf(ParseState *pstate, A_Expr *a)
1095 Node *lexpr = a->lexpr;
1100 bool matched = false;
1102 if (operator_precedence_warning)
1103 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
1107 lexpr = transformExprRecurse(pstate, lexpr);
1109 ltype = exprType(lexpr);
1110 foreach(telem, (List *) a->rexpr)
1112 rtype = typenameTypeId(pstate, lfirst(telem));
1113 matched = (rtype == ltype);
1119 * We have two forms: equals or not equals. Flip the sense of the result
1122 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1123 matched = (!matched);
1125 result = (Const *) makeBoolConst(matched, false);
1127 /* Make the result have the original input's parse location */
1128 result->location = exprLocation((Node *) a);
1130 return (Node *) result;
1134 transformAExprIn(ParseState *pstate, A_Expr *a)
1136 Node *result = NULL;
1145 * If the operator is <>, combine with AND not OR.
1147 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1152 if (operator_precedence_warning)
1153 emit_precedence_warnings(pstate,
1154 useOr ? PREC_GROUP_IN : PREC_GROUP_NOT_IN,
1160 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
1161 * possible if there is a suitable array type available. If not, we fall
1162 * back to a boolean condition tree with multiple copies of the lefthand
1163 * expression. Also, any IN-list items that contain Vars are handled as
1164 * separate boolean conditions, because that gives the planner more scope
1165 * for optimization on such clauses.
1167 * First step: transform all the inputs, and detect whether any contain
1170 lexpr = transformExprRecurse(pstate, a->lexpr);
1171 rexprs = rvars = rnonvars = NIL;
1172 foreach(l, (List *) a->rexpr)
1174 Node *rexpr = transformExprRecurse(pstate, lfirst(l));
1176 rexprs = lappend(rexprs, rexpr);
1177 if (contain_vars_of_level(rexpr, 0))
1178 rvars = lappend(rvars, rexpr);
1180 rnonvars = lappend(rnonvars, rexpr);
1184 * ScalarArrayOpExpr is only going to be useful if there's more than one
1185 * non-Var righthand item.
1187 if (list_length(rnonvars) > 1)
1194 * Try to select a common type for the array elements. Note that
1195 * since the LHS' type is first in the list, it will be preferred when
1196 * there is doubt (eg, when all the RHS items are unknown literals).
1198 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1200 allexprs = list_concat(list_make1(lexpr), rnonvars);
1201 scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1204 * Do we have an array type to use? Aside from the case where there
1205 * isn't one, we don't risk using ScalarArrayOpExpr when the common
1206 * type is RECORD, because the RowExpr comparison logic below can cope
1207 * with some cases of non-identical row types.
1209 if (OidIsValid(scalar_type) && scalar_type != RECORDOID)
1210 array_type = get_array_type(scalar_type);
1212 array_type = InvalidOid;
1213 if (array_type != InvalidOid)
1216 * OK: coerce all the right-hand non-Var inputs to the common type
1217 * and build an ArrayExpr for them.
1223 foreach(l, rnonvars)
1225 Node *rexpr = (Node *) lfirst(l);
1227 rexpr = coerce_to_common_type(pstate, rexpr,
1230 aexprs = lappend(aexprs, rexpr);
1232 newa = makeNode(ArrayExpr);
1233 newa->array_typeid = array_type;
1234 /* array_collid will be set by parse_collate.c */
1235 newa->element_typeid = scalar_type;
1236 newa->elements = aexprs;
1237 newa->multidims = false;
1238 newa->location = -1;
1240 result = (Node *) make_scalar_array_op(pstate,
1247 /* Consider only the Vars (if any) in the loop below */
1253 * Must do it the hard way, ie, with a boolean expression tree.
1257 Node *rexpr = (Node *) lfirst(l);
1260 if (IsA(lexpr, RowExpr) &&
1261 IsA(rexpr, RowExpr))
1263 /* ROW() op ROW() is handled specially */
1264 cmp = make_row_comparison_op(pstate,
1266 copyObject(((RowExpr *) lexpr)->args),
1267 ((RowExpr *) rexpr)->args,
1272 /* Ordinary scalar operator */
1273 cmp = (Node *) make_op(pstate,
1281 cmp = coerce_to_boolean(pstate, cmp, "IN");
1285 result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1286 list_make2(result, cmp),
1294 transformAExprBetween(ParseState *pstate, A_Expr *a)
1304 /* Deconstruct A_Expr into three subexprs */
1306 args = castNode(List, a->rexpr);
1307 Assert(list_length(args) == 2);
1308 bexpr = (Node *) linitial(args);
1309 cexpr = (Node *) lsecond(args);
1311 if (operator_precedence_warning)
1316 opgroup = operator_precedence_group((Node *) a, &opname);
1317 emit_precedence_warnings(pstate, opgroup, opname,
1320 /* We can ignore bexpr thanks to syntactic restrictions */
1321 /* Wrap subexpressions to prevent extra warnings */
1322 aexpr = (Node *) makeA_Expr(AEXPR_PAREN, NIL, aexpr, NULL, -1);
1323 bexpr = (Node *) makeA_Expr(AEXPR_PAREN, NIL, bexpr, NULL, -1);
1324 cexpr = (Node *) makeA_Expr(AEXPR_PAREN, NIL, cexpr, NULL, -1);
1328 * Build the equivalent comparison expression. Make copies of
1329 * multiply-referenced subexpressions for safety. (XXX this is really
1330 * wrong since it results in multiple runtime evaluations of what may be
1331 * volatile expressions ...)
1333 * Ideally we would not use hard-wired operators here but instead use
1334 * opclasses. However, mixed data types and other issues make this
1336 * http://archives.postgresql.org/pgsql-hackers/2008-08/msg01142.php
1341 args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
1344 makeSimpleA_Expr(AEXPR_OP, "<=",
1345 copyObject(aexpr), cexpr,
1347 result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1349 case AEXPR_NOT_BETWEEN:
1350 args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
1353 makeSimpleA_Expr(AEXPR_OP, ">",
1354 copyObject(aexpr), cexpr,
1356 result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1358 case AEXPR_BETWEEN_SYM:
1359 args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
1362 makeSimpleA_Expr(AEXPR_OP, "<=",
1363 copyObject(aexpr), cexpr,
1365 sub1 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1366 args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
1367 copyObject(aexpr), copyObject(cexpr),
1369 makeSimpleA_Expr(AEXPR_OP, "<=",
1370 copyObject(aexpr), copyObject(bexpr),
1372 sub2 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1373 args = list_make2(sub1, sub2);
1374 result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1376 case AEXPR_NOT_BETWEEN_SYM:
1377 args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
1380 makeSimpleA_Expr(AEXPR_OP, ">",
1381 copyObject(aexpr), cexpr,
1383 sub1 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1384 args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
1385 copyObject(aexpr), copyObject(cexpr),
1387 makeSimpleA_Expr(AEXPR_OP, ">",
1388 copyObject(aexpr), copyObject(bexpr),
1390 sub2 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1391 args = list_make2(sub1, sub2);
1392 result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1395 elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
1396 result = NULL; /* keep compiler quiet */
1400 return transformExprRecurse(pstate, result);
1404 transformBoolExpr(ParseState *pstate, BoolExpr *a)
1422 elog(ERROR, "unrecognized boolop: %d", (int) a->boolop);
1423 opname = NULL; /* keep compiler quiet */
1427 foreach(lc, a->args)
1429 Node *arg = (Node *) lfirst(lc);
1431 arg = transformExprRecurse(pstate, arg);
1432 arg = coerce_to_boolean(pstate, arg, opname);
1433 args = lappend(args, arg);
1436 return (Node *) makeBoolExpr(a->boolop, args, a->location);
1440 transformFuncCall(ParseState *pstate, FuncCall *fn)
1442 Node *last_srf = pstate->p_last_srf;
1446 /* Transform the list of arguments ... */
1448 foreach(args, fn->args)
1450 targs = lappend(targs, transformExprRecurse(pstate,
1451 (Node *) lfirst(args)));
1455 * When WITHIN GROUP is used, we treat its ORDER BY expressions as
1456 * additional arguments to the function, for purposes of function lookup
1457 * and argument type coercion. So, transform each such expression and add
1458 * them to the targs list. We don't explicitly mark where each argument
1459 * came from, but ParseFuncOrColumn can tell what's what by reference to
1460 * list_length(fn->agg_order).
1462 if (fn->agg_within_group)
1464 Assert(fn->agg_order != NIL);
1465 foreach(args, fn->agg_order)
1467 SortBy *arg = (SortBy *) lfirst(args);
1469 targs = lappend(targs, transformExpr(pstate, arg->node,
1470 EXPR_KIND_ORDER_BY));
1474 /* ... and hand off to ParseFuncOrColumn */
1475 return ParseFuncOrColumn(pstate,
1484 transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref)
1491 /* We should only see this in first-stage processing of UPDATE tlists */
1492 Assert(pstate->p_expr_kind == EXPR_KIND_UPDATE_SOURCE);
1494 /* We only need to transform the source if this is the first column */
1495 if (maref->colno == 1)
1498 * For now, we only allow EXPR SubLinks and RowExprs as the source of
1499 * an UPDATE multiassignment. This is sufficient to cover interesting
1500 * cases; at worst, someone would have to write (SELECT * FROM expr)
1501 * to expand a composite-returning expression of another form.
1503 if (IsA(maref->source, SubLink) &&
1504 ((SubLink *) maref->source)->subLinkType == EXPR_SUBLINK)
1506 /* Relabel it as a MULTIEXPR_SUBLINK */
1507 sublink = (SubLink *) maref->source;
1508 sublink->subLinkType = MULTIEXPR_SUBLINK;
1509 /* And transform it */
1510 sublink = (SubLink *) transformExprRecurse(pstate,
1513 qtree = castNode(Query, sublink->subselect);
1515 /* Check subquery returns required number of columns */
1516 if (count_nonjunk_tlist_entries(qtree->targetList) != maref->ncolumns)
1518 (errcode(ERRCODE_SYNTAX_ERROR),
1519 errmsg("number of columns does not match number of values"),
1520 parser_errposition(pstate, sublink->location)));
1523 * Build a resjunk tlist item containing the MULTIEXPR SubLink,
1524 * and add it to pstate->p_multiassign_exprs, whence it will later
1525 * get appended to the completed targetlist. We needn't worry
1526 * about selecting a resno for it; transformUpdateStmt will do
1529 tle = makeTargetEntry((Expr *) sublink, 0, NULL, true);
1530 pstate->p_multiassign_exprs = lappend(pstate->p_multiassign_exprs,
1534 * Assign a unique-within-this-targetlist ID to the MULTIEXPR
1535 * SubLink. We can just use its position in the
1536 * p_multiassign_exprs list.
1538 sublink->subLinkId = list_length(pstate->p_multiassign_exprs);
1540 else if (IsA(maref->source, RowExpr))
1542 /* Transform the RowExpr, allowing SetToDefault items */
1543 rexpr = (RowExpr *) transformRowExpr(pstate,
1544 (RowExpr *) maref->source,
1547 /* Check it returns required number of columns */
1548 if (list_length(rexpr->args) != maref->ncolumns)
1550 (errcode(ERRCODE_SYNTAX_ERROR),
1551 errmsg("number of columns does not match number of values"),
1552 parser_errposition(pstate, rexpr->location)));
1555 * Temporarily append it to p_multiassign_exprs, so we can get it
1556 * back when we come back here for additional columns.
1558 tle = makeTargetEntry((Expr *) rexpr, 0, NULL, true);
1559 pstate->p_multiassign_exprs = lappend(pstate->p_multiassign_exprs,
1564 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1565 errmsg("source for a multiple-column UPDATE item must be a sub-SELECT or ROW() expression"),
1566 parser_errposition(pstate, exprLocation(maref->source))));
1571 * Second or later column in a multiassignment. Re-fetch the
1572 * transformed SubLink or RowExpr, which we assume is still the last
1573 * entry in p_multiassign_exprs.
1575 Assert(pstate->p_multiassign_exprs != NIL);
1576 tle = (TargetEntry *) llast(pstate->p_multiassign_exprs);
1580 * Emit the appropriate output expression for the current column
1582 if (IsA(tle->expr, SubLink))
1586 sublink = (SubLink *) tle->expr;
1587 Assert(sublink->subLinkType == MULTIEXPR_SUBLINK);
1588 qtree = castNode(Query, sublink->subselect);
1590 /* Build a Param representing the current subquery output column */
1591 tle = (TargetEntry *) list_nth(qtree->targetList, maref->colno - 1);
1592 Assert(!tle->resjunk);
1594 param = makeNode(Param);
1595 param->paramkind = PARAM_MULTIEXPR;
1596 param->paramid = (sublink->subLinkId << 16) | maref->colno;
1597 param->paramtype = exprType((Node *) tle->expr);
1598 param->paramtypmod = exprTypmod((Node *) tle->expr);
1599 param->paramcollid = exprCollation((Node *) tle->expr);
1600 param->location = exprLocation((Node *) tle->expr);
1602 return (Node *) param;
1605 if (IsA(tle->expr, RowExpr))
1609 rexpr = (RowExpr *) tle->expr;
1611 /* Just extract and return the next element of the RowExpr */
1612 result = (Node *) list_nth(rexpr->args, maref->colno - 1);
1615 * If we're at the last column, delete the RowExpr from
1616 * p_multiassign_exprs; we don't need it anymore, and don't want it in
1617 * the finished UPDATE tlist.
1619 if (maref->colno == maref->ncolumns)
1620 pstate->p_multiassign_exprs =
1621 list_delete_ptr(pstate->p_multiassign_exprs, tle);
1626 elog(ERROR, "unexpected expr type in multiassign list");
1627 return NULL; /* keep compiler quiet */
1631 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1633 CaseExpr *newc = makeNode(CaseExpr);
1634 Node *last_srf = pstate->p_last_srf;
1636 CaseTestExpr *placeholder;
1643 /* transform the test expression, if any */
1644 arg = transformExprRecurse(pstate, (Node *) c->arg);
1646 /* generate placeholder for test expression */
1650 * If test expression is an untyped literal, force it to text. We have
1651 * to do something now because we won't be able to do this coercion on
1652 * the placeholder. This is not as flexible as what was done in 7.4
1653 * and before, but it's good enough to handle the sort of silly coding
1656 if (exprType(arg) == UNKNOWNOID)
1657 arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1660 * Run collation assignment on the test expression so that we know
1661 * what collation to mark the placeholder with. In principle we could
1662 * leave it to parse_collate.c to do that later, but propagating the
1663 * result to the CaseTestExpr would be unnecessarily complicated.
1665 assign_expr_collations(pstate, arg);
1667 placeholder = makeNode(CaseTestExpr);
1668 placeholder->typeId = exprType(arg);
1669 placeholder->typeMod = exprTypmod(arg);
1670 placeholder->collation = exprCollation(arg);
1675 newc->arg = (Expr *) arg;
1677 /* transform the list of arguments */
1682 CaseWhen *w = lfirst_node(CaseWhen, l);
1683 CaseWhen *neww = makeNode(CaseWhen);
1686 warg = (Node *) w->expr;
1689 /* shorthand form was specified, so expand... */
1690 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1691 (Node *) placeholder,
1695 neww->expr = (Expr *) transformExprRecurse(pstate, warg);
1697 neww->expr = (Expr *) coerce_to_boolean(pstate,
1698 (Node *) neww->expr,
1701 warg = (Node *) w->result;
1702 neww->result = (Expr *) transformExprRecurse(pstate, warg);
1703 neww->location = w->location;
1705 newargs = lappend(newargs, neww);
1706 resultexprs = lappend(resultexprs, neww->result);
1709 newc->args = newargs;
1711 /* transform the default clause */
1712 defresult = (Node *) c->defresult;
1713 if (defresult == NULL)
1715 A_Const *n = makeNode(A_Const);
1717 n->val.type = T_Null;
1719 defresult = (Node *) n;
1721 newc->defresult = (Expr *) transformExprRecurse(pstate, defresult);
1724 * Note: default result is considered the most significant type in
1725 * determining preferred type. This is how the code worked before, but it
1726 * seems a little bogus to me --- tgl
1728 resultexprs = lcons(newc->defresult, resultexprs);
1730 ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1731 Assert(OidIsValid(ptype));
1732 newc->casetype = ptype;
1733 /* casecollid will be set by parse_collate.c */
1735 /* Convert default result clause, if necessary */
1736 newc->defresult = (Expr *)
1737 coerce_to_common_type(pstate,
1738 (Node *) newc->defresult,
1742 /* Convert when-clause results, if necessary */
1743 foreach(l, newc->args)
1745 CaseWhen *w = (CaseWhen *) lfirst(l);
1747 w->result = (Expr *)
1748 coerce_to_common_type(pstate,
1754 /* if any subexpression contained a SRF, complain */
1755 if (pstate->p_last_srf != last_srf)
1757 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1758 /* translator: %s is name of a SQL construct, eg GROUP BY */
1759 errmsg("set-returning functions are not allowed in %s",
1761 errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
1762 parser_errposition(pstate,
1763 exprLocation(pstate->p_last_srf))));
1765 newc->location = c->location;
1767 return (Node *) newc;
1771 transformSubLink(ParseState *pstate, SubLink *sublink)
1773 Node *result = (Node *) sublink;
1778 * Check to see if the sublink is in an invalid place within the query. We
1779 * allow sublinks everywhere in SELECT/INSERT/UPDATE/DELETE, but generally
1780 * not in utility statements.
1783 switch (pstate->p_expr_kind)
1785 case EXPR_KIND_NONE:
1786 Assert(false); /* can't happen */
1788 case EXPR_KIND_OTHER:
1789 /* Accept sublink here; caller must throw error if wanted */
1791 case EXPR_KIND_JOIN_ON:
1792 case EXPR_KIND_JOIN_USING:
1793 case EXPR_KIND_FROM_SUBSELECT:
1794 case EXPR_KIND_FROM_FUNCTION:
1795 case EXPR_KIND_WHERE:
1796 case EXPR_KIND_POLICY:
1797 case EXPR_KIND_HAVING:
1798 case EXPR_KIND_FILTER:
1799 case EXPR_KIND_WINDOW_PARTITION:
1800 case EXPR_KIND_WINDOW_ORDER:
1801 case EXPR_KIND_WINDOW_FRAME_RANGE:
1802 case EXPR_KIND_WINDOW_FRAME_ROWS:
1803 case EXPR_KIND_SELECT_TARGET:
1804 case EXPR_KIND_INSERT_TARGET:
1805 case EXPR_KIND_UPDATE_SOURCE:
1806 case EXPR_KIND_UPDATE_TARGET:
1807 case EXPR_KIND_GROUP_BY:
1808 case EXPR_KIND_ORDER_BY:
1809 case EXPR_KIND_DISTINCT_ON:
1810 case EXPR_KIND_LIMIT:
1811 case EXPR_KIND_OFFSET:
1812 case EXPR_KIND_RETURNING:
1813 case EXPR_KIND_VALUES:
1814 case EXPR_KIND_VALUES_SINGLE:
1817 case EXPR_KIND_CHECK_CONSTRAINT:
1818 case EXPR_KIND_DOMAIN_CHECK:
1819 err = _("cannot use subquery in check constraint");
1821 case EXPR_KIND_COLUMN_DEFAULT:
1822 case EXPR_KIND_FUNCTION_DEFAULT:
1823 err = _("cannot use subquery in DEFAULT expression");
1825 case EXPR_KIND_INDEX_EXPRESSION:
1826 err = _("cannot use subquery in index expression");
1828 case EXPR_KIND_INDEX_PREDICATE:
1829 err = _("cannot use subquery in index predicate");
1831 case EXPR_KIND_ALTER_COL_TRANSFORM:
1832 err = _("cannot use subquery in transform expression");
1834 case EXPR_KIND_EXECUTE_PARAMETER:
1835 err = _("cannot use subquery in EXECUTE parameter");
1837 case EXPR_KIND_TRIGGER_WHEN:
1838 err = _("cannot use subquery in trigger WHEN condition");
1840 case EXPR_KIND_PARTITION_EXPRESSION:
1841 err = _("cannot use subquery in partition key expression");
1845 * There is intentionally no default: case here, so that the
1846 * compiler will warn if we add a new ParseExprKind without
1847 * extending this switch. If we do see an unrecognized value at
1848 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
1849 * which is sane anyway.
1854 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1855 errmsg_internal("%s", err),
1856 parser_errposition(pstate, sublink->location)));
1858 pstate->p_hasSubLinks = true;
1861 * OK, let's transform the sub-SELECT.
1863 qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false, true);
1866 * Check that we got a SELECT. Anything else should be impossible given
1867 * restrictions of the grammar, but check anyway.
1869 if (!IsA(qtree, Query) ||
1870 qtree->commandType != CMD_SELECT)
1871 elog(ERROR, "unexpected non-SELECT command in SubLink");
1873 sublink->subselect = (Node *) qtree;
1875 if (sublink->subLinkType == EXISTS_SUBLINK)
1878 * EXISTS needs no test expression or combining operator. These fields
1879 * should be null already, but make sure.
1881 sublink->testexpr = NULL;
1882 sublink->operName = NIL;
1884 else if (sublink->subLinkType == EXPR_SUBLINK ||
1885 sublink->subLinkType == ARRAY_SUBLINK)
1888 * Make sure the subselect delivers a single column (ignoring resjunk
1891 if (count_nonjunk_tlist_entries(qtree->targetList) != 1)
1893 (errcode(ERRCODE_SYNTAX_ERROR),
1894 errmsg("subquery must return only one column"),
1895 parser_errposition(pstate, sublink->location)));
1898 * EXPR and ARRAY need no test expression or combining operator. These
1899 * fields should be null already, but make sure.
1901 sublink->testexpr = NULL;
1902 sublink->operName = NIL;
1904 else if (sublink->subLinkType == MULTIEXPR_SUBLINK)
1906 /* Same as EXPR case, except no restriction on number of columns */
1907 sublink->testexpr = NULL;
1908 sublink->operName = NIL;
1912 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1918 if (operator_precedence_warning)
1920 if (sublink->operName == NIL)
1921 emit_precedence_warnings(pstate, PREC_GROUP_IN, "IN",
1922 sublink->testexpr, NULL,
1925 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_OP,
1926 strVal(llast(sublink->operName)),
1927 sublink->testexpr, NULL,
1932 * If the source was "x IN (select)", convert to "x = ANY (select)".
1934 if (sublink->operName == NIL)
1935 sublink->operName = list_make1(makeString("="));
1938 * Transform lefthand expression, and convert to a list
1940 lefthand = transformExprRecurse(pstate, sublink->testexpr);
1941 if (lefthand && IsA(lefthand, RowExpr))
1942 left_list = ((RowExpr *) lefthand)->args;
1944 left_list = list_make1(lefthand);
1947 * Build a list of PARAM_SUBLINK nodes representing the output columns
1951 foreach(l, qtree->targetList)
1953 TargetEntry *tent = (TargetEntry *) lfirst(l);
1959 param = makeNode(Param);
1960 param->paramkind = PARAM_SUBLINK;
1961 param->paramid = tent->resno;
1962 param->paramtype = exprType((Node *) tent->expr);
1963 param->paramtypmod = exprTypmod((Node *) tent->expr);
1964 param->paramcollid = exprCollation((Node *) tent->expr);
1965 param->location = -1;
1967 right_list = lappend(right_list, param);
1971 * We could rely on make_row_comparison_op to complain if the list
1972 * lengths differ, but we prefer to generate a more specific error
1975 if (list_length(left_list) < list_length(right_list))
1977 (errcode(ERRCODE_SYNTAX_ERROR),
1978 errmsg("subquery has too many columns"),
1979 parser_errposition(pstate, sublink->location)));
1980 if (list_length(left_list) > list_length(right_list))
1982 (errcode(ERRCODE_SYNTAX_ERROR),
1983 errmsg("subquery has too few columns"),
1984 parser_errposition(pstate, sublink->location)));
1987 * Identify the combining operator(s) and generate a suitable
1988 * row-comparison expression.
1990 sublink->testexpr = make_row_comparison_op(pstate,
2001 * transformArrayExpr
2003 * If the caller specifies the target type, the resulting array will
2004 * be of exactly that type. Otherwise we try to infer a common type
2005 * for the elements using select_common_type().
2008 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
2009 Oid array_type, Oid element_type, int32 typmod)
2011 ArrayExpr *newa = makeNode(ArrayExpr);
2012 List *newelems = NIL;
2013 List *newcoercedelems = NIL;
2019 * Transform the element expressions
2021 * Assume that the array is one-dimensional unless we find an array-type
2022 * element expression.
2024 newa->multidims = false;
2025 foreach(element, a->elements)
2027 Node *e = (Node *) lfirst(element);
2030 /* Look through AEXPR_PAREN nodes so they don't affect test below */
2031 while (e && IsA(e, A_Expr) &&
2032 ((A_Expr *) e)->kind == AEXPR_PAREN)
2033 e = ((A_Expr *) e)->lexpr;
2036 * If an element is itself an A_ArrayExpr, recurse directly so that we
2037 * can pass down any target type we were given.
2039 if (IsA(e, A_ArrayExpr))
2041 newe = transformArrayExpr(pstate,
2046 /* we certainly have an array here */
2047 Assert(array_type == InvalidOid || array_type == exprType(newe));
2048 newa->multidims = true;
2052 newe = transformExprRecurse(pstate, e);
2055 * Check for sub-array expressions, if we haven't already found
2058 if (!newa->multidims && type_is_array(exprType(newe)))
2059 newa->multidims = true;
2062 newelems = lappend(newelems, newe);
2066 * Select a target type for the elements.
2068 * If we haven't been given a target array type, we must try to deduce a
2069 * common type based on the types of the individual elements present.
2071 if (OidIsValid(array_type))
2073 /* Caller must ensure array_type matches element_type */
2074 Assert(OidIsValid(element_type));
2075 coerce_type = (newa->multidims ? array_type : element_type);
2080 /* Can't handle an empty array without a target type */
2081 if (newelems == NIL)
2083 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
2084 errmsg("cannot determine type of empty array"),
2085 errhint("Explicitly cast to the desired type, "
2086 "for example ARRAY[]::integer[]."),
2087 parser_errposition(pstate, a->location)));
2089 /* Select a common type for the elements */
2090 coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
2092 if (newa->multidims)
2094 array_type = coerce_type;
2095 element_type = get_element_type(array_type);
2096 if (!OidIsValid(element_type))
2098 (errcode(ERRCODE_UNDEFINED_OBJECT),
2099 errmsg("could not find element type for data type %s",
2100 format_type_be(array_type)),
2101 parser_errposition(pstate, a->location)));
2105 element_type = coerce_type;
2106 array_type = get_array_type(element_type);
2107 if (!OidIsValid(array_type))
2109 (errcode(ERRCODE_UNDEFINED_OBJECT),
2110 errmsg("could not find array type for data type %s",
2111 format_type_be(element_type)),
2112 parser_errposition(pstate, a->location)));
2114 coerce_hard = false;
2118 * Coerce elements to target type
2120 * If the array has been explicitly cast, then the elements are in turn
2121 * explicitly coerced.
2123 * If the array's type was merely derived from the common type of its
2124 * elements, then the elements are implicitly coerced to the common type.
2125 * This is consistent with other uses of select_common_type().
2127 foreach(element, newelems)
2129 Node *e = (Node *) lfirst(element);
2134 newe = coerce_to_target_type(pstate, e,
2139 COERCE_EXPLICIT_CAST,
2143 (errcode(ERRCODE_CANNOT_COERCE),
2144 errmsg("cannot cast type %s to %s",
2145 format_type_be(exprType(e)),
2146 format_type_be(coerce_type)),
2147 parser_errposition(pstate, exprLocation(e))));
2150 newe = coerce_to_common_type(pstate, e,
2153 newcoercedelems = lappend(newcoercedelems, newe);
2156 newa->array_typeid = array_type;
2157 /* array_collid will be set by parse_collate.c */
2158 newa->element_typeid = element_type;
2159 newa->elements = newcoercedelems;
2160 newa->location = a->location;
2162 return (Node *) newa;
2166 transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault)
2173 newr = makeNode(RowExpr);
2175 /* Transform the field expressions */
2176 newr->args = transformExpressionList(pstate, r->args,
2177 pstate->p_expr_kind, allowDefault);
2179 /* Barring later casting, we consider the type RECORD */
2180 newr->row_typeid = RECORDOID;
2181 newr->row_format = COERCE_IMPLICIT_CAST;
2183 /* ROW() has anonymous columns, so invent some field names */
2184 newr->colnames = NIL;
2186 foreach(lc, newr->args)
2188 snprintf(fname, sizeof(fname), "f%d", fnum++);
2189 newr->colnames = lappend(newr->colnames, makeString(pstrdup(fname)));
2192 newr->location = r->location;
2194 return (Node *) newr;
2198 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
2200 CoalesceExpr *newc = makeNode(CoalesceExpr);
2201 Node *last_srf = pstate->p_last_srf;
2202 List *newargs = NIL;
2203 List *newcoercedargs = NIL;
2206 foreach(args, c->args)
2208 Node *e = (Node *) lfirst(args);
2211 newe = transformExprRecurse(pstate, e);
2212 newargs = lappend(newargs, newe);
2215 newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
2216 /* coalescecollid will be set by parse_collate.c */
2218 /* Convert arguments if necessary */
2219 foreach(args, newargs)
2221 Node *e = (Node *) lfirst(args);
2224 newe = coerce_to_common_type(pstate, e,
2227 newcoercedargs = lappend(newcoercedargs, newe);
2230 /* if any subexpression contained a SRF, complain */
2231 if (pstate->p_last_srf != last_srf)
2233 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2234 /* translator: %s is name of a SQL construct, eg GROUP BY */
2235 errmsg("set-returning functions are not allowed in %s",
2237 errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
2238 parser_errposition(pstate,
2239 exprLocation(pstate->p_last_srf))));
2241 newc->args = newcoercedargs;
2242 newc->location = c->location;
2243 return (Node *) newc;
2247 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
2249 MinMaxExpr *newm = makeNode(MinMaxExpr);
2250 List *newargs = NIL;
2251 List *newcoercedargs = NIL;
2252 const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
2256 foreach(args, m->args)
2258 Node *e = (Node *) lfirst(args);
2261 newe = transformExprRecurse(pstate, e);
2262 newargs = lappend(newargs, newe);
2265 newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
2266 /* minmaxcollid and inputcollid will be set by parse_collate.c */
2268 /* Convert arguments if necessary */
2269 foreach(args, newargs)
2271 Node *e = (Node *) lfirst(args);
2274 newe = coerce_to_common_type(pstate, e,
2277 newcoercedargs = lappend(newcoercedargs, newe);
2280 newm->args = newcoercedargs;
2281 newm->location = m->location;
2282 return (Node *) newm;
2286 transformSQLValueFunction(ParseState *pstate, SQLValueFunction *svf)
2289 * All we need to do is insert the correct result type and (where needed)
2290 * validate the typmod, so we just modify the node in-place.
2294 case SVFOP_CURRENT_DATE:
2295 svf->type = DATEOID;
2297 case SVFOP_CURRENT_TIME:
2298 svf->type = TIMETZOID;
2300 case SVFOP_CURRENT_TIME_N:
2301 svf->type = TIMETZOID;
2302 svf->typmod = anytime_typmod_check(true, svf->typmod);
2304 case SVFOP_CURRENT_TIMESTAMP:
2305 svf->type = TIMESTAMPTZOID;
2307 case SVFOP_CURRENT_TIMESTAMP_N:
2308 svf->type = TIMESTAMPTZOID;
2309 svf->typmod = anytimestamp_typmod_check(true, svf->typmod);
2311 case SVFOP_LOCALTIME:
2312 svf->type = TIMEOID;
2314 case SVFOP_LOCALTIME_N:
2315 svf->type = TIMEOID;
2316 svf->typmod = anytime_typmod_check(false, svf->typmod);
2318 case SVFOP_LOCALTIMESTAMP:
2319 svf->type = TIMESTAMPOID;
2321 case SVFOP_LOCALTIMESTAMP_N:
2322 svf->type = TIMESTAMPOID;
2323 svf->typmod = anytimestamp_typmod_check(false, svf->typmod);
2325 case SVFOP_CURRENT_ROLE:
2326 case SVFOP_CURRENT_USER:
2328 case SVFOP_SESSION_USER:
2329 case SVFOP_CURRENT_CATALOG:
2330 case SVFOP_CURRENT_SCHEMA:
2331 svf->type = NAMEOID;
2335 return (Node *) svf;
2339 transformXmlExpr(ParseState *pstate, XmlExpr *x)
2345 if (operator_precedence_warning && x->op == IS_DOCUMENT)
2346 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
2347 (Node *) linitial(x->args), NULL,
2350 newx = makeNode(XmlExpr);
2353 newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
2356 newx->xmloption = x->xmloption;
2357 newx->type = XMLOID; /* this just marks the node as transformed */
2359 newx->location = x->location;
2362 * gram.y built the named args as a list of ResTarget. Transform each,
2363 * and break the names out as a separate list.
2365 newx->named_args = NIL;
2366 newx->arg_names = NIL;
2368 foreach(lc, x->named_args)
2370 ResTarget *r = lfirst_node(ResTarget, lc);
2374 expr = transformExprRecurse(pstate, r->val);
2377 argname = map_sql_identifier_to_xml_name(r->name, false, false);
2378 else if (IsA(r->val, ColumnRef))
2379 argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
2384 (errcode(ERRCODE_SYNTAX_ERROR),
2385 x->op == IS_XMLELEMENT
2386 ? errmsg("unnamed XML attribute value must be a column reference")
2387 : errmsg("unnamed XML element value must be a column reference"),
2388 parser_errposition(pstate, r->location)));
2389 argname = NULL; /* keep compiler quiet */
2392 /* reject duplicate argnames in XMLELEMENT only */
2393 if (x->op == IS_XMLELEMENT)
2397 foreach(lc2, newx->arg_names)
2399 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
2401 (errcode(ERRCODE_SYNTAX_ERROR),
2402 errmsg("XML attribute name \"%s\" appears more than once",
2404 parser_errposition(pstate, r->location)));
2408 newx->named_args = lappend(newx->named_args, expr);
2409 newx->arg_names = lappend(newx->arg_names, makeString(argname));
2412 /* The other arguments are of varying types depending on the function */
2415 foreach(lc, x->args)
2417 Node *e = (Node *) lfirst(lc);
2420 newe = transformExprRecurse(pstate, e);
2424 newe = coerce_to_specific_type(pstate, newe, XMLOID,
2428 /* no coercion necessary */
2431 newe = coerce_to_specific_type(pstate, newe, XMLOID,
2436 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2439 newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
2442 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2447 newe = coerce_to_specific_type(pstate, newe, XMLOID,
2450 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2453 newe = coerce_to_specific_type(pstate, newe, INT4OID,
2456 case IS_XMLSERIALIZE:
2457 /* not handled here */
2461 newe = coerce_to_specific_type(pstate, newe, XMLOID,
2465 newx->args = lappend(newx->args, newe);
2469 return (Node *) newx;
2473 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
2480 xexpr = makeNode(XmlExpr);
2481 xexpr->op = IS_XMLSERIALIZE;
2482 xexpr->args = list_make1(coerce_to_specific_type(pstate,
2483 transformExprRecurse(pstate, xs->expr),
2487 typenameTypeIdAndMod(pstate, xs->typeName, &targetType, &targetTypmod);
2489 xexpr->xmloption = xs->xmloption;
2490 xexpr->location = xs->location;
2491 /* We actually only need these to be able to parse back the expression. */
2492 xexpr->type = targetType;
2493 xexpr->typmod = targetTypmod;
2496 * The actual target type is determined this way. SQL allows char and
2497 * varchar as target types. We allow anything that can be cast implicitly
2498 * from text. This way, user-defined text-like data types automatically
2501 result = coerce_to_target_type(pstate, (Node *) xexpr,
2502 TEXTOID, targetType, targetTypmod,
2504 COERCE_IMPLICIT_CAST,
2508 (errcode(ERRCODE_CANNOT_COERCE),
2509 errmsg("cannot cast XMLSERIALIZE result to %s",
2510 format_type_be(targetType)),
2511 parser_errposition(pstate, xexpr->location)));
2516 transformBooleanTest(ParseState *pstate, BooleanTest *b)
2518 const char *clausename;
2520 if (operator_precedence_warning)
2521 emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
2522 (Node *) b->arg, NULL,
2525 switch (b->booltesttype)
2528 clausename = "IS TRUE";
2531 clausename = "IS NOT TRUE";
2534 clausename = "IS FALSE";
2537 clausename = "IS NOT FALSE";
2540 clausename = "IS UNKNOWN";
2542 case IS_NOT_UNKNOWN:
2543 clausename = "IS NOT UNKNOWN";
2546 elog(ERROR, "unrecognized booltesttype: %d",
2547 (int) b->booltesttype);
2548 clausename = NULL; /* keep compiler quiet */
2551 b->arg = (Expr *) transformExprRecurse(pstate, (Node *) b->arg);
2553 b->arg = (Expr *) coerce_to_boolean(pstate,
2561 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
2565 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
2566 Assert(pstate->p_target_rangetblentry != NULL);
2567 cexpr->cvarno = RTERangeTablePosn(pstate,
2568 pstate->p_target_rangetblentry,
2570 Assert(sublevels_up == 0);
2573 * Check to see if the cursor name matches a parameter of type REFCURSOR.
2574 * If so, replace the raw name reference with a parameter reference. (This
2575 * is a hack for the convenience of plpgsql.)
2577 if (cexpr->cursor_name != NULL) /* in case already transformed */
2579 ColumnRef *cref = makeNode(ColumnRef);
2582 /* Build an unqualified ColumnRef with the given name */
2583 cref->fields = list_make1(makeString(cexpr->cursor_name));
2584 cref->location = -1;
2586 /* See if there is a translation available from a parser hook */
2587 if (pstate->p_pre_columnref_hook != NULL)
2588 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
2589 if (node == NULL && pstate->p_post_columnref_hook != NULL)
2590 node = (*pstate->p_post_columnref_hook) (pstate, cref, NULL);
2593 * XXX Should we throw an error if we get a translation that isn't a
2594 * refcursor Param? For now it seems best to silently ignore false
2597 if (node != NULL && IsA(node, Param))
2599 Param *p = (Param *) node;
2601 if (p->paramkind == PARAM_EXTERN &&
2602 p->paramtype == REFCURSOROID)
2604 /* Matches, so convert CURRENT OF to a param reference */
2605 cexpr->cursor_name = NULL;
2606 cexpr->cursor_param = p->paramid;
2611 return (Node *) cexpr;
2615 * Construct a whole-row reference to represent the notation "relation.*".
2618 transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte, int location)
2624 /* Find the RTE's rangetable location */
2625 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
2628 * Build the appropriate referencing node. Note that if the RTE is a
2629 * function returning scalar, we create just a plain reference to the
2630 * function value, not a composite containing a single column. This is
2631 * pretty inconsistent at first sight, but it's what we've done
2632 * historically. One argument for it is that "rel" and "rel.*" mean the
2633 * same thing for composite relations, so why not for scalar functions...
2635 result = makeWholeRowVar(rte, vnum, sublevels_up, true);
2637 /* location is not filled in by makeWholeRowVar */
2638 result->location = location;
2640 /* mark relation as requiring whole-row SELECT access */
2641 markVarForSelectPriv(pstate, result, rte);
2643 return (Node *) result;
2647 * Handle an explicit CAST construct.
2649 * Transform the argument, look up the type name, and apply any necessary
2650 * coercion function(s).
2653 transformTypeCast(ParseState *pstate, TypeCast *tc)
2656 Node *arg = tc->arg;
2663 /* Look up the type name first */
2664 typenameTypeIdAndMod(pstate, tc->typeName, &targetType, &targetTypmod);
2667 * Look through any AEXPR_PAREN nodes that may have been inserted thanks
2668 * to operator_precedence_warning. Otherwise, ARRAY[]::foo[] behaves
2669 * differently from (ARRAY[])::foo[].
2671 while (arg && IsA(arg, A_Expr) &&
2672 ((A_Expr *) arg)->kind == AEXPR_PAREN)
2673 arg = ((A_Expr *) arg)->lexpr;
2676 * If the subject of the typecast is an ARRAY[] construct and the target
2677 * type is an array type, we invoke transformArrayExpr() directly so that
2678 * we can pass down the type information. This avoids some cases where
2679 * transformArrayExpr() might not infer the correct type. Otherwise, just
2680 * transform the argument normally.
2682 if (IsA(arg, A_ArrayExpr))
2685 int32 targetBaseTypmod;
2689 * If target is a domain over array, work with the base array type
2690 * here. Below, we'll cast the array type to the domain. In the
2691 * usual case that the target is not a domain, the remaining steps
2694 targetBaseTypmod = targetTypmod;
2695 targetBaseType = getBaseTypeAndTypmod(targetType, &targetBaseTypmod);
2696 elementType = get_element_type(targetBaseType);
2697 if (OidIsValid(elementType))
2699 expr = transformArrayExpr(pstate,
2700 (A_ArrayExpr *) arg,
2706 expr = transformExprRecurse(pstate, arg);
2709 expr = transformExprRecurse(pstate, arg);
2711 inputType = exprType(expr);
2712 if (inputType == InvalidOid)
2713 return expr; /* do nothing if NULL input */
2716 * Location of the coercion is preferentially the location of the :: or
2717 * CAST symbol, but if there is none then use the location of the type
2718 * name (this can happen in TypeName 'string' syntax, for instance).
2720 location = tc->location;
2722 location = tc->typeName->location;
2724 result = coerce_to_target_type(pstate, expr, inputType,
2725 targetType, targetTypmod,
2727 COERCE_EXPLICIT_CAST,
2731 (errcode(ERRCODE_CANNOT_COERCE),
2732 errmsg("cannot cast type %s to %s",
2733 format_type_be(inputType),
2734 format_type_be(targetType)),
2735 parser_coercion_errposition(pstate, location, expr)));
2741 * Handle an explicit COLLATE clause.
2743 * Transform the argument, and look up the collation name.
2746 transformCollateClause(ParseState *pstate, CollateClause *c)
2751 newc = makeNode(CollateExpr);
2752 newc->arg = (Expr *) transformExprRecurse(pstate, c->arg);
2754 argtype = exprType((Node *) newc->arg);
2757 * The unknown type is not collatable, but coerce_type() takes care of it
2758 * separately, so we'll let it go here.
2760 if (!type_is_collatable(argtype) && argtype != UNKNOWNOID)
2762 (errcode(ERRCODE_DATATYPE_MISMATCH),
2763 errmsg("collations are not supported by type %s",
2764 format_type_be(argtype)),
2765 parser_errposition(pstate, c->location)));
2767 newc->collOid = LookupCollation(pstate, c->collname, c->location);
2768 newc->location = c->location;
2770 return (Node *) newc;
2774 * Transform a "row compare-op row" construct
2776 * The inputs are lists of already-transformed expressions.
2777 * As with coerce_type, pstate may be NULL if no special unknown-Param
2778 * processing is wanted.
2780 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2781 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2782 * The AND, OR, and RowCompareExpr cases further imply things about the
2783 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2786 make_row_comparison_op(ParseState *pstate, List *opname,
2787 List *largs, List *rargs, int location)
2789 RowCompareExpr *rcexpr;
2790 RowCompareType rctype;
2796 List **opinfo_lists;
2801 nopers = list_length(largs);
2802 if (nopers != list_length(rargs))
2804 (errcode(ERRCODE_SYNTAX_ERROR),
2805 errmsg("unequal number of entries in row expressions"),
2806 parser_errposition(pstate, location)));
2809 * We can't compare zero-length rows because there is no principled basis
2810 * for figuring out what the operator is.
2814 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2815 errmsg("cannot compare rows of zero length"),
2816 parser_errposition(pstate, location)));
2819 * Identify all the pairwise operators, using make_op so that behavior is
2820 * the same as in the simple scalar case.
2823 forboth(l, largs, r, rargs)
2825 Node *larg = (Node *) lfirst(l);
2826 Node *rarg = (Node *) lfirst(r);
2829 cmp = castNode(OpExpr, make_op(pstate, opname, larg, rarg,
2830 pstate->p_last_srf, location));
2833 * We don't use coerce_to_boolean here because we insist on the
2834 * operator yielding boolean directly, not via coercion. If it
2835 * doesn't yield bool it won't be in any index opfamilies...
2837 if (cmp->opresulttype != BOOLOID)
2839 (errcode(ERRCODE_DATATYPE_MISMATCH),
2840 errmsg("row comparison operator must yield type boolean, "
2842 format_type_be(cmp->opresulttype)),
2843 parser_errposition(pstate, location)));
2844 if (expression_returns_set((Node *) cmp))
2846 (errcode(ERRCODE_DATATYPE_MISMATCH),
2847 errmsg("row comparison operator must not return a set"),
2848 parser_errposition(pstate, location)));
2849 opexprs = lappend(opexprs, cmp);
2853 * If rows are length 1, just return the single operator. In this case we
2854 * don't insist on identifying btree semantics for the operator (but we
2855 * still require it to return boolean).
2858 return (Node *) linitial(opexprs);
2861 * Now we must determine which row comparison semantics (= <> < <= > >=)
2862 * apply to this set of operators. We look for btree opfamilies
2863 * containing the operators, and see which interpretations (strategy
2864 * numbers) exist for each operator.
2866 opinfo_lists = (List **) palloc(nopers * sizeof(List *));
2871 Oid opno = ((OpExpr *) lfirst(l))->opno;
2872 Bitmapset *this_strats;
2875 opinfo_lists[i] = get_op_btree_interpretation(opno);
2878 * convert strategy numbers into a Bitmapset to make the intersection
2882 foreach(j, opinfo_lists[i])
2884 OpBtreeInterpretation *opinfo = lfirst(j);
2886 this_strats = bms_add_member(this_strats, opinfo->strategy);
2889 strats = this_strats;
2891 strats = bms_int_members(strats, this_strats);
2896 * If there are multiple common interpretations, we may use any one of
2897 * them ... this coding arbitrarily picks the lowest btree strategy
2900 i = bms_first_member(strats);
2903 /* No common interpretation, so fail */
2905 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2906 errmsg("could not determine interpretation of row comparison operator %s",
2907 strVal(llast(opname))),
2908 errhint("Row comparison operators must be associated with btree operator families."),
2909 parser_errposition(pstate, location)));
2911 rctype = (RowCompareType) i;
2914 * For = and <> cases, we just combine the pairwise operators with AND or
2917 if (rctype == ROWCOMPARE_EQ)
2918 return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2919 if (rctype == ROWCOMPARE_NE)
2920 return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2923 * Otherwise we need to choose exactly which opfamily to associate with
2927 for (i = 0; i < nopers; i++)
2929 Oid opfamily = InvalidOid;
2932 foreach(j, opinfo_lists[i])
2934 OpBtreeInterpretation *opinfo = lfirst(j);
2936 if (opinfo->strategy == rctype)
2938 opfamily = opinfo->opfamily_id;
2942 if (OidIsValid(opfamily))
2943 opfamilies = lappend_oid(opfamilies, opfamily);
2944 else /* should not happen */
2946 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2947 errmsg("could not determine interpretation of row comparison operator %s",
2948 strVal(llast(opname))),
2949 errdetail("There are multiple equally-plausible candidates."),
2950 parser_errposition(pstate, location)));
2954 * Now deconstruct the OpExprs and create a RowCompareExpr.
2956 * Note: can't just reuse the passed largs/rargs lists, because of
2957 * possibility that make_op inserted coercion operations.
2964 OpExpr *cmp = (OpExpr *) lfirst(l);
2966 opnos = lappend_oid(opnos, cmp->opno);
2967 largs = lappend(largs, linitial(cmp->args));
2968 rargs = lappend(rargs, lsecond(cmp->args));
2971 rcexpr = makeNode(RowCompareExpr);
2972 rcexpr->rctype = rctype;
2973 rcexpr->opnos = opnos;
2974 rcexpr->opfamilies = opfamilies;
2975 rcexpr->inputcollids = NIL; /* assign_expr_collations will fix this */
2976 rcexpr->largs = largs;
2977 rcexpr->rargs = rargs;
2979 return (Node *) rcexpr;
2983 * Transform a "row IS DISTINCT FROM row" construct
2985 * The input RowExprs are already transformed
2988 make_row_distinct_op(ParseState *pstate, List *opname,
2989 RowExpr *lrow, RowExpr *rrow,
2992 Node *result = NULL;
2993 List *largs = lrow->args;
2994 List *rargs = rrow->args;
2998 if (list_length(largs) != list_length(rargs))
3000 (errcode(ERRCODE_SYNTAX_ERROR),
3001 errmsg("unequal number of entries in row expressions"),
3002 parser_errposition(pstate, location)));
3004 forboth(l, largs, r, rargs)
3006 Node *larg = (Node *) lfirst(l);
3007 Node *rarg = (Node *) lfirst(r);
3010 cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
3014 result = (Node *) makeBoolExpr(OR_EXPR,
3015 list_make2(result, cmp),
3021 /* zero-length rows? Generate constant FALSE */
3022 result = makeBoolConst(false, false);
3029 * make the node for an IS DISTINCT FROM operator
3032 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
3037 result = make_op(pstate, opname, ltree, rtree,
3038 pstate->p_last_srf, location);
3039 if (((OpExpr *) result)->opresulttype != BOOLOID)
3041 (errcode(ERRCODE_DATATYPE_MISMATCH),
3042 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
3043 parser_errposition(pstate, location)));
3044 if (((OpExpr *) result)->opretset)
3046 (errcode(ERRCODE_DATATYPE_MISMATCH),
3047 /* translator: %s is name of a SQL construct, eg NULLIF */
3048 errmsg("%s must not return a set", "IS DISTINCT FROM"),
3049 parser_errposition(pstate, location)));
3052 * We rely on DistinctExpr and OpExpr being same struct
3054 NodeSetTag(result, T_DistinctExpr);
3060 * Produce a NullTest node from an IS [NOT] DISTINCT FROM NULL construct
3062 * "arg" is the untransformed other argument
3065 make_nulltest_from_distinct(ParseState *pstate, A_Expr *distincta, Node *arg)
3067 NullTest *nt = makeNode(NullTest);
3069 nt->arg = (Expr *) transformExprRecurse(pstate, arg);
3070 /* the argument can be any type, so don't coerce it */
3071 if (distincta->kind == AEXPR_NOT_DISTINCT)
3072 nt->nulltesttype = IS_NULL;
3074 nt->nulltesttype = IS_NOT_NULL;
3075 /* argisrow = false is correct whether or not arg is composite */
3076 nt->argisrow = false;
3077 nt->location = distincta->location;
3082 * Identify node's group for operator precedence warnings
3084 * For items in nonzero groups, also return a suitable node name into *nodename
3086 * Note: group zero is used for nodes that are higher or lower precedence
3087 * than everything that changed precedence; we need never issue warnings
3088 * related to such nodes.
3091 operator_precedence_group(Node *node, const char **nodename)
3099 if (IsA(node, A_Expr))
3101 A_Expr *aexpr = (A_Expr *) node;
3103 if (aexpr->kind == AEXPR_OP &&
3104 aexpr->lexpr != NULL &&
3105 aexpr->rexpr != NULL)
3107 /* binary operator */
3108 if (list_length(aexpr->name) == 1)
3110 *nodename = strVal(linitial(aexpr->name));
3111 /* Ignore if op was always higher priority than IS-tests */
3112 if (strcmp(*nodename, "+") == 0 ||
3113 strcmp(*nodename, "-") == 0 ||
3114 strcmp(*nodename, "*") == 0 ||
3115 strcmp(*nodename, "/") == 0 ||
3116 strcmp(*nodename, "%") == 0 ||
3117 strcmp(*nodename, "^") == 0)
3119 else if (strcmp(*nodename, "<") == 0 ||
3120 strcmp(*nodename, ">") == 0)
3121 group = PREC_GROUP_LESS;
3122 else if (strcmp(*nodename, "=") == 0)
3123 group = PREC_GROUP_EQUAL;
3124 else if (strcmp(*nodename, "<=") == 0 ||
3125 strcmp(*nodename, ">=") == 0 ||
3126 strcmp(*nodename, "<>") == 0)
3127 group = PREC_GROUP_LESS_EQUAL;
3129 group = PREC_GROUP_INFIX_OP;
3133 /* schema-qualified operator syntax */
3134 *nodename = "OPERATOR()";
3135 group = PREC_GROUP_INFIX_OP;
3138 else if (aexpr->kind == AEXPR_OP &&
3139 aexpr->lexpr == NULL &&
3140 aexpr->rexpr != NULL)
3142 /* prefix operator */
3143 if (list_length(aexpr->name) == 1)
3145 *nodename = strVal(linitial(aexpr->name));
3146 /* Ignore if op was always higher priority than IS-tests */
3147 if (strcmp(*nodename, "+") == 0 ||
3148 strcmp(*nodename, "-"))
3151 group = PREC_GROUP_PREFIX_OP;
3155 /* schema-qualified operator syntax */
3156 *nodename = "OPERATOR()";
3157 group = PREC_GROUP_PREFIX_OP;
3160 else if (aexpr->kind == AEXPR_OP &&
3161 aexpr->lexpr != NULL &&
3162 aexpr->rexpr == NULL)
3164 /* postfix operator */
3165 if (list_length(aexpr->name) == 1)
3167 *nodename = strVal(linitial(aexpr->name));
3168 group = PREC_GROUP_POSTFIX_OP;
3172 /* schema-qualified operator syntax */
3173 *nodename = "OPERATOR()";
3174 group = PREC_GROUP_POSTFIX_OP;
3177 else if (aexpr->kind == AEXPR_OP_ANY ||
3178 aexpr->kind == AEXPR_OP_ALL)
3180 *nodename = strVal(llast(aexpr->name));
3181 group = PREC_GROUP_POSTFIX_OP;
3183 else if (aexpr->kind == AEXPR_DISTINCT ||
3184 aexpr->kind == AEXPR_NOT_DISTINCT)
3187 group = PREC_GROUP_INFIX_IS;
3189 else if (aexpr->kind == AEXPR_OF)
3192 group = PREC_GROUP_POSTFIX_IS;
3194 else if (aexpr->kind == AEXPR_IN)
3197 if (strcmp(strVal(linitial(aexpr->name)), "=") == 0)
3198 group = PREC_GROUP_IN;
3200 group = PREC_GROUP_NOT_IN;
3202 else if (aexpr->kind == AEXPR_LIKE)
3205 if (strcmp(strVal(linitial(aexpr->name)), "~~") == 0)
3206 group = PREC_GROUP_LIKE;
3208 group = PREC_GROUP_NOT_LIKE;
3210 else if (aexpr->kind == AEXPR_ILIKE)
3212 *nodename = "ILIKE";
3213 if (strcmp(strVal(linitial(aexpr->name)), "~~*") == 0)
3214 group = PREC_GROUP_LIKE;
3216 group = PREC_GROUP_NOT_LIKE;
3218 else if (aexpr->kind == AEXPR_SIMILAR)
3220 *nodename = "SIMILAR";
3221 if (strcmp(strVal(linitial(aexpr->name)), "~") == 0)
3222 group = PREC_GROUP_LIKE;
3224 group = PREC_GROUP_NOT_LIKE;
3226 else if (aexpr->kind == AEXPR_BETWEEN ||
3227 aexpr->kind == AEXPR_BETWEEN_SYM)
3229 Assert(list_length(aexpr->name) == 1);
3230 *nodename = strVal(linitial(aexpr->name));
3231 group = PREC_GROUP_BETWEEN;
3233 else if (aexpr->kind == AEXPR_NOT_BETWEEN ||
3234 aexpr->kind == AEXPR_NOT_BETWEEN_SYM)
3236 Assert(list_length(aexpr->name) == 1);
3237 *nodename = strVal(linitial(aexpr->name));
3238 group = PREC_GROUP_NOT_BETWEEN;
3241 else if (IsA(node, NullTest) ||
3242 IsA(node, BooleanTest))
3245 group = PREC_GROUP_POSTFIX_IS;
3247 else if (IsA(node, XmlExpr))
3249 XmlExpr *x = (XmlExpr *) node;
3251 if (x->op == IS_DOCUMENT)
3254 group = PREC_GROUP_POSTFIX_IS;
3257 else if (IsA(node, SubLink))
3259 SubLink *s = (SubLink *) node;
3261 if (s->subLinkType == ANY_SUBLINK ||
3262 s->subLinkType == ALL_SUBLINK)
3264 if (s->operName == NIL)
3267 group = PREC_GROUP_IN;
3271 *nodename = strVal(llast(s->operName));
3272 group = PREC_GROUP_POSTFIX_OP;
3276 else if (IsA(node, BoolExpr))
3279 * Must dig into NOTs to see if it's IS NOT DOCUMENT or NOT IN. This
3280 * opens us to possibly misrecognizing, eg, NOT (x IS DOCUMENT) as a
3281 * problematic construct. We can tell the difference by checking
3282 * whether the parse locations of the two nodes are identical.
3284 * Note that when we are comparing the child node to its own children,
3285 * we will not know that it was a NOT. Fortunately, that doesn't
3286 * matter for these cases.
3288 BoolExpr *b = (BoolExpr *) node;
3290 if (b->boolop == NOT_EXPR)
3292 Node *child = (Node *) linitial(b->args);
3294 if (IsA(child, XmlExpr))
3296 XmlExpr *x = (XmlExpr *) child;
3298 if (x->op == IS_DOCUMENT &&
3299 x->location == b->location)
3302 group = PREC_GROUP_POSTFIX_IS;
3305 else if (IsA(child, SubLink))
3307 SubLink *s = (SubLink *) child;
3309 if (s->subLinkType == ANY_SUBLINK && s->operName == NIL &&
3310 s->location == b->location)
3313 group = PREC_GROUP_NOT_IN;
3322 * helper routine for delivering 9.4-to-9.5 operator precedence warnings
3324 * opgroup/opname/location represent some parent node
3325 * lchild, rchild are its left and right children (either could be NULL)
3327 * This should be called before transforming the child nodes, since if a
3328 * precedence-driven parsing change has occurred in a query that used to work,
3329 * it's quite possible that we'll get a semantic failure while analyzing the
3330 * child expression. We want to produce the warning before that happens.
3331 * In any case, operator_precedence_group() expects untransformed input.
3334 emit_precedence_warnings(ParseState *pstate,
3335 int opgroup, const char *opname,
3336 Node *lchild, Node *rchild,
3340 const char *copname;
3342 Assert(opgroup > 0);
3345 * Complain if left child, which should be same or higher precedence
3346 * according to current rules, used to be lower precedence.
3348 * Exception to precedence rules: if left child is IN or NOT IN or a
3349 * postfix operator, the grouping is syntactically forced regardless of
3352 cgroup = operator_precedence_group(lchild, &copname);
3355 if (oldprecedence_l[cgroup] < oldprecedence_r[opgroup] &&
3356 cgroup != PREC_GROUP_IN &&
3357 cgroup != PREC_GROUP_NOT_IN &&
3358 cgroup != PREC_GROUP_POSTFIX_OP &&
3359 cgroup != PREC_GROUP_POSTFIX_IS)
3361 (errmsg("operator precedence change: %s is now lower precedence than %s",
3363 parser_errposition(pstate, location)));
3367 * Complain if right child, which should be higher precedence according to
3368 * current rules, used to be same or lower precedence.
3370 * Exception to precedence rules: if right child is a prefix operator, the
3371 * grouping is syntactically forced regardless of precedence.
3373 cgroup = operator_precedence_group(rchild, &copname);
3376 if (oldprecedence_r[cgroup] <= oldprecedence_l[opgroup] &&
3377 cgroup != PREC_GROUP_PREFIX_OP)
3379 (errmsg("operator precedence change: %s is now lower precedence than %s",
3381 parser_errposition(pstate, location)));
3386 * Produce a string identifying an expression by kind.
3388 * Note: when practical, use a simple SQL keyword for the result. If that
3389 * doesn't work well, check call sites to see whether custom error message
3390 * strings are required.
3393 ParseExprKindName(ParseExprKind exprKind)
3397 case EXPR_KIND_NONE:
3398 return "invalid expression context";
3399 case EXPR_KIND_OTHER:
3400 return "extension expression";
3401 case EXPR_KIND_JOIN_ON:
3403 case EXPR_KIND_JOIN_USING:
3404 return "JOIN/USING";
3405 case EXPR_KIND_FROM_SUBSELECT:
3406 return "sub-SELECT in FROM";
3407 case EXPR_KIND_FROM_FUNCTION:
3408 return "function in FROM";
3409 case EXPR_KIND_WHERE:
3411 case EXPR_KIND_POLICY:
3413 case EXPR_KIND_HAVING:
3415 case EXPR_KIND_FILTER:
3417 case EXPR_KIND_WINDOW_PARTITION:
3418 return "window PARTITION BY";
3419 case EXPR_KIND_WINDOW_ORDER:
3420 return "window ORDER BY";
3421 case EXPR_KIND_WINDOW_FRAME_RANGE:
3422 return "window RANGE";
3423 case EXPR_KIND_WINDOW_FRAME_ROWS:
3424 return "window ROWS";
3425 case EXPR_KIND_SELECT_TARGET:
3427 case EXPR_KIND_INSERT_TARGET:
3429 case EXPR_KIND_UPDATE_SOURCE:
3430 case EXPR_KIND_UPDATE_TARGET:
3432 case EXPR_KIND_GROUP_BY:
3434 case EXPR_KIND_ORDER_BY:
3436 case EXPR_KIND_DISTINCT_ON:
3437 return "DISTINCT ON";
3438 case EXPR_KIND_LIMIT:
3440 case EXPR_KIND_OFFSET:
3442 case EXPR_KIND_RETURNING:
3444 case EXPR_KIND_VALUES:
3445 case EXPR_KIND_VALUES_SINGLE:
3447 case EXPR_KIND_CHECK_CONSTRAINT:
3448 case EXPR_KIND_DOMAIN_CHECK:
3450 case EXPR_KIND_COLUMN_DEFAULT:
3451 case EXPR_KIND_FUNCTION_DEFAULT:
3453 case EXPR_KIND_INDEX_EXPRESSION:
3454 return "index expression";
3455 case EXPR_KIND_INDEX_PREDICATE:
3456 return "index predicate";
3457 case EXPR_KIND_ALTER_COL_TRANSFORM:
3459 case EXPR_KIND_EXECUTE_PARAMETER:
3461 case EXPR_KIND_TRIGGER_WHEN:
3463 case EXPR_KIND_PARTITION_EXPRESSION:
3464 return "PARTITION BY";
3467 * There is intentionally no default: case here, so that the
3468 * compiler will warn if we add a new ParseExprKind without
3469 * extending this switch. If we do see an unrecognized value at
3470 * runtime, we'll fall through to the "unrecognized" return.
3473 return "unrecognized expression kind";