OSDN Git Service

Revise collation derivation method and expression-tree representation.
[pg-rex/syncrep.git] / src / backend / parser / parse_target.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_target.c
4  *        handle target lists
5  *
6  * Portions Copyright (c) 1996-2011, 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/typcache.h"
33
34
35 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
36                                          Var *var, int levelsup);
37 static Node *transformAssignmentIndirection(ParseState *pstate,
38                                                            Node *basenode,
39                                                            const char *targetName,
40                                                            bool targetIsArray,
41                                                            Oid targetTypeId,
42                                                            int32 targetTypMod,
43                                                            ListCell *indirection,
44                                                            Node *rhs,
45                                                            int location);
46 static Node *transformAssignmentSubscripts(ParseState *pstate,
47                                                           Node *basenode,
48                                                           const char *targetName,
49                                                           Oid targetTypeId,
50                                                           int32 targetTypMod,
51                                                           List *subscripts,
52                                                           bool isSlice,
53                                                           ListCell *next_indirection,
54                                                           Node *rhs,
55                                                           int location);
56 static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
57                                         bool targetlist);
58 static List *ExpandAllTables(ParseState *pstate, int location);
59 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
60                                           bool targetlist);
61 static List *ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
62                                   int location, bool targetlist);
63 static List *ExpandRowReference(ParseState *pstate, Node *expr,
64                                    bool targetlist);
65 static int      FigureColnameInternal(Node *node, char **name);
66
67
68 /*
69  * transformTargetEntry()
70  *      Transform any ordinary "expression-type" node into a targetlist entry.
71  *      This is exported so that parse_clause.c can generate targetlist entries
72  *      for ORDER/GROUP BY items that are not already in the targetlist.
73  *
74  * node         the (untransformed) parse tree for the value expression.
75  * expr         the transformed expression, or NULL if caller didn't do it yet.
76  * colname      the column name to be assigned, or NULL if none yet set.
77  * resjunk      true if the target should be marked resjunk, ie, it is not
78  *                      wanted in the final projected tuple.
79  */
80 TargetEntry *
81 transformTargetEntry(ParseState *pstate,
82                                          Node *node,
83                                          Node *expr,
84                                          char *colname,
85                                          bool resjunk)
86 {
87         /* Transform the node if caller didn't do it already */
88         if (expr == NULL)
89                 expr = transformExpr(pstate, node);
90
91         if (colname == NULL && !resjunk)
92         {
93                 /*
94                  * Generate a suitable column name for a column without any explicit
95                  * 'AS ColumnName' clause.
96                  */
97                 colname = FigureColname(node);
98         }
99
100         return makeTargetEntry((Expr *) expr,
101                                                    (AttrNumber) pstate->p_next_resno++,
102                                                    colname,
103                                                    resjunk);
104 }
105
106
107 /*
108  * transformTargetList()
109  * Turns a list of ResTarget's into a list of TargetEntry's.
110  *
111  * At this point, we don't care whether we are doing SELECT, INSERT,
112  * or UPDATE; we just transform the given expressions (the "val" fields).
113  */
114 List *
115 transformTargetList(ParseState *pstate, List *targetlist)
116 {
117         List       *p_target = NIL;
118         ListCell   *o_target;
119
120         foreach(o_target, targetlist)
121         {
122                 ResTarget  *res = (ResTarget *) lfirst(o_target);
123
124                 /*
125                  * Check for "something.*".  Depending on the complexity of the
126                  * "something", the star could appear as the last field in ColumnRef,
127                  * or as the last indirection item in A_Indirection.
128                  */
129                 if (IsA(res->val, ColumnRef))
130                 {
131                         ColumnRef  *cref = (ColumnRef *) res->val;
132
133                         if (IsA(llast(cref->fields), A_Star))
134                         {
135                                 /* It is something.*, expand into multiple items */
136                                 p_target = list_concat(p_target,
137                                                                            ExpandColumnRefStar(pstate, cref,
138                                                                                                                    true));
139                                 continue;
140                         }
141                 }
142                 else if (IsA(res->val, A_Indirection))
143                 {
144                         A_Indirection *ind = (A_Indirection *) res->val;
145
146                         if (IsA(llast(ind->indirection), A_Star))
147                         {
148                                 /* It is something.*, expand into multiple items */
149                                 p_target = list_concat(p_target,
150                                                                            ExpandIndirectionStar(pstate, ind,
151                                                                                                                          true));
152                                 continue;
153                         }
154                 }
155
156                 /*
157                  * Not "something.*", so transform as a single expression
158                  */
159                 p_target = lappend(p_target,
160                                                    transformTargetEntry(pstate,
161                                                                                                 res->val,
162                                                                                                 NULL,
163                                                                                                 res->name,
164                                                                                                 false));
165         }
166
167         return p_target;
168 }
169
170
171 /*
172  * transformExpressionList()
173  *
174  * This is the identical transformation to transformTargetList, except that
175  * the input list elements are bare expressions without ResTarget decoration,
176  * and the output elements are likewise just expressions without TargetEntry
177  * decoration.  We use this for ROW() and VALUES() constructs.
178  */
179 List *
180 transformExpressionList(ParseState *pstate, List *exprlist)
181 {
182         List       *result = NIL;
183         ListCell   *lc;
184
185         foreach(lc, exprlist)
186         {
187                 Node       *e = (Node *) lfirst(lc);
188
189                 /*
190                  * Check for "something.*".  Depending on the complexity of the
191                  * "something", the star could appear as the last field in ColumnRef,
192                  * or as the last indirection item in A_Indirection.
193                  */
194                 if (IsA(e, ColumnRef))
195                 {
196                         ColumnRef  *cref = (ColumnRef *) e;
197
198                         if (IsA(llast(cref->fields), A_Star))
199                         {
200                                 /* It is something.*, expand into multiple items */
201                                 result = list_concat(result,
202                                                                          ExpandColumnRefStar(pstate, cref,
203                                                                                                                  false));
204                                 continue;
205                         }
206                 }
207                 else if (IsA(e, A_Indirection))
208                 {
209                         A_Indirection *ind = (A_Indirection *) e;
210
211                         if (IsA(llast(ind->indirection), A_Star))
212                         {
213                                 /* It is something.*, expand into multiple items */
214                                 result = list_concat(result,
215                                                                          ExpandIndirectionStar(pstate, ind,
216                                                                                                                    false));
217                                 continue;
218                         }
219                 }
220
221                 /*
222                  * Not "something.*", so transform as a single expression
223                  */
224                 result = lappend(result,
225                                                  transformExpr(pstate, e));
226         }
227
228         return result;
229 }
230
231
232 /*
233  * markTargetListOrigins()
234  *              Mark targetlist columns that are simple Vars with the source
235  *              table's OID and column number.
236  *
237  * Currently, this is done only for SELECT targetlists, since we only
238  * need the info if we are going to send it to the frontend.
239  */
240 void
241 markTargetListOrigins(ParseState *pstate, List *targetlist)
242 {
243         ListCell   *l;
244
245         foreach(l, targetlist)
246         {
247                 TargetEntry *tle = (TargetEntry *) lfirst(l);
248
249                 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
250         }
251 }
252
253 /*
254  * markTargetListOrigin()
255  *              If 'var' is a Var of a plain relation, mark 'tle' with its origin
256  *
257  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
258  *
259  * This is split out so it can recurse for join references.  Note that we
260  * do not drill down into views, but report the view as the column owner.
261  */
262 static void
263 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
264                                          Var *var, int levelsup)
265 {
266         int                     netlevelsup;
267         RangeTblEntry *rte;
268         AttrNumber      attnum;
269
270         if (var == NULL || !IsA(var, Var))
271                 return;
272         netlevelsup = var->varlevelsup + levelsup;
273         rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
274         attnum = var->varattno;
275
276         switch (rte->rtekind)
277         {
278                 case RTE_RELATION:
279                         /* It's a table or view, report it */
280                         tle->resorigtbl = rte->relid;
281                         tle->resorigcol = attnum;
282                         break;
283                 case RTE_SUBQUERY:
284                         /* Subselect-in-FROM: copy up from the subselect */
285                         if (attnum != InvalidAttrNumber)
286                         {
287                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
288                                                                                                         attnum);
289
290                                 if (ste == NULL || ste->resjunk)
291                                         elog(ERROR, "subquery %s does not have attribute %d",
292                                                  rte->eref->aliasname, attnum);
293                                 tle->resorigtbl = ste->resorigtbl;
294                                 tle->resorigcol = ste->resorigcol;
295                         }
296                         break;
297                 case RTE_JOIN:
298                         /* Join RTE --- recursively inspect the alias variable */
299                         if (attnum != InvalidAttrNumber)
300                         {
301                                 Var                *aliasvar;
302
303                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
304                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
305                                 markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
306                         }
307                         break;
308                 case RTE_FUNCTION:
309                 case RTE_VALUES:
310                         /* not a simple relation, leave it unmarked */
311                         break;
312                 case RTE_CTE:
313
314                         /*
315                          * CTE reference: copy up from the subquery, if possible. If the
316                          * RTE is a recursive self-reference then we can't do anything
317                          * because we haven't finished analyzing it yet. However, it's no
318                          * big loss because we must be down inside the recursive term of a
319                          * recursive CTE, and so any markings on the current targetlist
320                          * are not going to affect the results anyway.
321                          */
322                         if (attnum != InvalidAttrNumber && !rte->self_reference)
323                         {
324                                 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
325                                 TargetEntry *ste;
326
327                                 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
328                                 if (ste == NULL || ste->resjunk)
329                                         elog(ERROR, "subquery %s does not have attribute %d",
330                                                  rte->eref->aliasname, attnum);
331                                 tle->resorigtbl = ste->resorigtbl;
332                                 tle->resorigcol = ste->resorigcol;
333                         }
334                         break;
335         }
336 }
337
338
339 /*
340  * transformAssignedExpr()
341  *      This is used in INSERT and UPDATE statements only.      It prepares an
342  *      expression for assignment to a column of the target table.
343  *      This includes coercing the given value to the target column's type
344  *      (if necessary), and dealing with any subfield names or subscripts
345  *      attached to the target column itself.  The input expression has
346  *      already been through transformExpr().
347  *
348  * pstate               parse state
349  * expr                 expression to be modified
350  * colname              target column name (ie, name of attribute to be assigned to)
351  * attrno               target attribute number
352  * indirection  subscripts/field names for target column, if any
353  * location             error cursor position for the target column, or -1
354  *
355  * Returns the modified expression.
356  *
357  * Note: location points at the target column name (SET target or INSERT
358  * column name list entry), and must therefore be -1 in an INSERT that
359  * omits the column name list.  So we should usually prefer to use
360  * exprLocation(expr) for errors that can happen in a default INSERT.
361  */
362 Expr *
363 transformAssignedExpr(ParseState *pstate,
364                                           Expr *expr,
365                                           char *colname,
366                                           int attrno,
367                                           List *indirection,
368                                           int location)
369 {
370         Oid                     type_id;                /* type of value provided */
371         Oid                     attrtype;               /* type of target column */
372         int32           attrtypmod;
373         Oid                     attrcollation;
374         Relation        rd = pstate->p_target_relation;
375
376         Assert(rd != NULL);
377         if (attrno <= 0)
378                 ereport(ERROR,
379                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
380                                  errmsg("cannot assign to system column \"%s\"",
381                                                 colname),
382                                  parser_errposition(pstate, location)));
383         attrtype = attnumTypeId(rd, attrno);
384         attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
385         attrcollation = rd->rd_att->attrs[attrno - 1]->attcollation;
386
387         /*
388          * If the expression is a DEFAULT placeholder, insert the attribute's
389          * type/typmod into it so that exprType will report the right things. (We
390          * expect that the eventually substituted default expression will in fact
391          * have this type and typmod.)  Also, reject trying to update a subfield
392          * or array element with DEFAULT, since there can't be any default for
393          * portions of a column.
394          */
395         if (expr && IsA(expr, SetToDefault))
396         {
397                 SetToDefault *def = (SetToDefault *) expr;
398
399                 def->typeId = attrtype;
400                 def->typeMod = attrtypmod;
401                 def->collation = attrcollation;
402                 if (indirection)
403                 {
404                         if (IsA(linitial(indirection), A_Indices))
405                                 ereport(ERROR,
406                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
407                                                  errmsg("cannot set an array element to DEFAULT"),
408                                                  parser_errposition(pstate, location)));
409                         else
410                                 ereport(ERROR,
411                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
412                                                  errmsg("cannot set a subfield to DEFAULT"),
413                                                  parser_errposition(pstate, location)));
414                 }
415         }
416
417         /* Now we can use exprType() safely. */
418         type_id = exprType((Node *) expr);
419
420         /*
421          * If there is indirection on the target column, prepare an array or
422          * subfield assignment expression.      This will generate a new column value
423          * that the source value has been inserted into, which can then be placed
424          * in the new tuple constructed by INSERT or UPDATE.
425          */
426         if (indirection)
427         {
428                 Node       *colVar;
429
430                 if (pstate->p_is_insert)
431                 {
432                         /*
433                          * The command is INSERT INTO table (col.something) ... so there
434                          * is not really a source value to work with. Insert a NULL
435                          * constant as the source value.
436                          */
437                         colVar = (Node *) makeNullConst(attrtype, attrtypmod);
438                 }
439                 else
440                 {
441                         /*
442                          * Build a Var for the column to be updated.
443                          */
444                         colVar = (Node *) make_var(pstate,
445                                                                            pstate->p_target_rangetblentry,
446                                                                            attrno,
447                                                                            location);
448                 }
449
450                 expr = (Expr *)
451                         transformAssignmentIndirection(pstate,
452                                                                                    colVar,
453                                                                                    colname,
454                                                                                    false,
455                                                                                    attrtype,
456                                                                                    attrtypmod,
457                                                                                    list_head(indirection),
458                                                                                    (Node *) expr,
459                                                                                    location);
460         }
461         else
462         {
463                 /*
464                  * For normal non-qualified target column, do type checking and
465                  * coercion.
466                  */
467                 Node       *orig_expr = (Node *) expr;
468
469                 expr = (Expr *)
470                         coerce_to_target_type(pstate,
471                                                                   orig_expr, type_id,
472                                                                   attrtype, attrtypmod,
473                                                                   COERCION_ASSIGNMENT,
474                                                                   COERCE_IMPLICIT_CAST,
475                                                                   -1);
476                 if (expr == NULL)
477                         ereport(ERROR,
478                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
479                                          errmsg("column \"%s\" is of type %s"
480                                                         " but expression is of type %s",
481                                                         colname,
482                                                         format_type_be(attrtype),
483                                                         format_type_be(type_id)),
484                                  errhint("You will need to rewrite or cast the expression."),
485                                          parser_errposition(pstate, exprLocation(orig_expr))));
486         }
487
488         return expr;
489 }
490
491
492 /*
493  * updateTargetListEntry()
494  *      This is used in UPDATE statements only. It prepares an UPDATE
495  *      TargetEntry for assignment to a column of the target table.
496  *      This includes coercing the given value to the target column's type
497  *      (if necessary), and dealing with any subfield names or subscripts
498  *      attached to the target column itself.
499  *
500  * pstate               parse state
501  * tle                  target list entry to be modified
502  * colname              target column name (ie, name of attribute to be assigned to)
503  * attrno               target attribute number
504  * indirection  subscripts/field names for target column, if any
505  * location             error cursor position (should point at column name), or -1
506  */
507 void
508 updateTargetListEntry(ParseState *pstate,
509                                           TargetEntry *tle,
510                                           char *colname,
511                                           int attrno,
512                                           List *indirection,
513                                           int location)
514 {
515         /* Fix up expression as needed */
516         tle->expr = transformAssignedExpr(pstate,
517                                                                           tle->expr,
518                                                                           colname,
519                                                                           attrno,
520                                                                           indirection,
521                                                                           location);
522
523         /*
524          * Set the resno to identify the target column --- the rewriter and
525          * planner depend on this.      We also set the resname to identify the target
526          * column, but this is only for debugging purposes; it should not be
527          * relied on.  (In particular, it might be out of date in a stored rule.)
528          */
529         tle->resno = (AttrNumber) attrno;
530         tle->resname = colname;
531 }
532
533
534 /*
535  * Process indirection (field selection or subscripting) of the target
536  * column in INSERT/UPDATE.  This routine recurses for multiple levels
537  * of indirection --- but note that several adjacent A_Indices nodes in
538  * the indirection list are treated as a single multidimensional subscript
539  * operation.
540  *
541  * In the initial call, basenode is a Var for the target column in UPDATE,
542  * or a null Const of the target's type in INSERT.  In recursive calls,
543  * basenode is NULL, indicating that a substitute node should be consed up if
544  * needed.
545  *
546  * targetName is the name of the field or subfield we're assigning to, and
547  * targetIsArray is true if we're subscripting it.  These are just for
548  * error reporting.
549  *
550  * targetTypeId and targetTypMod indicate the datatype of the object to
551  * be assigned to (initially the target column, later some subobject).
552  *
553  * indirection is the sublist remaining to process.  When it's NULL, we're
554  * done recursing and can just coerce and return the RHS.
555  *
556  * rhs is the already-transformed value to be assigned; note it has not been
557  * coerced to any particular type.
558  *
559  * location is the cursor error position for any errors.  (Note: this points
560  * to the head of the target clause, eg "foo" in "foo.bar[baz]".  Later we
561  * might want to decorate indirection cells with their own location info,
562  * in which case the location argument could probably be dropped.)
563  */
564 static Node *
565 transformAssignmentIndirection(ParseState *pstate,
566                                                            Node *basenode,
567                                                            const char *targetName,
568                                                            bool targetIsArray,
569                                                            Oid targetTypeId,
570                                                            int32 targetTypMod,
571                                                            ListCell *indirection,
572                                                            Node *rhs,
573                                                            int location)
574 {
575         Node       *result;
576         List       *subscripts = NIL;
577         bool            isSlice = false;
578         ListCell   *i;
579
580         if (indirection && !basenode)
581         {
582                 /* Set up a substitution.  We reuse CaseTestExpr for this. */
583                 CaseTestExpr *ctest = makeNode(CaseTestExpr);
584
585                 ctest->typeId = targetTypeId;
586                 ctest->typeMod = targetTypMod;
587                 basenode = (Node *) ctest;
588         }
589
590         /*
591          * We have to split any field-selection operations apart from
592          * subscripting.  Adjacent A_Indices nodes have to be treated as a single
593          * multidimensional subscript operation.
594          */
595         for_each_cell(i, indirection)
596         {
597                 Node       *n = lfirst(i);
598
599                 if (IsA(n, A_Indices))
600                 {
601                         subscripts = lappend(subscripts, n);
602                         if (((A_Indices *) n)->lidx != NULL)
603                                 isSlice = true;
604                 }
605                 else if (IsA(n, A_Star))
606                 {
607                         ereport(ERROR,
608                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
609                                          errmsg("row expansion via \"*\" is not supported here"),
610                                          parser_errposition(pstate, location)));
611                 }
612                 else
613                 {
614                         FieldStore *fstore;
615                         Oid                     typrelid;
616                         AttrNumber      attnum;
617                         Oid                     fieldTypeId;
618                         int32           fieldTypMod;
619
620                         Assert(IsA(n, String));
621
622                         /* process subscripts before this field selection */
623                         if (subscripts)
624                         {
625                                 /* recurse, and then return because we're done */
626                                 return transformAssignmentSubscripts(pstate,
627                                                                                                          basenode,
628                                                                                                          targetName,
629                                                                                                          targetTypeId,
630                                                                                                          targetTypMod,
631                                                                                                          subscripts,
632                                                                                                          isSlice,
633                                                                                                          i,
634                                                                                                          rhs,
635                                                                                                          location);
636                         }
637
638                         /* No subscripts, so can process field selection here */
639
640                         typrelid = typeidTypeRelid(targetTypeId);
641                         if (!typrelid)
642                                 ereport(ERROR,
643                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
644                                                  errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
645                                                                 strVal(n), targetName,
646                                                                 format_type_be(targetTypeId)),
647                                                  parser_errposition(pstate, location)));
648
649                         attnum = get_attnum(typrelid, strVal(n));
650                         if (attnum == InvalidAttrNumber)
651                                 ereport(ERROR,
652                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
653                                                  errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
654                                                                 strVal(n), targetName,
655                                                                 format_type_be(targetTypeId)),
656                                                  parser_errposition(pstate, location)));
657                         if (attnum < 0)
658                                 ereport(ERROR,
659                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
660                                                  errmsg("cannot assign to system column \"%s\"",
661                                                                 strVal(n)),
662                                                  parser_errposition(pstate, location)));
663
664                         get_atttypetypmod(typrelid, attnum,
665                                                           &fieldTypeId, &fieldTypMod);
666
667                         /* recurse to create appropriate RHS for field assign */
668                         rhs = transformAssignmentIndirection(pstate,
669                                                                                                  NULL,
670                                                                                                  strVal(n),
671                                                                                                  false,
672                                                                                                  fieldTypeId,
673                                                                                                  fieldTypMod,
674                                                                                                  lnext(i),
675                                                                                                  rhs,
676                                                                                                  location);
677
678                         /* and build a FieldStore node */
679                         fstore = makeNode(FieldStore);
680                         fstore->arg = (Expr *) basenode;
681                         fstore->newvals = list_make1(rhs);
682                         fstore->fieldnums = list_make1_int(attnum);
683                         fstore->resulttype = targetTypeId;
684
685                         return (Node *) fstore;
686                 }
687         }
688
689         /* process trailing subscripts, if any */
690         if (subscripts)
691         {
692                 /* recurse, and then return because we're done */
693                 return transformAssignmentSubscripts(pstate,
694                                                                                          basenode,
695                                                                                          targetName,
696                                                                                          targetTypeId,
697                                                                                          targetTypMod,
698                                                                                          subscripts,
699                                                                                          isSlice,
700                                                                                          NULL,
701                                                                                          rhs,
702                                                                                          location);
703         }
704
705         /* base case: just coerce RHS to match target type ID */
706
707         result = coerce_to_target_type(pstate,
708                                                                    rhs, exprType(rhs),
709                                                                    targetTypeId, targetTypMod,
710                                                                    COERCION_ASSIGNMENT,
711                                                                    COERCE_IMPLICIT_CAST,
712                                                                    -1);
713         if (result == NULL)
714         {
715                 if (targetIsArray)
716                         ereport(ERROR,
717                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
718                                          errmsg("array assignment to \"%s\" requires type %s"
719                                                         " but expression is of type %s",
720                                                         targetName,
721                                                         format_type_be(targetTypeId),
722                                                         format_type_be(exprType(rhs))),
723                                  errhint("You will need to rewrite or cast the expression."),
724                                          parser_errposition(pstate, location)));
725                 else
726                         ereport(ERROR,
727                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
728                                          errmsg("subfield \"%s\" is of type %s"
729                                                         " but expression is of type %s",
730                                                         targetName,
731                                                         format_type_be(targetTypeId),
732                                                         format_type_be(exprType(rhs))),
733                                  errhint("You will need to rewrite or cast the expression."),
734                                          parser_errposition(pstate, location)));
735         }
736
737         return result;
738 }
739
740 /*
741  * helper for transformAssignmentIndirection: process array assignment
742  */
743 static Node *
744 transformAssignmentSubscripts(ParseState *pstate,
745                                                           Node *basenode,
746                                                           const char *targetName,
747                                                           Oid targetTypeId,
748                                                           int32 targetTypMod,
749                                                           List *subscripts,
750                                                           bool isSlice,
751                                                           ListCell *next_indirection,
752                                                           Node *rhs,
753                                                           int location)
754 {
755         Node       *result;
756         Oid                     arrayType;
757         int32           arrayTypMod;
758         Oid                     elementTypeId;
759         Oid                     typeNeeded;
760
761         Assert(subscripts != NIL);
762
763         /* Identify the actual array type and element type involved */
764         arrayType = targetTypeId;
765         arrayTypMod = targetTypMod;
766         elementTypeId = transformArrayType(&arrayType, &arrayTypMod);
767
768         /* Identify type that RHS must provide */
769         typeNeeded = isSlice ? arrayType : elementTypeId;
770
771         /* recurse to create appropriate RHS for array assign */
772         rhs = transformAssignmentIndirection(pstate,
773                                                                                  NULL,
774                                                                                  targetName,
775                                                                                  true,
776                                                                                  typeNeeded,
777                                                                                  arrayTypMod,
778                                                                                  next_indirection,
779                                                                                  rhs,
780                                                                                  location);
781
782         /* process subscripts */
783         result = (Node *) transformArraySubscripts(pstate,
784                                                                                            basenode,
785                                                                                            arrayType,
786                                                                                            elementTypeId,
787                                                                                            arrayTypMod,
788                                                                                            subscripts,
789                                                                                            rhs);
790
791         /* If target was a domain over array, need to coerce up to the domain */
792         if (arrayType != targetTypeId)
793         {
794                 result = coerce_to_target_type(pstate,
795                                                                            result, exprType(result),
796                                                                            targetTypeId, targetTypMod,
797                                                                            COERCION_ASSIGNMENT,
798                                                                            COERCE_IMPLICIT_CAST,
799                                                                            -1);
800                 /* probably shouldn't fail, but check */
801                 if (result == NULL)
802                         ereport(ERROR,
803                                         (errcode(ERRCODE_CANNOT_COERCE),
804                                          errmsg("cannot cast type %s to %s",
805                                                         format_type_be(exprType(result)),
806                                                         format_type_be(targetTypeId)),
807                                          parser_errposition(pstate, location)));
808         }
809
810         return result;
811 }
812
813
814 /*
815  * checkInsertTargets -
816  *        generate a list of INSERT column targets if not supplied, or
817  *        test supplied column names to make sure they are in target table.
818  *        Also return an integer list of the columns' attribute numbers.
819  */
820 List *
821 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
822 {
823         *attrnos = NIL;
824
825         if (cols == NIL)
826         {
827                 /*
828                  * Generate default column list for INSERT.
829                  */
830                 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
831                 int                     numcol = pstate->p_target_relation->rd_rel->relnatts;
832                 int                     i;
833
834                 for (i = 0; i < numcol; i++)
835                 {
836                         ResTarget  *col;
837
838                         if (attr[i]->attisdropped)
839                                 continue;
840
841                         col = makeNode(ResTarget);
842                         col->name = pstrdup(NameStr(attr[i]->attname));
843                         col->indirection = NIL;
844                         col->val = NULL;
845                         col->location = -1;
846                         cols = lappend(cols, col);
847                         *attrnos = lappend_int(*attrnos, i + 1);
848                 }
849         }
850         else
851         {
852                 /*
853                  * Do initial validation of user-supplied INSERT column list.
854                  */
855                 Bitmapset  *wholecols = NULL;
856                 Bitmapset  *partialcols = NULL;
857                 ListCell   *tl;
858
859                 foreach(tl, cols)
860                 {
861                         ResTarget  *col = (ResTarget *) lfirst(tl);
862                         char       *name = col->name;
863                         int                     attrno;
864
865                         /* Lookup column name, ereport on failure */
866                         attrno = attnameAttNum(pstate->p_target_relation, name, false);
867                         if (attrno == InvalidAttrNumber)
868                                 ereport(ERROR,
869                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
870                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
871                                                    name,
872                                                  RelationGetRelationName(pstate->p_target_relation)),
873                                                  parser_errposition(pstate, col->location)));
874
875                         /*
876                          * Check for duplicates, but only of whole columns --- we allow
877                          * INSERT INTO foo (col.subcol1, col.subcol2)
878                          */
879                         if (col->indirection == NIL)
880                         {
881                                 /* whole column; must not have any other assignment */
882                                 if (bms_is_member(attrno, wholecols) ||
883                                         bms_is_member(attrno, partialcols))
884                                         ereport(ERROR,
885                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
886                                                          errmsg("column \"%s\" specified more than once",
887                                                                         name),
888                                                          parser_errposition(pstate, col->location)));
889                                 wholecols = bms_add_member(wholecols, attrno);
890                         }
891                         else
892                         {
893                                 /* partial column; must not have any whole assignment */
894                                 if (bms_is_member(attrno, wholecols))
895                                         ereport(ERROR,
896                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
897                                                          errmsg("column \"%s\" specified more than once",
898                                                                         name),
899                                                          parser_errposition(pstate, col->location)));
900                                 partialcols = bms_add_member(partialcols, attrno);
901                         }
902
903                         *attrnos = lappend_int(*attrnos, attrno);
904                 }
905         }
906
907         return cols;
908 }
909
910 /*
911  * ExpandColumnRefStar()
912  *              Transforms foo.* into a list of expressions or targetlist entries.
913  *
914  * This handles the case where '*' appears as the last or only item in a
915  * ColumnRef.  The code is shared between the case of foo.* at the top level
916  * in a SELECT target list (where we want TargetEntry nodes in the result)
917  * and foo.* in a ROW() or VALUES() construct (where we want just bare
918  * expressions).
919  *
920  * The referenced columns are marked as requiring SELECT access.
921  */
922 static List *
923 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
924                                         bool targetlist)
925 {
926         List       *fields = cref->fields;
927         int                     numnames = list_length(fields);
928
929         if (numnames == 1)
930         {
931                 /*
932                  * Target item is a bare '*', expand all tables
933                  *
934                  * (e.g., SELECT * FROM emp, dept)
935                  *
936                  * Since the grammar only accepts bare '*' at top level of SELECT, we
937                  * need not handle the targetlist==false case here.
938                  */
939                 Assert(targetlist);
940                 return ExpandAllTables(pstate, cref->location);
941         }
942         else
943         {
944                 /*
945                  * Target item is relation.*, expand that table
946                  *
947                  * (e.g., SELECT emp.*, dname FROM emp, dept)
948                  *
949                  * Note: this code is a lot like transformColumnRef; it's tempting to
950                  * call that instead and then replace the resulting whole-row Var with
951                  * a list of Vars.      However, that would leave us with the RTE's
952                  * selectedCols bitmap showing the whole row as needing select
953                  * permission, as well as the individual columns.  That would be
954                  * incorrect (since columns added later shouldn't need select
955                  * permissions).  We could try to remove the whole-row permission bit
956                  * after the fact, but duplicating code is less messy.
957                  */
958                 char       *nspname = NULL;
959                 char       *relname = NULL;
960                 RangeTblEntry *rte = NULL;
961                 int                     levels_up;
962                 enum
963                 {
964                         CRSERR_NO_RTE,
965                         CRSERR_WRONG_DB,
966                         CRSERR_TOO_MANY
967                 }                       crserr = CRSERR_NO_RTE;
968
969                 /*
970                  * Give the PreParseColumnRefHook, if any, first shot.  If it returns
971                  * non-null then we should use that expression.
972                  */
973                 if (pstate->p_pre_columnref_hook != NULL)
974                 {
975                         Node       *node;
976
977                         node = (*pstate->p_pre_columnref_hook) (pstate, cref);
978                         if (node != NULL)
979                                 return ExpandRowReference(pstate, node, targetlist);
980                 }
981
982                 switch (numnames)
983                 {
984                         case 2:
985                                 relname = strVal(linitial(fields));
986                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
987                                                                                    cref->location,
988                                                                                    &levels_up);
989                                 break;
990                         case 3:
991                                 nspname = strVal(linitial(fields));
992                                 relname = strVal(lsecond(fields));
993                                 rte = refnameRangeTblEntry(pstate, nspname, relname,
994                                                                                    cref->location,
995                                                                                    &levels_up);
996                                 break;
997                         case 4:
998                                 {
999                                         char       *catname = strVal(linitial(fields));
1000
1001                                         /*
1002                                          * We check the catalog name and then ignore it.
1003                                          */
1004                                         if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1005                                         {
1006                                                 crserr = CRSERR_WRONG_DB;
1007                                                 break;
1008                                         }
1009                                         nspname = strVal(lsecond(fields));
1010                                         relname = strVal(lthird(fields));
1011                                         rte = refnameRangeTblEntry(pstate, nspname, relname,
1012                                                                                            cref->location,
1013                                                                                            &levels_up);
1014                                         break;
1015                                 }
1016                         default:
1017                                 crserr = CRSERR_TOO_MANY;
1018                                 break;
1019                 }
1020
1021                 /*
1022                  * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1023                  * bit by passing the RangeTblEntry, not a Var, as the planned
1024                  * translation.  (A single Var wouldn't be strictly correct anyway.
1025                  * This convention allows hooks that really care to know what is
1026                  * happening.)
1027                  */
1028                 if (pstate->p_post_columnref_hook != NULL)
1029                 {
1030                         Node       *node;
1031
1032                         node = (*pstate->p_post_columnref_hook) (pstate, cref,
1033                                                                                                          (Node *) rte);
1034                         if (node != NULL)
1035                         {
1036                                 if (rte != NULL)
1037                                         ereport(ERROR,
1038                                                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1039                                                          errmsg("column reference \"%s\" is ambiguous",
1040                                                                         NameListToString(cref->fields)),
1041                                                          parser_errposition(pstate, cref->location)));
1042                                 return ExpandRowReference(pstate, node, targetlist);
1043                         }
1044                 }
1045
1046                 /*
1047                  * Throw error if no translation found.
1048                  */
1049                 if (rte == NULL)
1050                 {
1051                         switch (crserr)
1052                         {
1053                                 case CRSERR_NO_RTE:
1054                                         errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1055                                                                                                                  cref->location));
1056                                         break;
1057                                 case CRSERR_WRONG_DB:
1058                                         ereport(ERROR,
1059                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1060                                                          errmsg("cross-database references are not implemented: %s",
1061                                                                         NameListToString(cref->fields)),
1062                                                          parser_errposition(pstate, cref->location)));
1063                                         break;
1064                                 case CRSERR_TOO_MANY:
1065                                         ereport(ERROR,
1066                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1067                                                          errmsg("improper qualified name (too many dotted names): %s",
1068                                                                         NameListToString(cref->fields)),
1069                                                          parser_errposition(pstate, cref->location)));
1070                                         break;
1071                         }
1072                 }
1073
1074                 /*
1075                  * OK, expand the RTE into fields.
1076                  */
1077                 return ExpandSingleTable(pstate, rte, cref->location, targetlist);
1078         }
1079 }
1080
1081 /*
1082  * ExpandAllTables()
1083  *              Transforms '*' (in the target list) into a list of targetlist entries.
1084  *
1085  * tlist entries are generated for each relation appearing in the query's
1086  * varnamespace.  We do not consider relnamespace because that would include
1087  * input tables of aliasless JOINs, NEW/OLD pseudo-entries, etc.
1088  *
1089  * The referenced relations/columns are marked as requiring SELECT access.
1090  */
1091 static List *
1092 ExpandAllTables(ParseState *pstate, int location)
1093 {
1094         List       *target = NIL;
1095         ListCell   *l;
1096
1097         /* Check for SELECT *; */
1098         if (!pstate->p_varnamespace)
1099                 ereport(ERROR,
1100                                 (errcode(ERRCODE_SYNTAX_ERROR),
1101                                  errmsg("SELECT * with no tables specified is not valid"),
1102                                  parser_errposition(pstate, location)));
1103
1104         foreach(l, pstate->p_varnamespace)
1105         {
1106                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1107                 int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1108
1109                 target = list_concat(target,
1110                                                          expandRelAttrs(pstate, rte, rtindex, 0,
1111                                                                                         location));
1112         }
1113
1114         return target;
1115 }
1116
1117 /*
1118  * ExpandIndirectionStar()
1119  *              Transforms foo.* into a list of expressions or targetlist entries.
1120  *
1121  * This handles the case where '*' appears as the last item in A_Indirection.
1122  * The code is shared between the case of foo.* at the top level in a SELECT
1123  * target list (where we want TargetEntry nodes in the result) and foo.* in
1124  * a ROW() or VALUES() construct (where we want just bare expressions).
1125  */
1126 static List *
1127 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1128                                           bool targetlist)
1129 {
1130         Node       *expr;
1131
1132         /* Strip off the '*' to create a reference to the rowtype object */
1133         ind = copyObject(ind);
1134         ind->indirection = list_truncate(ind->indirection,
1135                                                                          list_length(ind->indirection) - 1);
1136
1137         /* And transform that */
1138         expr = transformExpr(pstate, (Node *) ind);
1139
1140         /* Expand the rowtype expression into individual fields */
1141         return ExpandRowReference(pstate, expr, targetlist);
1142 }
1143
1144 /*
1145  * ExpandSingleTable()
1146  *              Transforms foo.* into a list of expressions or targetlist entries.
1147  *
1148  * This handles the case where foo has been determined to be a simple
1149  * reference to an RTE, so we can just generate Vars for the expressions.
1150  *
1151  * The referenced columns are marked as requiring SELECT access.
1152  */
1153 static List *
1154 ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
1155                                   int location, bool targetlist)
1156 {
1157         int                     sublevels_up;
1158         int                     rtindex;
1159
1160         rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1161
1162         if (targetlist)
1163         {
1164                 /* expandRelAttrs handles permissions marking */
1165                 return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1166                                                           location);
1167         }
1168         else
1169         {
1170                 List       *vars;
1171                 ListCell   *l;
1172
1173                 expandRTE(rte, rtindex, sublevels_up, location, false,
1174                                   NULL, &vars);
1175
1176                 /*
1177                  * Require read access to the table.  This is normally redundant with
1178                  * the markVarForSelectPriv calls below, but not if the table has zero
1179                  * columns.
1180                  */
1181                 rte->requiredPerms |= ACL_SELECT;
1182
1183                 /* Require read access to each column */
1184                 foreach(l, vars)
1185                 {
1186                         Var                *var = (Var *) lfirst(l);
1187
1188                         markVarForSelectPriv(pstate, var, rte);
1189                 }
1190
1191                 return vars;
1192         }
1193 }
1194
1195 /*
1196  * ExpandRowReference()
1197  *              Transforms foo.* into a list of expressions or targetlist entries.
1198  *
1199  * This handles the case where foo is an arbitrary expression of composite
1200  * type.
1201  */
1202 static List *
1203 ExpandRowReference(ParseState *pstate, Node *expr,
1204                                    bool targetlist)
1205 {
1206         List       *result = NIL;
1207         TupleDesc       tupleDesc;
1208         int                     numAttrs;
1209         int                     i;
1210
1211         /*
1212          * If the rowtype expression is a whole-row Var, we can expand the fields
1213          * as simple Vars.      Note: if the RTE is a relation, this case leaves us
1214          * with the RTE's selectedCols bitmap showing the whole row as needing
1215          * select permission, as well as the individual columns.  However, we can
1216          * only get here for weird notations like (table.*).*, so it's not worth
1217          * trying to clean up --- arguably, the permissions marking is correct
1218          * anyway for such cases.
1219          */
1220         if (IsA(expr, Var) &&
1221                 ((Var *) expr)->varattno == InvalidAttrNumber)
1222         {
1223                 Var                *var = (Var *) expr;
1224                 RangeTblEntry *rte;
1225
1226                 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1227                 return ExpandSingleTable(pstate, rte, var->location, targetlist);
1228         }
1229
1230         /*
1231          * Otherwise we have to do it the hard way.  Our current implementation is
1232          * to generate multiple copies of the expression and do FieldSelects.
1233          * (This can be pretty inefficient if the expression involves nontrivial
1234          * computation :-(.)
1235          *
1236          * Verify it's a composite type, and get the tupdesc.  We use
1237          * get_expr_result_type() because that can handle references to functions
1238          * returning anonymous record types.  If that fails, use
1239          * lookup_rowtype_tupdesc(), which will almost certainly fail as well, but
1240          * it will give an appropriate error message.
1241          *
1242          * If it's a Var of type RECORD, we have to work even harder: we have to
1243          * find what the Var refers to, and pass that to get_expr_result_type.
1244          * That task is handled by expandRecordVariable().
1245          */
1246         if (IsA(expr, Var) &&
1247                 ((Var *) expr)->vartype == RECORDOID)
1248                 tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1249         else if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1250                 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1251                                                                                                 exprTypmod(expr));
1252         Assert(tupleDesc);
1253
1254         /* Generate a list of references to the individual fields */
1255         numAttrs = tupleDesc->natts;
1256         for (i = 0; i < numAttrs; i++)
1257         {
1258                 Form_pg_attribute att = tupleDesc->attrs[i];
1259                 FieldSelect *fselect;
1260
1261                 if (att->attisdropped)
1262                         continue;
1263
1264                 fselect = makeNode(FieldSelect);
1265                 fselect->arg = (Expr *) copyObject(expr);
1266                 fselect->fieldnum = i + 1;
1267                 fselect->resulttype = att->atttypid;
1268                 fselect->resulttypmod = att->atttypmod;
1269                 /* resultcollid may get overridden by parse_collate.c */
1270                 fselect->resultcollid = att->attcollation;
1271
1272                 if (targetlist)
1273                 {
1274                         /* add TargetEntry decoration */
1275                         TargetEntry *te;
1276
1277                         te = makeTargetEntry((Expr *) fselect,
1278                                                                  (AttrNumber) pstate->p_next_resno++,
1279                                                                  pstrdup(NameStr(att->attname)),
1280                                                                  false);
1281                         result = lappend(result, te);
1282                 }
1283                 else
1284                         result = lappend(result, fselect);
1285         }
1286
1287         return result;
1288 }
1289
1290 /*
1291  * expandRecordVariable
1292  *              Get the tuple descriptor for a Var of type RECORD, if possible.
1293  *
1294  * Since no actual table or view column is allowed to have type RECORD, such
1295  * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output.  We
1296  * drill down to find the ultimate defining expression and attempt to infer
1297  * the tupdesc from it.  We ereport if we can't determine the tupdesc.
1298  *
1299  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1300  */
1301 TupleDesc
1302 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1303 {
1304         TupleDesc       tupleDesc;
1305         int                     netlevelsup;
1306         RangeTblEntry *rte;
1307         AttrNumber      attnum;
1308         Node       *expr;
1309
1310         /* Check my caller didn't mess up */
1311         Assert(IsA(var, Var));
1312         Assert(var->vartype == RECORDOID);
1313
1314         netlevelsup = var->varlevelsup + levelsup;
1315         rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1316         attnum = var->varattno;
1317
1318         if (attnum == InvalidAttrNumber)
1319         {
1320                 /* Whole-row reference to an RTE, so expand the known fields */
1321                 List       *names,
1322                                    *vars;
1323                 ListCell   *lname,
1324                                    *lvar;
1325                 int                     i;
1326
1327                 expandRTE(rte, var->varno, 0, var->location, false,
1328                                   &names, &vars);
1329
1330                 tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1331                 i = 1;
1332                 forboth(lname, names, lvar, vars)
1333                 {
1334                         char       *label = strVal(lfirst(lname));
1335                         Node       *varnode = (Node *) lfirst(lvar);
1336
1337                         TupleDescInitEntry(tupleDesc, i,
1338                                                            label,
1339                                                            exprType(varnode),
1340                                                            exprTypmod(varnode),
1341                                                            0);
1342                         TupleDescInitEntryCollation(tupleDesc, i,
1343                                                                                 exprCollation(varnode));
1344                         i++;
1345                 }
1346                 Assert(lname == NULL && lvar == NULL);  /* lists same length? */
1347
1348                 return tupleDesc;
1349         }
1350
1351         expr = (Node *) var;            /* default if we can't drill down */
1352
1353         switch (rte->rtekind)
1354         {
1355                 case RTE_RELATION:
1356                 case RTE_VALUES:
1357
1358                         /*
1359                          * This case should not occur: a column of a table or values list
1360                          * shouldn't have type RECORD.  Fall through and fail (most
1361                          * likely) at the bottom.
1362                          */
1363                         break;
1364                 case RTE_SUBQUERY:
1365                         {
1366                                 /* Subselect-in-FROM: examine sub-select's output expr */
1367                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1368                                                                                                         attnum);
1369
1370                                 if (ste == NULL || ste->resjunk)
1371                                         elog(ERROR, "subquery %s does not have attribute %d",
1372                                                  rte->eref->aliasname, attnum);
1373                                 expr = (Node *) ste->expr;
1374                                 if (IsA(expr, Var))
1375                                 {
1376                                         /*
1377                                          * Recurse into the sub-select to see what its Var refers
1378                                          * to.  We have to build an additional level of ParseState
1379                                          * to keep in step with varlevelsup in the subselect.
1380                                          */
1381                                         ParseState      mypstate;
1382
1383                                         MemSet(&mypstate, 0, sizeof(mypstate));
1384                                         mypstate.parentParseState = pstate;
1385                                         mypstate.p_rtable = rte->subquery->rtable;
1386                                         /* don't bother filling the rest of the fake pstate */
1387
1388                                         return expandRecordVariable(&mypstate, (Var *) expr, 0);
1389                                 }
1390                                 /* else fall through to inspect the expression */
1391                         }
1392                         break;
1393                 case RTE_JOIN:
1394                         /* Join RTE --- recursively inspect the alias variable */
1395                         Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1396                         expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1397                         if (IsA(expr, Var))
1398                                 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1399                         /* else fall through to inspect the expression */
1400                         break;
1401                 case RTE_FUNCTION:
1402
1403                         /*
1404                          * We couldn't get here unless a function is declared with one of
1405                          * its result columns as RECORD, which is not allowed.
1406                          */
1407                         break;
1408                 case RTE_CTE:
1409                         /* CTE reference: examine subquery's output expr */
1410                         if (!rte->self_reference)
1411                         {
1412                                 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1413                                 TargetEntry *ste;
1414
1415                                 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1416                                 if (ste == NULL || ste->resjunk)
1417                                         elog(ERROR, "subquery %s does not have attribute %d",
1418                                                  rte->eref->aliasname, attnum);
1419                                 expr = (Node *) ste->expr;
1420                                 if (IsA(expr, Var))
1421                                 {
1422                                         /*
1423                                          * Recurse into the CTE to see what its Var refers to. We
1424                                          * have to build an additional level of ParseState to keep
1425                                          * in step with varlevelsup in the CTE; furthermore it
1426                                          * could be an outer CTE.
1427                                          */
1428                                         ParseState      mypstate;
1429                                         Index           levelsup;
1430
1431                                         MemSet(&mypstate, 0, sizeof(mypstate));
1432                                         /* this loop must work, since GetCTEForRTE did */
1433                                         for (levelsup = 0;
1434                                                  levelsup < rte->ctelevelsup + netlevelsup;
1435                                                  levelsup++)
1436                                                 pstate = pstate->parentParseState;
1437                                         mypstate.parentParseState = pstate;
1438                                         mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1439                                         /* don't bother filling the rest of the fake pstate */
1440
1441                                         return expandRecordVariable(&mypstate, (Var *) expr, 0);
1442                                 }
1443                                 /* else fall through to inspect the expression */
1444                         }
1445                         break;
1446         }
1447
1448         /*
1449          * We now have an expression we can't expand any more, so see if
1450          * get_expr_result_type() can do anything with it.      If not, pass to
1451          * lookup_rowtype_tupdesc() which will probably fail, but will give an
1452          * appropriate error message while failing.
1453          */
1454         if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1455                 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1456                                                                                                 exprTypmod(expr));
1457
1458         return tupleDesc;
1459 }
1460
1461
1462 /*
1463  * FigureColname -
1464  *        if the name of the resulting column is not specified in the target
1465  *        list, we have to guess a suitable name.  The SQL spec provides some
1466  *        guidance, but not much...
1467  *
1468  * Note that the argument is the *untransformed* parse tree for the target
1469  * item.  This is a shade easier to work with than the transformed tree.
1470  */
1471 char *
1472 FigureColname(Node *node)
1473 {
1474         char       *name = NULL;
1475
1476         (void) FigureColnameInternal(node, &name);
1477         if (name != NULL)
1478                 return name;
1479         /* default result if we can't guess anything */
1480         return "?column?";
1481 }
1482
1483 /*
1484  * FigureIndexColname -
1485  *        choose the name for an expression column in an index
1486  *
1487  * This is actually just like FigureColname, except we return NULL if
1488  * we can't pick a good name.
1489  */
1490 char *
1491 FigureIndexColname(Node *node)
1492 {
1493         char       *name = NULL;
1494
1495         (void) FigureColnameInternal(node, &name);
1496         return name;
1497 }
1498
1499 /*
1500  * FigureColnameInternal -
1501  *        internal workhorse for FigureColname
1502  *
1503  * Return value indicates strength of confidence in result:
1504  *              0 - no information
1505  *              1 - second-best name choice
1506  *              2 - good name choice
1507  * The return value is actually only used internally.
1508  * If the result isn't zero, *name is set to the chosen name.
1509  */
1510 static int
1511 FigureColnameInternal(Node *node, char **name)
1512 {
1513         int                     strength = 0;
1514
1515         if (node == NULL)
1516                 return strength;
1517
1518         switch (nodeTag(node))
1519         {
1520                 case T_ColumnRef:
1521                         {
1522                                 char       *fname = NULL;
1523                                 ListCell   *l;
1524
1525                                 /* find last field name, if any, ignoring "*" */
1526                                 foreach(l, ((ColumnRef *) node)->fields)
1527                                 {
1528                                         Node       *i = lfirst(l);
1529
1530                                         if (IsA(i, String))
1531                                                 fname = strVal(i);
1532                                 }
1533                                 if (fname)
1534                                 {
1535                                         *name = fname;
1536                                         return 2;
1537                                 }
1538                         }
1539                         break;
1540                 case T_A_Indirection:
1541                         {
1542                                 A_Indirection *ind = (A_Indirection *) node;
1543                                 char       *fname = NULL;
1544                                 ListCell   *l;
1545
1546                                 /* find last field name, if any, ignoring "*" and subscripts */
1547                                 foreach(l, ind->indirection)
1548                                 {
1549                                         Node       *i = lfirst(l);
1550
1551                                         if (IsA(i, String))
1552                                                 fname = strVal(i);
1553                                 }
1554                                 if (fname)
1555                                 {
1556                                         *name = fname;
1557                                         return 2;
1558                                 }
1559                                 return FigureColnameInternal(ind->arg, name);
1560                         }
1561                         break;
1562                 case T_FuncCall:
1563                         *name = strVal(llast(((FuncCall *) node)->funcname));
1564                         return 2;
1565                 case T_A_Expr:
1566                         /* make nullif() act like a regular function */
1567                         if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1568                         {
1569                                 *name = "nullif";
1570                                 return 2;
1571                         }
1572                         break;
1573                 case T_TypeCast:
1574                         strength = FigureColnameInternal(((TypeCast *) node)->arg,
1575                                                                                          name);
1576                         if (strength <= 1)
1577                         {
1578                                 if (((TypeCast *) node)->typeName != NULL)
1579                                 {
1580                                         *name = strVal(llast(((TypeCast *) node)->typeName->names));
1581                                         return 1;
1582                                 }
1583                         }
1584                         break;
1585                 case T_CollateClause:
1586                         return FigureColnameInternal(((CollateClause *) node)->arg, name);
1587                 case T_CaseExpr:
1588                         strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1589                                                                                          name);
1590                         if (strength <= 1)
1591                         {
1592                                 *name = "case";
1593                                 return 1;
1594                         }
1595                         break;
1596                 case T_A_ArrayExpr:
1597                         /* make ARRAY[] act like a function */
1598                         *name = "array";
1599                         return 2;
1600                 case T_RowExpr:
1601                         /* make ROW() act like a function */
1602                         *name = "row";
1603                         return 2;
1604                 case T_CoalesceExpr:
1605                         /* make coalesce() act like a regular function */
1606                         *name = "coalesce";
1607                         return 2;
1608                 case T_MinMaxExpr:
1609                         /* make greatest/least act like a regular function */
1610                         switch (((MinMaxExpr *) node)->op)
1611                         {
1612                                 case IS_GREATEST:
1613                                         *name = "greatest";
1614                                         return 2;
1615                                 case IS_LEAST:
1616                                         *name = "least";
1617                                         return 2;
1618                         }
1619                         break;
1620                 case T_XmlExpr:
1621                         /* make SQL/XML functions act like a regular function */
1622                         switch (((XmlExpr *) node)->op)
1623                         {
1624                                 case IS_XMLCONCAT:
1625                                         *name = "xmlconcat";
1626                                         return 2;
1627                                 case IS_XMLELEMENT:
1628                                         *name = "xmlelement";
1629                                         return 2;
1630                                 case IS_XMLFOREST:
1631                                         *name = "xmlforest";
1632                                         return 2;
1633                                 case IS_XMLPARSE:
1634                                         *name = "xmlparse";
1635                                         return 2;
1636                                 case IS_XMLPI:
1637                                         *name = "xmlpi";
1638                                         return 2;
1639                                 case IS_XMLROOT:
1640                                         *name = "xmlroot";
1641                                         return 2;
1642                                 case IS_XMLSERIALIZE:
1643                                         *name = "xmlserialize";
1644                                         return 2;
1645                                 case IS_DOCUMENT:
1646                                         /* nothing */
1647                                         break;
1648                         }
1649                         break;
1650                 case T_XmlSerialize:
1651                         *name = "xmlserialize";
1652                         return 2;
1653                 default:
1654                         break;
1655         }
1656
1657         return strength;
1658 }