1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2006, 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.151 2006/12/24 00:29:19 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_type.h"
18 #include "commands/dbcommands.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "parser/parsetree.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_expr.h"
25 #include "parser/parse_func.h"
26 #include "parser/parse_relation.h"
27 #include "parser/parse_target.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/typcache.h"
34 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
35 Var *var, int levelsup);
36 static Node *transformAssignmentIndirection(ParseState *pstate,
38 const char *targetName,
42 ListCell *indirection,
45 static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
47 static List *ExpandAllTables(ParseState *pstate);
48 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
50 static int FigureColnameInternal(Node *node, char **name);
54 * transformTargetEntry()
55 * Transform any ordinary "expression-type" node into a targetlist entry.
56 * This is exported so that parse_clause.c can generate targetlist entries
57 * for ORDER/GROUP BY items that are not already in the targetlist.
59 * node the (untransformed) parse tree for the value expression.
60 * expr the transformed expression, or NULL if caller didn't do it yet.
61 * colname the column name to be assigned, or NULL if none yet set.
62 * resjunk true if the target should be marked resjunk, ie, it is not
63 * wanted in the final projected tuple.
66 transformTargetEntry(ParseState *pstate,
72 /* Transform the node if caller didn't do it already */
74 expr = transformExpr(pstate, node);
76 if (colname == NULL && !resjunk)
79 * Generate a suitable column name for a column without any explicit
80 * 'AS ColumnName' clause.
82 colname = FigureColname(node);
85 return makeTargetEntry((Expr *) expr,
86 (AttrNumber) pstate->p_next_resno++,
93 * transformTargetList()
94 * Turns a list of ResTarget's into a list of TargetEntry's.
96 * At this point, we don't care whether we are doing SELECT, INSERT,
97 * or UPDATE; we just transform the given expressions (the "val" fields).
100 transformTargetList(ParseState *pstate, List *targetlist)
102 List *p_target = NIL;
105 foreach(o_target, targetlist)
107 ResTarget *res = (ResTarget *) lfirst(o_target);
110 * Check for "something.*". Depending on the complexity of the
111 * "something", the star could appear as the last name in ColumnRef,
112 * or as the last indirection item in A_Indirection.
114 if (IsA(res->val, ColumnRef))
116 ColumnRef *cref = (ColumnRef *) res->val;
118 if (strcmp(strVal(llast(cref->fields)), "*") == 0)
120 /* It is something.*, expand into multiple items */
121 p_target = list_concat(p_target,
122 ExpandColumnRefStar(pstate, cref,
127 else if (IsA(res->val, A_Indirection))
129 A_Indirection *ind = (A_Indirection *) res->val;
130 Node *lastitem = llast(ind->indirection);
132 if (IsA(lastitem, String) &&
133 strcmp(strVal(lastitem), "*") == 0)
135 /* It is something.*, expand into multiple items */
136 p_target = list_concat(p_target,
137 ExpandIndirectionStar(pstate, ind,
144 * Not "something.*", so transform as a single expression
146 p_target = lappend(p_target,
147 transformTargetEntry(pstate,
159 * transformExpressionList()
161 * This is the identical transformation to transformTargetList, except that
162 * the input list elements are bare expressions without ResTarget decoration,
163 * and the output elements are likewise just expressions without TargetEntry
164 * decoration. We use this for ROW() and VALUES() constructs.
167 transformExpressionList(ParseState *pstate, List *exprlist)
172 foreach(lc, exprlist)
174 Node *e = (Node *) lfirst(lc);
177 * Check for "something.*". Depending on the complexity of the
178 * "something", the star could appear as the last name in ColumnRef,
179 * or as the last indirection item in A_Indirection.
181 if (IsA(e, ColumnRef))
183 ColumnRef *cref = (ColumnRef *) e;
185 if (strcmp(strVal(llast(cref->fields)), "*") == 0)
187 /* It is something.*, expand into multiple items */
188 result = list_concat(result,
189 ExpandColumnRefStar(pstate, cref,
194 else if (IsA(e, A_Indirection))
196 A_Indirection *ind = (A_Indirection *) e;
197 Node *lastitem = llast(ind->indirection);
199 if (IsA(lastitem, String) &&
200 strcmp(strVal(lastitem), "*") == 0)
202 /* It is something.*, expand into multiple items */
203 result = list_concat(result,
204 ExpandIndirectionStar(pstate, ind,
211 * Not "something.*", so transform as a single expression
213 result = lappend(result,
214 transformExpr(pstate, e));
222 * markTargetListOrigins()
223 * Mark targetlist columns that are simple Vars with the source
224 * table's OID and column number.
226 * Currently, this is done only for SELECT targetlists, since we only
227 * need the info if we are going to send it to the frontend.
230 markTargetListOrigins(ParseState *pstate, List *targetlist)
234 foreach(l, targetlist)
236 TargetEntry *tle = (TargetEntry *) lfirst(l);
238 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
243 * markTargetListOrigin()
244 * If 'var' is a Var of a plain relation, mark 'tle' with its origin
246 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
248 * This is split out so it can recurse for join references. Note that we
249 * do not drill down into views, but report the view as the column owner.
252 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
253 Var *var, int levelsup)
259 if (var == NULL || !IsA(var, Var))
261 netlevelsup = var->varlevelsup + levelsup;
262 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
263 attnum = var->varattno;
265 switch (rte->rtekind)
268 /* It's a table or view, report it */
269 tle->resorigtbl = rte->relid;
270 tle->resorigcol = attnum;
273 /* Subselect-in-FROM: copy up from the subselect */
274 if (attnum != InvalidAttrNumber)
276 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
279 if (ste == NULL || ste->resjunk)
280 elog(ERROR, "subquery %s does not have attribute %d",
281 rte->eref->aliasname, attnum);
282 tle->resorigtbl = ste->resorigtbl;
283 tle->resorigcol = ste->resorigcol;
287 /* Join RTE --- recursively inspect the alias variable */
288 if (attnum != InvalidAttrNumber)
292 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
293 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
294 markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
300 /* not a simple relation, leave it unmarked */
307 * transformAssignedExpr()
308 * This is used in INSERT and UPDATE statements only. It prepares an
309 * expression for assignment to a column of the target table.
310 * This includes coercing the given value to the target column's type
311 * (if necessary), and dealing with any subfield names or subscripts
312 * attached to the target column itself. The input expression has
313 * already been through transformExpr().
316 * expr expression to be modified
317 * colname target column name (ie, name of attribute to be assigned to)
318 * attrno target attribute number
319 * indirection subscripts/field names for target column, if any
320 * location error cursor position, or -1
322 * Returns the modified expression.
325 transformAssignedExpr(ParseState *pstate,
332 Oid type_id; /* type of value provided */
333 Oid attrtype; /* type of target column */
335 Relation rd = pstate->p_target_relation;
340 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
341 errmsg("cannot assign to system column \"%s\"",
343 parser_errposition(pstate, location)));
344 attrtype = attnumTypeId(rd, attrno);
345 attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
348 * If the expression is a DEFAULT placeholder, insert the attribute's
349 * type/typmod into it so that exprType will report the right things. (We
350 * expect that the eventually substituted default expression will in fact
351 * have this type and typmod.) Also, reject trying to update a subfield
352 * or array element with DEFAULT, since there can't be any default for
353 * portions of a column.
355 if (expr && IsA(expr, SetToDefault))
357 SetToDefault *def = (SetToDefault *) expr;
359 def->typeId = attrtype;
360 def->typeMod = attrtypmod;
363 if (IsA(linitial(indirection), A_Indices))
365 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
366 errmsg("cannot set an array element to DEFAULT"),
367 parser_errposition(pstate, location)));
370 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
371 errmsg("cannot set a subfield to DEFAULT"),
372 parser_errposition(pstate, location)));
376 /* Now we can use exprType() safely. */
377 type_id = exprType((Node *) expr);
380 * If there is indirection on the target column, prepare an array or
381 * subfield assignment expression. This will generate a new column value
382 * that the source value has been inserted into, which can then be placed
383 * in the new tuple constructed by INSERT or UPDATE.
389 if (pstate->p_is_insert)
392 * The command is INSERT INTO table (col.something) ... so there
393 * is not really a source value to work with. Insert a NULL
394 * constant as the source value.
396 colVar = (Node *) makeNullConst(attrtype);
401 * Build a Var for the column to be updated.
403 colVar = (Node *) make_var(pstate,
404 pstate->p_target_rangetblentry,
409 transformAssignmentIndirection(pstate,
415 list_head(indirection),
422 * For normal non-qualified target column, do type checking and
426 coerce_to_target_type(pstate,
427 (Node *) expr, type_id,
428 attrtype, attrtypmod,
430 COERCE_IMPLICIT_CAST);
433 (errcode(ERRCODE_DATATYPE_MISMATCH),
434 errmsg("column \"%s\" is of type %s"
435 " but expression is of type %s",
437 format_type_be(attrtype),
438 format_type_be(type_id)),
439 errhint("You will need to rewrite or cast the expression."),
440 parser_errposition(pstate, location)));
448 * updateTargetListEntry()
449 * This is used in UPDATE statements only. It prepares an UPDATE
450 * TargetEntry for assignment to a column of the target table.
451 * This includes coercing the given value to the target column's type
452 * (if necessary), and dealing with any subfield names or subscripts
453 * attached to the target column itself.
456 * tle target list entry to be modified
457 * colname target column name (ie, name of attribute to be assigned to)
458 * attrno target attribute number
459 * indirection subscripts/field names for target column, if any
460 * location error cursor position (should point at column name), or -1
463 updateTargetListEntry(ParseState *pstate,
470 /* Fix up expression as needed */
471 tle->expr = transformAssignedExpr(pstate,
479 * Set the resno to identify the target column --- the rewriter and
480 * planner depend on this. We also set the resname to identify the target
481 * column, but this is only for debugging purposes; it should not be
482 * relied on. (In particular, it might be out of date in a stored rule.)
484 tle->resno = (AttrNumber) attrno;
485 tle->resname = colname;
490 * Process indirection (field selection or subscripting) of the target
491 * column in INSERT/UPDATE. This routine recurses for multiple levels
492 * of indirection --- but note that several adjacent A_Indices nodes in
493 * the indirection list are treated as a single multidimensional subscript
496 * In the initial call, basenode is a Var for the target column in UPDATE,
497 * or a null Const of the target's type in INSERT. In recursive calls,
498 * basenode is NULL, indicating that a substitute node should be consed up if
501 * targetName is the name of the field or subfield we're assigning to, and
502 * targetIsArray is true if we're subscripting it. These are just for
505 * targetTypeId and targetTypMod indicate the datatype of the object to
506 * be assigned to (initially the target column, later some subobject).
508 * indirection is the sublist remaining to process. When it's NULL, we're
509 * done recursing and can just coerce and return the RHS.
511 * rhs is the already-transformed value to be assigned; note it has not been
512 * coerced to any particular type.
514 * location is the cursor error position for any errors. (Note: this points
515 * to the head of the target clause, eg "foo" in "foo.bar[baz]". Later we
516 * might want to decorate indirection cells with their own location info,
517 * in which case the location argument could probably be dropped.)
520 transformAssignmentIndirection(ParseState *pstate,
522 const char *targetName,
526 ListCell *indirection,
531 List *subscripts = NIL;
532 bool isSlice = false;
535 if (indirection && !basenode)
537 /* Set up a substitution. We reuse CaseTestExpr for this. */
538 CaseTestExpr *ctest = makeNode(CaseTestExpr);
540 ctest->typeId = targetTypeId;
541 ctest->typeMod = targetTypMod;
542 basenode = (Node *) ctest;
546 * We have to split any field-selection operations apart from
547 * subscripting. Adjacent A_Indices nodes have to be treated as a single
548 * multidimensional subscript operation.
550 for_each_cell(i, indirection)
554 if (IsA(n, A_Indices))
556 subscripts = lappend(subscripts, n);
557 if (((A_Indices *) n)->lidx != NULL)
568 Assert(IsA(n, String));
570 /* process subscripts before this field selection */
573 Oid elementTypeId = transformArrayType(targetTypeId);
574 Oid typeNeeded = isSlice ? targetTypeId : elementTypeId;
576 /* recurse to create appropriate RHS for array assign */
577 rhs = transformAssignmentIndirection(pstate,
586 /* process subscripts */
587 return (Node *) transformArraySubscripts(pstate,
596 /* No subscripts, so can process field selection here */
598 typrelid = typeidTypeRelid(targetTypeId);
601 (errcode(ERRCODE_DATATYPE_MISMATCH),
602 errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
603 strVal(n), targetName,
604 format_type_be(targetTypeId)),
605 parser_errposition(pstate, location)));
607 attnum = get_attnum(typrelid, strVal(n));
608 if (attnum == InvalidAttrNumber)
610 (errcode(ERRCODE_UNDEFINED_COLUMN),
611 errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
612 strVal(n), targetName,
613 format_type_be(targetTypeId)),
614 parser_errposition(pstate, location)));
617 (errcode(ERRCODE_UNDEFINED_COLUMN),
618 errmsg("cannot assign to system column \"%s\"",
620 parser_errposition(pstate, location)));
622 get_atttypetypmod(typrelid, attnum,
623 &fieldTypeId, &fieldTypMod);
625 /* recurse to create appropriate RHS for field assign */
626 rhs = transformAssignmentIndirection(pstate,
636 /* and build a FieldStore node */
637 fstore = makeNode(FieldStore);
638 fstore->arg = (Expr *) basenode;
639 fstore->newvals = list_make1(rhs);
640 fstore->fieldnums = list_make1_int(attnum);
641 fstore->resulttype = targetTypeId;
643 return (Node *) fstore;
647 /* process trailing subscripts, if any */
650 Oid elementTypeId = transformArrayType(targetTypeId);
651 Oid typeNeeded = isSlice ? targetTypeId : elementTypeId;
653 /* recurse to create appropriate RHS for array assign */
654 rhs = transformAssignmentIndirection(pstate,
663 /* process subscripts */
664 return (Node *) transformArraySubscripts(pstate,
673 /* base case: just coerce RHS to match target type ID */
675 result = coerce_to_target_type(pstate,
677 targetTypeId, targetTypMod,
679 COERCE_IMPLICIT_CAST);
684 (errcode(ERRCODE_DATATYPE_MISMATCH),
685 errmsg("array assignment to \"%s\" requires type %s"
686 " but expression is of type %s",
688 format_type_be(targetTypeId),
689 format_type_be(exprType(rhs))),
690 errhint("You will need to rewrite or cast the expression."),
691 parser_errposition(pstate, location)));
694 (errcode(ERRCODE_DATATYPE_MISMATCH),
695 errmsg("subfield \"%s\" is of type %s"
696 " but expression is of type %s",
698 format_type_be(targetTypeId),
699 format_type_be(exprType(rhs))),
700 errhint("You will need to rewrite or cast the expression."),
701 parser_errposition(pstate, location)));
709 * checkInsertTargets -
710 * generate a list of INSERT column targets if not supplied, or
711 * test supplied column names to make sure they are in target table.
712 * Also return an integer list of the columns' attribute numbers.
715 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
722 * Generate default column list for INSERT.
724 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
725 int numcol = pstate->p_target_relation->rd_rel->relnatts;
728 for (i = 0; i < numcol; i++)
732 if (attr[i]->attisdropped)
735 col = makeNode(ResTarget);
736 col->name = pstrdup(NameStr(attr[i]->attname));
737 col->indirection = NIL;
740 cols = lappend(cols, col);
741 *attrnos = lappend_int(*attrnos, i + 1);
747 * Do initial validation of user-supplied INSERT column list.
749 Bitmapset *wholecols = NULL;
750 Bitmapset *partialcols = NULL;
755 ResTarget *col = (ResTarget *) lfirst(tl);
756 char *name = col->name;
759 /* Lookup column name, ereport on failure */
760 attrno = attnameAttNum(pstate->p_target_relation, name, false);
761 if (attrno == InvalidAttrNumber)
763 (errcode(ERRCODE_UNDEFINED_COLUMN),
764 errmsg("column \"%s\" of relation \"%s\" does not exist",
766 RelationGetRelationName(pstate->p_target_relation)),
767 parser_errposition(pstate, col->location)));
770 * Check for duplicates, but only of whole columns --- we allow
771 * INSERT INTO foo (col.subcol1, col.subcol2)
773 if (col->indirection == NIL)
775 /* whole column; must not have any other assignment */
776 if (bms_is_member(attrno, wholecols) ||
777 bms_is_member(attrno, partialcols))
779 (errcode(ERRCODE_DUPLICATE_COLUMN),
780 errmsg("column \"%s\" specified more than once",
782 parser_errposition(pstate, col->location)));
783 wholecols = bms_add_member(wholecols, attrno);
787 /* partial column; must not have any whole assignment */
788 if (bms_is_member(attrno, wholecols))
790 (errcode(ERRCODE_DUPLICATE_COLUMN),
791 errmsg("column \"%s\" specified more than once",
793 parser_errposition(pstate, col->location)));
794 partialcols = bms_add_member(partialcols, attrno);
797 *attrnos = lappend_int(*attrnos, attrno);
805 * ExpandColumnRefStar()
806 * Transforms foo.* into a list of expressions or targetlist entries.
808 * This handles the case where '*' appears as the last or only name in a
809 * ColumnRef. The code is shared between the case of foo.* at the top level
810 * in a SELECT target list (where we want TargetEntry nodes in the result)
811 * and foo.* in a ROW() or VALUES() construct (where we want just bare
815 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
818 List *fields = cref->fields;
819 int numnames = list_length(fields);
824 * Target item is a bare '*', expand all tables
826 * (e.g., SELECT * FROM emp, dept)
828 * Since the grammar only accepts bare '*' at top level of SELECT, we
829 * need not handle the targetlist==false case here.
833 return ExpandAllTables(pstate);
838 * Target item is relation.*, expand that table
840 * (e.g., SELECT emp.*, dname FROM emp, dept)
852 relname = strVal(linitial(fields));
855 schemaname = strVal(linitial(fields));
856 relname = strVal(lsecond(fields));
860 char *name1 = strVal(linitial(fields));
863 * We check the catalog name and then ignore it.
865 if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
867 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
868 errmsg("cross-database references are not implemented: %s",
869 NameListToString(fields)),
870 parser_errposition(pstate, cref->location)));
871 schemaname = strVal(lsecond(fields));
872 relname = strVal(lthird(fields));
877 (errcode(ERRCODE_SYNTAX_ERROR),
878 errmsg("improper qualified name (too many dotted names): %s",
879 NameListToString(fields)),
880 parser_errposition(pstate, cref->location)));
881 schemaname = NULL; /* keep compiler quiet */
886 rte = refnameRangeTblEntry(pstate, schemaname, relname,
889 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, relname),
892 /* Require read access --- see comments in setTargetTable() */
893 rte->requiredPerms |= ACL_SELECT;
895 rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
898 return expandRelAttrs(pstate, rte, rtindex, sublevels_up);
903 expandRTE(rte, rtindex, sublevels_up, false,
912 * Transforms '*' (in the target list) into a list of targetlist entries.
914 * tlist entries are generated for each relation appearing in the query's
915 * varnamespace. We do not consider relnamespace because that would include
916 * input tables of aliasless JOINs, NEW/OLD pseudo-entries, implicit RTEs,
920 ExpandAllTables(ParseState *pstate)
925 /* Check for SELECT *; */
926 if (!pstate->p_varnamespace)
928 (errcode(ERRCODE_SYNTAX_ERROR),
929 errmsg("SELECT * with no tables specified is not valid")));
931 foreach(l, pstate->p_varnamespace)
933 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
934 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
936 /* Require read access --- see comments in setTargetTable() */
937 rte->requiredPerms |= ACL_SELECT;
939 target = list_concat(target,
940 expandRelAttrs(pstate, rte, rtindex, 0));
947 * ExpandIndirectionStar()
948 * Transforms foo.* into a list of expressions or targetlist entries.
950 * This handles the case where '*' appears as the last item in A_Indirection.
951 * The code is shared between the case of foo.* at the top level in a SELECT
952 * target list (where we want TargetEntry nodes in the result) and foo.* in
953 * a ROW() or VALUES() construct (where we want just bare expressions).
956 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
965 /* Strip off the '*' to create a reference to the rowtype object */
966 ind = copyObject(ind);
967 ind->indirection = list_truncate(ind->indirection,
968 list_length(ind->indirection) - 1);
970 /* And transform that */
971 expr = transformExpr(pstate, (Node *) ind);
974 * Verify it's a composite type, and get the tupdesc. We use
975 * get_expr_result_type() because that can handle references to functions
976 * returning anonymous record types. If that fails, use
977 * lookup_rowtype_tupdesc(), which will almost certainly fail as well, but
978 * it will give an appropriate error message.
980 * If it's a Var of type RECORD, we have to work even harder: we have to
981 * find what the Var refers to, and pass that to get_expr_result_type.
982 * That task is handled by expandRecordVariable().
984 if (IsA(expr, Var) &&
985 ((Var *) expr)->vartype == RECORDOID)
986 tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
987 else if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
988 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
992 /* Generate a list of references to the individual fields */
993 numAttrs = tupleDesc->natts;
994 for (i = 0; i < numAttrs; i++)
996 Form_pg_attribute att = tupleDesc->attrs[i];
999 if (att->attisdropped)
1003 * If we got a whole-row Var from the rowtype reference, we can expand
1004 * the fields as simple Vars. Otherwise we must generate multiple
1005 * copies of the rowtype reference and do FieldSelects.
1007 if (IsA(expr, Var) &&
1008 ((Var *) expr)->varattno == InvalidAttrNumber)
1010 Var *var = (Var *) expr;
1012 fieldnode = (Node *) makeVar(var->varno,
1020 FieldSelect *fselect = makeNode(FieldSelect);
1022 fselect->arg = (Expr *) copyObject(expr);
1023 fselect->fieldnum = i + 1;
1024 fselect->resulttype = att->atttypid;
1025 fselect->resulttypmod = att->atttypmod;
1027 fieldnode = (Node *) fselect;
1032 /* add TargetEntry decoration */
1035 te = makeTargetEntry((Expr *) fieldnode,
1036 (AttrNumber) pstate->p_next_resno++,
1037 pstrdup(NameStr(att->attname)),
1039 result = lappend(result, te);
1042 result = lappend(result, fieldnode);
1049 * expandRecordVariable
1050 * Get the tuple descriptor for a Var of type RECORD, if possible.
1052 * Since no actual table or view column is allowed to have type RECORD, such
1053 * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
1054 * drill down to find the ultimate defining expression and attempt to infer
1055 * the tupdesc from it. We ereport if we can't determine the tupdesc.
1057 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1060 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1062 TupleDesc tupleDesc;
1068 /* Check my caller didn't mess up */
1069 Assert(IsA(var, Var));
1070 Assert(var->vartype == RECORDOID);
1072 netlevelsup = var->varlevelsup + levelsup;
1073 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1074 attnum = var->varattno;
1076 if (attnum == InvalidAttrNumber)
1078 /* Whole-row reference to an RTE, so expand the known fields */
1085 expandRTE(rte, var->varno, 0, false,
1088 tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1090 forboth(lname, names, lvar, vars)
1092 char *label = strVal(lfirst(lname));
1093 Node *varnode = (Node *) lfirst(lvar);
1095 TupleDescInitEntry(tupleDesc, i,
1098 exprTypmod(varnode),
1102 Assert(lname == NULL && lvar == NULL); /* lists same length? */
1107 expr = (Node *) var; /* default if we can't drill down */
1109 switch (rte->rtekind)
1116 * This case should not occur: a column of a table or values list
1117 * shouldn't have type RECORD. Fall through and fail (most
1118 * likely) at the bottom.
1123 /* Subselect-in-FROM: examine sub-select's output expr */
1124 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1127 if (ste == NULL || ste->resjunk)
1128 elog(ERROR, "subquery %s does not have attribute %d",
1129 rte->eref->aliasname, attnum);
1130 expr = (Node *) ste->expr;
1134 * Recurse into the sub-select to see what its Var refers
1135 * to. We have to build an additional level of ParseState
1136 * to keep in step with varlevelsup in the subselect.
1138 ParseState mypstate;
1140 MemSet(&mypstate, 0, sizeof(mypstate));
1141 mypstate.parentParseState = pstate;
1142 mypstate.p_rtable = rte->subquery->rtable;
1143 /* don't bother filling the rest of the fake pstate */
1145 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1147 /* else fall through to inspect the expression */
1151 /* Join RTE --- recursively inspect the alias variable */
1152 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1153 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1155 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1156 /* else fall through to inspect the expression */
1161 * We couldn't get here unless a function is declared with one of
1162 * its result columns as RECORD, which is not allowed.
1168 * We now have an expression we can't expand any more, so see if
1169 * get_expr_result_type() can do anything with it. If not, pass to
1170 * lookup_rowtype_tupdesc() which will probably fail, but will give an
1171 * appropriate error message while failing.
1173 if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1174 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1183 * if the name of the resulting column is not specified in the target
1184 * list, we have to guess a suitable name. The SQL spec provides some
1185 * guidance, but not much...
1187 * Note that the argument is the *untransformed* parse tree for the target
1188 * item. This is a shade easier to work with than the transformed tree.
1191 FigureColname(Node *node)
1195 FigureColnameInternal(node, &name);
1198 /* default result if we can't guess anything */
1203 FigureColnameInternal(Node *node, char **name)
1210 switch (nodeTag(node))
1217 /* find last field name, if any, ignoring "*" */
1218 foreach(l, ((ColumnRef *) node)->fields)
1220 Node *i = lfirst(l);
1222 if (strcmp(strVal(i), "*") != 0)
1232 case T_A_Indirection:
1234 A_Indirection *ind = (A_Indirection *) node;
1238 /* find last field name, if any, ignoring "*" */
1239 foreach(l, ind->indirection)
1241 Node *i = lfirst(l);
1243 if (IsA(i, String) &&
1244 strcmp(strVal(i), "*") != 0)
1252 return FigureColnameInternal(ind->arg, name);
1256 *name = strVal(llast(((FuncCall *) node)->funcname));
1259 /* make nullif() act like a regular function */
1260 if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1267 if (((A_Const *) node)->typename != NULL)
1269 *name = strVal(llast(((A_Const *) node)->typename->names));
1274 strength = FigureColnameInternal(((TypeCast *) node)->arg,
1278 if (((TypeCast *) node)->typename != NULL)
1280 *name = strVal(llast(((TypeCast *) node)->typename->names));
1286 strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1295 /* make ARRAY[] act like a function */
1299 /* make ROW() act like a function */
1302 case T_CoalesceExpr:
1303 /* make coalesce() act like a regular function */
1307 /* make greatest/least act like a regular function */
1308 switch (((MinMaxExpr *) node)->op)
1319 /* make SQL/XML functions act like a regular function */
1320 switch (((XmlExpr*) node)->op)
1323 *name = "xmlconcat";
1326 *name = "xmlelement";
1329 *name = "xmlforest";