1 /*-------------------------------------------------------------------------
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
11 * $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.252 2010/01/01 23:03:10 tgl Exp $
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/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, RangeTblEntry *rte,
65 static Node *transformIndirection(ParseState *pstate, Node *basenode,
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);
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
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.
101 transformExpr(ParseState *pstate, Node *expr)
108 /* Guard against stack overflow due to overly complex expressions */
111 switch (nodeTag(expr))
114 result = transformColumnRef(pstate, (ColumnRef *) expr);
118 result = transformParamRef(pstate, (ParamRef *) expr);
123 A_Const *con = (A_Const *) expr;
124 Value *val = &con->val;
126 result = (Node *) make_const(pstate, val, con->location);
130 case T_A_Indirection:
132 A_Indirection *ind = (A_Indirection *) expr;
134 result = transformExpr(pstate, ind->arg);
135 result = transformIndirection(pstate, result,
141 result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
142 InvalidOid, InvalidOid, -1);
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))
162 targetType = typenameTypeId(pstate, tc->typeName,
164 elementType = get_element_type(targetType);
165 if (OidIsValid(elementType))
168 * tranformArrayExpr doesn't know how to check domain
169 * constraints, so ask it to return the base type
170 * instead. transformTypeCast below will cast it to
171 * the domain. In the usual case that the target is
172 * not a domain, transformTypeCast is a no-op.
174 targetType = getBaseTypeAndTypmod(targetType,
178 tc->arg = transformArrayExpr(pstate,
179 (A_ArrayExpr *) tc->arg,
186 result = transformTypeCast(pstate, tc);
192 A_Expr *a = (A_Expr *) expr;
197 result = transformAExprOp(pstate, a);
200 result = transformAExprAnd(pstate, a);
203 result = transformAExprOr(pstate, a);
206 result = transformAExprNot(pstate, a);
209 result = transformAExprOpAny(pstate, a);
212 result = transformAExprOpAll(pstate, a);
215 result = transformAExprDistinct(pstate, a);
218 result = transformAExprNullIf(pstate, a);
221 result = transformAExprOf(pstate, a);
224 result = transformAExprIn(pstate, a);
227 elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
233 result = transformFuncCall(pstate, (FuncCall *) expr);
238 NamedArgExpr *na = (NamedArgExpr *) expr;
240 na->arg = (Expr *) transformExpr(pstate, (Node *) na->arg);
246 result = transformSubLink(pstate, (SubLink *) expr);
250 result = transformCaseExpr(pstate, (CaseExpr *) expr);
254 result = transformRowExpr(pstate, (RowExpr *) expr);
258 result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
262 result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
266 result = transformXmlExpr(pstate, (XmlExpr *) expr);
270 result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
275 NullTest *n = (NullTest *) expr;
277 n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
278 /* the argument can be any type, so don't coerce it */
279 n->argisrow = type_is_rowtype(exprType((Node *) n->arg));
285 result = transformBooleanTest(pstate, (BooleanTest *) expr);
288 case T_CurrentOfExpr:
289 result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
292 /*********************************************
293 * Quietly accept node types that may be presented when we are
294 * called on an already-transformed tree.
296 * Do any other node types need to be accepted? For now we are
297 * taking a conservative approach, and only accepting node
298 * types that are demonstrably necessary to accept.
299 *********************************************/
309 case T_ScalarArrayOpExpr:
316 case T_ArrayCoerceExpr:
317 case T_ConvertRowtypeExpr:
320 case T_CoerceToDomain:
321 case T_CoerceToDomainValue:
324 result = (Node *) expr;
329 /* should not reach here */
330 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
338 * helper routine for delivering "column does not exist" error message
340 * (Usually we don't have to work this hard, but the general case of field
341 * selection from an arbitrary node needs it.)
344 unknown_attribute(ParseState *pstate, Node *relref, char *attname,
349 if (IsA(relref, Var) &&
350 ((Var *) relref)->varattno == InvalidAttrNumber)
352 /* Reference the RTE by alias not by actual table name */
353 rte = GetRTEByRangeTablePosn(pstate,
354 ((Var *) relref)->varno,
355 ((Var *) relref)->varlevelsup);
357 (errcode(ERRCODE_UNDEFINED_COLUMN),
358 errmsg("column %s.%s does not exist",
359 rte->eref->aliasname, attname),
360 parser_errposition(pstate, location)));
364 /* Have to do it by reference to the type of the expression */
365 Oid relTypeId = exprType(relref);
367 if (ISCOMPLEX(relTypeId))
369 (errcode(ERRCODE_UNDEFINED_COLUMN),
370 errmsg("column \"%s\" not found in data type %s",
371 attname, format_type_be(relTypeId)),
372 parser_errposition(pstate, location)));
373 else if (relTypeId == RECORDOID)
375 (errcode(ERRCODE_UNDEFINED_COLUMN),
376 errmsg("could not identify column \"%s\" in record data type",
378 parser_errposition(pstate, location)));
381 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
382 errmsg("column notation .%s applied to type %s, "
383 "which is not a composite type",
384 attname, format_type_be(relTypeId)),
385 parser_errposition(pstate, location)));
390 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
392 Node *result = basenode;
393 List *subscripts = NIL;
394 int location = exprLocation(basenode);
398 * We have to split any field-selection operations apart from
399 * subscripting. Adjacent A_Indices nodes have to be treated as a single
400 * multidimensional subscript operation.
402 foreach(i, indirection)
406 if (IsA(n, A_Indices))
407 subscripts = lappend(subscripts, n);
408 else if (IsA(n, A_Star))
411 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
412 errmsg("row expansion via \"*\" is not supported here"),
413 parser_errposition(pstate, location)));
419 Assert(IsA(n, String));
421 /* process subscripts before this field selection */
423 result = (Node *) transformArraySubscripts(pstate,
432 newresult = ParseFuncOrColumn(pstate,
435 NIL, false, false, false,
436 NULL, true, location);
437 if (newresult == NULL)
438 unknown_attribute(pstate, result, strVal(n), location);
442 /* process trailing subscripts, if any */
444 result = (Node *) transformArraySubscripts(pstate,
456 * Transform a ColumnRef.
458 * If you find yourself changing this code, see also ExpandColumnRefStar.
461 transformColumnRef(ParseState *pstate, ColumnRef *cref)
464 char *nspname = NULL;
465 char *relname = NULL;
466 char *colname = NULL;
474 } crerr = CRERR_NO_COLUMN;
477 * Give the PreParseColumnRefHook, if any, first shot. If it returns
478 * non-null then that's all, folks.
480 if (pstate->p_pre_columnref_hook != NULL)
482 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
488 * The allowed syntaxes are:
490 * A First try to resolve as unqualified column name;
491 * if no luck, try to resolve as unqualified table name (A.*).
492 * A.B A is an unqualified table name; B is either a
493 * column or function name (trying column name first).
494 * A.B.C schema A, table B, col or func name C.
495 * A.B.C.D catalog A, schema B, table C, col or func D.
496 * A.* A is an unqualified table name; means whole-row value.
497 * A.B.* whole-row value of table B in schema A.
498 * A.B.C.* whole-row value of table C in schema B in catalog A.
500 * We do not need to cope with bare "*"; that will only be accepted by
501 * the grammar at the top level of a SELECT list, and transformTargetList
502 * will take care of it before it ever gets here. Also, "A.*" etc will
503 * be expanded by transformTargetList if they appear at SELECT top level,
504 * so here we are only going to see them as function or operator inputs.
506 * Currently, if a catalog name is given then it must equal the current
507 * database name; we check it here and then discard it.
510 switch (list_length(cref->fields))
514 Node *field1 = (Node *) linitial(cref->fields);
516 Assert(IsA(field1, String));
517 colname = strVal(field1);
519 /* Try to identify as an unqualified column */
520 node = colNameToVar(pstate, colname, false, cref->location);
525 * Not known as a column of any range-table entry.
527 * Consider the possibility that it's VALUE in a domain
528 * check expression. (We handle VALUE as a name, not a
529 * keyword, to avoid breaking a lot of applications that
530 * have used VALUE as a column name in the past.)
532 if (pstate->p_value_substitute != NULL &&
533 strcmp(colname, "value") == 0)
535 node = (Node *) copyObject(pstate->p_value_substitute);
538 * Try to propagate location knowledge. This should
539 * be extended if p_value_substitute can ever take on
542 if (IsA(node, CoerceToDomainValue))
543 ((CoerceToDomainValue *) node)->location = cref->location;
548 * Try to find the name as a relation. Note that only
549 * relations already entered into the rangetable will be
552 * This is a hack for backwards compatibility with
553 * PostQUEL-inspired syntax. The preferred form now is
556 rte = refnameRangeTblEntry(pstate, NULL, colname,
560 node = transformWholeRowRef(pstate, rte,
567 Node *field1 = (Node *) linitial(cref->fields);
568 Node *field2 = (Node *) lsecond(cref->fields);
570 Assert(IsA(field1, String));
571 relname = strVal(field1);
573 /* Locate the referenced RTE */
574 rte = refnameRangeTblEntry(pstate, nspname, relname,
579 crerr = CRERR_NO_RTE;
583 /* Whole-row reference? */
584 if (IsA(field2, A_Star))
586 node = transformWholeRowRef(pstate, rte, cref->location);
590 Assert(IsA(field2, String));
591 colname = strVal(field2);
593 /* Try to identify as a column of the RTE */
594 node = scanRTEForColumn(pstate, rte, colname, cref->location);
597 /* Try it as a function call on the whole row */
598 node = transformWholeRowRef(pstate, rte, cref->location);
599 node = ParseFuncOrColumn(pstate,
600 list_make1(makeString(colname)),
602 NIL, false, false, false,
603 NULL, true, cref->location);
609 Node *field1 = (Node *) linitial(cref->fields);
610 Node *field2 = (Node *) lsecond(cref->fields);
611 Node *field3 = (Node *) lthird(cref->fields);
613 Assert(IsA(field1, String));
614 nspname = strVal(field1);
615 Assert(IsA(field2, String));
616 relname = strVal(field2);
618 /* Locate the referenced RTE */
619 rte = refnameRangeTblEntry(pstate, nspname, relname,
624 crerr = CRERR_NO_RTE;
628 /* Whole-row reference? */
629 if (IsA(field3, A_Star))
631 node = transformWholeRowRef(pstate, rte, cref->location);
635 Assert(IsA(field3, String));
636 colname = strVal(field3);
638 /* Try to identify as a column of the RTE */
639 node = scanRTEForColumn(pstate, rte, colname, cref->location);
642 /* Try it as a function call on the whole row */
643 node = transformWholeRowRef(pstate, rte, cref->location);
644 node = ParseFuncOrColumn(pstate,
645 list_make1(makeString(colname)),
647 NIL, false, false, false,
648 NULL, true, cref->location);
654 Node *field1 = (Node *) linitial(cref->fields);
655 Node *field2 = (Node *) lsecond(cref->fields);
656 Node *field3 = (Node *) lthird(cref->fields);
657 Node *field4 = (Node *) lfourth(cref->fields);
660 Assert(IsA(field1, String));
661 catname = strVal(field1);
662 Assert(IsA(field2, String));
663 nspname = strVal(field2);
664 Assert(IsA(field3, String));
665 relname = strVal(field3);
668 * We check the catalog name and then ignore it.
670 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
672 crerr = CRERR_WRONG_DB;
676 /* Locate the referenced RTE */
677 rte = refnameRangeTblEntry(pstate, nspname, relname,
682 crerr = CRERR_NO_RTE;
686 /* Whole-row reference? */
687 if (IsA(field4, A_Star))
689 node = transformWholeRowRef(pstate, rte, cref->location);
693 Assert(IsA(field4, String));
694 colname = strVal(field4);
696 /* Try to identify as a column of the RTE */
697 node = scanRTEForColumn(pstate, rte, colname, cref->location);
700 /* Try it as a function call on the whole row */
701 node = transformWholeRowRef(pstate, rte, cref->location);
702 node = ParseFuncOrColumn(pstate,
703 list_make1(makeString(colname)),
705 NIL, false, false, false,
706 NULL, true, cref->location);
711 crerr = CRERR_TOO_MANY; /* too many dotted names */
716 * Now give the PostParseColumnRefHook, if any, a chance. We pass the
717 * translation-so-far so that it can throw an error if it wishes in the
718 * case that it has a conflicting interpretation of the ColumnRef.
719 * (If it just translates anyway, we'll throw an error, because we can't
720 * undo whatever effects the preceding steps may have had on the pstate.)
721 * If it returns NULL, use the standard translation, or throw a suitable
722 * error if there is none.
724 if (pstate->p_post_columnref_hook != NULL)
728 hookresult = (*pstate->p_post_columnref_hook) (pstate, cref, node);
731 else if (hookresult != NULL)
733 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
734 errmsg("column reference \"%s\" is ambiguous",
735 NameListToString(cref->fields)),
736 parser_errposition(pstate, cref->location)));
740 * Throw error if no translation found.
746 case CRERR_NO_COLUMN:
749 (errcode(ERRCODE_UNDEFINED_COLUMN),
750 errmsg("column %s.%s does not exist",
752 parser_errposition(pstate, cref->location)));
756 (errcode(ERRCODE_UNDEFINED_COLUMN),
757 errmsg("column \"%s\" does not exist",
759 parser_errposition(pstate, cref->location)));
762 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
767 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768 errmsg("cross-database references are not implemented: %s",
769 NameListToString(cref->fields)),
770 parser_errposition(pstate, cref->location)));
774 (errcode(ERRCODE_SYNTAX_ERROR),
775 errmsg("improper qualified name (too many dotted names): %s",
776 NameListToString(cref->fields)),
777 parser_errposition(pstate, cref->location)));
786 transformParamRef(ParseState *pstate, ParamRef *pref)
791 * The core parser knows nothing about Params. If a hook is supplied,
792 * call it. If not, or if the hook returns NULL, throw a generic error.
794 if (pstate->p_paramref_hook != NULL)
795 result = (*pstate->p_paramref_hook) (pstate, pref);
801 (errcode(ERRCODE_UNDEFINED_PARAMETER),
802 errmsg("there is no parameter $%d", pref->number),
803 parser_errposition(pstate, pref->location)));
808 /* Test whether an a_expr is a plain NULL constant or not */
810 exprIsNullConstant(Node *arg)
812 if (arg && IsA(arg, A_Const))
814 A_Const *con = (A_Const *) arg;
816 if (con->val.type == T_Null)
823 transformAExprOp(ParseState *pstate, A_Expr *a)
825 Node *lexpr = a->lexpr;
826 Node *rexpr = a->rexpr;
830 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
831 * standards-broken products (like Microsoft's). Turn these into IS NULL
834 if (Transform_null_equals &&
835 list_length(a->name) == 1 &&
836 strcmp(strVal(linitial(a->name)), "=") == 0 &&
837 (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)))
839 NullTest *n = makeNode(NullTest);
841 n->nulltesttype = IS_NULL;
843 if (exprIsNullConstant(lexpr))
844 n->arg = (Expr *) rexpr;
846 n->arg = (Expr *) lexpr;
848 result = transformExpr(pstate, (Node *) n);
850 else if (lexpr && IsA(lexpr, RowExpr) &&
851 rexpr && IsA(rexpr, SubLink) &&
852 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
855 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
856 * grammar did this, but now that a row construct is allowed anywhere
857 * in expressions, it's easier to do it here.
859 SubLink *s = (SubLink *) rexpr;
861 s->subLinkType = ROWCOMPARE_SUBLINK;
863 s->operName = a->name;
864 s->location = a->location;
865 result = transformExpr(pstate, (Node *) s);
867 else if (lexpr && IsA(lexpr, RowExpr) &&
868 rexpr && IsA(rexpr, RowExpr))
871 lexpr = transformExpr(pstate, lexpr);
872 rexpr = transformExpr(pstate, rexpr);
873 Assert(IsA(lexpr, RowExpr));
874 Assert(IsA(rexpr, RowExpr));
876 result = make_row_comparison_op(pstate,
878 ((RowExpr *) lexpr)->args,
879 ((RowExpr *) rexpr)->args,
884 /* Ordinary scalar operator */
885 lexpr = transformExpr(pstate, lexpr);
886 rexpr = transformExpr(pstate, rexpr);
888 result = (Node *) make_op(pstate,
899 transformAExprAnd(ParseState *pstate, A_Expr *a)
901 Node *lexpr = transformExpr(pstate, a->lexpr);
902 Node *rexpr = transformExpr(pstate, a->rexpr);
904 lexpr = coerce_to_boolean(pstate, lexpr, "AND");
905 rexpr = coerce_to_boolean(pstate, rexpr, "AND");
907 return (Node *) makeBoolExpr(AND_EXPR,
908 list_make2(lexpr, rexpr),
913 transformAExprOr(ParseState *pstate, A_Expr *a)
915 Node *lexpr = transformExpr(pstate, a->lexpr);
916 Node *rexpr = transformExpr(pstate, a->rexpr);
918 lexpr = coerce_to_boolean(pstate, lexpr, "OR");
919 rexpr = coerce_to_boolean(pstate, rexpr, "OR");
921 return (Node *) makeBoolExpr(OR_EXPR,
922 list_make2(lexpr, rexpr),
927 transformAExprNot(ParseState *pstate, A_Expr *a)
929 Node *rexpr = transformExpr(pstate, a->rexpr);
931 rexpr = coerce_to_boolean(pstate, rexpr, "NOT");
933 return (Node *) makeBoolExpr(NOT_EXPR,
939 transformAExprOpAny(ParseState *pstate, A_Expr *a)
941 Node *lexpr = transformExpr(pstate, a->lexpr);
942 Node *rexpr = transformExpr(pstate, a->rexpr);
944 return (Node *) make_scalar_array_op(pstate,
953 transformAExprOpAll(ParseState *pstate, A_Expr *a)
955 Node *lexpr = transformExpr(pstate, a->lexpr);
956 Node *rexpr = transformExpr(pstate, a->rexpr);
958 return (Node *) make_scalar_array_op(pstate,
967 transformAExprDistinct(ParseState *pstate, A_Expr *a)
969 Node *lexpr = transformExpr(pstate, a->lexpr);
970 Node *rexpr = transformExpr(pstate, a->rexpr);
972 if (lexpr && IsA(lexpr, RowExpr) &&
973 rexpr && IsA(rexpr, RowExpr))
976 return make_row_distinct_op(pstate, a->name,
983 /* Ordinary scalar operator */
984 return (Node *) make_distinct_op(pstate,
993 transformAExprNullIf(ParseState *pstate, A_Expr *a)
995 Node *lexpr = transformExpr(pstate, a->lexpr);
996 Node *rexpr = transformExpr(pstate, a->rexpr);
999 result = (Node *) make_op(pstate,
1004 if (((OpExpr *) result)->opresulttype != BOOLOID)
1006 (errcode(ERRCODE_DATATYPE_MISMATCH),
1007 errmsg("NULLIF requires = operator to yield boolean"),
1008 parser_errposition(pstate, a->location)));
1011 * We rely on NullIfExpr and OpExpr being the same struct
1013 NodeSetTag(result, T_NullIfExpr);
1019 transformAExprOf(ParseState *pstate, A_Expr *a)
1022 * Checking an expression for match to a list of type names. Will result
1023 * in a boolean constant node.
1025 Node *lexpr = transformExpr(pstate, a->lexpr);
1030 bool matched = false;
1032 ltype = exprType(lexpr);
1033 foreach(telem, (List *) a->rexpr)
1035 rtype = typenameTypeId(pstate, lfirst(telem), NULL);
1036 matched = (rtype == ltype);
1042 * We have two forms: equals or not equals. Flip the sense of the result
1045 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1046 matched = (!matched);
1048 result = (Const *) makeBoolConst(matched, false);
1050 /* Make the result have the original input's parse location */
1051 result->location = exprLocation((Node *) a);
1053 return (Node *) result;
1057 transformAExprIn(ParseState *pstate, A_Expr *a)
1059 Node *result = NULL;
1069 * If the operator is <>, combine with AND not OR.
1071 if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1077 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
1078 * possible if the inputs are all scalars (no RowExprs) and there is a
1079 * suitable array type available. If not, we fall back to a boolean
1080 * condition tree with multiple copies of the lefthand expression. Also,
1081 * any IN-list items that contain Vars are handled as separate boolean
1082 * conditions, because that gives the planner more scope for optimization
1085 * First step: transform all the inputs, and detect whether any are
1086 * RowExprs or contain Vars.
1088 lexpr = transformExpr(pstate, a->lexpr);
1089 haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
1090 rexprs = rvars = rnonvars = NIL;
1091 foreach(l, (List *) a->rexpr)
1093 Node *rexpr = transformExpr(pstate, lfirst(l));
1095 haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
1096 rexprs = lappend(rexprs, rexpr);
1097 if (contain_vars_of_level(rexpr, 0))
1098 rvars = lappend(rvars, rexpr);
1100 rnonvars = lappend(rnonvars, rexpr);
1104 * ScalarArrayOpExpr is only going to be useful if there's more than one
1105 * non-Var righthand item. Also, it won't work for RowExprs.
1107 if (!haveRowExpr && list_length(rnonvars) > 1)
1114 * Try to select a common type for the array elements. Note that
1115 * since the LHS' type is first in the list, it will be preferred when
1116 * there is doubt (eg, when all the RHS items are unknown literals).
1118 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1120 allexprs = list_concat(list_make1(lexpr), rnonvars);
1121 scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1123 /* Do we have an array type to use? */
1124 if (OidIsValid(scalar_type))
1125 array_type = get_array_type(scalar_type);
1127 array_type = InvalidOid;
1128 if (array_type != InvalidOid)
1131 * OK: coerce all the right-hand non-Var inputs to the common type
1132 * and build an ArrayExpr for them.
1138 foreach(l, rnonvars)
1140 Node *rexpr = (Node *) lfirst(l);
1142 rexpr = coerce_to_common_type(pstate, rexpr,
1145 aexprs = lappend(aexprs, rexpr);
1147 newa = makeNode(ArrayExpr);
1148 newa->array_typeid = array_type;
1149 newa->element_typeid = scalar_type;
1150 newa->elements = aexprs;
1151 newa->multidims = false;
1152 newa->location = -1;
1154 result = (Node *) make_scalar_array_op(pstate,
1161 /* Consider only the Vars (if any) in the loop below */
1167 * Must do it the hard way, ie, with a boolean expression tree.
1171 Node *rexpr = (Node *) lfirst(l);
1176 if (!IsA(lexpr, RowExpr) ||
1177 !IsA(rexpr, RowExpr))
1179 (errcode(ERRCODE_SYNTAX_ERROR),
1180 errmsg("arguments of row IN must all be row expressions"),
1181 parser_errposition(pstate, a->location)));
1182 cmp = make_row_comparison_op(pstate,
1184 (List *) copyObject(((RowExpr *) lexpr)->args),
1185 ((RowExpr *) rexpr)->args,
1189 cmp = (Node *) make_op(pstate,
1195 cmp = coerce_to_boolean(pstate, cmp, "IN");
1199 result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1200 list_make2(result, cmp),
1208 transformFuncCall(ParseState *pstate, FuncCall *fn)
1213 /* Transform the list of arguments ... */
1215 foreach(args, fn->args)
1217 targs = lappend(targs, transformExpr(pstate,
1218 (Node *) lfirst(args)));
1221 /* ... and hand off to ParseFuncOrColumn */
1222 return ParseFuncOrColumn(pstate,
1235 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1239 CaseTestExpr *placeholder;
1246 /* If we already transformed this node, do nothing */
1247 if (OidIsValid(c->casetype))
1250 newc = makeNode(CaseExpr);
1252 /* transform the test expression, if any */
1253 arg = transformExpr(pstate, (Node *) c->arg);
1255 /* generate placeholder for test expression */
1259 * If test expression is an untyped literal, force it to text. We have
1260 * to do something now because we won't be able to do this coercion on
1261 * the placeholder. This is not as flexible as what was done in 7.4
1262 * and before, but it's good enough to handle the sort of silly coding
1265 if (exprType(arg) == UNKNOWNOID)
1266 arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1268 placeholder = makeNode(CaseTestExpr);
1269 placeholder->typeId = exprType(arg);
1270 placeholder->typeMod = exprTypmod(arg);
1275 newc->arg = (Expr *) arg;
1277 /* transform the list of arguments */
1282 CaseWhen *w = (CaseWhen *) lfirst(l);
1283 CaseWhen *neww = makeNode(CaseWhen);
1286 Assert(IsA(w, CaseWhen));
1288 warg = (Node *) w->expr;
1291 /* shorthand form was specified, so expand... */
1292 warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1293 (Node *) placeholder,
1297 neww->expr = (Expr *) transformExpr(pstate, warg);
1299 neww->expr = (Expr *) coerce_to_boolean(pstate,
1300 (Node *) neww->expr,
1303 warg = (Node *) w->result;
1304 neww->result = (Expr *) transformExpr(pstate, warg);
1305 neww->location = w->location;
1307 newargs = lappend(newargs, neww);
1308 resultexprs = lappend(resultexprs, neww->result);
1311 newc->args = newargs;
1313 /* transform the default clause */
1314 defresult = (Node *) c->defresult;
1315 if (defresult == NULL)
1317 A_Const *n = makeNode(A_Const);
1319 n->val.type = T_Null;
1321 defresult = (Node *) n;
1323 newc->defresult = (Expr *) transformExpr(pstate, defresult);
1326 * Note: default result is considered the most significant type in
1327 * determining preferred type. This is how the code worked before, but it
1328 * seems a little bogus to me --- tgl
1330 resultexprs = lcons(newc->defresult, resultexprs);
1332 ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1333 Assert(OidIsValid(ptype));
1334 newc->casetype = ptype;
1336 /* Convert default result clause, if necessary */
1337 newc->defresult = (Expr *)
1338 coerce_to_common_type(pstate,
1339 (Node *) newc->defresult,
1343 /* Convert when-clause results, if necessary */
1344 foreach(l, newc->args)
1346 CaseWhen *w = (CaseWhen *) lfirst(l);
1348 w->result = (Expr *)
1349 coerce_to_common_type(pstate,
1355 newc->location = c->location;
1357 return (Node *) newc;
1361 transformSubLink(ParseState *pstate, SubLink *sublink)
1363 Node *result = (Node *) sublink;
1366 /* If we already transformed this node, do nothing */
1367 if (IsA(sublink->subselect, Query))
1370 pstate->p_hasSubLinks = true;
1371 qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false);
1374 * Check that we got something reasonable. Many of these conditions are
1375 * impossible given restrictions of the grammar, but check 'em anyway.
1377 if (!IsA(qtree, Query) ||
1378 qtree->commandType != CMD_SELECT ||
1379 qtree->utilityStmt != NULL)
1380 elog(ERROR, "unexpected non-SELECT command in SubLink");
1381 if (qtree->intoClause)
1383 (errcode(ERRCODE_SYNTAX_ERROR),
1384 errmsg("subquery cannot have SELECT INTO"),
1385 parser_errposition(pstate,
1386 exprLocation((Node *) qtree->intoClause))));
1388 sublink->subselect = (Node *) qtree;
1390 if (sublink->subLinkType == EXISTS_SUBLINK)
1393 * EXISTS needs no test expression or combining operator. These fields
1394 * should be null already, but make sure.
1396 sublink->testexpr = NULL;
1397 sublink->operName = NIL;
1399 else if (sublink->subLinkType == EXPR_SUBLINK ||
1400 sublink->subLinkType == ARRAY_SUBLINK)
1402 ListCell *tlist_item = list_head(qtree->targetList);
1405 * Make sure the subselect delivers a single column (ignoring resjunk
1408 if (tlist_item == NULL ||
1409 ((TargetEntry *) lfirst(tlist_item))->resjunk)
1411 (errcode(ERRCODE_SYNTAX_ERROR),
1412 errmsg("subquery must return a column"),
1413 parser_errposition(pstate, sublink->location)));
1414 while ((tlist_item = lnext(tlist_item)) != NULL)
1416 if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1418 (errcode(ERRCODE_SYNTAX_ERROR),
1419 errmsg("subquery must return only one column"),
1420 parser_errposition(pstate, sublink->location)));
1424 * EXPR and ARRAY need no test expression or combining operator. These
1425 * fields should be null already, but make sure.
1427 sublink->testexpr = NULL;
1428 sublink->operName = NIL;
1432 /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1439 * Transform lefthand expression, and convert to a list
1441 lefthand = transformExpr(pstate, sublink->testexpr);
1442 if (lefthand && IsA(lefthand, RowExpr))
1443 left_list = ((RowExpr *) lefthand)->args;
1445 left_list = list_make1(lefthand);
1448 * Build a list of PARAM_SUBLINK nodes representing the output columns
1452 foreach(l, qtree->targetList)
1454 TargetEntry *tent = (TargetEntry *) lfirst(l);
1460 param = makeNode(Param);
1461 param->paramkind = PARAM_SUBLINK;
1462 param->paramid = tent->resno;
1463 param->paramtype = exprType((Node *) tent->expr);
1464 param->paramtypmod = exprTypmod((Node *) tent->expr);
1465 param->location = -1;
1467 right_list = lappend(right_list, param);
1471 * We could rely on make_row_comparison_op to complain if the list
1472 * lengths differ, but we prefer to generate a more specific error
1475 if (list_length(left_list) < list_length(right_list))
1477 (errcode(ERRCODE_SYNTAX_ERROR),
1478 errmsg("subquery has too many columns"),
1479 parser_errposition(pstate, sublink->location)));
1480 if (list_length(left_list) > list_length(right_list))
1482 (errcode(ERRCODE_SYNTAX_ERROR),
1483 errmsg("subquery has too few columns"),
1484 parser_errposition(pstate, sublink->location)));
1487 * Identify the combining operator(s) and generate a suitable
1488 * row-comparison expression.
1490 sublink->testexpr = make_row_comparison_op(pstate,
1501 * transformArrayExpr
1503 * If the caller specifies the target type, the resulting array will
1504 * be of exactly that type. Otherwise we try to infer a common type
1505 * for the elements using select_common_type().
1508 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
1509 Oid array_type, Oid element_type, int32 typmod)
1511 ArrayExpr *newa = makeNode(ArrayExpr);
1512 List *newelems = NIL;
1513 List *newcoercedelems = NIL;
1519 * Transform the element expressions
1521 * Assume that the array is one-dimensional unless we find an array-type
1522 * element expression.
1524 newa->multidims = false;
1525 foreach(element, a->elements)
1527 Node *e = (Node *) lfirst(element);
1531 * If an element is itself an A_ArrayExpr, recurse directly so that we
1532 * can pass down any target type we were given.
1534 if (IsA(e, A_ArrayExpr))
1536 newe = transformArrayExpr(pstate,
1541 /* we certainly have an array here */
1542 Assert(array_type == InvalidOid || array_type == exprType(newe));
1543 newa->multidims = true;
1547 newe = transformExpr(pstate, e);
1550 * Check for sub-array expressions, if we haven't already found
1553 if (!newa->multidims && type_is_array(exprType(newe)))
1554 newa->multidims = true;
1557 newelems = lappend(newelems, newe);
1561 * Select a target type for the elements.
1563 * If we haven't been given a target array type, we must try to deduce a
1564 * common type based on the types of the individual elements present.
1566 if (OidIsValid(array_type))
1568 /* Caller must ensure array_type matches element_type */
1569 Assert(OidIsValid(element_type));
1570 coerce_type = (newa->multidims ? array_type : element_type);
1575 /* Can't handle an empty array without a target type */
1576 if (newelems == NIL)
1578 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1579 errmsg("cannot determine type of empty array"),
1580 errhint("Explicitly cast to the desired type, "
1581 "for example ARRAY[]::integer[]."),
1582 parser_errposition(pstate, a->location)));
1584 /* Select a common type for the elements */
1585 coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1587 if (newa->multidims)
1589 array_type = coerce_type;
1590 element_type = get_element_type(array_type);
1591 if (!OidIsValid(element_type))
1593 (errcode(ERRCODE_UNDEFINED_OBJECT),
1594 errmsg("could not find element type for data type %s",
1595 format_type_be(array_type)),
1596 parser_errposition(pstate, a->location)));
1600 element_type = coerce_type;
1601 array_type = get_array_type(element_type);
1602 if (!OidIsValid(array_type))
1604 (errcode(ERRCODE_UNDEFINED_OBJECT),
1605 errmsg("could not find array type for data type %s",
1606 format_type_be(element_type)),
1607 parser_errposition(pstate, a->location)));
1609 coerce_hard = false;
1613 * Coerce elements to target type
1615 * If the array has been explicitly cast, then the elements are in turn
1616 * explicitly coerced.
1618 * If the array's type was merely derived from the common type of its
1619 * elements, then the elements are implicitly coerced to the common type.
1620 * This is consistent with other uses of select_common_type().
1622 foreach(element, newelems)
1624 Node *e = (Node *) lfirst(element);
1629 newe = coerce_to_target_type(pstate, e,
1634 COERCE_EXPLICIT_CAST,
1638 (errcode(ERRCODE_CANNOT_COERCE),
1639 errmsg("cannot cast type %s to %s",
1640 format_type_be(exprType(e)),
1641 format_type_be(coerce_type)),
1642 parser_errposition(pstate, exprLocation(e))));
1645 newe = coerce_to_common_type(pstate, e,
1648 newcoercedelems = lappend(newcoercedelems, newe);
1651 newa->array_typeid = array_type;
1652 newa->element_typeid = element_type;
1653 newa->elements = newcoercedelems;
1654 newa->location = a->location;
1656 return (Node *) newa;
1660 transformRowExpr(ParseState *pstate, RowExpr *r)
1662 RowExpr *newr = makeNode(RowExpr);
1664 /* Transform the field expressions */
1665 newr->args = transformExpressionList(pstate, r->args);
1667 /* Barring later casting, we consider the type RECORD */
1668 newr->row_typeid = RECORDOID;
1669 newr->row_format = COERCE_IMPLICIT_CAST;
1670 newr->colnames = NIL; /* ROW() has anonymous columns */
1671 newr->location = r->location;
1673 return (Node *) newr;
1677 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
1679 CoalesceExpr *newc = makeNode(CoalesceExpr);
1680 List *newargs = NIL;
1681 List *newcoercedargs = NIL;
1684 foreach(args, c->args)
1686 Node *e = (Node *) lfirst(args);
1689 newe = transformExpr(pstate, e);
1690 newargs = lappend(newargs, newe);
1693 newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1695 /* Convert arguments if necessary */
1696 foreach(args, newargs)
1698 Node *e = (Node *) lfirst(args);
1701 newe = coerce_to_common_type(pstate, e,
1704 newcoercedargs = lappend(newcoercedargs, newe);
1707 newc->args = newcoercedargs;
1708 newc->location = c->location;
1709 return (Node *) newc;
1713 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
1715 MinMaxExpr *newm = makeNode(MinMaxExpr);
1716 List *newargs = NIL;
1717 List *newcoercedargs = NIL;
1718 const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1722 foreach(args, m->args)
1724 Node *e = (Node *) lfirst(args);
1727 newe = transformExpr(pstate, e);
1728 newargs = lappend(newargs, newe);
1731 newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1733 /* Convert arguments if necessary */
1734 foreach(args, newargs)
1736 Node *e = (Node *) lfirst(args);
1739 newe = coerce_to_common_type(pstate, e,
1742 newcoercedargs = lappend(newcoercedargs, newe);
1745 newm->args = newcoercedargs;
1746 newm->location = m->location;
1747 return (Node *) newm;
1751 transformXmlExpr(ParseState *pstate, XmlExpr *x)
1753 XmlExpr *newx = makeNode(XmlExpr);
1759 newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1762 newx->xmloption = x->xmloption;
1763 newx->location = x->location;
1766 * gram.y built the named args as a list of ResTarget. Transform each,
1767 * and break the names out as a separate list.
1769 newx->named_args = NIL;
1770 newx->arg_names = NIL;
1772 foreach(lc, x->named_args)
1774 ResTarget *r = (ResTarget *) lfirst(lc);
1778 Assert(IsA(r, ResTarget));
1780 expr = transformExpr(pstate, r->val);
1783 argname = map_sql_identifier_to_xml_name(r->name, false, false);
1784 else if (IsA(r->val, ColumnRef))
1785 argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1790 (errcode(ERRCODE_SYNTAX_ERROR),
1791 x->op == IS_XMLELEMENT
1792 ? errmsg("unnamed XML attribute value must be a column reference")
1793 : errmsg("unnamed XML element value must be a column reference"),
1794 parser_errposition(pstate, r->location)));
1795 argname = NULL; /* keep compiler quiet */
1798 /* reject duplicate argnames in XMLELEMENT only */
1799 if (x->op == IS_XMLELEMENT)
1803 foreach(lc2, newx->arg_names)
1805 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1807 (errcode(ERRCODE_SYNTAX_ERROR),
1808 errmsg("XML attribute name \"%s\" appears more than once",
1810 parser_errposition(pstate, r->location)));
1814 newx->named_args = lappend(newx->named_args, expr);
1815 newx->arg_names = lappend(newx->arg_names, makeString(argname));
1818 /* The other arguments are of varying types depending on the function */
1821 foreach(lc, x->args)
1823 Node *e = (Node *) lfirst(lc);
1826 newe = transformExpr(pstate, e);
1830 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1834 /* no coercion necessary */
1837 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1842 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1845 newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
1848 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1853 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1856 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
1859 newe = coerce_to_specific_type(pstate, newe, INT4OID,
1862 case IS_XMLSERIALIZE:
1863 /* not handled here */
1867 newe = coerce_to_specific_type(pstate, newe, XMLOID,
1871 newx->args = lappend(newx->args, newe);
1875 return (Node *) newx;
1879 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1886 xexpr = makeNode(XmlExpr);
1887 xexpr->op = IS_XMLSERIALIZE;
1888 xexpr->args = list_make1(coerce_to_specific_type(pstate,
1889 transformExpr(pstate, xs->expr),
1893 targetType = typenameTypeId(pstate, xs->typeName, &targetTypmod);
1895 xexpr->xmloption = xs->xmloption;
1896 xexpr->location = xs->location;
1897 /* We actually only need these to be able to parse back the expression. */
1898 xexpr->type = targetType;
1899 xexpr->typmod = targetTypmod;
1902 * The actual target type is determined this way. SQL allows char and
1903 * varchar as target types. We allow anything that can be cast implicitly
1904 * from text. This way, user-defined text-like data types automatically
1907 result = coerce_to_target_type(pstate, (Node *) xexpr,
1908 TEXTOID, targetType, targetTypmod,
1910 COERCE_IMPLICIT_CAST,
1914 (errcode(ERRCODE_CANNOT_COERCE),
1915 errmsg("cannot cast XMLSERIALIZE result to %s",
1916 format_type_be(targetType)),
1917 parser_errposition(pstate, xexpr->location)));
1922 transformBooleanTest(ParseState *pstate, BooleanTest *b)
1924 const char *clausename;
1926 switch (b->booltesttype)
1929 clausename = "IS TRUE";
1932 clausename = "IS NOT TRUE";
1935 clausename = "IS FALSE";
1938 clausename = "IS NOT FALSE";
1941 clausename = "IS UNKNOWN";
1943 case IS_NOT_UNKNOWN:
1944 clausename = "IS NOT UNKNOWN";
1947 elog(ERROR, "unrecognized booltesttype: %d",
1948 (int) b->booltesttype);
1949 clausename = NULL; /* keep compiler quiet */
1952 b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);
1954 b->arg = (Expr *) coerce_to_boolean(pstate,
1962 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1966 /* CURRENT OF can only appear at top level of UPDATE/DELETE */
1967 Assert(pstate->p_target_rangetblentry != NULL);
1968 cexpr->cvarno = RTERangeTablePosn(pstate,
1969 pstate->p_target_rangetblentry,
1971 Assert(sublevels_up == 0);
1974 * Check to see if the cursor name matches a parameter of type REFCURSOR.
1975 * If so, replace the raw name reference with a parameter reference.
1976 * (This is a hack for the convenience of plpgsql.)
1978 if (cexpr->cursor_name != NULL) /* in case already transformed */
1980 ColumnRef *cref = makeNode(ColumnRef);
1983 /* Build an unqualified ColumnRef with the given name */
1984 cref->fields = list_make1(makeString(cexpr->cursor_name));
1985 cref->location = -1;
1987 /* See if there is a translation available from a parser hook */
1988 if (pstate->p_pre_columnref_hook != NULL)
1989 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
1990 if (node == NULL && pstate->p_post_columnref_hook != NULL)
1991 node = (*pstate->p_post_columnref_hook) (pstate, cref, NULL);
1994 * XXX Should we throw an error if we get a translation that isn't
1995 * a refcursor Param? For now it seems best to silently ignore
1998 if (node != NULL && IsA(node, Param))
2000 Param *p = (Param *) node;
2002 if (p->paramkind == PARAM_EXTERN &&
2003 p->paramtype == REFCURSOROID)
2005 /* Matches, so convert CURRENT OF to a param reference */
2006 cexpr->cursor_name = NULL;
2007 cexpr->cursor_param = p->paramid;
2012 return (Node *) cexpr;
2016 * Construct a whole-row reference to represent the notation "relation.*".
2018 * A whole-row reference is a Var with varno set to the correct range
2019 * table entry, and varattno == 0 to signal that it references the whole
2020 * tuple. (Use of zero here is unclean, since it could easily be confused
2021 * with error cases, but it's not worth changing now.) The vartype indicates
2022 * a rowtype; either a named composite type, or RECORD.
2025 transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte, int location)
2032 /* Find the RTE's rangetable location */
2034 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
2036 /* Build the appropriate referencing node */
2038 switch (rte->rtekind)
2041 /* relation: the rowtype is a named composite type */
2042 toid = get_rel_type_id(rte->relid);
2043 if (!OidIsValid(toid))
2044 elog(ERROR, "could not find type OID for relation %u",
2046 result = makeVar(vnum,
2053 toid = exprType(rte->funcexpr);
2054 if (type_is_rowtype(toid))
2056 /* func returns composite; same as relation case */
2057 result = makeVar(vnum,
2066 * func returns scalar; instead of making a whole-row Var,
2067 * just reference the function's scalar output. (XXX this
2068 * seems a tad inconsistent, especially if "f.*" was
2069 * explicitly written ...)
2071 result = makeVar(vnum,
2080 /* returns composite; same as relation case */
2081 result = makeVar(vnum,
2090 * RTE is a join or subselect. We represent this as a whole-row
2091 * Var of RECORD type. (Note that in most cases the Var will be
2092 * expanded to a RowExpr during planning, but that is not our
2095 result = makeVar(vnum,
2103 /* location is not filled in by makeVar */
2104 result->location = location;
2106 /* mark relation as requiring whole-row SELECT access */
2107 markVarForSelectPriv(pstate, result, rte);
2109 return (Node *) result;
2113 * Handle an explicit CAST construct.
2115 * Transform the argument, then look up the type name and apply any necessary
2116 * coercion function(s).
2119 transformTypeCast(ParseState *pstate, TypeCast *tc)
2122 Node *expr = transformExpr(pstate, tc->arg);
2123 Oid inputType = exprType(expr);
2128 targetType = typenameTypeId(pstate, tc->typeName, &targetTypmod);
2130 if (inputType == InvalidOid)
2131 return expr; /* do nothing if NULL input */
2134 * Location of the coercion is preferentially the location of the :: or
2135 * CAST symbol, but if there is none then use the location of the type
2136 * name (this can happen in TypeName 'string' syntax, for instance).
2138 location = tc->location;
2140 location = tc->typeName->location;
2142 result = coerce_to_target_type(pstate, expr, inputType,
2143 targetType, targetTypmod,
2145 COERCE_EXPLICIT_CAST,
2149 (errcode(ERRCODE_CANNOT_COERCE),
2150 errmsg("cannot cast type %s to %s",
2151 format_type_be(inputType),
2152 format_type_be(targetType)),
2153 parser_coercion_errposition(pstate, location, expr)));
2159 * Transform a "row compare-op row" construct
2161 * The inputs are lists of already-transformed expressions.
2162 * As with coerce_type, pstate may be NULL if no special unknown-Param
2163 * processing is wanted.
2165 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2166 * or a RowCompareExpr. In all cases it is guaranteed to return boolean.
2167 * The AND, OR, and RowCompareExpr cases further imply things about the
2168 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2171 make_row_comparison_op(ParseState *pstate, List *opname,
2172 List *largs, List *rargs, int location)
2174 RowCompareExpr *rcexpr;
2175 RowCompareType rctype;
2181 List **opfamily_lists;
2182 List **opstrat_lists;
2187 nopers = list_length(largs);
2188 if (nopers != list_length(rargs))
2190 (errcode(ERRCODE_SYNTAX_ERROR),
2191 errmsg("unequal number of entries in row expressions"),
2192 parser_errposition(pstate, location)));
2195 * We can't compare zero-length rows because there is no principled basis
2196 * for figuring out what the operator is.
2200 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2201 errmsg("cannot compare rows of zero length"),
2202 parser_errposition(pstate, location)));
2205 * Identify all the pairwise operators, using make_op so that behavior is
2206 * the same as in the simple scalar case.
2209 forboth(l, largs, r, rargs)
2211 Node *larg = (Node *) lfirst(l);
2212 Node *rarg = (Node *) lfirst(r);
2215 cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2216 Assert(IsA(cmp, OpExpr));
2219 * We don't use coerce_to_boolean here because we insist on the
2220 * operator yielding boolean directly, not via coercion. If it
2221 * doesn't yield bool it won't be in any index opfamilies...
2223 if (cmp->opresulttype != BOOLOID)
2225 (errcode(ERRCODE_DATATYPE_MISMATCH),
2226 errmsg("row comparison operator must yield type boolean, "
2228 format_type_be(cmp->opresulttype)),
2229 parser_errposition(pstate, location)));
2230 if (expression_returns_set((Node *) cmp))
2232 (errcode(ERRCODE_DATATYPE_MISMATCH),
2233 errmsg("row comparison operator must not return a set"),
2234 parser_errposition(pstate, location)));
2235 opexprs = lappend(opexprs, cmp);
2239 * If rows are length 1, just return the single operator. In this case we
2240 * don't insist on identifying btree semantics for the operator (but we
2241 * still require it to return boolean).
2244 return (Node *) linitial(opexprs);
2247 * Now we must determine which row comparison semantics (= <> < <= > >=)
2248 * apply to this set of operators. We look for btree opfamilies
2249 * containing the operators, and see which interpretations (strategy
2250 * numbers) exist for each operator.
2252 opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2253 opstrat_lists = (List **) palloc(nopers * sizeof(List *));
2258 Oid opno = ((OpExpr *) lfirst(l))->opno;
2259 Bitmapset *this_strats;
2262 get_op_btree_interpretation(opno,
2263 &opfamily_lists[i], &opstrat_lists[i]);
2266 * convert strategy number list to a Bitmapset to make the
2267 * intersection calculation easy.
2270 foreach(j, opstrat_lists[i])
2272 this_strats = bms_add_member(this_strats, lfirst_int(j));
2275 strats = this_strats;
2277 strats = bms_int_members(strats, this_strats);
2282 * If there are multiple common interpretations, we may use any one of
2283 * them ... this coding arbitrarily picks the lowest btree strategy
2286 i = bms_first_member(strats);
2289 /* No common interpretation, so fail */
2291 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2292 errmsg("could not determine interpretation of row comparison operator %s",
2293 strVal(llast(opname))),
2294 errhint("Row comparison operators must be associated with btree operator families."),
2295 parser_errposition(pstate, location)));
2297 rctype = (RowCompareType) i;
2300 * For = and <> cases, we just combine the pairwise operators with AND or
2303 * Note: this is presently the only place where the parser generates
2304 * BoolExpr with more than two arguments. Should be OK since the rest of
2305 * the system thinks BoolExpr is N-argument anyway.
2307 if (rctype == ROWCOMPARE_EQ)
2308 return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2309 if (rctype == ROWCOMPARE_NE)
2310 return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2313 * Otherwise we need to choose exactly which opfamily to associate with
2317 for (i = 0; i < nopers; i++)
2319 Oid opfamily = InvalidOid;
2321 forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2323 int opstrat = lfirst_int(r);
2325 if (opstrat == rctype)
2327 opfamily = lfirst_oid(l);
2331 if (OidIsValid(opfamily))
2332 opfamilies = lappend_oid(opfamilies, opfamily);
2333 else /* should not happen */
2335 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2336 errmsg("could not determine interpretation of row comparison operator %s",
2337 strVal(llast(opname))),
2338 errdetail("There are multiple equally-plausible candidates."),
2339 parser_errposition(pstate, location)));
2343 * Now deconstruct the OpExprs and create a RowCompareExpr.
2345 * Note: can't just reuse the passed largs/rargs lists, because of
2346 * possibility that make_op inserted coercion operations.
2353 OpExpr *cmp = (OpExpr *) lfirst(l);
2355 opnos = lappend_oid(opnos, cmp->opno);
2356 largs = lappend(largs, linitial(cmp->args));
2357 rargs = lappend(rargs, lsecond(cmp->args));
2360 rcexpr = makeNode(RowCompareExpr);
2361 rcexpr->rctype = rctype;
2362 rcexpr->opnos = opnos;
2363 rcexpr->opfamilies = opfamilies;
2364 rcexpr->largs = largs;
2365 rcexpr->rargs = rargs;
2367 return (Node *) rcexpr;
2371 * Transform a "row IS DISTINCT FROM row" construct
2373 * The input RowExprs are already transformed
2376 make_row_distinct_op(ParseState *pstate, List *opname,
2377 RowExpr *lrow, RowExpr *rrow,
2380 Node *result = NULL;
2381 List *largs = lrow->args;
2382 List *rargs = rrow->args;
2386 if (list_length(largs) != list_length(rargs))
2388 (errcode(ERRCODE_SYNTAX_ERROR),
2389 errmsg("unequal number of entries in row expressions"),
2390 parser_errposition(pstate, location)));
2392 forboth(l, largs, r, rargs)
2394 Node *larg = (Node *) lfirst(l);
2395 Node *rarg = (Node *) lfirst(r);
2398 cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2402 result = (Node *) makeBoolExpr(OR_EXPR,
2403 list_make2(result, cmp),
2409 /* zero-length rows? Generate constant FALSE */
2410 result = makeBoolConst(false, false);
2417 * make the node for an IS DISTINCT FROM operator
2420 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
2425 result = make_op(pstate, opname, ltree, rtree, location);
2426 if (((OpExpr *) result)->opresulttype != BOOLOID)
2428 (errcode(ERRCODE_DATATYPE_MISMATCH),
2429 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2430 parser_errposition(pstate, location)));
2433 * We rely on DistinctExpr and OpExpr being same struct
2435 NodeSetTag(result, T_DistinctExpr);