1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_target.c
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_type.h"
18 #include "commands/dbcommands.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "parser/parsetree.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_expr.h"
26 #include "parser/parse_func.h"
27 #include "parser/parse_relation.h"
28 #include "parser/parse_target.h"
29 #include "parser/parse_type.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/typcache.h"
35 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
36 Var *var, int levelsup);
37 static Node *transformAssignmentIndirection(ParseState *pstate,
39 const char *targetName,
43 ListCell *indirection,
46 static Node *transformAssignmentSubscripts(ParseState *pstate,
48 const char *targetName,
53 ListCell *next_indirection,
56 static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
58 static List *ExpandAllTables(ParseState *pstate, int location);
59 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
61 static List *ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
62 int location, bool targetlist);
63 static List *ExpandRowReference(ParseState *pstate, Node *expr,
65 static int FigureColnameInternal(Node *node, char **name);
69 * transformTargetEntry()
70 * Transform any ordinary "expression-type" node into a targetlist entry.
71 * This is exported so that parse_clause.c can generate targetlist entries
72 * for ORDER/GROUP BY items that are not already in the targetlist.
74 * node the (untransformed) parse tree for the value expression.
75 * expr the transformed expression, or NULL if caller didn't do it yet.
76 * colname the column name to be assigned, or NULL if none yet set.
77 * resjunk true if the target should be marked resjunk, ie, it is not
78 * wanted in the final projected tuple.
81 transformTargetEntry(ParseState *pstate,
87 /* Transform the node if caller didn't do it already */
89 expr = transformExpr(pstate, node);
91 if (colname == NULL && !resjunk)
94 * Generate a suitable column name for a column without any explicit
95 * 'AS ColumnName' clause.
97 colname = FigureColname(node);
100 return makeTargetEntry((Expr *) expr,
101 (AttrNumber) pstate->p_next_resno++,
108 * transformTargetList()
109 * Turns a list of ResTarget's into a list of TargetEntry's.
111 * At this point, we don't care whether we are doing SELECT, INSERT,
112 * or UPDATE; we just transform the given expressions (the "val" fields).
115 transformTargetList(ParseState *pstate, List *targetlist)
117 List *p_target = NIL;
120 foreach(o_target, targetlist)
122 ResTarget *res = (ResTarget *) lfirst(o_target);
125 * Check for "something.*". Depending on the complexity of the
126 * "something", the star could appear as the last field in ColumnRef,
127 * or as the last indirection item in A_Indirection.
129 if (IsA(res->val, ColumnRef))
131 ColumnRef *cref = (ColumnRef *) res->val;
133 if (IsA(llast(cref->fields), A_Star))
135 /* It is something.*, expand into multiple items */
136 p_target = list_concat(p_target,
137 ExpandColumnRefStar(pstate, cref,
142 else if (IsA(res->val, A_Indirection))
144 A_Indirection *ind = (A_Indirection *) res->val;
146 if (IsA(llast(ind->indirection), A_Star))
148 /* It is something.*, expand into multiple items */
149 p_target = list_concat(p_target,
150 ExpandIndirectionStar(pstate, ind,
157 * Not "something.*", so transform as a single expression
159 p_target = lappend(p_target,
160 transformTargetEntry(pstate,
172 * transformExpressionList()
174 * This is the identical transformation to transformTargetList, except that
175 * the input list elements are bare expressions without ResTarget decoration,
176 * and the output elements are likewise just expressions without TargetEntry
177 * decoration. We use this for ROW() and VALUES() constructs.
180 transformExpressionList(ParseState *pstate, List *exprlist)
185 foreach(lc, exprlist)
187 Node *e = (Node *) lfirst(lc);
190 * Check for "something.*". Depending on the complexity of the
191 * "something", the star could appear as the last field in ColumnRef,
192 * or as the last indirection item in A_Indirection.
194 if (IsA(e, ColumnRef))
196 ColumnRef *cref = (ColumnRef *) e;
198 if (IsA(llast(cref->fields), A_Star))
200 /* It is something.*, expand into multiple items */
201 result = list_concat(result,
202 ExpandColumnRefStar(pstate, cref,
207 else if (IsA(e, A_Indirection))
209 A_Indirection *ind = (A_Indirection *) e;
211 if (IsA(llast(ind->indirection), A_Star))
213 /* It is something.*, expand into multiple items */
214 result = list_concat(result,
215 ExpandIndirectionStar(pstate, ind,
222 * Not "something.*", so transform as a single expression
224 result = lappend(result,
225 transformExpr(pstate, e));
233 * markTargetListOrigins()
234 * Mark targetlist columns that are simple Vars with the source
235 * table's OID and column number.
237 * Currently, this is done only for SELECT targetlists, since we only
238 * need the info if we are going to send it to the frontend.
241 markTargetListOrigins(ParseState *pstate, List *targetlist)
245 foreach(l, targetlist)
247 TargetEntry *tle = (TargetEntry *) lfirst(l);
249 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
254 * markTargetListOrigin()
255 * If 'var' is a Var of a plain relation, mark 'tle' with its origin
257 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
259 * This is split out so it can recurse for join references. Note that we
260 * do not drill down into views, but report the view as the column owner.
263 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
264 Var *var, int levelsup)
270 if (var == NULL || !IsA(var, Var))
272 netlevelsup = var->varlevelsup + levelsup;
273 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
274 attnum = var->varattno;
276 switch (rte->rtekind)
279 /* It's a table or view, report it */
280 tle->resorigtbl = rte->relid;
281 tle->resorigcol = attnum;
284 /* Subselect-in-FROM: copy up from the subselect */
285 if (attnum != InvalidAttrNumber)
287 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
290 if (ste == NULL || ste->resjunk)
291 elog(ERROR, "subquery %s does not have attribute %d",
292 rte->eref->aliasname, attnum);
293 tle->resorigtbl = ste->resorigtbl;
294 tle->resorigcol = ste->resorigcol;
298 /* Join RTE --- recursively inspect the alias variable */
299 if (attnum != InvalidAttrNumber)
303 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
304 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
305 markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
310 /* not a simple relation, leave it unmarked */
315 * CTE reference: copy up from the subquery, if possible. If the
316 * RTE is a recursive self-reference then we can't do anything
317 * because we haven't finished analyzing it yet. However, it's no
318 * big loss because we must be down inside the recursive term of a
319 * recursive CTE, and so any markings on the current targetlist
320 * are not going to affect the results anyway.
322 if (attnum != InvalidAttrNumber && !rte->self_reference)
324 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
327 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
328 if (ste == NULL || ste->resjunk)
329 elog(ERROR, "subquery %s does not have attribute %d",
330 rte->eref->aliasname, attnum);
331 tle->resorigtbl = ste->resorigtbl;
332 tle->resorigcol = ste->resorigcol;
340 * transformAssignedExpr()
341 * This is used in INSERT and UPDATE statements only. It prepares an
342 * expression for assignment to a column of the target table.
343 * This includes coercing the given value to the target column's type
344 * (if necessary), and dealing with any subfield names or subscripts
345 * attached to the target column itself. The input expression has
346 * already been through transformExpr().
349 * expr expression to be modified
350 * colname target column name (ie, name of attribute to be assigned to)
351 * attrno target attribute number
352 * indirection subscripts/field names for target column, if any
353 * location error cursor position for the target column, or -1
355 * Returns the modified expression.
357 * Note: location points at the target column name (SET target or INSERT
358 * column name list entry), and must therefore be -1 in an INSERT that
359 * omits the column name list. So we should usually prefer to use
360 * exprLocation(expr) for errors that can happen in a default INSERT.
363 transformAssignedExpr(ParseState *pstate,
370 Oid type_id; /* type of value provided */
371 Oid attrtype; /* type of target column */
374 Relation rd = pstate->p_target_relation;
379 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
380 errmsg("cannot assign to system column \"%s\"",
382 parser_errposition(pstate, location)));
383 attrtype = attnumTypeId(rd, attrno);
384 attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
385 attrcollation = rd->rd_att->attrs[attrno - 1]->attcollation;
388 * If the expression is a DEFAULT placeholder, insert the attribute's
389 * type/typmod into it so that exprType will report the right things. (We
390 * expect that the eventually substituted default expression will in fact
391 * have this type and typmod.) Also, reject trying to update a subfield
392 * or array element with DEFAULT, since there can't be any default for
393 * portions of a column.
395 if (expr && IsA(expr, SetToDefault))
397 SetToDefault *def = (SetToDefault *) expr;
399 def->typeId = attrtype;
400 def->typeMod = attrtypmod;
401 def->collation = attrcollation;
404 if (IsA(linitial(indirection), A_Indices))
406 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
407 errmsg("cannot set an array element to DEFAULT"),
408 parser_errposition(pstate, location)));
411 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
412 errmsg("cannot set a subfield to DEFAULT"),
413 parser_errposition(pstate, location)));
417 /* Now we can use exprType() safely. */
418 type_id = exprType((Node *) expr);
421 * If there is indirection on the target column, prepare an array or
422 * subfield assignment expression. This will generate a new column value
423 * that the source value has been inserted into, which can then be placed
424 * in the new tuple constructed by INSERT or UPDATE.
430 if (pstate->p_is_insert)
433 * The command is INSERT INTO table (col.something) ... so there
434 * is not really a source value to work with. Insert a NULL
435 * constant as the source value.
437 colVar = (Node *) makeNullConst(attrtype, attrtypmod);
442 * Build a Var for the column to be updated.
444 colVar = (Node *) make_var(pstate,
445 pstate->p_target_rangetblentry,
451 transformAssignmentIndirection(pstate,
457 list_head(indirection),
464 * For normal non-qualified target column, do type checking and
467 Node *orig_expr = (Node *) expr;
470 coerce_to_target_type(pstate,
472 attrtype, attrtypmod,
474 COERCE_IMPLICIT_CAST,
478 (errcode(ERRCODE_DATATYPE_MISMATCH),
479 errmsg("column \"%s\" is of type %s"
480 " but expression is of type %s",
482 format_type_be(attrtype),
483 format_type_be(type_id)),
484 errhint("You will need to rewrite or cast the expression."),
485 parser_errposition(pstate, exprLocation(orig_expr))));
493 * updateTargetListEntry()
494 * This is used in UPDATE statements only. It prepares an UPDATE
495 * TargetEntry for assignment to a column of the target table.
496 * This includes coercing the given value to the target column's type
497 * (if necessary), and dealing with any subfield names or subscripts
498 * attached to the target column itself.
501 * tle target list entry to be modified
502 * colname target column name (ie, name of attribute to be assigned to)
503 * attrno target attribute number
504 * indirection subscripts/field names for target column, if any
505 * location error cursor position (should point at column name), or -1
508 updateTargetListEntry(ParseState *pstate,
515 /* Fix up expression as needed */
516 tle->expr = transformAssignedExpr(pstate,
524 * Set the resno to identify the target column --- the rewriter and
525 * planner depend on this. We also set the resname to identify the target
526 * column, but this is only for debugging purposes; it should not be
527 * relied on. (In particular, it might be out of date in a stored rule.)
529 tle->resno = (AttrNumber) attrno;
530 tle->resname = colname;
535 * Process indirection (field selection or subscripting) of the target
536 * column in INSERT/UPDATE. This routine recurses for multiple levels
537 * of indirection --- but note that several adjacent A_Indices nodes in
538 * the indirection list are treated as a single multidimensional subscript
541 * In the initial call, basenode is a Var for the target column in UPDATE,
542 * or a null Const of the target's type in INSERT. In recursive calls,
543 * basenode is NULL, indicating that a substitute node should be consed up if
546 * targetName is the name of the field or subfield we're assigning to, and
547 * targetIsArray is true if we're subscripting it. These are just for
550 * targetTypeId and targetTypMod indicate the datatype of the object to
551 * be assigned to (initially the target column, later some subobject).
553 * indirection is the sublist remaining to process. When it's NULL, we're
554 * done recursing and can just coerce and return the RHS.
556 * rhs is the already-transformed value to be assigned; note it has not been
557 * coerced to any particular type.
559 * location is the cursor error position for any errors. (Note: this points
560 * to the head of the target clause, eg "foo" in "foo.bar[baz]". Later we
561 * might want to decorate indirection cells with their own location info,
562 * in which case the location argument could probably be dropped.)
565 transformAssignmentIndirection(ParseState *pstate,
567 const char *targetName,
571 ListCell *indirection,
576 List *subscripts = NIL;
577 bool isSlice = false;
580 if (indirection && !basenode)
582 /* Set up a substitution. We reuse CaseTestExpr for this. */
583 CaseTestExpr *ctest = makeNode(CaseTestExpr);
585 ctest->typeId = targetTypeId;
586 ctest->typeMod = targetTypMod;
587 basenode = (Node *) ctest;
591 * We have to split any field-selection operations apart from
592 * subscripting. Adjacent A_Indices nodes have to be treated as a single
593 * multidimensional subscript operation.
595 for_each_cell(i, indirection)
599 if (IsA(n, A_Indices))
601 subscripts = lappend(subscripts, n);
602 if (((A_Indices *) n)->lidx != NULL)
605 else if (IsA(n, A_Star))
608 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
609 errmsg("row expansion via \"*\" is not supported here"),
610 parser_errposition(pstate, location)));
620 Assert(IsA(n, String));
622 /* process subscripts before this field selection */
625 /* recurse, and then return because we're done */
626 return transformAssignmentSubscripts(pstate,
638 /* No subscripts, so can process field selection here */
640 typrelid = typeidTypeRelid(targetTypeId);
643 (errcode(ERRCODE_DATATYPE_MISMATCH),
644 errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
645 strVal(n), targetName,
646 format_type_be(targetTypeId)),
647 parser_errposition(pstate, location)));
649 attnum = get_attnum(typrelid, strVal(n));
650 if (attnum == InvalidAttrNumber)
652 (errcode(ERRCODE_UNDEFINED_COLUMN),
653 errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
654 strVal(n), targetName,
655 format_type_be(targetTypeId)),
656 parser_errposition(pstate, location)));
659 (errcode(ERRCODE_UNDEFINED_COLUMN),
660 errmsg("cannot assign to system column \"%s\"",
662 parser_errposition(pstate, location)));
664 get_atttypetypmod(typrelid, attnum,
665 &fieldTypeId, &fieldTypMod);
667 /* recurse to create appropriate RHS for field assign */
668 rhs = transformAssignmentIndirection(pstate,
678 /* and build a FieldStore node */
679 fstore = makeNode(FieldStore);
680 fstore->arg = (Expr *) basenode;
681 fstore->newvals = list_make1(rhs);
682 fstore->fieldnums = list_make1_int(attnum);
683 fstore->resulttype = targetTypeId;
685 return (Node *) fstore;
689 /* process trailing subscripts, if any */
692 /* recurse, and then return because we're done */
693 return transformAssignmentSubscripts(pstate,
705 /* base case: just coerce RHS to match target type ID */
707 result = coerce_to_target_type(pstate,
709 targetTypeId, targetTypMod,
711 COERCE_IMPLICIT_CAST,
717 (errcode(ERRCODE_DATATYPE_MISMATCH),
718 errmsg("array assignment to \"%s\" requires type %s"
719 " but expression is of type %s",
721 format_type_be(targetTypeId),
722 format_type_be(exprType(rhs))),
723 errhint("You will need to rewrite or cast the expression."),
724 parser_errposition(pstate, location)));
727 (errcode(ERRCODE_DATATYPE_MISMATCH),
728 errmsg("subfield \"%s\" is of type %s"
729 " but expression is of type %s",
731 format_type_be(targetTypeId),
732 format_type_be(exprType(rhs))),
733 errhint("You will need to rewrite or cast the expression."),
734 parser_errposition(pstate, location)));
741 * helper for transformAssignmentIndirection: process array assignment
744 transformAssignmentSubscripts(ParseState *pstate,
746 const char *targetName,
751 ListCell *next_indirection,
761 Assert(subscripts != NIL);
763 /* Identify the actual array type and element type involved */
764 arrayType = targetTypeId;
765 arrayTypMod = targetTypMod;
766 elementTypeId = transformArrayType(&arrayType, &arrayTypMod);
768 /* Identify type that RHS must provide */
769 typeNeeded = isSlice ? arrayType : elementTypeId;
771 /* recurse to create appropriate RHS for array assign */
772 rhs = transformAssignmentIndirection(pstate,
782 /* process subscripts */
783 result = (Node *) transformArraySubscripts(pstate,
791 /* If target was a domain over array, need to coerce up to the domain */
792 if (arrayType != targetTypeId)
794 result = coerce_to_target_type(pstate,
795 result, exprType(result),
796 targetTypeId, targetTypMod,
798 COERCE_IMPLICIT_CAST,
800 /* probably shouldn't fail, but check */
803 (errcode(ERRCODE_CANNOT_COERCE),
804 errmsg("cannot cast type %s to %s",
805 format_type_be(exprType(result)),
806 format_type_be(targetTypeId)),
807 parser_errposition(pstate, location)));
815 * checkInsertTargets -
816 * generate a list of INSERT column targets if not supplied, or
817 * test supplied column names to make sure they are in target table.
818 * Also return an integer list of the columns' attribute numbers.
821 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
828 * Generate default column list for INSERT.
830 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
831 int numcol = pstate->p_target_relation->rd_rel->relnatts;
834 for (i = 0; i < numcol; i++)
838 if (attr[i]->attisdropped)
841 col = makeNode(ResTarget);
842 col->name = pstrdup(NameStr(attr[i]->attname));
843 col->indirection = NIL;
846 cols = lappend(cols, col);
847 *attrnos = lappend_int(*attrnos, i + 1);
853 * Do initial validation of user-supplied INSERT column list.
855 Bitmapset *wholecols = NULL;
856 Bitmapset *partialcols = NULL;
861 ResTarget *col = (ResTarget *) lfirst(tl);
862 char *name = col->name;
865 /* Lookup column name, ereport on failure */
866 attrno = attnameAttNum(pstate->p_target_relation, name, false);
867 if (attrno == InvalidAttrNumber)
869 (errcode(ERRCODE_UNDEFINED_COLUMN),
870 errmsg("column \"%s\" of relation \"%s\" does not exist",
872 RelationGetRelationName(pstate->p_target_relation)),
873 parser_errposition(pstate, col->location)));
876 * Check for duplicates, but only of whole columns --- we allow
877 * INSERT INTO foo (col.subcol1, col.subcol2)
879 if (col->indirection == NIL)
881 /* whole column; must not have any other assignment */
882 if (bms_is_member(attrno, wholecols) ||
883 bms_is_member(attrno, partialcols))
885 (errcode(ERRCODE_DUPLICATE_COLUMN),
886 errmsg("column \"%s\" specified more than once",
888 parser_errposition(pstate, col->location)));
889 wholecols = bms_add_member(wholecols, attrno);
893 /* partial column; must not have any whole assignment */
894 if (bms_is_member(attrno, wholecols))
896 (errcode(ERRCODE_DUPLICATE_COLUMN),
897 errmsg("column \"%s\" specified more than once",
899 parser_errposition(pstate, col->location)));
900 partialcols = bms_add_member(partialcols, attrno);
903 *attrnos = lappend_int(*attrnos, attrno);
911 * ExpandColumnRefStar()
912 * Transforms foo.* into a list of expressions or targetlist entries.
914 * This handles the case where '*' appears as the last or only item in a
915 * ColumnRef. The code is shared between the case of foo.* at the top level
916 * in a SELECT target list (where we want TargetEntry nodes in the result)
917 * and foo.* in a ROW() or VALUES() construct (where we want just bare
920 * The referenced columns are marked as requiring SELECT access.
923 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
926 List *fields = cref->fields;
927 int numnames = list_length(fields);
932 * Target item is a bare '*', expand all tables
934 * (e.g., SELECT * FROM emp, dept)
936 * Since the grammar only accepts bare '*' at top level of SELECT, we
937 * need not handle the targetlist==false case here.
940 return ExpandAllTables(pstate, cref->location);
945 * Target item is relation.*, expand that table
947 * (e.g., SELECT emp.*, dname FROM emp, dept)
949 * Note: this code is a lot like transformColumnRef; it's tempting to
950 * call that instead and then replace the resulting whole-row Var with
951 * a list of Vars. However, that would leave us with the RTE's
952 * selectedCols bitmap showing the whole row as needing select
953 * permission, as well as the individual columns. That would be
954 * incorrect (since columns added later shouldn't need select
955 * permissions). We could try to remove the whole-row permission bit
956 * after the fact, but duplicating code is less messy.
958 char *nspname = NULL;
959 char *relname = NULL;
960 RangeTblEntry *rte = NULL;
967 } crserr = CRSERR_NO_RTE;
970 * Give the PreParseColumnRefHook, if any, first shot. If it returns
971 * non-null then we should use that expression.
973 if (pstate->p_pre_columnref_hook != NULL)
977 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
979 return ExpandRowReference(pstate, node, targetlist);
985 relname = strVal(linitial(fields));
986 rte = refnameRangeTblEntry(pstate, nspname, relname,
991 nspname = strVal(linitial(fields));
992 relname = strVal(lsecond(fields));
993 rte = refnameRangeTblEntry(pstate, nspname, relname,
999 char *catname = strVal(linitial(fields));
1002 * We check the catalog name and then ignore it.
1004 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1006 crserr = CRSERR_WRONG_DB;
1009 nspname = strVal(lsecond(fields));
1010 relname = strVal(lthird(fields));
1011 rte = refnameRangeTblEntry(pstate, nspname, relname,
1017 crserr = CRSERR_TOO_MANY;
1022 * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1023 * bit by passing the RangeTblEntry, not a Var, as the planned
1024 * translation. (A single Var wouldn't be strictly correct anyway.
1025 * This convention allows hooks that really care to know what is
1028 if (pstate->p_post_columnref_hook != NULL)
1032 node = (*pstate->p_post_columnref_hook) (pstate, cref,
1038 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1039 errmsg("column reference \"%s\" is ambiguous",
1040 NameListToString(cref->fields)),
1041 parser_errposition(pstate, cref->location)));
1042 return ExpandRowReference(pstate, node, targetlist);
1047 * Throw error if no translation found.
1054 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1057 case CRSERR_WRONG_DB:
1059 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1060 errmsg("cross-database references are not implemented: %s",
1061 NameListToString(cref->fields)),
1062 parser_errposition(pstate, cref->location)));
1064 case CRSERR_TOO_MANY:
1066 (errcode(ERRCODE_SYNTAX_ERROR),
1067 errmsg("improper qualified name (too many dotted names): %s",
1068 NameListToString(cref->fields)),
1069 parser_errposition(pstate, cref->location)));
1075 * OK, expand the RTE into fields.
1077 return ExpandSingleTable(pstate, rte, cref->location, targetlist);
1083 * Transforms '*' (in the target list) into a list of targetlist entries.
1085 * tlist entries are generated for each relation appearing in the query's
1086 * varnamespace. We do not consider relnamespace because that would include
1087 * input tables of aliasless JOINs, NEW/OLD pseudo-entries, etc.
1089 * The referenced relations/columns are marked as requiring SELECT access.
1092 ExpandAllTables(ParseState *pstate, int location)
1097 /* Check for SELECT *; */
1098 if (!pstate->p_varnamespace)
1100 (errcode(ERRCODE_SYNTAX_ERROR),
1101 errmsg("SELECT * with no tables specified is not valid"),
1102 parser_errposition(pstate, location)));
1104 foreach(l, pstate->p_varnamespace)
1106 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1107 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1109 target = list_concat(target,
1110 expandRelAttrs(pstate, rte, rtindex, 0,
1118 * ExpandIndirectionStar()
1119 * Transforms foo.* into a list of expressions or targetlist entries.
1121 * This handles the case where '*' appears as the last item in A_Indirection.
1122 * The code is shared between the case of foo.* at the top level in a SELECT
1123 * target list (where we want TargetEntry nodes in the result) and foo.* in
1124 * a ROW() or VALUES() construct (where we want just bare expressions).
1127 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1132 /* Strip off the '*' to create a reference to the rowtype object */
1133 ind = copyObject(ind);
1134 ind->indirection = list_truncate(ind->indirection,
1135 list_length(ind->indirection) - 1);
1137 /* And transform that */
1138 expr = transformExpr(pstate, (Node *) ind);
1140 /* Expand the rowtype expression into individual fields */
1141 return ExpandRowReference(pstate, expr, targetlist);
1145 * ExpandSingleTable()
1146 * Transforms foo.* into a list of expressions or targetlist entries.
1148 * This handles the case where foo has been determined to be a simple
1149 * reference to an RTE, so we can just generate Vars for the expressions.
1151 * The referenced columns are marked as requiring SELECT access.
1154 ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
1155 int location, bool targetlist)
1160 rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1164 /* expandRelAttrs handles permissions marking */
1165 return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1173 expandRTE(rte, rtindex, sublevels_up, location, false,
1177 * Require read access to the table. This is normally redundant with
1178 * the markVarForSelectPriv calls below, but not if the table has zero
1181 rte->requiredPerms |= ACL_SELECT;
1183 /* Require read access to each column */
1186 Var *var = (Var *) lfirst(l);
1188 markVarForSelectPriv(pstate, var, rte);
1196 * ExpandRowReference()
1197 * Transforms foo.* into a list of expressions or targetlist entries.
1199 * This handles the case where foo is an arbitrary expression of composite
1203 ExpandRowReference(ParseState *pstate, Node *expr,
1207 TupleDesc tupleDesc;
1212 * If the rowtype expression is a whole-row Var, we can expand the fields
1213 * as simple Vars. Note: if the RTE is a relation, this case leaves us
1214 * with the RTE's selectedCols bitmap showing the whole row as needing
1215 * select permission, as well as the individual columns. However, we can
1216 * only get here for weird notations like (table.*).*, so it's not worth
1217 * trying to clean up --- arguably, the permissions marking is correct
1218 * anyway for such cases.
1220 if (IsA(expr, Var) &&
1221 ((Var *) expr)->varattno == InvalidAttrNumber)
1223 Var *var = (Var *) expr;
1226 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1227 return ExpandSingleTable(pstate, rte, var->location, targetlist);
1231 * Otherwise we have to do it the hard way. Our current implementation is
1232 * to generate multiple copies of the expression and do FieldSelects.
1233 * (This can be pretty inefficient if the expression involves nontrivial
1236 * Verify it's a composite type, and get the tupdesc. We use
1237 * get_expr_result_type() because that can handle references to functions
1238 * returning anonymous record types. If that fails, use
1239 * lookup_rowtype_tupdesc(), which will almost certainly fail as well, but
1240 * it will give an appropriate error message.
1242 * If it's a Var of type RECORD, we have to work even harder: we have to
1243 * find what the Var refers to, and pass that to get_expr_result_type.
1244 * That task is handled by expandRecordVariable().
1246 if (IsA(expr, Var) &&
1247 ((Var *) expr)->vartype == RECORDOID)
1248 tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1249 else if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1250 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1254 /* Generate a list of references to the individual fields */
1255 numAttrs = tupleDesc->natts;
1256 for (i = 0; i < numAttrs; i++)
1258 Form_pg_attribute att = tupleDesc->attrs[i];
1259 FieldSelect *fselect;
1261 if (att->attisdropped)
1264 fselect = makeNode(FieldSelect);
1265 fselect->arg = (Expr *) copyObject(expr);
1266 fselect->fieldnum = i + 1;
1267 fselect->resulttype = att->atttypid;
1268 fselect->resulttypmod = att->atttypmod;
1269 /* resultcollid may get overridden by parse_collate.c */
1270 fselect->resultcollid = att->attcollation;
1274 /* add TargetEntry decoration */
1277 te = makeTargetEntry((Expr *) fselect,
1278 (AttrNumber) pstate->p_next_resno++,
1279 pstrdup(NameStr(att->attname)),
1281 result = lappend(result, te);
1284 result = lappend(result, fselect);
1291 * expandRecordVariable
1292 * Get the tuple descriptor for a Var of type RECORD, if possible.
1294 * Since no actual table or view column is allowed to have type RECORD, such
1295 * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
1296 * drill down to find the ultimate defining expression and attempt to infer
1297 * the tupdesc from it. We ereport if we can't determine the tupdesc.
1299 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1302 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1304 TupleDesc tupleDesc;
1310 /* Check my caller didn't mess up */
1311 Assert(IsA(var, Var));
1312 Assert(var->vartype == RECORDOID);
1314 netlevelsup = var->varlevelsup + levelsup;
1315 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1316 attnum = var->varattno;
1318 if (attnum == InvalidAttrNumber)
1320 /* Whole-row reference to an RTE, so expand the known fields */
1327 expandRTE(rte, var->varno, 0, var->location, false,
1330 tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1332 forboth(lname, names, lvar, vars)
1334 char *label = strVal(lfirst(lname));
1335 Node *varnode = (Node *) lfirst(lvar);
1337 TupleDescInitEntry(tupleDesc, i,
1340 exprTypmod(varnode),
1342 TupleDescInitEntryCollation(tupleDesc, i,
1343 exprCollation(varnode));
1346 Assert(lname == NULL && lvar == NULL); /* lists same length? */
1351 expr = (Node *) var; /* default if we can't drill down */
1353 switch (rte->rtekind)
1359 * This case should not occur: a column of a table or values list
1360 * shouldn't have type RECORD. Fall through and fail (most
1361 * likely) at the bottom.
1366 /* Subselect-in-FROM: examine sub-select's output expr */
1367 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1370 if (ste == NULL || ste->resjunk)
1371 elog(ERROR, "subquery %s does not have attribute %d",
1372 rte->eref->aliasname, attnum);
1373 expr = (Node *) ste->expr;
1377 * Recurse into the sub-select to see what its Var refers
1378 * to. We have to build an additional level of ParseState
1379 * to keep in step with varlevelsup in the subselect.
1381 ParseState mypstate;
1383 MemSet(&mypstate, 0, sizeof(mypstate));
1384 mypstate.parentParseState = pstate;
1385 mypstate.p_rtable = rte->subquery->rtable;
1386 /* don't bother filling the rest of the fake pstate */
1388 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1390 /* else fall through to inspect the expression */
1394 /* Join RTE --- recursively inspect the alias variable */
1395 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1396 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1398 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1399 /* else fall through to inspect the expression */
1404 * We couldn't get here unless a function is declared with one of
1405 * its result columns as RECORD, which is not allowed.
1409 /* CTE reference: examine subquery's output expr */
1410 if (!rte->self_reference)
1412 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1415 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1416 if (ste == NULL || ste->resjunk)
1417 elog(ERROR, "subquery %s does not have attribute %d",
1418 rte->eref->aliasname, attnum);
1419 expr = (Node *) ste->expr;
1423 * Recurse into the CTE to see what its Var refers to. We
1424 * have to build an additional level of ParseState to keep
1425 * in step with varlevelsup in the CTE; furthermore it
1426 * could be an outer CTE.
1428 ParseState mypstate;
1431 MemSet(&mypstate, 0, sizeof(mypstate));
1432 /* this loop must work, since GetCTEForRTE did */
1434 levelsup < rte->ctelevelsup + netlevelsup;
1436 pstate = pstate->parentParseState;
1437 mypstate.parentParseState = pstate;
1438 mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1439 /* don't bother filling the rest of the fake pstate */
1441 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1443 /* else fall through to inspect the expression */
1449 * We now have an expression we can't expand any more, so see if
1450 * get_expr_result_type() can do anything with it. If not, pass to
1451 * lookup_rowtype_tupdesc() which will probably fail, but will give an
1452 * appropriate error message while failing.
1454 if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1455 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1464 * if the name of the resulting column is not specified in the target
1465 * list, we have to guess a suitable name. The SQL spec provides some
1466 * guidance, but not much...
1468 * Note that the argument is the *untransformed* parse tree for the target
1469 * item. This is a shade easier to work with than the transformed tree.
1472 FigureColname(Node *node)
1476 (void) FigureColnameInternal(node, &name);
1479 /* default result if we can't guess anything */
1484 * FigureIndexColname -
1485 * choose the name for an expression column in an index
1487 * This is actually just like FigureColname, except we return NULL if
1488 * we can't pick a good name.
1491 FigureIndexColname(Node *node)
1495 (void) FigureColnameInternal(node, &name);
1500 * FigureColnameInternal -
1501 * internal workhorse for FigureColname
1503 * Return value indicates strength of confidence in result:
1504 * 0 - no information
1505 * 1 - second-best name choice
1506 * 2 - good name choice
1507 * The return value is actually only used internally.
1508 * If the result isn't zero, *name is set to the chosen name.
1511 FigureColnameInternal(Node *node, char **name)
1518 switch (nodeTag(node))
1525 /* find last field name, if any, ignoring "*" */
1526 foreach(l, ((ColumnRef *) node)->fields)
1528 Node *i = lfirst(l);
1540 case T_A_Indirection:
1542 A_Indirection *ind = (A_Indirection *) node;
1546 /* find last field name, if any, ignoring "*" and subscripts */
1547 foreach(l, ind->indirection)
1549 Node *i = lfirst(l);
1559 return FigureColnameInternal(ind->arg, name);
1563 *name = strVal(llast(((FuncCall *) node)->funcname));
1566 /* make nullif() act like a regular function */
1567 if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1574 strength = FigureColnameInternal(((TypeCast *) node)->arg,
1578 if (((TypeCast *) node)->typeName != NULL)
1580 *name = strVal(llast(((TypeCast *) node)->typeName->names));
1585 case T_CollateClause:
1586 return FigureColnameInternal(((CollateClause *) node)->arg, name);
1588 strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1597 /* make ARRAY[] act like a function */
1601 /* make ROW() act like a function */
1604 case T_CoalesceExpr:
1605 /* make coalesce() act like a regular function */
1609 /* make greatest/least act like a regular function */
1610 switch (((MinMaxExpr *) node)->op)
1621 /* make SQL/XML functions act like a regular function */
1622 switch (((XmlExpr *) node)->op)
1625 *name = "xmlconcat";
1628 *name = "xmlelement";
1631 *name = "xmlforest";
1642 case IS_XMLSERIALIZE:
1643 *name = "xmlserialize";
1650 case T_XmlSerialize:
1651 *name = "xmlserialize";