1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_target.c,v 1.124 2004/08/29 04:12:42 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "commands/dbcommands.h"
18 #include "miscadmin.h"
19 #include "nodes/makefuncs.h"
20 #include "parser/parsetree.h"
21 #include "parser/parse_coerce.h"
22 #include "parser/parse_expr.h"
23 #include "parser/parse_func.h"
24 #include "parser/parse_relation.h"
25 #include "parser/parse_target.h"
26 #include "parser/parse_type.h"
27 #include "utils/builtins.h"
28 #include "utils/lsyscache.h"
29 #include "utils/typcache.h"
32 static void markTargetListOrigin(ParseState *pstate, Resdom *res, Var *var);
33 static Node *transformAssignmentIndirection(ParseState *pstate,
35 const char *targetName,
39 ListCell *indirection,
41 static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref);
42 static List *ExpandAllTables(ParseState *pstate);
43 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind);
44 static char *FigureColname(Node *node);
45 static int FigureColnameInternal(Node *node, char **name);
49 * transformTargetEntry()
50 * Transform any ordinary "expression-type" node into a targetlist entry.
51 * This is exported so that parse_clause.c can generate targetlist entries
52 * for ORDER/GROUP BY items that are not already in the targetlist.
54 * node the (untransformed) parse tree for the value expression.
55 * expr the transformed expression, or NULL if caller didn't do it yet.
56 * colname the column name to be assigned, or NULL if none yet set.
57 * resjunk true if the target should be marked resjunk, ie, it is not
58 * wanted in the final projected tuple.
61 transformTargetEntry(ParseState *pstate,
71 /* Transform the node if caller didn't do it already */
73 expr = transformExpr(pstate, node);
75 type_id = exprType(expr);
76 type_mod = exprTypmod(expr);
78 if (colname == NULL && !resjunk)
81 * Generate a suitable column name for a column without any
82 * explicit 'AS ColumnName' clause.
84 colname = FigureColname(node);
87 resnode = makeResdom((AttrNumber) pstate->p_next_resno++,
93 return makeTargetEntry(resnode, (Expr *) expr);
98 * transformTargetList()
99 * Turns a list of ResTarget's into a list of TargetEntry's.
101 * At this point, we don't care whether we are doing SELECT, INSERT,
102 * or UPDATE; we just transform the given expressions (the "val" fields).
105 transformTargetList(ParseState *pstate, List *targetlist)
107 List *p_target = NIL;
110 foreach(o_target, targetlist)
112 ResTarget *res = (ResTarget *) lfirst(o_target);
115 * Check for "something.*". Depending on the complexity of the
116 * "something", the star could appear as the last name in ColumnRef,
117 * or as the last indirection item in A_Indirection.
119 if (IsA(res->val, ColumnRef))
121 ColumnRef *cref = (ColumnRef *) res->val;
123 if (strcmp(strVal(llast(cref->fields)), "*") == 0)
125 /* It is something.*, expand into multiple items */
126 p_target = list_concat(p_target,
127 ExpandColumnRefStar(pstate, cref));
131 else if (IsA(res->val, A_Indirection))
133 A_Indirection *ind = (A_Indirection *) res->val;
134 Node *lastitem = llast(ind->indirection);
136 if (IsA(lastitem, String) &&
137 strcmp(strVal(lastitem), "*") == 0)
139 /* It is something.*, expand into multiple items */
140 p_target = list_concat(p_target,
141 ExpandIndirectionStar(pstate, ind));
147 * Not "something.*", so transform as a single expression
149 p_target = lappend(p_target,
150 transformTargetEntry(pstate,
162 * markTargetListOrigins()
163 * Mark targetlist columns that are simple Vars with the source
164 * table's OID and column number.
166 * Currently, this is done only for SELECT targetlists, since we only
167 * need the info if we are going to send it to the frontend.
170 markTargetListOrigins(ParseState *pstate, List *targetlist)
174 foreach(l, targetlist)
176 TargetEntry *tle = (TargetEntry *) lfirst(l);
178 markTargetListOrigin(pstate, tle->resdom, (Var *) tle->expr);
183 * markTargetListOrigin()
184 * If 'var' is a Var of a plain relation, mark 'res' with its origin
186 * This is split out so it can recurse for join references. Note that we
187 * do not drill down into views, but report the view as the column owner.
190 markTargetListOrigin(ParseState *pstate, Resdom *res, Var *var)
195 if (var == NULL || !IsA(var, Var))
197 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
198 attnum = var->varattno;
200 switch (rte->rtekind)
203 /* It's a table or view, report it */
204 res->resorigtbl = rte->relid;
205 res->resorigcol = attnum;
209 /* Subselect-in-FROM: copy up from the subselect */
210 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
213 if (te == NULL || te->resdom->resjunk)
214 elog(ERROR, "subquery %s does not have attribute %d",
215 rte->eref->aliasname, attnum);
216 res->resorigtbl = te->resdom->resorigtbl;
217 res->resorigcol = te->resdom->resorigcol;
222 /* Join RTE --- recursively inspect the alias variable */
225 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
226 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
227 markTargetListOrigin(pstate, res, aliasvar);
232 /* not a simple relation, leave it unmarked */
239 * updateTargetListEntry()
240 * This is used in INSERT and UPDATE statements only. It prepares a
241 * TargetEntry for assignment to a column of the target table.
242 * This includes coercing the given value to the target column's type
243 * (if necessary), and dealing with any subfield names or subscripts
244 * attached to the target column itself.
247 * tle target list entry to be modified
248 * colname target column name (ie, name of attribute to be assigned to)
249 * attrno target attribute number
250 * indirection subscripts/field names for target column, if any
253 updateTargetListEntry(ParseState *pstate,
259 Oid type_id; /* type of value provided */
260 Oid attrtype; /* type of target column */
262 Resdom *resnode = tle->resdom;
263 Relation rd = pstate->p_target_relation;
268 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
269 errmsg("cannot assign to system column \"%s\"",
271 attrtype = attnumTypeId(rd, attrno);
272 attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
275 * If the expression is a DEFAULT placeholder, insert the attribute's
276 * type/typmod into it so that exprType will report the right things.
277 * (We expect that the eventually substituted default expression will
278 * in fact have this type and typmod.) Also, reject trying to update
279 * a subfield or array element with DEFAULT, since there can't be any
280 * default for portions of a column.
282 if (tle->expr && IsA(tle->expr, SetToDefault))
284 SetToDefault *def = (SetToDefault *) tle->expr;
286 def->typeId = attrtype;
287 def->typeMod = attrtypmod;
290 if (IsA(linitial(indirection), A_Indices))
292 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
293 errmsg("cannot set an array element to DEFAULT")));
296 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
297 errmsg("cannot set a subfield to DEFAULT")));
301 /* Now we can use exprType() safely. */
302 type_id = exprType((Node *) tle->expr);
305 * If there is indirection on the target column, prepare an array or
306 * subfield assignment expression. This will generate a new column value
307 * that the source value has been inserted into, which can then be placed
308 * in the new tuple constructed by INSERT or UPDATE.
314 if (pstate->p_is_insert)
317 * The command is INSERT INTO table (col.something) ...
318 * so there is not really a source value to work with.
319 * Insert a NULL constant as the source value.
321 colVar = (Node *) makeNullConst(attrtype);
326 * Build a Var for the column to be updated.
328 colVar = (Node *) make_var(pstate,
329 pstate->p_target_rangetblentry,
334 transformAssignmentIndirection(pstate,
340 list_head(indirection),
346 * For normal non-qualified target column, do type checking and
350 coerce_to_target_type(pstate,
351 (Node *) tle->expr, type_id,
352 attrtype, attrtypmod,
354 COERCE_IMPLICIT_CAST);
355 if (tle->expr == NULL)
357 (errcode(ERRCODE_DATATYPE_MISMATCH),
358 errmsg("column \"%s\" is of type %s"
359 " but expression is of type %s",
361 format_type_be(attrtype),
362 format_type_be(type_id)),
363 errhint("You will need to rewrite or cast the expression.")));
367 * The result of the target expression should now match the
368 * destination column's type.
370 resnode->restype = attrtype;
371 resnode->restypmod = attrtypmod;
373 * Set the resno to identify the target column --- the rewriter and
374 * planner depend on this. We also set the resname to identify the
375 * target column, but this is only for debugging purposes; it should
376 * not be relied on. (In particular, it might be out of date in a
379 resnode->resno = (AttrNumber) attrno;
380 resnode->resname = colname;
384 * Process indirection (field selection or subscripting) of the target
385 * column in INSERT/UPDATE. This routine recurses for multiple levels
386 * of indirection --- but note that several adjacent A_Indices nodes in
387 * the indirection list are treated as a single multidimensional subscript
390 * In the initial call, basenode is a Var for the target column in UPDATE,
391 * or a null Const of the target's type in INSERT. In recursive calls,
392 * basenode is NULL, indicating that a substitute node should be consed up if
395 * targetName is the name of the field or subfield we're assigning to, and
396 * targetIsArray is true if we're subscripting it. These are just for
399 * targetTypeId and targetTypMod indicate the datatype of the object to
400 * be assigned to (initially the target column, later some subobject).
402 * indirection is the sublist remaining to process. When it's NULL, we're
403 * done recursing and can just coerce and return the RHS.
405 * rhs is the already-transformed value to be assigned; note it has not been
406 * coerced to any particular type.
409 transformAssignmentIndirection(ParseState *pstate,
411 const char *targetName,
415 ListCell *indirection,
419 List *subscripts = NIL;
420 bool isSlice = false;
423 if (indirection && !basenode)
425 /* Set up a substitution. We reuse CaseTestExpr for this. */
426 CaseTestExpr *ctest = makeNode(CaseTestExpr);
428 ctest->typeId = targetTypeId;
429 ctest->typeMod = targetTypMod;
430 basenode = (Node *) ctest;
434 * We have to split any field-selection operations apart from
435 * subscripting. Adjacent A_Indices nodes have to be treated
436 * as a single multidimensional subscript operation.
438 for_each_cell(i, indirection)
442 if (IsA(n, A_Indices))
444 subscripts = lappend(subscripts, n);
445 if (((A_Indices *) n)->lidx != NULL)
456 Assert(IsA(n, String));
458 /* process subscripts before this field selection */
461 Oid elementTypeId = transformArrayType(targetTypeId);
462 Oid typeNeeded = isSlice ? targetTypeId : elementTypeId;
464 /* recurse to create appropriate RHS for array assign */
465 rhs = transformAssignmentIndirection(pstate,
473 /* process subscripts */
474 return (Node *) transformArraySubscripts(pstate,
483 /* No subscripts, so can process field selection here */
485 typrelid = typeidTypeRelid(targetTypeId);
488 (errcode(ERRCODE_DATATYPE_MISMATCH),
489 errmsg("cannot assign to a column of type %s because it is not a composite type",
490 format_type_be(targetTypeId))));
492 attnum = get_attnum(typrelid, strVal(n));
493 if (attnum == InvalidAttrNumber)
495 (errcode(ERRCODE_UNDEFINED_COLUMN),
496 errmsg("column \"%s\" not found in data type %s",
497 strVal(n), format_type_be(targetTypeId))));
500 (errcode(ERRCODE_UNDEFINED_COLUMN),
501 errmsg("cannot assign to system column \"%s\"",
504 get_atttypetypmod(typrelid, attnum,
505 &fieldTypeId, &fieldTypMod);
507 /* recurse to create appropriate RHS for field assign */
508 rhs = transformAssignmentIndirection(pstate,
517 /* and build a FieldStore node */
518 fstore = makeNode(FieldStore);
519 fstore->arg = (Expr *) basenode;
520 fstore->newvals = list_make1(rhs);
521 fstore->fieldnums = list_make1_int(attnum);
522 fstore->resulttype = targetTypeId;
524 return (Node *) fstore;
528 /* process trailing subscripts, if any */
531 Oid elementTypeId = transformArrayType(targetTypeId);
532 Oid typeNeeded = isSlice ? targetTypeId : elementTypeId;
534 /* recurse to create appropriate RHS for array assign */
535 rhs = transformAssignmentIndirection(pstate,
543 /* process subscripts */
544 return (Node *) transformArraySubscripts(pstate,
553 /* base case: just coerce RHS to match target type ID */
555 result = coerce_to_target_type(pstate,
557 targetTypeId, targetTypMod,
559 COERCE_IMPLICIT_CAST);
564 (errcode(ERRCODE_DATATYPE_MISMATCH),
565 errmsg("array assignment to \"%s\" requires type %s"
566 " but expression is of type %s",
568 format_type_be(targetTypeId),
569 format_type_be(exprType(rhs))),
570 errhint("You will need to rewrite or cast the expression.")));
573 (errcode(ERRCODE_DATATYPE_MISMATCH),
574 errmsg("subfield \"%s\" is of type %s"
575 " but expression is of type %s",
577 format_type_be(targetTypeId),
578 format_type_be(exprType(rhs))),
579 errhint("You will need to rewrite or cast the expression.")));
587 * checkInsertTargets -
588 * generate a list of INSERT column targets if not supplied, or
589 * test supplied column names to make sure they are in target table.
590 * Also return an integer list of the columns' attribute numbers.
593 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
600 * Generate default column list for INSERT.
602 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
603 int numcol = pstate->p_target_relation->rd_rel->relnatts;
606 for (i = 0; i < numcol; i++)
610 if (attr[i]->attisdropped)
613 col = makeNode(ResTarget);
614 col->name = pstrdup(NameStr(attr[i]->attname));
615 col->indirection = NIL;
617 cols = lappend(cols, col);
618 *attrnos = lappend_int(*attrnos, i + 1);
624 * Do initial validation of user-supplied INSERT column list.
626 List *wholecols = NIL;
631 ResTarget *col = (ResTarget *) lfirst(tl);
632 char *name = col->name;
635 /* Lookup column name, ereport on failure */
636 attrno = attnameAttNum(pstate->p_target_relation, name, false);
639 * Check for duplicates, but only of whole columns --- we
640 * allow INSERT INTO foo (col.subcol1, col.subcol2)
642 if (col->indirection == NIL)
644 /* whole column; must not have any other assignment */
645 if (list_member_int(*attrnos, attrno))
647 (errcode(ERRCODE_DUPLICATE_COLUMN),
648 errmsg("column \"%s\" specified more than once",
650 wholecols = lappend_int(wholecols, attrno);
654 /* partial column; must not have any whole assignment */
655 if (list_member_int(wholecols, attrno))
657 (errcode(ERRCODE_DUPLICATE_COLUMN),
658 errmsg("column \"%s\" specified more than once",
662 *attrnos = lappend_int(*attrnos, attrno);
670 * ExpandColumnRefStar()
671 * Turns foo.* (in the target list) into a list of targetlist entries.
673 * This handles the case where '*' appears as the last or only name in a
677 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref)
679 List *fields = cref->fields;
680 int numnames = list_length(fields);
685 * Target item is a bare '*', expand all tables
687 * (e.g., SELECT * FROM emp, dept)
689 return ExpandAllTables(pstate);
694 * Target item is relation.*, expand that table
696 * (e.g., SELECT emp.*, dname FROM emp, dept)
709 relname = strVal(linitial(fields));
712 schemaname = strVal(linitial(fields));
713 relname = strVal(lsecond(fields));
717 char *name1 = strVal(linitial(fields));
720 * We check the catalog name and then ignore
723 if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
725 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
726 errmsg("cross-database references are not implemented: %s",
727 NameListToString(fields))));
728 schemaname = strVal(lsecond(fields));
729 relname = strVal(lthird(fields));
734 (errcode(ERRCODE_SYNTAX_ERROR),
735 errmsg("improper qualified name (too many dotted names): %s",
736 NameListToString(fields))));
737 schemaname = NULL; /* keep compiler quiet */
742 rte = refnameRangeTblEntry(pstate, schemaname, relname,
745 rte = addImplicitRTE(pstate, makeRangeVar(schemaname,
748 rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
749 rtable = GetLevelNRangeTable(pstate, sublevels_up);
751 return expandRelAttrs(pstate, rtable, rtindex, sublevels_up);
757 * Turns '*' (in the target list) into a list of targetlist entries.
759 * tlist entries are generated for each relation appearing at the top level
760 * of the query's namespace, except for RTEs marked not inFromCl. (These
761 * may include NEW/OLD pseudo-entries, implicit RTEs, etc.)
764 ExpandAllTables(ParseState *pstate)
767 bool found_table = false;
770 foreach(ns, pstate->p_namespace)
772 Node *n = (Node *) lfirst(ns);
776 if (IsA(n, RangeTblRef))
777 rtindex = ((RangeTblRef *) n)->rtindex;
778 else if (IsA(n, JoinExpr))
779 rtindex = ((JoinExpr *) n)->rtindex;
782 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
783 rtindex = 0; /* keep compiler quiet */
787 * Ignore added-on relations that were not listed in the FROM
790 rte = rt_fetch(rtindex, pstate->p_rtable);
795 target = list_concat(target,
796 expandRelAttrs(pstate, pstate->p_rtable,
800 /* Check for SELECT *; */
803 (errcode(ERRCODE_SYNTAX_ERROR),
804 errmsg("SELECT * with no tables specified is not valid")));
810 * ExpandIndirectionStar()
811 * Turns foo.* (in the target list) into a list of targetlist entries.
813 * This handles the case where '*' appears as the last item in A_Indirection.
816 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind)
824 /* Strip off the '*' to create a reference to the rowtype object */
825 ind = copyObject(ind);
826 ind->indirection = list_truncate(ind->indirection,
827 list_length(ind->indirection) - 1);
829 /* And transform that */
830 expr = transformExpr(pstate, (Node *) ind);
832 /* Verify it's a composite type, and get the tupdesc */
833 tupleDesc = lookup_rowtype_tupdesc(exprType(expr), exprTypmod(expr));
835 /* Generate a list of references to the individual fields */
836 numAttrs = tupleDesc->natts;
837 for (i = 0; i < numAttrs; i++)
839 Form_pg_attribute att = tupleDesc->attrs[i];
843 if (att->attisdropped)
847 * If we got a whole-row Var from the rowtype reference, we can
848 * expand the fields as simple Vars. Otherwise we must generate
849 * multiple copies of the rowtype reference and do FieldSelects.
851 if (IsA(expr, Var) &&
852 ((Var *) expr)->varattno == InvalidAttrNumber)
854 Var *var = (Var *) expr;
856 fieldnode = (Node *) makeVar(var->varno,
864 FieldSelect *fselect = makeNode(FieldSelect);
866 fselect->arg = (Expr *) copyObject(expr);
867 fselect->fieldnum = i + 1;
868 fselect->resulttype = att->atttypid;
869 fselect->resulttypmod = att->atttypmod;
871 fieldnode = (Node *) fselect;
874 te = makeNode(TargetEntry);
875 te->resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
878 pstrdup(NameStr(att->attname)),
880 te->expr = (Expr *) fieldnode;
881 te_list = lappend(te_list, te);
889 * if the name of the resulting column is not specified in the target
890 * list, we have to guess a suitable name. The SQL spec provides some
891 * guidance, but not much...
893 * Note that the argument is the *untransformed* parse tree for the target
894 * item. This is a shade easier to work with than the transformed tree.
897 FigureColname(Node *node)
901 FigureColnameInternal(node, &name);
904 /* default result if we can't guess anything */
909 FigureColnameInternal(Node *node, char **name)
916 switch (nodeTag(node))
923 /* find last field name, if any, ignoring "*" */
924 foreach(l, ((ColumnRef *) node)->fields)
928 if (strcmp(strVal(i), "*") != 0)
938 case T_A_Indirection:
940 A_Indirection *ind = (A_Indirection *) node;
944 /* find last field name, if any, ignoring "*" */
945 foreach(l, ind->indirection)
949 if (IsA(i, String) &&
950 strcmp(strVal(i), "*") != 0)
958 return FigureColnameInternal(ind->arg, name);
962 *name = strVal(llast(((FuncCall *) node)->funcname));
965 /* make nullif() act like a regular function */
966 if (((A_Expr *) node)->kind == AEXPR_NULLIF)
973 if (((A_Const *) node)->typename != NULL)
975 *name = strVal(llast(((A_Const *) node)->typename->names));
980 strength = FigureColnameInternal(((TypeCast *) node)->arg,
984 if (((TypeCast *) node)->typename != NULL)
986 *name = strVal(llast(((TypeCast *) node)->typename->names));
992 strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1001 /* make ARRAY[] act like a function */
1005 /* make ROW() act like a function */
1008 case T_CoalesceExpr:
1009 /* make coalesce() act like a regular function */