1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2015, 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/rel.h"
33 #include "utils/typcache.h"
36 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
37 Var *var, int levelsup);
38 static Node *transformAssignmentIndirection(ParseState *pstate,
40 const char *targetName,
45 ListCell *indirection,
48 static Node *transformAssignmentSubscripts(ParseState *pstate,
50 const char *targetName,
56 ListCell *next_indirection,
59 static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
60 bool make_target_entry);
61 static List *ExpandAllTables(ParseState *pstate, int location);
62 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
63 bool make_target_entry, ParseExprKind exprKind);
64 static List *ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
65 int location, bool make_target_entry);
66 static List *ExpandRowReference(ParseState *pstate, Node *expr,
67 bool make_target_entry);
68 static int FigureColnameInternal(Node *node, char **name);
72 * transformTargetEntry()
73 * Transform any ordinary "expression-type" node into a targetlist entry.
74 * This is exported so that parse_clause.c can generate targetlist entries
75 * for ORDER/GROUP BY items that are not already in the targetlist.
77 * node the (untransformed) parse tree for the value expression.
78 * expr the transformed expression, or NULL if caller didn't do it yet.
79 * exprKind expression kind (EXPR_KIND_SELECT_TARGET, etc)
80 * colname the column name to be assigned, or NULL if none yet set.
81 * resjunk true if the target should be marked resjunk, ie, it is not
82 * wanted in the final projected tuple.
85 transformTargetEntry(ParseState *pstate,
88 ParseExprKind exprKind,
92 /* Transform the node if caller didn't do it already */
94 expr = transformExpr(pstate, node, exprKind);
96 if (colname == NULL && !resjunk)
99 * Generate a suitable column name for a column without any explicit
100 * 'AS ColumnName' clause.
102 colname = FigureColname(node);
105 return makeTargetEntry((Expr *) expr,
106 (AttrNumber) pstate->p_next_resno++,
113 * transformTargetList()
114 * Turns a list of ResTarget's into a list of TargetEntry's.
116 * This code acts mostly the same for SELECT, UPDATE, or RETURNING lists;
117 * the main thing is to transform the given expressions (the "val" fields).
118 * The exprKind parameter distinguishes these cases when necesssary.
121 transformTargetList(ParseState *pstate, List *targetlist,
122 ParseExprKind exprKind)
124 List *p_target = NIL;
127 /* Shouldn't have any leftover multiassign items at start */
128 Assert(pstate->p_multiassign_exprs == NIL);
130 foreach(o_target, targetlist)
132 ResTarget *res = (ResTarget *) lfirst(o_target);
135 * Check for "something.*". Depending on the complexity of the
136 * "something", the star could appear as the last field in ColumnRef,
137 * or as the last indirection item in A_Indirection.
139 if (IsA(res->val, ColumnRef))
141 ColumnRef *cref = (ColumnRef *) res->val;
143 if (IsA(llast(cref->fields), A_Star))
145 /* It is something.*, expand into multiple items */
146 p_target = list_concat(p_target,
147 ExpandColumnRefStar(pstate, cref,
152 else if (IsA(res->val, A_Indirection))
154 A_Indirection *ind = (A_Indirection *) res->val;
156 if (IsA(llast(ind->indirection), A_Star))
158 /* It is something.*, expand into multiple items */
159 p_target = list_concat(p_target,
160 ExpandIndirectionStar(pstate, ind,
167 * Not "something.*", so transform as a single expression
169 p_target = lappend(p_target,
170 transformTargetEntry(pstate,
179 * If any multiassign resjunk items were created, attach them to the end
180 * of the targetlist. This should only happen in an UPDATE tlist. We
181 * don't need to worry about numbering of these items; transformUpdateStmt
182 * will set their resnos.
184 if (pstate->p_multiassign_exprs)
186 Assert(exprKind == EXPR_KIND_UPDATE_SOURCE);
187 p_target = list_concat(p_target, pstate->p_multiassign_exprs);
188 pstate->p_multiassign_exprs = NIL;
196 * transformExpressionList()
198 * This is the identical transformation to transformTargetList, except that
199 * the input list elements are bare expressions without ResTarget decoration,
200 * and the output elements are likewise just expressions without TargetEntry
201 * decoration. We use this for ROW() and VALUES() constructs.
204 transformExpressionList(ParseState *pstate, List *exprlist,
205 ParseExprKind exprKind)
210 foreach(lc, exprlist)
212 Node *e = (Node *) lfirst(lc);
215 * Check for "something.*". Depending on the complexity of the
216 * "something", the star could appear as the last field in ColumnRef,
217 * or as the last indirection item in A_Indirection.
219 if (IsA(e, ColumnRef))
221 ColumnRef *cref = (ColumnRef *) e;
223 if (IsA(llast(cref->fields), A_Star))
225 /* It is something.*, expand into multiple items */
226 result = list_concat(result,
227 ExpandColumnRefStar(pstate, cref,
232 else if (IsA(e, A_Indirection))
234 A_Indirection *ind = (A_Indirection *) e;
236 if (IsA(llast(ind->indirection), A_Star))
238 /* It is something.*, expand into multiple items */
239 result = list_concat(result,
240 ExpandIndirectionStar(pstate, ind,
247 * Not "something.*", so transform as a single expression
249 result = lappend(result,
250 transformExpr(pstate, e, exprKind));
253 /* Shouldn't have any multiassign items here */
254 Assert(pstate->p_multiassign_exprs == NIL);
261 * markTargetListOrigins()
262 * Mark targetlist columns that are simple Vars with the source
263 * table's OID and column number.
265 * Currently, this is done only for SELECT targetlists, since we only
266 * need the info if we are going to send it to the frontend.
269 markTargetListOrigins(ParseState *pstate, List *targetlist)
273 foreach(l, targetlist)
275 TargetEntry *tle = (TargetEntry *) lfirst(l);
277 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
282 * markTargetListOrigin()
283 * If 'var' is a Var of a plain relation, mark 'tle' with its origin
285 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
287 * This is split out so it can recurse for join references. Note that we
288 * do not drill down into views, but report the view as the column owner.
291 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
292 Var *var, int levelsup)
298 if (var == NULL || !IsA(var, Var))
300 netlevelsup = var->varlevelsup + levelsup;
301 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
302 attnum = var->varattno;
304 switch (rte->rtekind)
307 /* It's a table or view, report it */
308 tle->resorigtbl = rte->relid;
309 tle->resorigcol = attnum;
312 /* Subselect-in-FROM: copy up from the subselect */
313 if (attnum != InvalidAttrNumber)
315 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
318 if (ste == NULL || ste->resjunk)
319 elog(ERROR, "subquery %s does not have attribute %d",
320 rte->eref->aliasname, attnum);
321 tle->resorigtbl = ste->resorigtbl;
322 tle->resorigcol = ste->resorigcol;
326 /* Join RTE --- recursively inspect the alias variable */
327 if (attnum != InvalidAttrNumber)
331 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
332 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
333 /* We intentionally don't strip implicit coercions here */
334 markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
339 /* not a simple relation, leave it unmarked */
344 * CTE reference: copy up from the subquery, if possible. If the
345 * RTE is a recursive self-reference then we can't do anything
346 * because we haven't finished analyzing it yet. However, it's no
347 * big loss because we must be down inside the recursive term of a
348 * recursive CTE, and so any markings on the current targetlist
349 * are not going to affect the results anyway.
351 if (attnum != InvalidAttrNumber && !rte->self_reference)
353 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
356 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
357 if (ste == NULL || ste->resjunk)
358 elog(ERROR, "subquery %s does not have attribute %d",
359 rte->eref->aliasname, attnum);
360 tle->resorigtbl = ste->resorigtbl;
361 tle->resorigcol = ste->resorigcol;
369 * transformAssignedExpr()
370 * This is used in INSERT and UPDATE statements only. It prepares an
371 * expression for assignment to a column of the target table.
372 * This includes coercing the given value to the target column's type
373 * (if necessary), and dealing with any subfield names or subscripts
374 * attached to the target column itself. The input expression has
375 * already been through transformExpr().
378 * expr expression to be modified
379 * exprKind indicates which type of statement we're dealing with
380 * colname target column name (ie, name of attribute to be assigned to)
381 * attrno target attribute number
382 * indirection subscripts/field names for target column, if any
383 * location error cursor position for the target column, or -1
385 * Returns the modified expression.
387 * Note: location points at the target column name (SET target or INSERT
388 * column name list entry), and must therefore be -1 in an INSERT that
389 * omits the column name list. So we should usually prefer to use
390 * exprLocation(expr) for errors that can happen in a default INSERT.
393 transformAssignedExpr(ParseState *pstate,
395 ParseExprKind exprKind,
401 Relation rd = pstate->p_target_relation;
402 Oid type_id; /* type of value provided */
403 Oid attrtype; /* type of target column */
405 Oid attrcollation; /* collation of target column */
406 ParseExprKind sv_expr_kind;
409 * Save and restore identity of expression type we're parsing. We must
410 * set p_expr_kind here because we can parse subscripts without going
411 * through transformExpr().
413 Assert(exprKind != EXPR_KIND_NONE);
414 sv_expr_kind = pstate->p_expr_kind;
415 pstate->p_expr_kind = exprKind;
420 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
421 errmsg("cannot assign to system column \"%s\"",
423 parser_errposition(pstate, location)));
424 attrtype = attnumTypeId(rd, attrno);
425 attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
426 attrcollation = rd->rd_att->attrs[attrno - 1]->attcollation;
429 * If the expression is a DEFAULT placeholder, insert the attribute's
430 * type/typmod/collation into it so that exprType etc will report the
431 * right things. (We expect that the eventually substituted default
432 * expression will in fact have this type and typmod. The collation
433 * likely doesn't matter, but let's set it correctly anyway.) Also,
434 * reject trying to update a subfield or array element with DEFAULT, since
435 * there can't be any default for portions of a column.
437 if (expr && IsA(expr, SetToDefault))
439 SetToDefault *def = (SetToDefault *) expr;
441 def->typeId = attrtype;
442 def->typeMod = attrtypmod;
443 def->collation = attrcollation;
446 if (IsA(linitial(indirection), A_Indices))
448 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
449 errmsg("cannot set an array element to DEFAULT"),
450 parser_errposition(pstate, location)));
453 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
454 errmsg("cannot set a subfield to DEFAULT"),
455 parser_errposition(pstate, location)));
459 /* Now we can use exprType() safely. */
460 type_id = exprType((Node *) expr);
463 * If there is indirection on the target column, prepare an array or
464 * subfield assignment expression. This will generate a new column value
465 * that the source value has been inserted into, which can then be placed
466 * in the new tuple constructed by INSERT or UPDATE.
472 if (pstate->p_is_insert)
475 * The command is INSERT INTO table (col.something) ... so there
476 * is not really a source value to work with. Insert a NULL
477 * constant as the source value.
479 colVar = (Node *) makeNullConst(attrtype, attrtypmod,
485 * Build a Var for the column to be updated.
487 colVar = (Node *) make_var(pstate,
488 pstate->p_target_rangetblentry,
494 transformAssignmentIndirection(pstate,
501 list_head(indirection),
508 * For normal non-qualified target column, do type checking and
511 Node *orig_expr = (Node *) expr;
514 coerce_to_target_type(pstate,
516 attrtype, attrtypmod,
518 COERCE_IMPLICIT_CAST,
522 (errcode(ERRCODE_DATATYPE_MISMATCH),
523 errmsg("column \"%s\" is of type %s"
524 " but expression is of type %s",
526 format_type_be(attrtype),
527 format_type_be(type_id)),
528 errhint("You will need to rewrite or cast the expression."),
529 parser_errposition(pstate, exprLocation(orig_expr))));
532 pstate->p_expr_kind = sv_expr_kind;
539 * updateTargetListEntry()
540 * This is used in UPDATE statements (and ON CONFLICT DO UPDATE)
541 * only. It prepares an UPDATE TargetEntry for assignment to a
542 * column of the target table. This includes coercing the given
543 * value to the target column's type (if necessary), and dealing with
544 * any subfield names or subscripts attached to the target column
548 * tle target list entry to be modified
549 * colname target column name (ie, name of attribute to be assigned to)
550 * attrno target attribute number
551 * indirection subscripts/field names for target column, if any
552 * location error cursor position (should point at column name), or -1
555 updateTargetListEntry(ParseState *pstate,
562 /* Fix up expression as needed */
563 tle->expr = transformAssignedExpr(pstate,
565 EXPR_KIND_UPDATE_TARGET,
572 * Set the resno to identify the target column --- the rewriter and
573 * planner depend on this. We also set the resname to identify the target
574 * column, but this is only for debugging purposes; it should not be
575 * relied on. (In particular, it might be out of date in a stored rule.)
577 tle->resno = (AttrNumber) attrno;
578 tle->resname = colname;
583 * Process indirection (field selection or subscripting) of the target
584 * column in INSERT/UPDATE. This routine recurses for multiple levels
585 * of indirection --- but note that several adjacent A_Indices nodes in
586 * the indirection list are treated as a single multidimensional subscript
589 * In the initial call, basenode is a Var for the target column in UPDATE,
590 * or a null Const of the target's type in INSERT. In recursive calls,
591 * basenode is NULL, indicating that a substitute node should be consed up if
594 * targetName is the name of the field or subfield we're assigning to, and
595 * targetIsArray is true if we're subscripting it. These are just for
598 * targetTypeId, targetTypMod, targetCollation indicate the datatype and
599 * collation of the object to be assigned to (initially the target column,
600 * later some subobject).
602 * indirection is the sublist remaining to process. When it's NULL, we're
603 * done recursing and can just coerce and return the RHS.
605 * rhs is the already-transformed value to be assigned; note it has not been
606 * coerced to any particular type.
608 * location is the cursor error position for any errors. (Note: this points
609 * to the head of the target clause, eg "foo" in "foo.bar[baz]". Later we
610 * might want to decorate indirection cells with their own location info,
611 * in which case the location argument could probably be dropped.)
614 transformAssignmentIndirection(ParseState *pstate,
616 const char *targetName,
621 ListCell *indirection,
626 List *subscripts = NIL;
627 bool isSlice = false;
630 if (indirection && !basenode)
632 /* Set up a substitution. We reuse CaseTestExpr for this. */
633 CaseTestExpr *ctest = makeNode(CaseTestExpr);
635 ctest->typeId = targetTypeId;
636 ctest->typeMod = targetTypMod;
637 ctest->collation = targetCollation;
638 basenode = (Node *) ctest;
642 * We have to split any field-selection operations apart from
643 * subscripting. Adjacent A_Indices nodes have to be treated as a single
644 * multidimensional subscript operation.
646 for_each_cell(i, indirection)
650 if (IsA(n, A_Indices))
652 subscripts = lappend(subscripts, n);
653 if (((A_Indices *) n)->lidx != NULL)
656 else if (IsA(n, A_Star))
659 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
660 errmsg("row expansion via \"*\" is not supported here"),
661 parser_errposition(pstate, location)));
672 Assert(IsA(n, String));
674 /* process subscripts before this field selection */
677 /* recurse, and then return because we're done */
678 return transformAssignmentSubscripts(pstate,
691 /* No subscripts, so can process field selection here */
693 typrelid = typeidTypeRelid(targetTypeId);
696 (errcode(ERRCODE_DATATYPE_MISMATCH),
697 errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
698 strVal(n), targetName,
699 format_type_be(targetTypeId)),
700 parser_errposition(pstate, location)));
702 attnum = get_attnum(typrelid, strVal(n));
703 if (attnum == InvalidAttrNumber)
705 (errcode(ERRCODE_UNDEFINED_COLUMN),
706 errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
707 strVal(n), targetName,
708 format_type_be(targetTypeId)),
709 parser_errposition(pstate, location)));
712 (errcode(ERRCODE_UNDEFINED_COLUMN),
713 errmsg("cannot assign to system column \"%s\"",
715 parser_errposition(pstate, location)));
717 get_atttypetypmodcoll(typrelid, attnum,
718 &fieldTypeId, &fieldTypMod, &fieldCollation);
720 /* recurse to create appropriate RHS for field assign */
721 rhs = transformAssignmentIndirection(pstate,
732 /* and build a FieldStore node */
733 fstore = makeNode(FieldStore);
734 fstore->arg = (Expr *) basenode;
735 fstore->newvals = list_make1(rhs);
736 fstore->fieldnums = list_make1_int(attnum);
737 fstore->resulttype = targetTypeId;
739 return (Node *) fstore;
743 /* process trailing subscripts, if any */
746 /* recurse, and then return because we're done */
747 return transformAssignmentSubscripts(pstate,
760 /* base case: just coerce RHS to match target type ID */
762 result = coerce_to_target_type(pstate,
764 targetTypeId, targetTypMod,
766 COERCE_IMPLICIT_CAST,
772 (errcode(ERRCODE_DATATYPE_MISMATCH),
773 errmsg("array assignment to \"%s\" requires type %s"
774 " but expression is of type %s",
776 format_type_be(targetTypeId),
777 format_type_be(exprType(rhs))),
778 errhint("You will need to rewrite or cast the expression."),
779 parser_errposition(pstate, location)));
782 (errcode(ERRCODE_DATATYPE_MISMATCH),
783 errmsg("subfield \"%s\" is of type %s"
784 " but expression is of type %s",
786 format_type_be(targetTypeId),
787 format_type_be(exprType(rhs))),
788 errhint("You will need to rewrite or cast the expression."),
789 parser_errposition(pstate, location)));
796 * helper for transformAssignmentIndirection: process array assignment
799 transformAssignmentSubscripts(ParseState *pstate,
801 const char *targetName,
807 ListCell *next_indirection,
818 Assert(subscripts != NIL);
820 /* Identify the actual array type and element type involved */
821 arrayType = targetTypeId;
822 arrayTypMod = targetTypMod;
823 elementTypeId = transformArrayType(&arrayType, &arrayTypMod);
825 /* Identify type that RHS must provide */
826 typeNeeded = isSlice ? arrayType : elementTypeId;
829 * Array normally has same collation as elements, but there's an
830 * exception: we might be subscripting a domain over an array type. In
831 * that case use collation of the base type.
833 if (arrayType == targetTypeId)
834 collationNeeded = targetCollation;
836 collationNeeded = get_typcollation(arrayType);
838 /* recurse to create appropriate RHS for array assign */
839 rhs = transformAssignmentIndirection(pstate,
850 /* process subscripts */
851 result = (Node *) transformArraySubscripts(pstate,
859 /* If target was a domain over array, need to coerce up to the domain */
860 if (arrayType != targetTypeId)
862 Oid resulttype = exprType(result);
864 result = coerce_to_target_type(pstate,
866 targetTypeId, targetTypMod,
868 COERCE_IMPLICIT_CAST,
870 /* can fail if we had int2vector/oidvector, but not for true domains */
873 (errcode(ERRCODE_CANNOT_COERCE),
874 errmsg("cannot cast type %s to %s",
875 format_type_be(resulttype),
876 format_type_be(targetTypeId)),
877 parser_errposition(pstate, location)));
885 * checkInsertTargets -
886 * generate a list of INSERT column targets if not supplied, or
887 * test supplied column names to make sure they are in target table.
888 * Also return an integer list of the columns' attribute numbers.
891 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
898 * Generate default column list for INSERT.
900 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
901 int numcol = pstate->p_target_relation->rd_rel->relnatts;
904 for (i = 0; i < numcol; i++)
908 if (attr[i]->attisdropped)
911 col = makeNode(ResTarget);
912 col->name = pstrdup(NameStr(attr[i]->attname));
913 col->indirection = NIL;
916 cols = lappend(cols, col);
917 *attrnos = lappend_int(*attrnos, i + 1);
923 * Do initial validation of user-supplied INSERT column list.
925 Bitmapset *wholecols = NULL;
926 Bitmapset *partialcols = NULL;
931 ResTarget *col = (ResTarget *) lfirst(tl);
932 char *name = col->name;
935 /* Lookup column name, ereport on failure */
936 attrno = attnameAttNum(pstate->p_target_relation, name, false);
937 if (attrno == InvalidAttrNumber)
939 (errcode(ERRCODE_UNDEFINED_COLUMN),
940 errmsg("column \"%s\" of relation \"%s\" does not exist",
942 RelationGetRelationName(pstate->p_target_relation)),
943 parser_errposition(pstate, col->location)));
946 * Check for duplicates, but only of whole columns --- we allow
947 * INSERT INTO foo (col.subcol1, col.subcol2)
949 if (col->indirection == NIL)
951 /* whole column; must not have any other assignment */
952 if (bms_is_member(attrno, wholecols) ||
953 bms_is_member(attrno, partialcols))
955 (errcode(ERRCODE_DUPLICATE_COLUMN),
956 errmsg("column \"%s\" specified more than once",
958 parser_errposition(pstate, col->location)));
959 wholecols = bms_add_member(wholecols, attrno);
963 /* partial column; must not have any whole assignment */
964 if (bms_is_member(attrno, wholecols))
966 (errcode(ERRCODE_DUPLICATE_COLUMN),
967 errmsg("column \"%s\" specified more than once",
969 parser_errposition(pstate, col->location)));
970 partialcols = bms_add_member(partialcols, attrno);
973 *attrnos = lappend_int(*attrnos, attrno);
981 * ExpandColumnRefStar()
982 * Transforms foo.* into a list of expressions or targetlist entries.
984 * This handles the case where '*' appears as the last or only item in a
985 * ColumnRef. The code is shared between the case of foo.* at the top level
986 * in a SELECT target list (where we want TargetEntry nodes in the result)
987 * and foo.* in a ROW() or VALUES() construct (where we want just bare
990 * The referenced columns are marked as requiring SELECT access.
993 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
994 bool make_target_entry)
996 List *fields = cref->fields;
997 int numnames = list_length(fields);
1002 * Target item is a bare '*', expand all tables
1004 * (e.g., SELECT * FROM emp, dept)
1006 * Since the grammar only accepts bare '*' at top level of SELECT, we
1007 * need not handle the make_target_entry==false case here.
1009 Assert(make_target_entry);
1010 return ExpandAllTables(pstate, cref->location);
1015 * Target item is relation.*, expand that table
1017 * (e.g., SELECT emp.*, dname FROM emp, dept)
1019 * Note: this code is a lot like transformColumnRef; it's tempting to
1020 * call that instead and then replace the resulting whole-row Var with
1021 * a list of Vars. However, that would leave us with the RTE's
1022 * selectedCols bitmap showing the whole row as needing select
1023 * permission, as well as the individual columns. That would be
1024 * incorrect (since columns added later shouldn't need select
1025 * permissions). We could try to remove the whole-row permission bit
1026 * after the fact, but duplicating code is less messy.
1028 char *nspname = NULL;
1029 char *relname = NULL;
1030 RangeTblEntry *rte = NULL;
1037 } crserr = CRSERR_NO_RTE;
1040 * Give the PreParseColumnRefHook, if any, first shot. If it returns
1041 * non-null then we should use that expression.
1043 if (pstate->p_pre_columnref_hook != NULL)
1047 node = (*pstate->p_pre_columnref_hook) (pstate, cref);
1049 return ExpandRowReference(pstate, node, make_target_entry);
1055 relname = strVal(linitial(fields));
1056 rte = refnameRangeTblEntry(pstate, nspname, relname,
1061 nspname = strVal(linitial(fields));
1062 relname = strVal(lsecond(fields));
1063 rte = refnameRangeTblEntry(pstate, nspname, relname,
1069 char *catname = strVal(linitial(fields));
1072 * We check the catalog name and then ignore it.
1074 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1076 crserr = CRSERR_WRONG_DB;
1079 nspname = strVal(lsecond(fields));
1080 relname = strVal(lthird(fields));
1081 rte = refnameRangeTblEntry(pstate, nspname, relname,
1087 crserr = CRSERR_TOO_MANY;
1092 * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1093 * bit by passing the RangeTblEntry, not a Var, as the planned
1094 * translation. (A single Var wouldn't be strictly correct anyway.
1095 * This convention allows hooks that really care to know what is
1098 if (pstate->p_post_columnref_hook != NULL)
1102 node = (*pstate->p_post_columnref_hook) (pstate, cref,
1108 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1109 errmsg("column reference \"%s\" is ambiguous",
1110 NameListToString(cref->fields)),
1111 parser_errposition(pstate, cref->location)));
1112 return ExpandRowReference(pstate, node, make_target_entry);
1117 * Throw error if no translation found.
1124 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1127 case CRSERR_WRONG_DB:
1129 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1130 errmsg("cross-database references are not implemented: %s",
1131 NameListToString(cref->fields)),
1132 parser_errposition(pstate, cref->location)));
1134 case CRSERR_TOO_MANY:
1136 (errcode(ERRCODE_SYNTAX_ERROR),
1137 errmsg("improper qualified name (too many dotted names): %s",
1138 NameListToString(cref->fields)),
1139 parser_errposition(pstate, cref->location)));
1145 * OK, expand the RTE into fields.
1147 return ExpandSingleTable(pstate, rte, cref->location, make_target_entry);
1153 * Transforms '*' (in the target list) into a list of targetlist entries.
1155 * tlist entries are generated for each relation visible for unqualified
1156 * column name access. We do not consider qualified-name-only entries because
1157 * that would include input tables of aliasless JOINs, NEW/OLD pseudo-entries,
1160 * The referenced relations/columns are marked as requiring SELECT access.
1163 ExpandAllTables(ParseState *pstate, int location)
1166 bool found_table = false;
1169 foreach(l, pstate->p_namespace)
1171 ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1172 RangeTblEntry *rte = nsitem->p_rte;
1174 /* Ignore table-only items */
1175 if (!nsitem->p_cols_visible)
1177 /* Should not have any lateral-only items when parsing targetlist */
1178 Assert(!nsitem->p_lateral_only);
1179 /* Remember we found a p_cols_visible item */
1182 target = list_concat(target,
1183 expandRelAttrs(pstate,
1185 RTERangeTablePosn(pstate, rte,
1192 * Check for "SELECT *;". We do it this way, rather than checking for
1193 * target == NIL, because we want to allow SELECT * FROM a zero_column
1198 (errcode(ERRCODE_SYNTAX_ERROR),
1199 errmsg("SELECT * with no tables specified is not valid"),
1200 parser_errposition(pstate, location)));
1206 * ExpandIndirectionStar()
1207 * Transforms foo.* into a list of expressions or targetlist entries.
1209 * This handles the case where '*' appears as the last item in A_Indirection.
1210 * The code is shared between the case of foo.* at the top level in a SELECT
1211 * target list (where we want TargetEntry nodes in the result) and foo.* in
1212 * a ROW() or VALUES() construct (where we want just bare expressions).
1213 * For robustness, we use a separate "make_target_entry" flag to control
1214 * this rather than relying on exprKind.
1217 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1218 bool make_target_entry, ParseExprKind exprKind)
1222 /* Strip off the '*' to create a reference to the rowtype object */
1223 ind = copyObject(ind);
1224 ind->indirection = list_truncate(ind->indirection,
1225 list_length(ind->indirection) - 1);
1227 /* And transform that */
1228 expr = transformExpr(pstate, (Node *) ind, exprKind);
1230 /* Expand the rowtype expression into individual fields */
1231 return ExpandRowReference(pstate, expr, make_target_entry);
1235 * ExpandSingleTable()
1236 * Transforms foo.* into a list of expressions or targetlist entries.
1238 * This handles the case where foo has been determined to be a simple
1239 * reference to an RTE, so we can just generate Vars for the expressions.
1241 * The referenced columns are marked as requiring SELECT access.
1244 ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
1245 int location, bool make_target_entry)
1250 rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1252 if (make_target_entry)
1254 /* expandRelAttrs handles permissions marking */
1255 return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1263 expandRTE(rte, rtindex, sublevels_up, location, false,
1267 * Require read access to the table. This is normally redundant with
1268 * the markVarForSelectPriv calls below, but not if the table has zero
1271 rte->requiredPerms |= ACL_SELECT;
1273 /* Require read access to each column */
1276 Var *var = (Var *) lfirst(l);
1278 markVarForSelectPriv(pstate, var, rte);
1286 * ExpandRowReference()
1287 * Transforms foo.* into a list of expressions or targetlist entries.
1289 * This handles the case where foo is an arbitrary expression of composite
1293 ExpandRowReference(ParseState *pstate, Node *expr,
1294 bool make_target_entry)
1297 TupleDesc tupleDesc;
1302 * If the rowtype expression is a whole-row Var, we can expand the fields
1303 * as simple Vars. Note: if the RTE is a relation, this case leaves us
1304 * with the RTE's selectedCols bitmap showing the whole row as needing
1305 * select permission, as well as the individual columns. However, we can
1306 * only get here for weird notations like (table.*).*, so it's not worth
1307 * trying to clean up --- arguably, the permissions marking is correct
1308 * anyway for such cases.
1310 if (IsA(expr, Var) &&
1311 ((Var *) expr)->varattno == InvalidAttrNumber)
1313 Var *var = (Var *) expr;
1316 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1317 return ExpandSingleTable(pstate, rte, var->location, make_target_entry);
1321 * Otherwise we have to do it the hard way. Our current implementation is
1322 * to generate multiple copies of the expression and do FieldSelects.
1323 * (This can be pretty inefficient if the expression involves nontrivial
1326 * Verify it's a composite type, and get the tupdesc. We use
1327 * get_expr_result_type() because that can handle references to functions
1328 * returning anonymous record types. If that fails, use
1329 * lookup_rowtype_tupdesc(), which will almost certainly fail as well, but
1330 * it will give an appropriate error message.
1332 * If it's a Var of type RECORD, we have to work even harder: we have to
1333 * find what the Var refers to, and pass that to get_expr_result_type.
1334 * That task is handled by expandRecordVariable().
1336 if (IsA(expr, Var) &&
1337 ((Var *) expr)->vartype == RECORDOID)
1338 tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1339 else if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1340 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1344 /* Generate a list of references to the individual fields */
1345 numAttrs = tupleDesc->natts;
1346 for (i = 0; i < numAttrs; i++)
1348 Form_pg_attribute att = tupleDesc->attrs[i];
1349 FieldSelect *fselect;
1351 if (att->attisdropped)
1354 fselect = makeNode(FieldSelect);
1355 fselect->arg = (Expr *) copyObject(expr);
1356 fselect->fieldnum = i + 1;
1357 fselect->resulttype = att->atttypid;
1358 fselect->resulttypmod = att->atttypmod;
1359 /* save attribute's collation for parse_collate.c */
1360 fselect->resultcollid = att->attcollation;
1362 if (make_target_entry)
1364 /* add TargetEntry decoration */
1367 te = makeTargetEntry((Expr *) fselect,
1368 (AttrNumber) pstate->p_next_resno++,
1369 pstrdup(NameStr(att->attname)),
1371 result = lappend(result, te);
1374 result = lappend(result, fselect);
1381 * expandRecordVariable
1382 * Get the tuple descriptor for a Var of type RECORD, if possible.
1384 * Since no actual table or view column is allowed to have type RECORD, such
1385 * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
1386 * drill down to find the ultimate defining expression and attempt to infer
1387 * the tupdesc from it. We ereport if we can't determine the tupdesc.
1389 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1392 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1394 TupleDesc tupleDesc;
1400 /* Check my caller didn't mess up */
1401 Assert(IsA(var, Var));
1402 Assert(var->vartype == RECORDOID);
1404 netlevelsup = var->varlevelsup + levelsup;
1405 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1406 attnum = var->varattno;
1408 if (attnum == InvalidAttrNumber)
1410 /* Whole-row reference to an RTE, so expand the known fields */
1417 expandRTE(rte, var->varno, 0, var->location, false,
1420 tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1422 forboth(lname, names, lvar, vars)
1424 char *label = strVal(lfirst(lname));
1425 Node *varnode = (Node *) lfirst(lvar);
1427 TupleDescInitEntry(tupleDesc, i,
1430 exprTypmod(varnode),
1432 TupleDescInitEntryCollation(tupleDesc, i,
1433 exprCollation(varnode));
1436 Assert(lname == NULL && lvar == NULL); /* lists same length? */
1441 expr = (Node *) var; /* default if we can't drill down */
1443 switch (rte->rtekind)
1449 * This case should not occur: a column of a table or values list
1450 * shouldn't have type RECORD. Fall through and fail (most
1451 * likely) at the bottom.
1456 /* Subselect-in-FROM: examine sub-select's output expr */
1457 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1460 if (ste == NULL || ste->resjunk)
1461 elog(ERROR, "subquery %s does not have attribute %d",
1462 rte->eref->aliasname, attnum);
1463 expr = (Node *) ste->expr;
1467 * Recurse into the sub-select to see what its Var refers
1468 * to. We have to build an additional level of ParseState
1469 * to keep in step with varlevelsup in the subselect.
1471 ParseState mypstate;
1473 MemSet(&mypstate, 0, sizeof(mypstate));
1474 mypstate.parentParseState = pstate;
1475 mypstate.p_rtable = rte->subquery->rtable;
1476 /* don't bother filling the rest of the fake pstate */
1478 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1480 /* else fall through to inspect the expression */
1484 /* Join RTE --- recursively inspect the alias variable */
1485 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1486 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1487 Assert(expr != NULL);
1488 /* We intentionally don't strip implicit coercions here */
1490 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1491 /* else fall through to inspect the expression */
1496 * We couldn't get here unless a function is declared with one of
1497 * its result columns as RECORD, which is not allowed.
1501 /* CTE reference: examine subquery's output expr */
1502 if (!rte->self_reference)
1504 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1507 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1508 if (ste == NULL || ste->resjunk)
1509 elog(ERROR, "subquery %s does not have attribute %d",
1510 rte->eref->aliasname, attnum);
1511 expr = (Node *) ste->expr;
1515 * Recurse into the CTE to see what its Var refers to. We
1516 * have to build an additional level of ParseState to keep
1517 * in step with varlevelsup in the CTE; furthermore it
1518 * could be an outer CTE.
1520 ParseState mypstate;
1523 MemSet(&mypstate, 0, sizeof(mypstate));
1524 /* this loop must work, since GetCTEForRTE did */
1526 levelsup < rte->ctelevelsup + netlevelsup;
1528 pstate = pstate->parentParseState;
1529 mypstate.parentParseState = pstate;
1530 mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1531 /* don't bother filling the rest of the fake pstate */
1533 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1535 /* else fall through to inspect the expression */
1541 * We now have an expression we can't expand any more, so see if
1542 * get_expr_result_type() can do anything with it. If not, pass to
1543 * lookup_rowtype_tupdesc() which will probably fail, but will give an
1544 * appropriate error message while failing.
1546 if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1547 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1556 * if the name of the resulting column is not specified in the target
1557 * list, we have to guess a suitable name. The SQL spec provides some
1558 * guidance, but not much...
1560 * Note that the argument is the *untransformed* parse tree for the target
1561 * item. This is a shade easier to work with than the transformed tree.
1564 FigureColname(Node *node)
1568 (void) FigureColnameInternal(node, &name);
1571 /* default result if we can't guess anything */
1576 * FigureIndexColname -
1577 * choose the name for an expression column in an index
1579 * This is actually just like FigureColname, except we return NULL if
1580 * we can't pick a good name.
1583 FigureIndexColname(Node *node)
1587 (void) FigureColnameInternal(node, &name);
1592 * FigureColnameInternal -
1593 * internal workhorse for FigureColname
1595 * Return value indicates strength of confidence in result:
1596 * 0 - no information
1597 * 1 - second-best name choice
1598 * 2 - good name choice
1599 * The return value is actually only used internally.
1600 * If the result isn't zero, *name is set to the chosen name.
1603 FigureColnameInternal(Node *node, char **name)
1610 switch (nodeTag(node))
1617 /* find last field name, if any, ignoring "*" */
1618 foreach(l, ((ColumnRef *) node)->fields)
1620 Node *i = lfirst(l);
1632 case T_A_Indirection:
1634 A_Indirection *ind = (A_Indirection *) node;
1638 /* find last field name, if any, ignoring "*" and subscripts */
1639 foreach(l, ind->indirection)
1641 Node *i = lfirst(l);
1651 return FigureColnameInternal(ind->arg, name);
1655 *name = strVal(llast(((FuncCall *) node)->funcname));
1658 if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1660 /* make nullif() act like a regular function */
1664 if (((A_Expr *) node)->kind == AEXPR_PAREN)
1666 /* look through dummy parenthesis node */
1667 return FigureColnameInternal(((A_Expr *) node)->lexpr, name);
1671 strength = FigureColnameInternal(((TypeCast *) node)->arg,
1675 if (((TypeCast *) node)->typeName != NULL)
1677 *name = strVal(llast(((TypeCast *) node)->typeName->names));
1682 case T_CollateClause:
1683 return FigureColnameInternal(((CollateClause *) node)->arg, name);
1685 switch (((SubLink *) node)->subLinkType)
1687 case EXISTS_SUBLINK:
1695 /* Get column name of the subquery's single target */
1696 SubLink *sublink = (SubLink *) node;
1697 Query *query = (Query *) sublink->subselect;
1700 * The subquery has probably already been transformed,
1701 * but let's be careful and check that. (The reason
1702 * we can see a transformed subquery here is that
1703 * transformSubLink is lazy and modifies the SubLink
1706 if (IsA(query, Query))
1708 TargetEntry *te = (TargetEntry *) linitial(query->targetList);
1712 *name = te->resname;
1718 /* As with other operator-like nodes, these have no names */
1719 case MULTIEXPR_SUBLINK:
1722 case ROWCOMPARE_SUBLINK:
1728 strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1737 /* make ARRAY[] act like a function */
1741 /* make ROW() act like a function */
1744 case T_CoalesceExpr:
1745 /* make coalesce() act like a regular function */
1749 /* make greatest/least act like a regular function */
1750 switch (((MinMaxExpr *) node)->op)
1761 /* make SQL/XML functions act like a regular function */
1762 switch (((XmlExpr *) node)->op)
1765 *name = "xmlconcat";
1768 *name = "xmlelement";
1771 *name = "xmlforest";
1782 case IS_XMLSERIALIZE:
1783 *name = "xmlserialize";
1790 case T_XmlSerialize:
1791 *name = "xmlserialize";