Make INSERT-from-multiple-VALUES-rows handle domain target columns.
[pgsql.git] / src / backend / parser / parse_target.c
blob5affb9e2bec4e6981999c1be760cf1eeca6632ac
1 /*-------------------------------------------------------------------------
3 * parse_target.c
4 * handle target lists
6 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * src/backend/parser/parse_target.c
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include "catalog/pg_type.h"
18 #include "commands/dbcommands.h"
19 #include "funcapi.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.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 "parser/parsetree.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/rel.h"
33 #include "utils/typcache.h"
35 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
36 Var *var, int levelsup);
37 static Node *transformAssignmentSubscripts(ParseState *pstate,
38 Node *basenode,
39 const char *targetName,
40 Oid targetTypeId,
41 int32 targetTypMod,
42 Oid targetCollation,
43 List *subscripts,
44 List *indirection,
45 ListCell *next_indirection,
46 Node *rhs,
47 CoercionContext ccontext,
48 int location);
49 static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
50 bool make_target_entry);
51 static List *ExpandAllTables(ParseState *pstate, int location);
52 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
53 bool make_target_entry, ParseExprKind exprKind);
54 static List *ExpandSingleTable(ParseState *pstate, ParseNamespaceItem *nsitem,
55 int sublevels_up, int location,
56 bool make_target_entry);
57 static List *ExpandRowReference(ParseState *pstate, Node *expr,
58 bool make_target_entry);
59 static int FigureColnameInternal(Node *node, char **name);
63 * transformTargetEntry()
64 * Transform any ordinary "expression-type" node into a targetlist entry.
65 * This is exported so that parse_clause.c can generate targetlist entries
66 * for ORDER/GROUP BY items that are not already in the targetlist.
68 * node the (untransformed) parse tree for the value expression.
69 * expr the transformed expression, or NULL if caller didn't do it yet.
70 * exprKind expression kind (EXPR_KIND_SELECT_TARGET, etc)
71 * colname the column name to be assigned, or NULL if none yet set.
72 * resjunk true if the target should be marked resjunk, ie, it is not
73 * wanted in the final projected tuple.
75 TargetEntry *
76 transformTargetEntry(ParseState *pstate,
77 Node *node,
78 Node *expr,
79 ParseExprKind exprKind,
80 char *colname,
81 bool resjunk)
83 /* Transform the node if caller didn't do it already */
84 if (expr == NULL)
87 * If it's a SetToDefault node and we should allow that, pass it
88 * through unmodified. (transformExpr will throw the appropriate
89 * error if we're disallowing it.)
91 if (exprKind == EXPR_KIND_UPDATE_SOURCE && IsA(node, SetToDefault))
92 expr = node;
93 else
94 expr = transformExpr(pstate, node, exprKind);
97 if (colname == NULL && !resjunk)
100 * Generate a suitable column name for a column without any explicit
101 * 'AS ColumnName' clause.
103 colname = FigureColname(node);
106 return makeTargetEntry((Expr *) expr,
107 (AttrNumber) pstate->p_next_resno++,
108 colname,
109 resjunk);
114 * transformTargetList()
115 * Turns a list of ResTarget's into a list of TargetEntry's.
117 * This code acts mostly the same for SELECT, UPDATE, or RETURNING lists;
118 * the main thing is to transform the given expressions (the "val" fields).
119 * The exprKind parameter distinguishes these cases when necessary.
121 List *
122 transformTargetList(ParseState *pstate, List *targetlist,
123 ParseExprKind exprKind)
125 List *p_target = NIL;
126 bool expand_star;
127 ListCell *o_target;
129 /* Shouldn't have any leftover multiassign items at start */
130 Assert(pstate->p_multiassign_exprs == NIL);
132 /* Expand "something.*" in SELECT and RETURNING, but not UPDATE */
133 expand_star = (exprKind != EXPR_KIND_UPDATE_SOURCE);
135 foreach(o_target, targetlist)
137 ResTarget *res = (ResTarget *) lfirst(o_target);
140 * Check for "something.*". Depending on the complexity of the
141 * "something", the star could appear as the last field in ColumnRef,
142 * or as the last indirection item in A_Indirection.
144 if (expand_star)
146 if (IsA(res->val, ColumnRef))
148 ColumnRef *cref = (ColumnRef *) res->val;
150 if (IsA(llast(cref->fields), A_Star))
152 /* It is something.*, expand into multiple items */
153 p_target = list_concat(p_target,
154 ExpandColumnRefStar(pstate,
155 cref,
156 true));
157 continue;
160 else if (IsA(res->val, A_Indirection))
162 A_Indirection *ind = (A_Indirection *) res->val;
164 if (IsA(llast(ind->indirection), A_Star))
166 /* It is something.*, expand into multiple items */
167 p_target = list_concat(p_target,
168 ExpandIndirectionStar(pstate,
169 ind,
170 true,
171 exprKind));
172 continue;
178 * Not "something.*", or we want to treat that as a plain whole-row
179 * variable, so transform as a single expression
181 p_target = lappend(p_target,
182 transformTargetEntry(pstate,
183 res->val,
184 NULL,
185 exprKind,
186 res->name,
187 false));
191 * If any multiassign resjunk items were created, attach them to the end
192 * of the targetlist. This should only happen in an UPDATE tlist. We
193 * don't need to worry about numbering of these items; transformUpdateStmt
194 * will set their resnos.
196 if (pstate->p_multiassign_exprs)
198 Assert(exprKind == EXPR_KIND_UPDATE_SOURCE);
199 p_target = list_concat(p_target, pstate->p_multiassign_exprs);
200 pstate->p_multiassign_exprs = NIL;
203 return p_target;
208 * transformExpressionList()
210 * This is the identical transformation to transformTargetList, except that
211 * the input list elements are bare expressions without ResTarget decoration,
212 * and the output elements are likewise just expressions without TargetEntry
213 * decoration. Also, we don't expect any multiassign constructs within the
214 * list, so there's nothing to do for that. We use this for ROW() and
215 * VALUES() constructs.
217 * exprKind is not enough to tell us whether to allow SetToDefault, so
218 * an additional flag is needed for that.
220 List *
221 transformExpressionList(ParseState *pstate, List *exprlist,
222 ParseExprKind exprKind, bool allowDefault)
224 List *result = NIL;
225 ListCell *lc;
227 foreach(lc, exprlist)
229 Node *e = (Node *) lfirst(lc);
232 * Check for "something.*". Depending on the complexity of the
233 * "something", the star could appear as the last field in ColumnRef,
234 * or as the last indirection item in A_Indirection.
236 if (IsA(e, ColumnRef))
238 ColumnRef *cref = (ColumnRef *) e;
240 if (IsA(llast(cref->fields), A_Star))
242 /* It is something.*, expand into multiple items */
243 result = list_concat(result,
244 ExpandColumnRefStar(pstate, cref,
245 false));
246 continue;
249 else if (IsA(e, A_Indirection))
251 A_Indirection *ind = (A_Indirection *) e;
253 if (IsA(llast(ind->indirection), A_Star))
255 /* It is something.*, expand into multiple items */
256 result = list_concat(result,
257 ExpandIndirectionStar(pstate, ind,
258 false, exprKind));
259 continue;
264 * Not "something.*", so transform as a single expression. If it's a
265 * SetToDefault node and we should allow that, pass it through
266 * unmodified. (transformExpr will throw the appropriate error if
267 * we're disallowing it.)
269 if (allowDefault && IsA(e, SetToDefault))
270 /* do nothing */ ;
271 else
272 e = transformExpr(pstate, e, exprKind);
274 result = lappend(result, e);
277 return result;
282 * resolveTargetListUnknowns()
283 * Convert any unknown-type targetlist entries to type TEXT.
285 * We do this after we've exhausted all other ways of identifying the output
286 * column types of a query.
288 void
289 resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
291 ListCell *l;
293 foreach(l, targetlist)
295 TargetEntry *tle = (TargetEntry *) lfirst(l);
296 Oid restype = exprType((Node *) tle->expr);
298 if (restype == UNKNOWNOID)
300 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
301 restype, TEXTOID, -1,
302 COERCION_IMPLICIT,
303 COERCE_IMPLICIT_CAST,
304 -1);
311 * markTargetListOrigins()
312 * Mark targetlist columns that are simple Vars with the source
313 * table's OID and column number.
315 * Currently, this is done only for SELECT targetlists and RETURNING lists,
316 * since we only need the info if we are going to send it to the frontend.
318 void
319 markTargetListOrigins(ParseState *pstate, List *targetlist)
321 ListCell *l;
323 foreach(l, targetlist)
325 TargetEntry *tle = (TargetEntry *) lfirst(l);
327 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
332 * markTargetListOrigin()
333 * If 'var' is a Var of a plain relation, mark 'tle' with its origin
335 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
337 * Note that we do not drill down into views, but report the view as the
338 * column owner. There's also no need to drill down into joins: if we see
339 * a join alias Var, it must be a merged JOIN USING column (or possibly a
340 * whole-row Var); that is not a direct reference to any plain table column,
341 * so we don't report it.
343 static void
344 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
345 Var *var, int levelsup)
347 int netlevelsup;
348 RangeTblEntry *rte;
349 AttrNumber attnum;
351 if (var == NULL || !IsA(var, Var))
352 return;
353 netlevelsup = var->varlevelsup + levelsup;
354 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
355 attnum = var->varattno;
357 switch (rte->rtekind)
359 case RTE_RELATION:
360 /* It's a table or view, report it */
361 tle->resorigtbl = rte->relid;
362 tle->resorigcol = attnum;
363 break;
364 case RTE_SUBQUERY:
365 /* Subselect-in-FROM: copy up from the subselect */
366 if (attnum != InvalidAttrNumber)
368 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
369 attnum);
371 if (ste == NULL || ste->resjunk)
372 elog(ERROR, "subquery %s does not have attribute %d",
373 rte->eref->aliasname, attnum);
374 tle->resorigtbl = ste->resorigtbl;
375 tle->resorigcol = ste->resorigcol;
377 break;
378 case RTE_JOIN:
379 case RTE_FUNCTION:
380 case RTE_VALUES:
381 case RTE_TABLEFUNC:
382 case RTE_NAMEDTUPLESTORE:
383 case RTE_RESULT:
384 /* not a simple relation, leave it unmarked */
385 break;
386 case RTE_CTE:
389 * CTE reference: copy up from the subquery, if possible. If the
390 * RTE is a recursive self-reference then we can't do anything
391 * because we haven't finished analyzing it yet. However, it's no
392 * big loss because we must be down inside the recursive term of a
393 * recursive CTE, and so any markings on the current targetlist
394 * are not going to affect the results anyway.
396 if (attnum != InvalidAttrNumber && !rte->self_reference)
398 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
399 TargetEntry *ste;
400 List *tl = GetCTETargetList(cte);
401 int extra_cols = 0;
404 * RTE for CTE will already have the search and cycle columns
405 * added, but the subquery won't, so skip looking those up.
407 if (cte->search_clause)
408 extra_cols += 1;
409 if (cte->cycle_clause)
410 extra_cols += 2;
411 if (extra_cols &&
412 attnum > list_length(tl) &&
413 attnum <= list_length(tl) + extra_cols)
414 break;
416 ste = get_tle_by_resno(tl, attnum);
417 if (ste == NULL || ste->resjunk)
418 elog(ERROR, "CTE %s does not have attribute %d",
419 rte->eref->aliasname, attnum);
420 tle->resorigtbl = ste->resorigtbl;
421 tle->resorigcol = ste->resorigcol;
423 break;
429 * transformAssignedExpr()
430 * This is used in INSERT and UPDATE statements only. It prepares an
431 * expression for assignment to a column of the target table.
432 * This includes coercing the given value to the target column's type
433 * (if necessary), and dealing with any subfield names or subscripts
434 * attached to the target column itself. The input expression has
435 * already been through transformExpr().
437 * pstate parse state
438 * expr expression to be modified
439 * exprKind indicates which type of statement we're dealing with
440 * colname target column name (ie, name of attribute to be assigned to)
441 * attrno target attribute number
442 * indirection subscripts/field names for target column, if any
443 * location error cursor position for the target column, or -1
445 * Returns the modified expression.
447 * Note: location points at the target column name (SET target or INSERT
448 * column name list entry), and must therefore be -1 in an INSERT that
449 * omits the column name list. So we should usually prefer to use
450 * exprLocation(expr) for errors that can happen in a default INSERT.
452 Expr *
453 transformAssignedExpr(ParseState *pstate,
454 Expr *expr,
455 ParseExprKind exprKind,
456 const char *colname,
457 int attrno,
458 List *indirection,
459 int location)
461 Relation rd = pstate->p_target_relation;
462 Oid type_id; /* type of value provided */
463 Oid attrtype; /* type of target column */
464 int32 attrtypmod;
465 Oid attrcollation; /* collation of target column */
466 ParseExprKind sv_expr_kind;
469 * Save and restore identity of expression type we're parsing. We must
470 * set p_expr_kind here because we can parse subscripts without going
471 * through transformExpr().
473 Assert(exprKind != EXPR_KIND_NONE);
474 sv_expr_kind = pstate->p_expr_kind;
475 pstate->p_expr_kind = exprKind;
477 Assert(rd != NULL);
478 if (attrno <= 0)
479 ereport(ERROR,
480 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
481 errmsg("cannot assign to system column \"%s\"",
482 colname),
483 parser_errposition(pstate, location)));
484 attrtype = attnumTypeId(rd, attrno);
485 attrtypmod = TupleDescAttr(rd->rd_att, attrno - 1)->atttypmod;
486 attrcollation = TupleDescAttr(rd->rd_att, attrno - 1)->attcollation;
489 * If the expression is a DEFAULT placeholder, insert the attribute's
490 * type/typmod/collation into it so that exprType etc will report the
491 * right things. (We expect that the eventually substituted default
492 * expression will in fact have this type and typmod. The collation
493 * likely doesn't matter, but let's set it correctly anyway.) Also,
494 * reject trying to update a subfield or array element with DEFAULT, since
495 * there can't be any default for portions of a column.
497 if (expr && IsA(expr, SetToDefault))
499 SetToDefault *def = (SetToDefault *) expr;
501 def->typeId = attrtype;
502 def->typeMod = attrtypmod;
503 def->collation = attrcollation;
504 if (indirection)
506 if (IsA(linitial(indirection), A_Indices))
507 ereport(ERROR,
508 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
509 errmsg("cannot set an array element to DEFAULT"),
510 parser_errposition(pstate, location)));
511 else
512 ereport(ERROR,
513 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
514 errmsg("cannot set a subfield to DEFAULT"),
515 parser_errposition(pstate, location)));
519 /* Now we can use exprType() safely. */
520 type_id = exprType((Node *) expr);
523 * If there is indirection on the target column, prepare an array or
524 * subfield assignment expression. This will generate a new column value
525 * that the source value has been inserted into, which can then be placed
526 * in the new tuple constructed by INSERT or UPDATE.
528 if (indirection)
530 Node *colVar;
532 if (pstate->p_is_insert)
535 * The command is INSERT INTO table (col.something) ... so there
536 * is not really a source value to work with. Insert a NULL
537 * constant as the source value.
539 colVar = (Node *) makeNullConst(attrtype, attrtypmod,
540 attrcollation);
542 else
545 * Build a Var for the column to be updated.
547 Var *var;
549 var = makeVar(pstate->p_target_nsitem->p_rtindex, attrno,
550 attrtype, attrtypmod, attrcollation, 0);
551 var->location = location;
553 colVar = (Node *) var;
556 expr = (Expr *)
557 transformAssignmentIndirection(pstate,
558 colVar,
559 colname,
560 false,
561 attrtype,
562 attrtypmod,
563 attrcollation,
564 indirection,
565 list_head(indirection),
566 (Node *) expr,
567 COERCION_ASSIGNMENT,
568 location);
570 else
573 * For normal non-qualified target column, do type checking and
574 * coercion.
576 Node *orig_expr = (Node *) expr;
578 expr = (Expr *)
579 coerce_to_target_type(pstate,
580 orig_expr, type_id,
581 attrtype, attrtypmod,
582 COERCION_ASSIGNMENT,
583 COERCE_IMPLICIT_CAST,
584 -1);
585 if (expr == NULL)
586 ereport(ERROR,
587 (errcode(ERRCODE_DATATYPE_MISMATCH),
588 errmsg("column \"%s\" is of type %s"
589 " but expression is of type %s",
590 colname,
591 format_type_be(attrtype),
592 format_type_be(type_id)),
593 errhint("You will need to rewrite or cast the expression."),
594 parser_errposition(pstate, exprLocation(orig_expr))));
597 pstate->p_expr_kind = sv_expr_kind;
599 return expr;
604 * updateTargetListEntry()
605 * This is used in UPDATE statements (and ON CONFLICT DO UPDATE)
606 * only. It prepares an UPDATE TargetEntry for assignment to a
607 * column of the target table. This includes coercing the given
608 * value to the target column's type (if necessary), and dealing with
609 * any subfield names or subscripts attached to the target column
610 * itself.
612 * pstate parse state
613 * tle target list entry to be modified
614 * colname target column name (ie, name of attribute to be assigned to)
615 * attrno target attribute number
616 * indirection subscripts/field names for target column, if any
617 * location error cursor position (should point at column name), or -1
619 void
620 updateTargetListEntry(ParseState *pstate,
621 TargetEntry *tle,
622 char *colname,
623 int attrno,
624 List *indirection,
625 int location)
627 /* Fix up expression as needed */
628 tle->expr = transformAssignedExpr(pstate,
629 tle->expr,
630 EXPR_KIND_UPDATE_TARGET,
631 colname,
632 attrno,
633 indirection,
634 location);
637 * Set the resno to identify the target column --- the rewriter and
638 * planner depend on this. We also set the resname to identify the target
639 * column, but this is only for debugging purposes; it should not be
640 * relied on. (In particular, it might be out of date in a stored rule.)
642 tle->resno = (AttrNumber) attrno;
643 tle->resname = colname;
648 * Process indirection (field selection or subscripting) of the target
649 * column in INSERT/UPDATE/assignment. This routine recurses for multiple
650 * levels of indirection --- but note that several adjacent A_Indices nodes
651 * in the indirection list are treated as a single multidimensional subscript
652 * operation.
654 * In the initial call, basenode is a Var for the target column in UPDATE,
655 * or a null Const of the target's type in INSERT, or a Param for the target
656 * variable in PL/pgSQL assignment. In recursive calls, basenode is NULL,
657 * indicating that a substitute node should be consed up if needed.
659 * targetName is the name of the field or subfield we're assigning to, and
660 * targetIsSubscripting is true if we're subscripting it. These are just for
661 * error reporting.
663 * targetTypeId, targetTypMod, targetCollation indicate the datatype and
664 * collation of the object to be assigned to (initially the target column,
665 * later some subobject).
667 * indirection is the list of indirection nodes, and indirection_cell is the
668 * start of the sublist remaining to process. When it's NULL, we're done
669 * recursing and can just coerce and return the RHS.
671 * rhs is the already-transformed value to be assigned; note it has not been
672 * coerced to any particular type.
674 * ccontext is the coercion level to use while coercing the rhs. For
675 * normal statements it'll be COERCION_ASSIGNMENT, but PL/pgSQL uses
676 * a special value.
678 * location is the cursor error position for any errors. (Note: this points
679 * to the head of the target clause, eg "foo" in "foo.bar[baz]". Later we
680 * might want to decorate indirection cells with their own location info,
681 * in which case the location argument could probably be dropped.)
683 Node *
684 transformAssignmentIndirection(ParseState *pstate,
685 Node *basenode,
686 const char *targetName,
687 bool targetIsSubscripting,
688 Oid targetTypeId,
689 int32 targetTypMod,
690 Oid targetCollation,
691 List *indirection,
692 ListCell *indirection_cell,
693 Node *rhs,
694 CoercionContext ccontext,
695 int location)
697 Node *result;
698 List *subscripts = NIL;
699 ListCell *i;
701 if (indirection_cell && !basenode)
704 * Set up a substitution. We abuse CaseTestExpr for this. It's safe
705 * to do so because the only nodes that will be above the CaseTestExpr
706 * in the finished expression will be FieldStore and SubscriptingRef
707 * nodes. (There could be other stuff in the tree, but it will be
708 * within other child fields of those node types.)
710 CaseTestExpr *ctest = makeNode(CaseTestExpr);
712 ctest->typeId = targetTypeId;
713 ctest->typeMod = targetTypMod;
714 ctest->collation = targetCollation;
715 basenode = (Node *) ctest;
719 * We have to split any field-selection operations apart from
720 * subscripting. Adjacent A_Indices nodes have to be treated as a single
721 * multidimensional subscript operation.
723 for_each_cell(i, indirection, indirection_cell)
725 Node *n = lfirst(i);
727 if (IsA(n, A_Indices))
728 subscripts = lappend(subscripts, n);
729 else if (IsA(n, A_Star))
731 ereport(ERROR,
732 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
733 errmsg("row expansion via \"*\" is not supported here"),
734 parser_errposition(pstate, location)));
736 else
738 FieldStore *fstore;
739 Oid baseTypeId;
740 int32 baseTypeMod;
741 Oid typrelid;
742 AttrNumber attnum;
743 Oid fieldTypeId;
744 int32 fieldTypMod;
745 Oid fieldCollation;
747 Assert(IsA(n, String));
749 /* process subscripts before this field selection */
750 if (subscripts)
752 /* recurse, and then return because we're done */
753 return transformAssignmentSubscripts(pstate,
754 basenode,
755 targetName,
756 targetTypeId,
757 targetTypMod,
758 targetCollation,
759 subscripts,
760 indirection,
762 rhs,
763 ccontext,
764 location);
767 /* No subscripts, so can process field selection here */
770 * Look up the composite type, accounting for possibility that
771 * what we are given is a domain over composite.
773 baseTypeMod = targetTypMod;
774 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
776 typrelid = typeidTypeRelid(baseTypeId);
777 if (!typrelid)
778 ereport(ERROR,
779 (errcode(ERRCODE_DATATYPE_MISMATCH),
780 errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
781 strVal(n), targetName,
782 format_type_be(targetTypeId)),
783 parser_errposition(pstate, location)));
785 attnum = get_attnum(typrelid, strVal(n));
786 if (attnum == InvalidAttrNumber)
787 ereport(ERROR,
788 (errcode(ERRCODE_UNDEFINED_COLUMN),
789 errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
790 strVal(n), targetName,
791 format_type_be(targetTypeId)),
792 parser_errposition(pstate, location)));
793 if (attnum < 0)
794 ereport(ERROR,
795 (errcode(ERRCODE_UNDEFINED_COLUMN),
796 errmsg("cannot assign to system column \"%s\"",
797 strVal(n)),
798 parser_errposition(pstate, location)));
800 get_atttypetypmodcoll(typrelid, attnum,
801 &fieldTypeId, &fieldTypMod, &fieldCollation);
803 /* recurse to create appropriate RHS for field assign */
804 rhs = transformAssignmentIndirection(pstate,
805 NULL,
806 strVal(n),
807 false,
808 fieldTypeId,
809 fieldTypMod,
810 fieldCollation,
811 indirection,
812 lnext(indirection, i),
813 rhs,
814 ccontext,
815 location);
817 /* and build a FieldStore node */
818 fstore = makeNode(FieldStore);
819 fstore->arg = (Expr *) basenode;
820 fstore->newvals = list_make1(rhs);
821 fstore->fieldnums = list_make1_int(attnum);
822 fstore->resulttype = baseTypeId;
825 * If target is a domain, apply constraints. Notice that this
826 * isn't totally right: the expression tree we build would check
827 * the domain's constraints on a composite value with only this
828 * one field populated or updated, possibly leading to an unwanted
829 * failure. The rewriter will merge together any subfield
830 * assignments to the same table column, resulting in the domain's
831 * constraints being checked only once after we've assigned to all
832 * the fields that the INSERT or UPDATE means to.
834 if (baseTypeId != targetTypeId)
835 return coerce_to_domain((Node *) fstore,
836 baseTypeId, baseTypeMod,
837 targetTypeId,
838 COERCION_IMPLICIT,
839 COERCE_IMPLICIT_CAST,
840 location,
841 false);
843 return (Node *) fstore;
847 /* process trailing subscripts, if any */
848 if (subscripts)
850 /* recurse, and then return because we're done */
851 return transformAssignmentSubscripts(pstate,
852 basenode,
853 targetName,
854 targetTypeId,
855 targetTypMod,
856 targetCollation,
857 subscripts,
858 indirection,
859 NULL,
860 rhs,
861 ccontext,
862 location);
865 /* base case: just coerce RHS to match target type ID */
867 result = coerce_to_target_type(pstate,
868 rhs, exprType(rhs),
869 targetTypeId, targetTypMod,
870 ccontext,
871 COERCE_IMPLICIT_CAST,
872 -1);
873 if (result == NULL)
875 if (targetIsSubscripting)
876 ereport(ERROR,
877 (errcode(ERRCODE_DATATYPE_MISMATCH),
878 errmsg("subscripted assignment to \"%s\" requires type %s"
879 " but expression is of type %s",
880 targetName,
881 format_type_be(targetTypeId),
882 format_type_be(exprType(rhs))),
883 errhint("You will need to rewrite or cast the expression."),
884 parser_errposition(pstate, location)));
885 else
886 ereport(ERROR,
887 (errcode(ERRCODE_DATATYPE_MISMATCH),
888 errmsg("subfield \"%s\" is of type %s"
889 " but expression is of type %s",
890 targetName,
891 format_type_be(targetTypeId),
892 format_type_be(exprType(rhs))),
893 errhint("You will need to rewrite or cast the expression."),
894 parser_errposition(pstate, location)));
897 return result;
901 * helper for transformAssignmentIndirection: process container assignment
903 static Node *
904 transformAssignmentSubscripts(ParseState *pstate,
905 Node *basenode,
906 const char *targetName,
907 Oid targetTypeId,
908 int32 targetTypMod,
909 Oid targetCollation,
910 List *subscripts,
911 List *indirection,
912 ListCell *next_indirection,
913 Node *rhs,
914 CoercionContext ccontext,
915 int location)
917 Node *result;
918 SubscriptingRef *sbsref;
919 Oid containerType;
920 int32 containerTypMod;
921 Oid typeNeeded;
922 int32 typmodNeeded;
923 Oid collationNeeded;
925 Assert(subscripts != NIL);
927 /* Identify the actual container type involved */
928 containerType = targetTypeId;
929 containerTypMod = targetTypMod;
930 transformContainerType(&containerType, &containerTypMod);
932 /* Process subscripts and identify required type for RHS */
933 sbsref = transformContainerSubscripts(pstate,
934 basenode,
935 containerType,
936 containerTypMod,
937 subscripts,
938 true);
940 typeNeeded = sbsref->refrestype;
941 typmodNeeded = sbsref->reftypmod;
944 * Container normally has same collation as its elements, but there's an
945 * exception: we might be subscripting a domain over a container type. In
946 * that case use collation of the base type. (This is shaky for arbitrary
947 * subscripting semantics, but it doesn't matter all that much since we
948 * only use this to label the collation of a possible CaseTestExpr.)
950 if (containerType == targetTypeId)
951 collationNeeded = targetCollation;
952 else
953 collationNeeded = get_typcollation(containerType);
955 /* recurse to create appropriate RHS for container assign */
956 rhs = transformAssignmentIndirection(pstate,
957 NULL,
958 targetName,
959 true,
960 typeNeeded,
961 typmodNeeded,
962 collationNeeded,
963 indirection,
964 next_indirection,
965 rhs,
966 ccontext,
967 location);
970 * Insert the already-properly-coerced RHS into the SubscriptingRef. Then
971 * set refrestype and reftypmod back to the container type's values.
973 sbsref->refassgnexpr = (Expr *) rhs;
974 sbsref->refrestype = containerType;
975 sbsref->reftypmod = containerTypMod;
977 result = (Node *) sbsref;
980 * If target was a domain over container, need to coerce up to the domain.
981 * As in transformAssignmentIndirection, this coercion is premature if the
982 * query assigns to multiple elements of the container; but we'll fix that
983 * during query rewrite.
985 if (containerType != targetTypeId)
987 Oid resulttype = exprType(result);
989 result = coerce_to_target_type(pstate,
990 result, resulttype,
991 targetTypeId, targetTypMod,
992 ccontext,
993 COERCE_IMPLICIT_CAST,
994 -1);
995 /* can fail if we had int2vector/oidvector, but not for true domains */
996 if (result == NULL)
997 ereport(ERROR,
998 (errcode(ERRCODE_CANNOT_COERCE),
999 errmsg("cannot cast type %s to %s",
1000 format_type_be(resulttype),
1001 format_type_be(targetTypeId)),
1002 parser_errposition(pstate, location)));
1005 return result;
1010 * checkInsertTargets -
1011 * generate a list of INSERT column targets if not supplied, or
1012 * test supplied column names to make sure they are in target table.
1013 * Also return an integer list of the columns' attribute numbers.
1015 List *
1016 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
1018 *attrnos = NIL;
1020 if (cols == NIL)
1023 * Generate default column list for INSERT.
1025 int numcol = RelationGetNumberOfAttributes(pstate->p_target_relation);
1027 int i;
1029 for (i = 0; i < numcol; i++)
1031 ResTarget *col;
1032 Form_pg_attribute attr;
1034 attr = TupleDescAttr(pstate->p_target_relation->rd_att, i);
1036 if (attr->attisdropped)
1037 continue;
1039 col = makeNode(ResTarget);
1040 col->name = pstrdup(NameStr(attr->attname));
1041 col->indirection = NIL;
1042 col->val = NULL;
1043 col->location = -1;
1044 cols = lappend(cols, col);
1045 *attrnos = lappend_int(*attrnos, i + 1);
1048 else
1051 * Do initial validation of user-supplied INSERT column list.
1053 Bitmapset *wholecols = NULL;
1054 Bitmapset *partialcols = NULL;
1055 ListCell *tl;
1057 foreach(tl, cols)
1059 ResTarget *col = (ResTarget *) lfirst(tl);
1060 char *name = col->name;
1061 int attrno;
1063 /* Lookup column name, ereport on failure */
1064 attrno = attnameAttNum(pstate->p_target_relation, name, false);
1065 if (attrno == InvalidAttrNumber)
1066 ereport(ERROR,
1067 (errcode(ERRCODE_UNDEFINED_COLUMN),
1068 errmsg("column \"%s\" of relation \"%s\" does not exist",
1069 name,
1070 RelationGetRelationName(pstate->p_target_relation)),
1071 parser_errposition(pstate, col->location)));
1074 * Check for duplicates, but only of whole columns --- we allow
1075 * INSERT INTO foo (col.subcol1, col.subcol2)
1077 if (col->indirection == NIL)
1079 /* whole column; must not have any other assignment */
1080 if (bms_is_member(attrno, wholecols) ||
1081 bms_is_member(attrno, partialcols))
1082 ereport(ERROR,
1083 (errcode(ERRCODE_DUPLICATE_COLUMN),
1084 errmsg("column \"%s\" specified more than once",
1085 name),
1086 parser_errposition(pstate, col->location)));
1087 wholecols = bms_add_member(wholecols, attrno);
1089 else
1091 /* partial column; must not have any whole assignment */
1092 if (bms_is_member(attrno, wholecols))
1093 ereport(ERROR,
1094 (errcode(ERRCODE_DUPLICATE_COLUMN),
1095 errmsg("column \"%s\" specified more than once",
1096 name),
1097 parser_errposition(pstate, col->location)));
1098 partialcols = bms_add_member(partialcols, attrno);
1101 *attrnos = lappend_int(*attrnos, attrno);
1105 return cols;
1109 * ExpandColumnRefStar()
1110 * Transforms foo.* into a list of expressions or targetlist entries.
1112 * This handles the case where '*' appears as the last or only item in a
1113 * ColumnRef. The code is shared between the case of foo.* at the top level
1114 * in a SELECT target list (where we want TargetEntry nodes in the result)
1115 * and foo.* in a ROW() or VALUES() construct (where we want just bare
1116 * expressions).
1118 * The referenced columns are marked as requiring SELECT access.
1120 static List *
1121 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
1122 bool make_target_entry)
1124 List *fields = cref->fields;
1125 int numnames = list_length(fields);
1127 if (numnames == 1)
1130 * Target item is a bare '*', expand all tables
1132 * (e.g., SELECT * FROM emp, dept)
1134 * Since the grammar only accepts bare '*' at top level of SELECT, we
1135 * need not handle the make_target_entry==false case here.
1137 Assert(make_target_entry);
1138 return ExpandAllTables(pstate, cref->location);
1140 else
1143 * Target item is relation.*, expand that table
1145 * (e.g., SELECT emp.*, dname FROM emp, dept)
1147 * Note: this code is a lot like transformColumnRef; it's tempting to
1148 * call that instead and then replace the resulting whole-row Var with
1149 * a list of Vars. However, that would leave us with the relation's
1150 * selectedCols bitmap showing the whole row as needing select
1151 * permission, as well as the individual columns. That would be
1152 * incorrect (since columns added later shouldn't need select
1153 * permissions). We could try to remove the whole-row permission bit
1154 * after the fact, but duplicating code is less messy.
1156 char *nspname = NULL;
1157 char *relname = NULL;
1158 ParseNamespaceItem *nsitem = NULL;
1159 int levels_up;
1160 enum
1162 CRSERR_NO_RTE,
1163 CRSERR_WRONG_DB,
1164 CRSERR_TOO_MANY
1165 } crserr = CRSERR_NO_RTE;
1168 * Give the PreParseColumnRefHook, if any, first shot. If it returns
1169 * non-null then we should use that expression.
1171 if (pstate->p_pre_columnref_hook != NULL)
1173 Node *node;
1175 node = pstate->p_pre_columnref_hook(pstate, cref);
1176 if (node != NULL)
1177 return ExpandRowReference(pstate, node, make_target_entry);
1180 switch (numnames)
1182 case 2:
1183 relname = strVal(linitial(fields));
1184 nsitem = refnameNamespaceItem(pstate, nspname, relname,
1185 cref->location,
1186 &levels_up);
1187 break;
1188 case 3:
1189 nspname = strVal(linitial(fields));
1190 relname = strVal(lsecond(fields));
1191 nsitem = refnameNamespaceItem(pstate, nspname, relname,
1192 cref->location,
1193 &levels_up);
1194 break;
1195 case 4:
1197 char *catname = strVal(linitial(fields));
1200 * We check the catalog name and then ignore it.
1202 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1204 crserr = CRSERR_WRONG_DB;
1205 break;
1207 nspname = strVal(lsecond(fields));
1208 relname = strVal(lthird(fields));
1209 nsitem = refnameNamespaceItem(pstate, nspname, relname,
1210 cref->location,
1211 &levels_up);
1212 break;
1214 default:
1215 crserr = CRSERR_TOO_MANY;
1216 break;
1220 * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1221 * bit by passing the RangeTblEntry, not a Var, as the planned
1222 * translation. (A single Var wouldn't be strictly correct anyway.
1223 * This convention allows hooks that really care to know what is
1224 * happening. It might be better to pass the nsitem, but we'd have to
1225 * promote that struct to a full-fledged Node type so that callees
1226 * could identify its type.)
1228 if (pstate->p_post_columnref_hook != NULL)
1230 Node *node;
1232 node = pstate->p_post_columnref_hook(pstate, cref,
1233 (Node *) (nsitem ? nsitem->p_rte : NULL));
1234 if (node != NULL)
1236 if (nsitem != NULL)
1237 ereport(ERROR,
1238 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1239 errmsg("column reference \"%s\" is ambiguous",
1240 NameListToString(cref->fields)),
1241 parser_errposition(pstate, cref->location)));
1242 return ExpandRowReference(pstate, node, make_target_entry);
1247 * Throw error if no translation found.
1249 if (nsitem == NULL)
1251 switch (crserr)
1253 case CRSERR_NO_RTE:
1254 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1255 cref->location));
1256 break;
1257 case CRSERR_WRONG_DB:
1258 ereport(ERROR,
1259 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1260 errmsg("cross-database references are not implemented: %s",
1261 NameListToString(cref->fields)),
1262 parser_errposition(pstate, cref->location)));
1263 break;
1264 case CRSERR_TOO_MANY:
1265 ereport(ERROR,
1266 (errcode(ERRCODE_SYNTAX_ERROR),
1267 errmsg("improper qualified name (too many dotted names): %s",
1268 NameListToString(cref->fields)),
1269 parser_errposition(pstate, cref->location)));
1270 break;
1275 * OK, expand the nsitem into fields.
1277 return ExpandSingleTable(pstate, nsitem, levels_up, cref->location,
1278 make_target_entry);
1283 * ExpandAllTables()
1284 * Transforms '*' (in the target list) into a list of targetlist entries.
1286 * tlist entries are generated for each relation visible for unqualified
1287 * column name access. We do not consider qualified-name-only entries because
1288 * that would include input tables of aliasless JOINs, NEW/OLD pseudo-entries,
1289 * etc.
1291 * The referenced relations/columns are marked as requiring SELECT access.
1293 static List *
1294 ExpandAllTables(ParseState *pstate, int location)
1296 List *target = NIL;
1297 bool found_table = false;
1298 ListCell *l;
1300 foreach(l, pstate->p_namespace)
1302 ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1304 /* Ignore table-only items */
1305 if (!nsitem->p_cols_visible)
1306 continue;
1307 /* Should not have any lateral-only items when parsing targetlist */
1308 Assert(!nsitem->p_lateral_only);
1309 /* Remember we found a p_cols_visible item */
1310 found_table = true;
1312 target = list_concat(target,
1313 expandNSItemAttrs(pstate,
1314 nsitem,
1316 true,
1317 location));
1321 * Check for "SELECT *;". We do it this way, rather than checking for
1322 * target == NIL, because we want to allow SELECT * FROM a zero_column
1323 * table.
1325 if (!found_table)
1326 ereport(ERROR,
1327 (errcode(ERRCODE_SYNTAX_ERROR),
1328 errmsg("SELECT * with no tables specified is not valid"),
1329 parser_errposition(pstate, location)));
1331 return target;
1335 * ExpandIndirectionStar()
1336 * Transforms foo.* into a list of expressions or targetlist entries.
1338 * This handles the case where '*' appears as the last item in A_Indirection.
1339 * The code is shared between the case of foo.* at the top level in a SELECT
1340 * target list (where we want TargetEntry nodes in the result) and foo.* in
1341 * a ROW() or VALUES() construct (where we want just bare expressions).
1342 * For robustness, we use a separate "make_target_entry" flag to control
1343 * this rather than relying on exprKind.
1345 static List *
1346 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1347 bool make_target_entry, ParseExprKind exprKind)
1349 Node *expr;
1351 /* Strip off the '*' to create a reference to the rowtype object */
1352 ind = copyObject(ind);
1353 ind->indirection = list_truncate(ind->indirection,
1354 list_length(ind->indirection) - 1);
1356 /* And transform that */
1357 expr = transformExpr(pstate, (Node *) ind, exprKind);
1359 /* Expand the rowtype expression into individual fields */
1360 return ExpandRowReference(pstate, expr, make_target_entry);
1364 * ExpandSingleTable()
1365 * Transforms foo.* into a list of expressions or targetlist entries.
1367 * This handles the case where foo has been determined to be a simple
1368 * reference to an RTE, so we can just generate Vars for the expressions.
1370 * The referenced columns are marked as requiring SELECT access.
1372 static List *
1373 ExpandSingleTable(ParseState *pstate, ParseNamespaceItem *nsitem,
1374 int sublevels_up, int location, bool make_target_entry)
1376 if (make_target_entry)
1378 /* expandNSItemAttrs handles permissions marking */
1379 return expandNSItemAttrs(pstate, nsitem, sublevels_up, true, location);
1381 else
1383 RangeTblEntry *rte = nsitem->p_rte;
1384 RTEPermissionInfo *perminfo = nsitem->p_perminfo;
1385 List *vars;
1386 ListCell *l;
1388 vars = expandNSItemVars(pstate, nsitem, sublevels_up, location, NULL);
1391 * Require read access to the table. This is normally redundant with
1392 * the markVarForSelectPriv calls below, but not if the table has zero
1393 * columns. We need not do anything if the nsitem is for a join: its
1394 * component tables will have been marked ACL_SELECT when they were
1395 * added to the rangetable. (This step changes things only for the
1396 * target relation of UPDATE/DELETE, which cannot be under a join.)
1398 if (rte->rtekind == RTE_RELATION)
1400 Assert(perminfo != NULL);
1401 perminfo->requiredPerms |= ACL_SELECT;
1404 /* Require read access to each column */
1405 foreach(l, vars)
1407 Var *var = (Var *) lfirst(l);
1409 markVarForSelectPriv(pstate, var);
1412 return vars;
1417 * ExpandRowReference()
1418 * Transforms foo.* into a list of expressions or targetlist entries.
1420 * This handles the case where foo is an arbitrary expression of composite
1421 * type.
1423 static List *
1424 ExpandRowReference(ParseState *pstate, Node *expr,
1425 bool make_target_entry)
1427 List *result = NIL;
1428 TupleDesc tupleDesc;
1429 int numAttrs;
1430 int i;
1433 * If the rowtype expression is a whole-row Var, we can expand the fields
1434 * as simple Vars. Note: if the RTE is a relation, this case leaves us
1435 * with its RTEPermissionInfo's selectedCols bitmap showing the whole row
1436 * as needing select permission, as well as the individual columns.
1437 * However, we can only get here for weird notations like (table.*).*, so
1438 * it's not worth trying to clean up --- arguably, the permissions marking
1439 * is correct anyway for such cases.
1441 if (IsA(expr, Var) &&
1442 ((Var *) expr)->varattno == InvalidAttrNumber)
1444 Var *var = (Var *) expr;
1445 ParseNamespaceItem *nsitem;
1447 nsitem = GetNSItemByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1448 return ExpandSingleTable(pstate, nsitem, var->varlevelsup, var->location, make_target_entry);
1452 * Otherwise we have to do it the hard way. Our current implementation is
1453 * to generate multiple copies of the expression and do FieldSelects.
1454 * (This can be pretty inefficient if the expression involves nontrivial
1455 * computation :-(.)
1457 * Verify it's a composite type, and get the tupdesc.
1458 * get_expr_result_tupdesc() handles this conveniently.
1460 * If it's a Var of type RECORD, we have to work even harder: we have to
1461 * find what the Var refers to, and pass that to get_expr_result_tupdesc.
1462 * That task is handled by expandRecordVariable().
1464 if (IsA(expr, Var) &&
1465 ((Var *) expr)->vartype == RECORDOID)
1466 tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1467 else
1468 tupleDesc = get_expr_result_tupdesc(expr, false);
1469 Assert(tupleDesc);
1471 /* Generate a list of references to the individual fields */
1472 numAttrs = tupleDesc->natts;
1473 for (i = 0; i < numAttrs; i++)
1475 Form_pg_attribute att = TupleDescAttr(tupleDesc, i);
1476 FieldSelect *fselect;
1478 if (att->attisdropped)
1479 continue;
1481 fselect = makeNode(FieldSelect);
1482 fselect->arg = (Expr *) copyObject(expr);
1483 fselect->fieldnum = i + 1;
1484 fselect->resulttype = att->atttypid;
1485 fselect->resulttypmod = att->atttypmod;
1486 /* save attribute's collation for parse_collate.c */
1487 fselect->resultcollid = att->attcollation;
1489 if (make_target_entry)
1491 /* add TargetEntry decoration */
1492 TargetEntry *te;
1494 te = makeTargetEntry((Expr *) fselect,
1495 (AttrNumber) pstate->p_next_resno++,
1496 pstrdup(NameStr(att->attname)),
1497 false);
1498 result = lappend(result, te);
1500 else
1501 result = lappend(result, fselect);
1504 return result;
1508 * expandRecordVariable
1509 * Get the tuple descriptor for a Var of type RECORD, if possible.
1511 * Since no actual table or view column is allowed to have type RECORD, such
1512 * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
1513 * drill down to find the ultimate defining expression and attempt to infer
1514 * the tupdesc from it. We ereport if we can't determine the tupdesc.
1516 * levelsup is an extra offset to interpret the Var's varlevelsup correctly
1517 * when recursing. Outside callers should pass zero.
1519 TupleDesc
1520 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1522 TupleDesc tupleDesc;
1523 int netlevelsup;
1524 RangeTblEntry *rte;
1525 AttrNumber attnum;
1526 Node *expr;
1528 /* Check my caller didn't mess up */
1529 Assert(IsA(var, Var));
1530 Assert(var->vartype == RECORDOID);
1533 * Note: it's tempting to use GetNSItemByRangeTablePosn here so that we
1534 * can use expandNSItemVars instead of expandRTE; but that does not work
1535 * for some of the recursion cases below, where we have consed up a
1536 * ParseState that lacks p_namespace data.
1538 netlevelsup = var->varlevelsup + levelsup;
1539 rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1540 attnum = var->varattno;
1542 if (attnum == InvalidAttrNumber)
1544 /* Whole-row reference to an RTE, so expand the known fields */
1545 List *names,
1546 *vars;
1547 ListCell *lname,
1548 *lvar;
1549 int i;
1551 expandRTE(rte, var->varno, 0, var->location, false,
1552 &names, &vars);
1554 tupleDesc = CreateTemplateTupleDesc(list_length(vars));
1555 i = 1;
1556 forboth(lname, names, lvar, vars)
1558 char *label = strVal(lfirst(lname));
1559 Node *varnode = (Node *) lfirst(lvar);
1561 TupleDescInitEntry(tupleDesc, i,
1562 label,
1563 exprType(varnode),
1564 exprTypmod(varnode),
1566 TupleDescInitEntryCollation(tupleDesc, i,
1567 exprCollation(varnode));
1568 i++;
1570 Assert(lname == NULL && lvar == NULL); /* lists same length? */
1572 return tupleDesc;
1575 expr = (Node *) var; /* default if we can't drill down */
1577 switch (rte->rtekind)
1579 case RTE_RELATION:
1580 case RTE_VALUES:
1581 case RTE_NAMEDTUPLESTORE:
1582 case RTE_RESULT:
1585 * This case should not occur: a column of a table, values list,
1586 * or ENR shouldn't have type RECORD. Fall through and fail (most
1587 * likely) at the bottom.
1589 break;
1590 case RTE_SUBQUERY:
1592 /* Subselect-in-FROM: examine sub-select's output expr */
1593 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1594 attnum);
1596 if (ste == NULL || ste->resjunk)
1597 elog(ERROR, "subquery %s does not have attribute %d",
1598 rte->eref->aliasname, attnum);
1599 expr = (Node *) ste->expr;
1600 if (IsA(expr, Var))
1603 * Recurse into the sub-select to see what its Var refers
1604 * to. We have to build an additional level of ParseState
1605 * to keep in step with varlevelsup in the subselect;
1606 * furthermore, the subquery RTE might be from an outer
1607 * query level, in which case the ParseState for the
1608 * subselect must have that outer level as parent.
1610 ParseState mypstate = {0};
1611 Index levelsup;
1613 /* this loop must work, since GetRTEByRangeTablePosn did */
1614 for (levelsup = 0; levelsup < netlevelsup; levelsup++)
1615 pstate = pstate->parentParseState;
1616 mypstate.parentParseState = pstate;
1617 mypstate.p_rtable = rte->subquery->rtable;
1618 /* don't bother filling the rest of the fake pstate */
1620 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1622 /* else fall through to inspect the expression */
1624 break;
1625 case RTE_JOIN:
1626 /* Join RTE --- recursively inspect the alias variable */
1627 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1628 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1629 Assert(expr != NULL);
1630 /* We intentionally don't strip implicit coercions here */
1631 if (IsA(expr, Var))
1632 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1633 /* else fall through to inspect the expression */
1634 break;
1635 case RTE_FUNCTION:
1638 * We couldn't get here unless a function is declared with one of
1639 * its result columns as RECORD, which is not allowed.
1641 break;
1642 case RTE_TABLEFUNC:
1645 * Table function cannot have columns with RECORD type.
1647 break;
1648 case RTE_CTE:
1649 /* CTE reference: examine subquery's output expr */
1650 if (!rte->self_reference)
1652 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1653 TargetEntry *ste;
1655 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1656 if (ste == NULL || ste->resjunk)
1657 elog(ERROR, "CTE %s does not have attribute %d",
1658 rte->eref->aliasname, attnum);
1659 expr = (Node *) ste->expr;
1660 if (IsA(expr, Var))
1663 * Recurse into the CTE to see what its Var refers to. We
1664 * have to build an additional level of ParseState to keep
1665 * in step with varlevelsup in the CTE; furthermore it
1666 * could be an outer CTE (compare SUBQUERY case above).
1668 ParseState mypstate = {0};
1669 Index levelsup;
1671 /* this loop must work, since GetCTEForRTE did */
1672 for (levelsup = 0;
1673 levelsup < rte->ctelevelsup + netlevelsup;
1674 levelsup++)
1675 pstate = pstate->parentParseState;
1676 mypstate.parentParseState = pstate;
1677 mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1678 /* don't bother filling the rest of the fake pstate */
1680 return expandRecordVariable(&mypstate, (Var *) expr, 0);
1682 /* else fall through to inspect the expression */
1684 break;
1688 * We now have an expression we can't expand any more, so see if
1689 * get_expr_result_tupdesc() can do anything with it.
1691 return get_expr_result_tupdesc(expr, false);
1696 * FigureColname -
1697 * if the name of the resulting column is not specified in the target
1698 * list, we have to guess a suitable name. The SQL spec provides some
1699 * guidance, but not much...
1701 * Note that the argument is the *untransformed* parse tree for the target
1702 * item. This is a shade easier to work with than the transformed tree.
1704 char *
1705 FigureColname(Node *node)
1707 char *name = NULL;
1709 (void) FigureColnameInternal(node, &name);
1710 if (name != NULL)
1711 return name;
1712 /* default result if we can't guess anything */
1713 return "?column?";
1717 * FigureIndexColname -
1718 * choose the name for an expression column in an index
1720 * This is actually just like FigureColname, except we return NULL if
1721 * we can't pick a good name.
1723 char *
1724 FigureIndexColname(Node *node)
1726 char *name = NULL;
1728 (void) FigureColnameInternal(node, &name);
1729 return name;
1733 * FigureColnameInternal -
1734 * internal workhorse for FigureColname
1736 * Return value indicates strength of confidence in result:
1737 * 0 - no information
1738 * 1 - second-best name choice
1739 * 2 - good name choice
1740 * The return value is actually only used internally.
1741 * If the result isn't zero, *name is set to the chosen name.
1743 static int
1744 FigureColnameInternal(Node *node, char **name)
1746 int strength = 0;
1748 if (node == NULL)
1749 return strength;
1751 switch (nodeTag(node))
1753 case T_ColumnRef:
1755 char *fname = NULL;
1756 ListCell *l;
1758 /* find last field name, if any, ignoring "*" */
1759 foreach(l, ((ColumnRef *) node)->fields)
1761 Node *i = lfirst(l);
1763 if (IsA(i, String))
1764 fname = strVal(i);
1766 if (fname)
1768 *name = fname;
1769 return 2;
1772 break;
1773 case T_A_Indirection:
1775 A_Indirection *ind = (A_Indirection *) node;
1776 char *fname = NULL;
1777 ListCell *l;
1779 /* find last field name, if any, ignoring "*" and subscripts */
1780 foreach(l, ind->indirection)
1782 Node *i = lfirst(l);
1784 if (IsA(i, String))
1785 fname = strVal(i);
1787 if (fname)
1789 *name = fname;
1790 return 2;
1792 return FigureColnameInternal(ind->arg, name);
1794 break;
1795 case T_FuncCall:
1796 *name = strVal(llast(((FuncCall *) node)->funcname));
1797 return 2;
1798 case T_A_Expr:
1799 if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1801 /* make nullif() act like a regular function */
1802 *name = "nullif";
1803 return 2;
1805 break;
1806 case T_TypeCast:
1807 strength = FigureColnameInternal(((TypeCast *) node)->arg,
1808 name);
1809 if (strength <= 1)
1811 if (((TypeCast *) node)->typeName != NULL)
1813 *name = strVal(llast(((TypeCast *) node)->typeName->names));
1814 return 1;
1817 break;
1818 case T_CollateClause:
1819 return FigureColnameInternal(((CollateClause *) node)->arg, name);
1820 case T_GroupingFunc:
1821 /* make GROUPING() act like a regular function */
1822 *name = "grouping";
1823 return 2;
1824 case T_SubLink:
1825 switch (((SubLink *) node)->subLinkType)
1827 case EXISTS_SUBLINK:
1828 *name = "exists";
1829 return 2;
1830 case ARRAY_SUBLINK:
1831 *name = "array";
1832 return 2;
1833 case EXPR_SUBLINK:
1835 /* Get column name of the subquery's single target */
1836 SubLink *sublink = (SubLink *) node;
1837 Query *query = (Query *) sublink->subselect;
1840 * The subquery has probably already been transformed,
1841 * but let's be careful and check that. (The reason
1842 * we can see a transformed subquery here is that
1843 * transformSubLink is lazy and modifies the SubLink
1844 * node in-place.)
1846 if (IsA(query, Query))
1848 TargetEntry *te = (TargetEntry *) linitial(query->targetList);
1850 if (te->resname)
1852 *name = te->resname;
1853 return 2;
1857 break;
1858 /* As with other operator-like nodes, these have no names */
1859 case MULTIEXPR_SUBLINK:
1860 case ALL_SUBLINK:
1861 case ANY_SUBLINK:
1862 case ROWCOMPARE_SUBLINK:
1863 case CTE_SUBLINK:
1864 break;
1866 break;
1867 case T_CaseExpr:
1868 strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1869 name);
1870 if (strength <= 1)
1872 *name = "case";
1873 return 1;
1875 break;
1876 case T_A_ArrayExpr:
1877 /* make ARRAY[] act like a function */
1878 *name = "array";
1879 return 2;
1880 case T_RowExpr:
1881 /* make ROW() act like a function */
1882 *name = "row";
1883 return 2;
1884 case T_CoalesceExpr:
1885 /* make coalesce() act like a regular function */
1886 *name = "coalesce";
1887 return 2;
1888 case T_MinMaxExpr:
1889 /* make greatest/least act like a regular function */
1890 switch (((MinMaxExpr *) node)->op)
1892 case IS_GREATEST:
1893 *name = "greatest";
1894 return 2;
1895 case IS_LEAST:
1896 *name = "least";
1897 return 2;
1899 break;
1900 case T_SQLValueFunction:
1901 /* make these act like a function or variable */
1902 switch (((SQLValueFunction *) node)->op)
1904 case SVFOP_CURRENT_DATE:
1905 *name = "current_date";
1906 return 2;
1907 case SVFOP_CURRENT_TIME:
1908 case SVFOP_CURRENT_TIME_N:
1909 *name = "current_time";
1910 return 2;
1911 case SVFOP_CURRENT_TIMESTAMP:
1912 case SVFOP_CURRENT_TIMESTAMP_N:
1913 *name = "current_timestamp";
1914 return 2;
1915 case SVFOP_LOCALTIME:
1916 case SVFOP_LOCALTIME_N:
1917 *name = "localtime";
1918 return 2;
1919 case SVFOP_LOCALTIMESTAMP:
1920 case SVFOP_LOCALTIMESTAMP_N:
1921 *name = "localtimestamp";
1922 return 2;
1923 case SVFOP_CURRENT_ROLE:
1924 *name = "current_role";
1925 return 2;
1926 case SVFOP_CURRENT_USER:
1927 *name = "current_user";
1928 return 2;
1929 case SVFOP_USER:
1930 *name = "user";
1931 return 2;
1932 case SVFOP_SESSION_USER:
1933 *name = "session_user";
1934 return 2;
1935 case SVFOP_CURRENT_CATALOG:
1936 *name = "current_catalog";
1937 return 2;
1938 case SVFOP_CURRENT_SCHEMA:
1939 *name = "current_schema";
1940 return 2;
1942 break;
1943 case T_XmlExpr:
1944 /* make SQL/XML functions act like a regular function */
1945 switch (((XmlExpr *) node)->op)
1947 case IS_XMLCONCAT:
1948 *name = "xmlconcat";
1949 return 2;
1950 case IS_XMLELEMENT:
1951 *name = "xmlelement";
1952 return 2;
1953 case IS_XMLFOREST:
1954 *name = "xmlforest";
1955 return 2;
1956 case IS_XMLPARSE:
1957 *name = "xmlparse";
1958 return 2;
1959 case IS_XMLPI:
1960 *name = "xmlpi";
1961 return 2;
1962 case IS_XMLROOT:
1963 *name = "xmlroot";
1964 return 2;
1965 case IS_XMLSERIALIZE:
1966 *name = "xmlserialize";
1967 return 2;
1968 case IS_DOCUMENT:
1969 /* nothing */
1970 break;
1972 break;
1973 case T_XmlSerialize:
1974 /* make XMLSERIALIZE act like a regular function */
1975 *name = "xmlserialize";
1976 return 2;
1977 case T_JsonObjectConstructor:
1978 /* make JSON_OBJECT act like a regular function */
1979 *name = "json_object";
1980 return 2;
1981 case T_JsonArrayConstructor:
1982 case T_JsonArrayQueryConstructor:
1983 /* make JSON_ARRAY act like a regular function */
1984 *name = "json_array";
1985 return 2;
1986 case T_JsonObjectAgg:
1987 /* make JSON_OBJECTAGG act like a regular function */
1988 *name = "json_objectagg";
1989 return 2;
1990 case T_JsonArrayAgg:
1991 /* make JSON_ARRAYAGG act like a regular function */
1992 *name = "json_arrayagg";
1993 return 2;
1994 default:
1995 break;
1998 return strength;