]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_target.c
Support GROUPING SETS, CUBE and ROLLUP.
[postgresql] / src / backend / parser / parse_target.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_target.c
4  *        handle target lists
5  *
6  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/parser/parse_target.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
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/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"
34
35
36 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
37                                          Var *var, int levelsup);
38 static Node *transformAssignmentIndirection(ParseState *pstate,
39                                                            Node *basenode,
40                                                            const char *targetName,
41                                                            bool targetIsArray,
42                                                            Oid targetTypeId,
43                                                            int32 targetTypMod,
44                                                            Oid targetCollation,
45                                                            ListCell *indirection,
46                                                            Node *rhs,
47                                                            int location);
48 static Node *transformAssignmentSubscripts(ParseState *pstate,
49                                                           Node *basenode,
50                                                           const char *targetName,
51                                                           Oid targetTypeId,
52                                                           int32 targetTypMod,
53                                                           Oid targetCollation,
54                                                           List *subscripts,
55                                                           bool isSlice,
56                                                           ListCell *next_indirection,
57                                                           Node *rhs,
58                                                           int location);
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);
69
70
71 /*
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.
76  *
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.
83  */
84 TargetEntry *
85 transformTargetEntry(ParseState *pstate,
86                                          Node *node,
87                                          Node *expr,
88                                          ParseExprKind exprKind,
89                                          char *colname,
90                                          bool resjunk)
91 {
92         /* Transform the node if caller didn't do it already */
93         if (expr == NULL)
94                 expr = transformExpr(pstate, node, exprKind);
95
96         if (colname == NULL && !resjunk)
97         {
98                 /*
99                  * Generate a suitable column name for a column without any explicit
100                  * 'AS ColumnName' clause.
101                  */
102                 colname = FigureColname(node);
103         }
104
105         return makeTargetEntry((Expr *) expr,
106                                                    (AttrNumber) pstate->p_next_resno++,
107                                                    colname,
108                                                    resjunk);
109 }
110
111
112 /*
113  * transformTargetList()
114  * Turns a list of ResTarget's into a list of TargetEntry's.
115  *
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.
119  */
120 List *
121 transformTargetList(ParseState *pstate, List *targetlist,
122                                         ParseExprKind exprKind)
123 {
124         List       *p_target = NIL;
125         ListCell   *o_target;
126
127         /* Shouldn't have any leftover multiassign items at start */
128         Assert(pstate->p_multiassign_exprs == NIL);
129
130         foreach(o_target, targetlist)
131         {
132                 ResTarget  *res = (ResTarget *) lfirst(o_target);
133
134                 /*
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.
138                  */
139                 if (IsA(res->val, ColumnRef))
140                 {
141                         ColumnRef  *cref = (ColumnRef *) res->val;
142
143                         if (IsA(llast(cref->fields), A_Star))
144                         {
145                                 /* It is something.*, expand into multiple items */
146                                 p_target = list_concat(p_target,
147                                                                            ExpandColumnRefStar(pstate, cref,
148                                                                                                                    true));
149                                 continue;
150                         }
151                 }
152                 else if (IsA(res->val, A_Indirection))
153                 {
154                         A_Indirection *ind = (A_Indirection *) res->val;
155
156                         if (IsA(llast(ind->indirection), A_Star))
157                         {
158                                 /* It is something.*, expand into multiple items */
159                                 p_target = list_concat(p_target,
160                                                                            ExpandIndirectionStar(pstate, ind,
161                                                                                                                          true, exprKind));
162                                 continue;
163                         }
164                 }
165
166                 /*
167                  * Not "something.*", so transform as a single expression
168                  */
169                 p_target = lappend(p_target,
170                                                    transformTargetEntry(pstate,
171                                                                                                 res->val,
172                                                                                                 NULL,
173                                                                                                 exprKind,
174                                                                                                 res->name,
175                                                                                                 false));
176         }
177
178         /*
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.
183          */
184         if (pstate->p_multiassign_exprs)
185         {
186                 Assert(exprKind == EXPR_KIND_UPDATE_SOURCE);
187                 p_target = list_concat(p_target, pstate->p_multiassign_exprs);
188                 pstate->p_multiassign_exprs = NIL;
189         }
190
191         return p_target;
192 }
193
194
195 /*
196  * transformExpressionList()
197  *
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.
202  */
203 List *
204 transformExpressionList(ParseState *pstate, List *exprlist,
205                                                 ParseExprKind exprKind)
206 {
207         List       *result = NIL;
208         ListCell   *lc;
209
210         foreach(lc, exprlist)
211         {
212                 Node       *e = (Node *) lfirst(lc);
213
214                 /*
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.
218                  */
219                 if (IsA(e, ColumnRef))
220                 {
221                         ColumnRef  *cref = (ColumnRef *) e;
222
223                         if (IsA(llast(cref->fields), A_Star))
224                         {
225                                 /* It is something.*, expand into multiple items */
226                                 result = list_concat(result,
227                                                                          ExpandColumnRefStar(pstate, cref,
228                                                                                                                  false));
229                                 continue;
230                         }
231                 }
232                 else if (IsA(e, A_Indirection))
233                 {
234                         A_Indirection *ind = (A_Indirection *) e;
235
236                         if (IsA(llast(ind->indirection), A_Star))
237                         {
238                                 /* It is something.*, expand into multiple items */
239                                 result = list_concat(result,
240                                                                          ExpandIndirectionStar(pstate, ind,
241                                                                                                                    false, exprKind));
242                                 continue;
243                         }
244                 }
245
246                 /*
247                  * Not "something.*", so transform as a single expression
248                  */
249                 result = lappend(result,
250                                                  transformExpr(pstate, e, exprKind));
251         }
252
253         /* Shouldn't have any multiassign items here */
254         Assert(pstate->p_multiassign_exprs == NIL);
255
256         return result;
257 }
258
259
260 /*
261  * markTargetListOrigins()
262  *              Mark targetlist columns that are simple Vars with the source
263  *              table's OID and column number.
264  *
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.
267  */
268 void
269 markTargetListOrigins(ParseState *pstate, List *targetlist)
270 {
271         ListCell   *l;
272
273         foreach(l, targetlist)
274         {
275                 TargetEntry *tle = (TargetEntry *) lfirst(l);
276
277                 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
278         }
279 }
280
281 /*
282  * markTargetListOrigin()
283  *              If 'var' is a Var of a plain relation, mark 'tle' with its origin
284  *
285  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
286  *
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.
289  */
290 static void
291 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
292                                          Var *var, int levelsup)
293 {
294         int                     netlevelsup;
295         RangeTblEntry *rte;
296         AttrNumber      attnum;
297
298         if (var == NULL || !IsA(var, Var))
299                 return;
300         netlevelsup = var->varlevelsup + levelsup;
301         rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
302         attnum = var->varattno;
303
304         switch (rte->rtekind)
305         {
306                 case RTE_RELATION:
307                         /* It's a table or view, report it */
308                         tle->resorigtbl = rte->relid;
309                         tle->resorigcol = attnum;
310                         break;
311                 case RTE_SUBQUERY:
312                         /* Subselect-in-FROM: copy up from the subselect */
313                         if (attnum != InvalidAttrNumber)
314                         {
315                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
316                                                                                                         attnum);
317
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;
323                         }
324                         break;
325                 case RTE_JOIN:
326                         /* Join RTE --- recursively inspect the alias variable */
327                         if (attnum != InvalidAttrNumber)
328                         {
329                                 Var                *aliasvar;
330
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);
335                         }
336                         break;
337                 case RTE_FUNCTION:
338                 case RTE_VALUES:
339                         /* not a simple relation, leave it unmarked */
340                         break;
341                 case RTE_CTE:
342
343                         /*
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.
350                          */
351                         if (attnum != InvalidAttrNumber && !rte->self_reference)
352                         {
353                                 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
354                                 TargetEntry *ste;
355
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;
362                         }
363                         break;
364         }
365 }
366
367
368 /*
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().
376  *
377  * pstate               parse state
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
384  *
385  * Returns the modified expression.
386  *
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.
391  */
392 Expr *
393 transformAssignedExpr(ParseState *pstate,
394                                           Expr *expr,
395                                           ParseExprKind exprKind,
396                                           char *colname,
397                                           int attrno,
398                                           List *indirection,
399                                           int location)
400 {
401         Relation        rd = pstate->p_target_relation;
402         Oid                     type_id;                /* type of value provided */
403         Oid                     attrtype;               /* type of target column */
404         int32           attrtypmod;
405         Oid                     attrcollation;  /* collation of target column */
406         ParseExprKind sv_expr_kind;
407
408         /*
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().
412          */
413         Assert(exprKind != EXPR_KIND_NONE);
414         sv_expr_kind = pstate->p_expr_kind;
415         pstate->p_expr_kind = exprKind;
416
417         Assert(rd != NULL);
418         if (attrno <= 0)
419                 ereport(ERROR,
420                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
421                                  errmsg("cannot assign to system column \"%s\"",
422                                                 colname),
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;
427
428         /*
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.
436          */
437         if (expr && IsA(expr, SetToDefault))
438         {
439                 SetToDefault *def = (SetToDefault *) expr;
440
441                 def->typeId = attrtype;
442                 def->typeMod = attrtypmod;
443                 def->collation = attrcollation;
444                 if (indirection)
445                 {
446                         if (IsA(linitial(indirection), A_Indices))
447                                 ereport(ERROR,
448                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
449                                                  errmsg("cannot set an array element to DEFAULT"),
450                                                  parser_errposition(pstate, location)));
451                         else
452                                 ereport(ERROR,
453                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
454                                                  errmsg("cannot set a subfield to DEFAULT"),
455                                                  parser_errposition(pstate, location)));
456                 }
457         }
458
459         /* Now we can use exprType() safely. */
460         type_id = exprType((Node *) expr);
461
462         /*
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.
467          */
468         if (indirection)
469         {
470                 Node       *colVar;
471
472                 if (pstate->p_is_insert)
473                 {
474                         /*
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.
478                          */
479                         colVar = (Node *) makeNullConst(attrtype, attrtypmod,
480                                                                                         attrcollation);
481                 }
482                 else
483                 {
484                         /*
485                          * Build a Var for the column to be updated.
486                          */
487                         colVar = (Node *) make_var(pstate,
488                                                                            pstate->p_target_rangetblentry,
489                                                                            attrno,
490                                                                            location);
491                 }
492
493                 expr = (Expr *)
494                         transformAssignmentIndirection(pstate,
495                                                                                    colVar,
496                                                                                    colname,
497                                                                                    false,
498                                                                                    attrtype,
499                                                                                    attrtypmod,
500                                                                                    attrcollation,
501                                                                                    list_head(indirection),
502                                                                                    (Node *) expr,
503                                                                                    location);
504         }
505         else
506         {
507                 /*
508                  * For normal non-qualified target column, do type checking and
509                  * coercion.
510                  */
511                 Node       *orig_expr = (Node *) expr;
512
513                 expr = (Expr *)
514                         coerce_to_target_type(pstate,
515                                                                   orig_expr, type_id,
516                                                                   attrtype, attrtypmod,
517                                                                   COERCION_ASSIGNMENT,
518                                                                   COERCE_IMPLICIT_CAST,
519                                                                   -1);
520                 if (expr == NULL)
521                         ereport(ERROR,
522                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
523                                          errmsg("column \"%s\" is of type %s"
524                                                         " but expression is of type %s",
525                                                         colname,
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))));
530         }
531
532         pstate->p_expr_kind = sv_expr_kind;
533
534         return expr;
535 }
536
537
538 /*
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
545  *      itself.
546  *
547  * pstate               parse state
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
553  */
554 void
555 updateTargetListEntry(ParseState *pstate,
556                                           TargetEntry *tle,
557                                           char *colname,
558                                           int attrno,
559                                           List *indirection,
560                                           int location)
561 {
562         /* Fix up expression as needed */
563         tle->expr = transformAssignedExpr(pstate,
564                                                                           tle->expr,
565                                                                           EXPR_KIND_UPDATE_TARGET,
566                                                                           colname,
567                                                                           attrno,
568                                                                           indirection,
569                                                                           location);
570
571         /*
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.)
576          */
577         tle->resno = (AttrNumber) attrno;
578         tle->resname = colname;
579 }
580
581
582 /*
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
587  * operation.
588  *
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
592  * needed.
593  *
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
596  * error reporting.
597  *
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).
601  *
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.
604  *
605  * rhs is the already-transformed value to be assigned; note it has not been
606  * coerced to any particular type.
607  *
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.)
612  */
613 static Node *
614 transformAssignmentIndirection(ParseState *pstate,
615                                                            Node *basenode,
616                                                            const char *targetName,
617                                                            bool targetIsArray,
618                                                            Oid targetTypeId,
619                                                            int32 targetTypMod,
620                                                            Oid targetCollation,
621                                                            ListCell *indirection,
622                                                            Node *rhs,
623                                                            int location)
624 {
625         Node       *result;
626         List       *subscripts = NIL;
627         bool            isSlice = false;
628         ListCell   *i;
629
630         if (indirection && !basenode)
631         {
632                 /* Set up a substitution.  We reuse CaseTestExpr for this. */
633                 CaseTestExpr *ctest = makeNode(CaseTestExpr);
634
635                 ctest->typeId = targetTypeId;
636                 ctest->typeMod = targetTypMod;
637                 ctest->collation = targetCollation;
638                 basenode = (Node *) ctest;
639         }
640
641         /*
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.
645          */
646         for_each_cell(i, indirection)
647         {
648                 Node       *n = lfirst(i);
649
650                 if (IsA(n, A_Indices))
651                 {
652                         subscripts = lappend(subscripts, n);
653                         if (((A_Indices *) n)->lidx != NULL)
654                                 isSlice = true;
655                 }
656                 else if (IsA(n, A_Star))
657                 {
658                         ereport(ERROR,
659                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
660                                          errmsg("row expansion via \"*\" is not supported here"),
661                                          parser_errposition(pstate, location)));
662                 }
663                 else
664                 {
665                         FieldStore *fstore;
666                         Oid                     typrelid;
667                         AttrNumber      attnum;
668                         Oid                     fieldTypeId;
669                         int32           fieldTypMod;
670                         Oid                     fieldCollation;
671
672                         Assert(IsA(n, String));
673
674                         /* process subscripts before this field selection */
675                         if (subscripts)
676                         {
677                                 /* recurse, and then return because we're done */
678                                 return transformAssignmentSubscripts(pstate,
679                                                                                                          basenode,
680                                                                                                          targetName,
681                                                                                                          targetTypeId,
682                                                                                                          targetTypMod,
683                                                                                                          targetCollation,
684                                                                                                          subscripts,
685                                                                                                          isSlice,
686                                                                                                          i,
687                                                                                                          rhs,
688                                                                                                          location);
689                         }
690
691                         /* No subscripts, so can process field selection here */
692
693                         typrelid = typeidTypeRelid(targetTypeId);
694                         if (!typrelid)
695                                 ereport(ERROR,
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)));
701
702                         attnum = get_attnum(typrelid, strVal(n));
703                         if (attnum == InvalidAttrNumber)
704                                 ereport(ERROR,
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)));
710                         if (attnum < 0)
711                                 ereport(ERROR,
712                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
713                                                  errmsg("cannot assign to system column \"%s\"",
714                                                                 strVal(n)),
715                                                  parser_errposition(pstate, location)));
716
717                         get_atttypetypmodcoll(typrelid, attnum,
718                                                                 &fieldTypeId, &fieldTypMod, &fieldCollation);
719
720                         /* recurse to create appropriate RHS for field assign */
721                         rhs = transformAssignmentIndirection(pstate,
722                                                                                                  NULL,
723                                                                                                  strVal(n),
724                                                                                                  false,
725                                                                                                  fieldTypeId,
726                                                                                                  fieldTypMod,
727                                                                                                  fieldCollation,
728                                                                                                  lnext(i),
729                                                                                                  rhs,
730                                                                                                  location);
731
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;
738
739                         return (Node *) fstore;
740                 }
741         }
742
743         /* process trailing subscripts, if any */
744         if (subscripts)
745         {
746                 /* recurse, and then return because we're done */
747                 return transformAssignmentSubscripts(pstate,
748                                                                                          basenode,
749                                                                                          targetName,
750                                                                                          targetTypeId,
751                                                                                          targetTypMod,
752                                                                                          targetCollation,
753                                                                                          subscripts,
754                                                                                          isSlice,
755                                                                                          NULL,
756                                                                                          rhs,
757                                                                                          location);
758         }
759
760         /* base case: just coerce RHS to match target type ID */
761
762         result = coerce_to_target_type(pstate,
763                                                                    rhs, exprType(rhs),
764                                                                    targetTypeId, targetTypMod,
765                                                                    COERCION_ASSIGNMENT,
766                                                                    COERCE_IMPLICIT_CAST,
767                                                                    -1);
768         if (result == NULL)
769         {
770                 if (targetIsArray)
771                         ereport(ERROR,
772                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
773                                          errmsg("array assignment to \"%s\" requires type %s"
774                                                         " but expression is of type %s",
775                                                         targetName,
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)));
780                 else
781                         ereport(ERROR,
782                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
783                                          errmsg("subfield \"%s\" is of type %s"
784                                                         " but expression is of type %s",
785                                                         targetName,
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)));
790         }
791
792         return result;
793 }
794
795 /*
796  * helper for transformAssignmentIndirection: process array assignment
797  */
798 static Node *
799 transformAssignmentSubscripts(ParseState *pstate,
800                                                           Node *basenode,
801                                                           const char *targetName,
802                                                           Oid targetTypeId,
803                                                           int32 targetTypMod,
804                                                           Oid targetCollation,
805                                                           List *subscripts,
806                                                           bool isSlice,
807                                                           ListCell *next_indirection,
808                                                           Node *rhs,
809                                                           int location)
810 {
811         Node       *result;
812         Oid                     arrayType;
813         int32           arrayTypMod;
814         Oid                     elementTypeId;
815         Oid                     typeNeeded;
816         Oid                     collationNeeded;
817
818         Assert(subscripts != NIL);
819
820         /* Identify the actual array type and element type involved */
821         arrayType = targetTypeId;
822         arrayTypMod = targetTypMod;
823         elementTypeId = transformArrayType(&arrayType, &arrayTypMod);
824
825         /* Identify type that RHS must provide */
826         typeNeeded = isSlice ? arrayType : elementTypeId;
827
828         /*
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.
832          */
833         if (arrayType == targetTypeId)
834                 collationNeeded = targetCollation;
835         else
836                 collationNeeded = get_typcollation(arrayType);
837
838         /* recurse to create appropriate RHS for array assign */
839         rhs = transformAssignmentIndirection(pstate,
840                                                                                  NULL,
841                                                                                  targetName,
842                                                                                  true,
843                                                                                  typeNeeded,
844                                                                                  arrayTypMod,
845                                                                                  collationNeeded,
846                                                                                  next_indirection,
847                                                                                  rhs,
848                                                                                  location);
849
850         /* process subscripts */
851         result = (Node *) transformArraySubscripts(pstate,
852                                                                                            basenode,
853                                                                                            arrayType,
854                                                                                            elementTypeId,
855                                                                                            arrayTypMod,
856                                                                                            subscripts,
857                                                                                            rhs);
858
859         /* If target was a domain over array, need to coerce up to the domain */
860         if (arrayType != targetTypeId)
861         {
862                 Oid                     resulttype = exprType(result);
863
864                 result = coerce_to_target_type(pstate,
865                                                                            result, resulttype,
866                                                                            targetTypeId, targetTypMod,
867                                                                            COERCION_ASSIGNMENT,
868                                                                            COERCE_IMPLICIT_CAST,
869                                                                            -1);
870                 /* can fail if we had int2vector/oidvector, but not for true domains */
871                 if (result == NULL)
872                         ereport(ERROR,
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)));
878         }
879
880         return result;
881 }
882
883
884 /*
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.
889  */
890 List *
891 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
892 {
893         *attrnos = NIL;
894
895         if (cols == NIL)
896         {
897                 /*
898                  * Generate default column list for INSERT.
899                  */
900                 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
901                 int                     numcol = pstate->p_target_relation->rd_rel->relnatts;
902                 int                     i;
903
904                 for (i = 0; i < numcol; i++)
905                 {
906                         ResTarget  *col;
907
908                         if (attr[i]->attisdropped)
909                                 continue;
910
911                         col = makeNode(ResTarget);
912                         col->name = pstrdup(NameStr(attr[i]->attname));
913                         col->indirection = NIL;
914                         col->val = NULL;
915                         col->location = -1;
916                         cols = lappend(cols, col);
917                         *attrnos = lappend_int(*attrnos, i + 1);
918                 }
919         }
920         else
921         {
922                 /*
923                  * Do initial validation of user-supplied INSERT column list.
924                  */
925                 Bitmapset  *wholecols = NULL;
926                 Bitmapset  *partialcols = NULL;
927                 ListCell   *tl;
928
929                 foreach(tl, cols)
930                 {
931                         ResTarget  *col = (ResTarget *) lfirst(tl);
932                         char       *name = col->name;
933                         int                     attrno;
934
935                         /* Lookup column name, ereport on failure */
936                         attrno = attnameAttNum(pstate->p_target_relation, name, false);
937                         if (attrno == InvalidAttrNumber)
938                                 ereport(ERROR,
939                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
940                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
941                                                    name,
942                                                  RelationGetRelationName(pstate->p_target_relation)),
943                                                  parser_errposition(pstate, col->location)));
944
945                         /*
946                          * Check for duplicates, but only of whole columns --- we allow
947                          * INSERT INTO foo (col.subcol1, col.subcol2)
948                          */
949                         if (col->indirection == NIL)
950                         {
951                                 /* whole column; must not have any other assignment */
952                                 if (bms_is_member(attrno, wholecols) ||
953                                         bms_is_member(attrno, partialcols))
954                                         ereport(ERROR,
955                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
956                                                          errmsg("column \"%s\" specified more than once",
957                                                                         name),
958                                                          parser_errposition(pstate, col->location)));
959                                 wholecols = bms_add_member(wholecols, attrno);
960                         }
961                         else
962                         {
963                                 /* partial column; must not have any whole assignment */
964                                 if (bms_is_member(attrno, wholecols))
965                                         ereport(ERROR,
966                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
967                                                          errmsg("column \"%s\" specified more than once",
968                                                                         name),
969                                                          parser_errposition(pstate, col->location)));
970                                 partialcols = bms_add_member(partialcols, attrno);
971                         }
972
973                         *attrnos = lappend_int(*attrnos, attrno);
974                 }
975         }
976
977         return cols;
978 }
979
980 /*
981  * ExpandColumnRefStar()
982  *              Transforms foo.* into a list of expressions or targetlist entries.
983  *
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
988  * expressions).
989  *
990  * The referenced columns are marked as requiring SELECT access.
991  */
992 static List *
993 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
994                                         bool make_target_entry)
995 {
996         List       *fields = cref->fields;
997         int                     numnames = list_length(fields);
998
999         if (numnames == 1)
1000         {
1001                 /*
1002                  * Target item is a bare '*', expand all tables
1003                  *
1004                  * (e.g., SELECT * FROM emp, dept)
1005                  *
1006                  * Since the grammar only accepts bare '*' at top level of SELECT, we
1007                  * need not handle the make_target_entry==false case here.
1008                  */
1009                 Assert(make_target_entry);
1010                 return ExpandAllTables(pstate, cref->location);
1011         }
1012         else
1013         {
1014                 /*
1015                  * Target item is relation.*, expand that table
1016                  *
1017                  * (e.g., SELECT emp.*, dname FROM emp, dept)
1018                  *
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.
1027                  */
1028                 char       *nspname = NULL;
1029                 char       *relname = NULL;
1030                 RangeTblEntry *rte = NULL;
1031                 int                     levels_up;
1032                 enum
1033                 {
1034                         CRSERR_NO_RTE,
1035                         CRSERR_WRONG_DB,
1036                         CRSERR_TOO_MANY
1037                 }                       crserr = CRSERR_NO_RTE;
1038
1039                 /*
1040                  * Give the PreParseColumnRefHook, if any, first shot.  If it returns
1041                  * non-null then we should use that expression.
1042                  */
1043                 if (pstate->p_pre_columnref_hook != NULL)
1044                 {
1045                         Node       *node;
1046
1047                         node = (*pstate->p_pre_columnref_hook) (pstate, cref);
1048                         if (node != NULL)
1049                                 return ExpandRowReference(pstate, node, make_target_entry);
1050                 }
1051
1052                 switch (numnames)
1053                 {
1054                         case 2:
1055                                 relname = strVal(linitial(fields));
1056                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
1057                                                                                    cref->location,
1058                                                                                    &levels_up);
1059                                 break;
1060                         case 3:
1061                                 nspname = strVal(linitial(fields));
1062                                 relname = strVal(lsecond(fields));
1063                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
1064                                                                                    cref->location,
1065                                                                                    &levels_up);
1066                                 break;
1067                         case 4:
1068                                 {
1069                                         char       *catname = strVal(linitial(fields));
1070
1071                                         /*
1072                                          * We check the catalog name and then ignore it.
1073                                          */
1074                                         if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1075                                         {
1076                                                 crserr = CRSERR_WRONG_DB;
1077                                                 break;
1078                                         }
1079                                         nspname = strVal(lsecond(fields));
1080                                         relname = strVal(lthird(fields));
1081                                         rte = refnameRangeTblEntry(pstate, nspname, relname,
1082                                                                                            cref->location,
1083                                                                                            &levels_up);
1084                                         break;
1085                                 }
1086                         default:
1087                                 crserr = CRSERR_TOO_MANY;
1088                                 break;
1089                 }
1090
1091                 /*
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
1096                  * happening.)
1097                  */
1098                 if (pstate->p_post_columnref_hook != NULL)
1099                 {
1100                         Node       *node;
1101
1102                         node = (*pstate->p_post_columnref_hook) (pstate, cref,
1103                                                                                                          (Node *) rte);
1104                         if (node != NULL)
1105                         {
1106                                 if (rte != NULL)
1107                                         ereport(ERROR,
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);
1113                         }
1114                 }
1115
1116                 /*
1117                  * Throw error if no translation found.
1118                  */
1119                 if (rte == NULL)
1120                 {
1121                         switch (crserr)
1122                         {
1123                                 case CRSERR_NO_RTE:
1124                                         errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1125                                                                                                                  cref->location));
1126                                         break;
1127                                 case CRSERR_WRONG_DB:
1128                                         ereport(ERROR,
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)));
1133                                         break;
1134                                 case CRSERR_TOO_MANY:
1135                                         ereport(ERROR,
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)));
1140                                         break;
1141                         }
1142                 }
1143
1144                 /*
1145                  * OK, expand the RTE into fields.
1146                  */
1147                 return ExpandSingleTable(pstate, rte, cref->location, make_target_entry);
1148         }
1149 }
1150
1151 /*
1152  * ExpandAllTables()
1153  *              Transforms '*' (in the target list) into a list of targetlist entries.
1154  *
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,
1158  * etc.
1159  *
1160  * The referenced relations/columns are marked as requiring SELECT access.
1161  */
1162 static List *
1163 ExpandAllTables(ParseState *pstate, int location)
1164 {
1165         List       *target = NIL;
1166         bool            found_table = false;
1167         ListCell   *l;
1168
1169         foreach(l, pstate->p_namespace)
1170         {
1171                 ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1172                 RangeTblEntry *rte = nsitem->p_rte;
1173
1174                 /* Ignore table-only items */
1175                 if (!nsitem->p_cols_visible)
1176                         continue;
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 */
1180                 found_table = true;
1181
1182                 target = list_concat(target,
1183                                                          expandRelAttrs(pstate,
1184                                                                                         rte,
1185                                                                                         RTERangeTablePosn(pstate, rte,
1186                                                                                                                           NULL),
1187                                                                                         0,
1188                                                                                         location));
1189         }
1190
1191         /*
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
1194          * table.
1195          */
1196         if (!found_table)
1197                 ereport(ERROR,
1198                                 (errcode(ERRCODE_SYNTAX_ERROR),
1199                                  errmsg("SELECT * with no tables specified is not valid"),
1200                                  parser_errposition(pstate, location)));
1201
1202         return target;
1203 }
1204
1205 /*
1206  * ExpandIndirectionStar()
1207  *              Transforms foo.* into a list of expressions or targetlist entries.
1208  *
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.
1215  */
1216 static List *
1217 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1218                                           bool make_target_entry, ParseExprKind exprKind)
1219 {
1220         Node       *expr;
1221
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);
1226
1227         /* And transform that */
1228         expr = transformExpr(pstate, (Node *) ind, exprKind);
1229
1230         /* Expand the rowtype expression into individual fields */
1231         return ExpandRowReference(pstate, expr, make_target_entry);
1232 }
1233
1234 /*
1235  * ExpandSingleTable()
1236  *              Transforms foo.* into a list of expressions or targetlist entries.
1237  *
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.
1240  *
1241  * The referenced columns are marked as requiring SELECT access.
1242  */
1243 static List *
1244 ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
1245                                   int location, bool make_target_entry)
1246 {
1247         int                     sublevels_up;
1248         int                     rtindex;
1249
1250         rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1251
1252         if (make_target_entry)
1253         {
1254                 /* expandRelAttrs handles permissions marking */
1255                 return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1256                                                           location);
1257         }
1258         else
1259         {
1260                 List       *vars;
1261                 ListCell   *l;
1262
1263                 expandRTE(rte, rtindex, sublevels_up, location, false,
1264                                   NULL, &vars);
1265
1266                 /*
1267                  * Require read access to the table.  This is normally redundant with
1268                  * the markVarForSelectPriv calls below, but not if the table has zero
1269                  * columns.
1270                  */
1271                 rte->requiredPerms |= ACL_SELECT;
1272
1273                 /* Require read access to each column */
1274                 foreach(l, vars)
1275                 {
1276                         Var                *var = (Var *) lfirst(l);
1277
1278                         markVarForSelectPriv(pstate, var, rte);
1279                 }
1280
1281                 return vars;
1282         }
1283 }
1284
1285 /*
1286  * ExpandRowReference()
1287  *              Transforms foo.* into a list of expressions or targetlist entries.
1288  *
1289  * This handles the case where foo is an arbitrary expression of composite
1290  * type.
1291  */
1292 static List *
1293 ExpandRowReference(ParseState *pstate, Node *expr,
1294                                    bool make_target_entry)
1295 {
1296         List       *result = NIL;
1297         TupleDesc       tupleDesc;
1298         int                     numAttrs;
1299         int                     i;
1300
1301         /*
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.
1309          */
1310         if (IsA(expr, Var) &&
1311                 ((Var *) expr)->varattno == InvalidAttrNumber)
1312         {
1313                 Var                *var = (Var *) expr;
1314                 RangeTblEntry *rte;
1315
1316                 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1317                 return ExpandSingleTable(pstate, rte, var->location, make_target_entry);
1318         }
1319
1320         /*
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
1324          * computation :-(.)
1325          *
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.
1331          *
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().
1335          */
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),
1341                                                                                                 exprTypmod(expr));
1342         Assert(tupleDesc);
1343
1344         /* Generate a list of references to the individual fields */
1345         numAttrs = tupleDesc->natts;
1346         for (i = 0; i < numAttrs; i++)
1347         {
1348                 Form_pg_attribute att = tupleDesc->attrs[i];
1349                 FieldSelect *fselect;
1350
1351                 if (att->attisdropped)
1352                         continue;
1353
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;
1361
1362                 if (make_target_entry)
1363                 {
1364                         /* add TargetEntry decoration */
1365                         TargetEntry *te;
1366
1367                         te = makeTargetEntry((Expr *) fselect,
1368                                                                  (AttrNumber) pstate->p_next_resno++,
1369                                                                  pstrdup(NameStr(att->attname)),
1370                                                                  false);
1371                         result = lappend(result, te);
1372                 }
1373                 else
1374                         result = lappend(result, fselect);
1375         }
1376
1377         return result;
1378 }
1379
1380 /*
1381  * expandRecordVariable
1382  *              Get the tuple descriptor for a Var of type RECORD, if possible.
1383  *
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.
1388  *
1389  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1390  */
1391 TupleDesc
1392 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1393 {
1394         TupleDesc       tupleDesc;
1395         int                     netlevelsup;
1396         RangeTblEntry *rte;
1397         AttrNumber      attnum;
1398         Node       *expr;
1399
1400         /* Check my caller didn't mess up */
1401         Assert(IsA(var, Var));
1402         Assert(var->vartype == RECORDOID);
1403
1404         netlevelsup = var->varlevelsup + levelsup;
1405         rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1406         attnum = var->varattno;
1407
1408         if (attnum == InvalidAttrNumber)
1409         {
1410                 /* Whole-row reference to an RTE, so expand the known fields */
1411                 List       *names,
1412                                    *vars;
1413                 ListCell   *lname,
1414                                    *lvar;
1415                 int                     i;
1416
1417                 expandRTE(rte, var->varno, 0, var->location, false,
1418                                   &names, &vars);
1419
1420                 tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1421                 i = 1;
1422                 forboth(lname, names, lvar, vars)
1423                 {
1424                         char       *label = strVal(lfirst(lname));
1425                         Node       *varnode = (Node *) lfirst(lvar);
1426
1427                         TupleDescInitEntry(tupleDesc, i,
1428                                                            label,
1429                                                            exprType(varnode),
1430                                                            exprTypmod(varnode),
1431                                                            0);
1432                         TupleDescInitEntryCollation(tupleDesc, i,
1433                                                                                 exprCollation(varnode));
1434                         i++;
1435                 }
1436                 Assert(lname == NULL && lvar == NULL);  /* lists same length? */
1437
1438                 return tupleDesc;
1439         }
1440
1441         expr = (Node *) var;            /* default if we can't drill down */
1442
1443         switch (rte->rtekind)
1444         {
1445                 case RTE_RELATION:
1446                 case RTE_VALUES:
1447
1448                         /*
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.
1452                          */
1453                         break;
1454                 case RTE_SUBQUERY:
1455                         {
1456                                 /* Subselect-in-FROM: examine sub-select's output expr */
1457                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1458                                                                                                         attnum);
1459
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;
1464                                 if (IsA(expr, Var))
1465                                 {
1466                                         /*
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.
1470                                          */
1471                                         ParseState      mypstate;
1472
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 */
1477
1478                                         return expandRecordVariable(&mypstate, (Var *) expr, 0);
1479                                 }
1480                                 /* else fall through to inspect the expression */
1481                         }
1482                         break;
1483                 case RTE_JOIN:
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 */
1489                         if (IsA(expr, Var))
1490                                 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1491                         /* else fall through to inspect the expression */
1492                         break;
1493                 case RTE_FUNCTION:
1494
1495                         /*
1496                          * We couldn't get here unless a function is declared with one of
1497                          * its result columns as RECORD, which is not allowed.
1498                          */
1499                         break;
1500                 case RTE_CTE:
1501                         /* CTE reference: examine subquery's output expr */
1502                         if (!rte->self_reference)
1503                         {
1504                                 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1505                                 TargetEntry *ste;
1506
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;
1512                                 if (IsA(expr, Var))
1513                                 {
1514                                         /*
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.
1519                                          */
1520                                         ParseState      mypstate;
1521                                         Index           levelsup;
1522
1523                                         MemSet(&mypstate, 0, sizeof(mypstate));
1524                                         /* this loop must work, since GetCTEForRTE did */
1525                                         for (levelsup = 0;
1526                                                  levelsup < rte->ctelevelsup + netlevelsup;
1527                                                  levelsup++)
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 */
1532
1533                                         return expandRecordVariable(&mypstate, (Var *) expr, 0);
1534                                 }
1535                                 /* else fall through to inspect the expression */
1536                         }
1537                         break;
1538         }
1539
1540         /*
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.
1545          */
1546         if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1547                 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1548                                                                                                 exprTypmod(expr));
1549
1550         return tupleDesc;
1551 }
1552
1553
1554 /*
1555  * FigureColname -
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...
1559  *
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.
1562  */
1563 char *
1564 FigureColname(Node *node)
1565 {
1566         char       *name = NULL;
1567
1568         (void) FigureColnameInternal(node, &name);
1569         if (name != NULL)
1570                 return name;
1571         /* default result if we can't guess anything */
1572         return "?column?";
1573 }
1574
1575 /*
1576  * FigureIndexColname -
1577  *        choose the name for an expression column in an index
1578  *
1579  * This is actually just like FigureColname, except we return NULL if
1580  * we can't pick a good name.
1581  */
1582 char *
1583 FigureIndexColname(Node *node)
1584 {
1585         char       *name = NULL;
1586
1587         (void) FigureColnameInternal(node, &name);
1588         return name;
1589 }
1590
1591 /*
1592  * FigureColnameInternal -
1593  *        internal workhorse for FigureColname
1594  *
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.
1601  */
1602 static int
1603 FigureColnameInternal(Node *node, char **name)
1604 {
1605         int                     strength = 0;
1606
1607         if (node == NULL)
1608                 return strength;
1609
1610         switch (nodeTag(node))
1611         {
1612                 case T_ColumnRef:
1613                         {
1614                                 char       *fname = NULL;
1615                                 ListCell   *l;
1616
1617                                 /* find last field name, if any, ignoring "*" */
1618                                 foreach(l, ((ColumnRef *) node)->fields)
1619                                 {
1620                                         Node       *i = lfirst(l);
1621
1622                                         if (IsA(i, String))
1623                                                 fname = strVal(i);
1624                                 }
1625                                 if (fname)
1626                                 {
1627                                         *name = fname;
1628                                         return 2;
1629                                 }
1630                         }
1631                         break;
1632                 case T_A_Indirection:
1633                         {
1634                                 A_Indirection *ind = (A_Indirection *) node;
1635                                 char       *fname = NULL;
1636                                 ListCell   *l;
1637
1638                                 /* find last field name, if any, ignoring "*" and subscripts */
1639                                 foreach(l, ind->indirection)
1640                                 {
1641                                         Node       *i = lfirst(l);
1642
1643                                         if (IsA(i, String))
1644                                                 fname = strVal(i);
1645                                 }
1646                                 if (fname)
1647                                 {
1648                                         *name = fname;
1649                                         return 2;
1650                                 }
1651                                 return FigureColnameInternal(ind->arg, name);
1652                         }
1653                         break;
1654                 case T_FuncCall:
1655                         *name = strVal(llast(((FuncCall *) node)->funcname));
1656                         return 2;
1657                 case T_A_Expr:
1658                         if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1659                         {
1660                                 /* make nullif() act like a regular function */
1661                                 *name = "nullif";
1662                                 return 2;
1663                         }
1664                         if (((A_Expr *) node)->kind == AEXPR_PAREN)
1665                         {
1666                                 /* look through dummy parenthesis node */
1667                                 return FigureColnameInternal(((A_Expr *) node)->lexpr, name);
1668                         }
1669                         break;
1670                 case T_TypeCast:
1671                         strength = FigureColnameInternal(((TypeCast *) node)->arg,
1672                                                                                          name);
1673                         if (strength <= 1)
1674                         {
1675                                 if (((TypeCast *) node)->typeName != NULL)
1676                                 {
1677                                         *name = strVal(llast(((TypeCast *) node)->typeName->names));
1678                                         return 1;
1679                                 }
1680                         }
1681                         break;
1682                 case T_CollateClause:
1683                         return FigureColnameInternal(((CollateClause *) node)->arg, name);
1684                 case T_GroupingFunc:
1685                         /* make GROUPING() act like a regular function */
1686                         *name = "grouping";
1687                         return 2;
1688                 case T_SubLink:
1689                         switch (((SubLink *) node)->subLinkType)
1690                         {
1691                                 case EXISTS_SUBLINK:
1692                                         *name = "exists";
1693                                         return 2;
1694                                 case ARRAY_SUBLINK:
1695                                         *name = "array";
1696                                         return 2;
1697                                 case EXPR_SUBLINK:
1698                                         {
1699                                                 /* Get column name of the subquery's single target */
1700                                                 SubLink    *sublink = (SubLink *) node;
1701                                                 Query      *query = (Query *) sublink->subselect;
1702
1703                                                 /*
1704                                                  * The subquery has probably already been transformed,
1705                                                  * but let's be careful and check that.  (The reason
1706                                                  * we can see a transformed subquery here is that
1707                                                  * transformSubLink is lazy and modifies the SubLink
1708                                                  * node in-place.)
1709                                                  */
1710                                                 if (IsA(query, Query))
1711                                                 {
1712                                                         TargetEntry *te = (TargetEntry *) linitial(query->targetList);
1713
1714                                                         if (te->resname)
1715                                                         {
1716                                                                 *name = te->resname;
1717                                                                 return 2;
1718                                                         }
1719                                                 }
1720                                         }
1721                                         break;
1722                                         /* As with other operator-like nodes, these have no names */
1723                                 case MULTIEXPR_SUBLINK:
1724                                 case ALL_SUBLINK:
1725                                 case ANY_SUBLINK:
1726                                 case ROWCOMPARE_SUBLINK:
1727                                 case CTE_SUBLINK:
1728                                         break;
1729                         }
1730                         break;
1731                 case T_CaseExpr:
1732                         strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1733                                                                                          name);
1734                         if (strength <= 1)
1735                         {
1736                                 *name = "case";
1737                                 return 1;
1738                         }
1739                         break;
1740                 case T_A_ArrayExpr:
1741                         /* make ARRAY[] act like a function */
1742                         *name = "array";
1743                         return 2;
1744                 case T_RowExpr:
1745                         /* make ROW() act like a function */
1746                         *name = "row";
1747                         return 2;
1748                 case T_CoalesceExpr:
1749                         /* make coalesce() act like a regular function */
1750                         *name = "coalesce";
1751                         return 2;
1752                 case T_MinMaxExpr:
1753                         /* make greatest/least act like a regular function */
1754                         switch (((MinMaxExpr *) node)->op)
1755                         {
1756                                 case IS_GREATEST:
1757                                         *name = "greatest";
1758                                         return 2;
1759                                 case IS_LEAST:
1760                                         *name = "least";
1761                                         return 2;
1762                         }
1763                         break;
1764                 case T_XmlExpr:
1765                         /* make SQL/XML functions act like a regular function */
1766                         switch (((XmlExpr *) node)->op)
1767                         {
1768                                 case IS_XMLCONCAT:
1769                                         *name = "xmlconcat";
1770                                         return 2;
1771                                 case IS_XMLELEMENT:
1772                                         *name = "xmlelement";
1773                                         return 2;
1774                                 case IS_XMLFOREST:
1775                                         *name = "xmlforest";
1776                                         return 2;
1777                                 case IS_XMLPARSE:
1778                                         *name = "xmlparse";
1779                                         return 2;
1780                                 case IS_XMLPI:
1781                                         *name = "xmlpi";
1782                                         return 2;
1783                                 case IS_XMLROOT:
1784                                         *name = "xmlroot";
1785                                         return 2;
1786                                 case IS_XMLSERIALIZE:
1787                                         *name = "xmlserialize";
1788                                         return 2;
1789                                 case IS_DOCUMENT:
1790                                         /* nothing */
1791                                         break;
1792                         }
1793                         break;
1794                 case T_XmlSerialize:
1795                         *name = "xmlserialize";
1796                         return 2;
1797                 default:
1798                         break;
1799         }
1800
1801         return strength;
1802 }