]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_target.c
Remove 576 references of include files that were not needed.
[postgresql] / src / backend / parser / parse_target.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_target.c
4  *        handle target lists
5  *
6  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_target.c,v 1.146 2006/07/14 14:52:22 momjian Exp $
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 "parser/parsetree.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_expr.h"
25 #include "parser/parse_func.h"
26 #include "parser/parse_relation.h"
27 #include "parser/parse_target.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/typcache.h"
32
33
34 static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
35                                          Var *var, int levelsup);
36 static Node *transformAssignmentIndirection(ParseState *pstate,
37                                                            Node *basenode,
38                                                            const char *targetName,
39                                                            bool targetIsArray,
40                                                            Oid targetTypeId,
41                                                            int32 targetTypMod,
42                                                            ListCell *indirection,
43                                                            Node *rhs,
44                                                            int location);
45 static List *ExpandAllTables(ParseState *pstate);
46 static int      FigureColnameInternal(Node *node, char **name);
47
48
49 /*
50  * transformTargetEntry()
51  *      Transform any ordinary "expression-type" node into a targetlist entry.
52  *      This is exported so that parse_clause.c can generate targetlist entries
53  *      for ORDER/GROUP BY items that are not already in the targetlist.
54  *
55  * node         the (untransformed) parse tree for the value expression.
56  * expr         the transformed expression, or NULL if caller didn't do it yet.
57  * colname      the column name to be assigned, or NULL if none yet set.
58  * resjunk      true if the target should be marked resjunk, ie, it is not
59  *                      wanted in the final projected tuple.
60  */
61 TargetEntry *
62 transformTargetEntry(ParseState *pstate,
63                                          Node *node,
64                                          Node *expr,
65                                          char *colname,
66                                          bool resjunk)
67 {
68         /* Transform the node if caller didn't do it already */
69         if (expr == NULL)
70                 expr = transformExpr(pstate, node);
71
72         if (colname == NULL && !resjunk)
73         {
74                 /*
75                  * Generate a suitable column name for a column without any explicit
76                  * 'AS ColumnName' clause.
77                  */
78                 colname = FigureColname(node);
79         }
80
81         return makeTargetEntry((Expr *) expr,
82                                                    (AttrNumber) pstate->p_next_resno++,
83                                                    colname,
84                                                    resjunk);
85 }
86
87
88 /*
89  * transformTargetList()
90  * Turns a list of ResTarget's into a list of TargetEntry's.
91  *
92  * At this point, we don't care whether we are doing SELECT, INSERT,
93  * or UPDATE; we just transform the given expressions (the "val" fields).
94  */
95 List *
96 transformTargetList(ParseState *pstate, List *targetlist)
97 {
98         List       *p_target = NIL;
99         ListCell   *o_target;
100
101         foreach(o_target, targetlist)
102         {
103                 ResTarget  *res = (ResTarget *) lfirst(o_target);
104
105                 /*
106                  * Check for "something.*".  Depending on the complexity of the
107                  * "something", the star could appear as the last name in ColumnRef,
108                  * or as the last indirection item in A_Indirection.
109                  */
110                 if (IsA(res->val, ColumnRef))
111                 {
112                         ColumnRef  *cref = (ColumnRef *) res->val;
113
114                         if (strcmp(strVal(llast(cref->fields)), "*") == 0)
115                         {
116                                 /* It is something.*, expand into multiple items */
117                                 p_target = list_concat(p_target,
118                                                                            ExpandColumnRefStar(pstate, cref,
119                                                                                                                    true));
120                                 continue;
121                         }
122                 }
123                 else if (IsA(res->val, A_Indirection))
124                 {
125                         A_Indirection *ind = (A_Indirection *) res->val;
126                         Node       *lastitem = llast(ind->indirection);
127
128                         if (IsA(lastitem, String) &&
129                                 strcmp(strVal(lastitem), "*") == 0)
130                         {
131                                 /* It is something.*, expand into multiple items */
132                                 p_target = list_concat(p_target,
133                                                                            ExpandIndirectionStar(pstate, ind,
134                                                                                                                          true));
135                                 continue;
136                         }
137                 }
138
139                 /*
140                  * Not "something.*", so transform as a single expression
141                  */
142                 p_target = lappend(p_target,
143                                                    transformTargetEntry(pstate,
144                                                                                                 res->val,
145                                                                                                 NULL,
146                                                                                                 res->name,
147                                                                                                 false));
148         }
149
150         return p_target;
151 }
152
153
154 /*
155  * markTargetListOrigins()
156  *              Mark targetlist columns that are simple Vars with the source
157  *              table's OID and column number.
158  *
159  * Currently, this is done only for SELECT targetlists, since we only
160  * need the info if we are going to send it to the frontend.
161  */
162 void
163 markTargetListOrigins(ParseState *pstate, List *targetlist)
164 {
165         ListCell   *l;
166
167         foreach(l, targetlist)
168         {
169                 TargetEntry *tle = (TargetEntry *) lfirst(l);
170
171                 markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
172         }
173 }
174
175 /*
176  * markTargetListOrigin()
177  *              If 'var' is a Var of a plain relation, mark 'tle' with its origin
178  *
179  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
180  *
181  * This is split out so it can recurse for join references.  Note that we
182  * do not drill down into views, but report the view as the column owner.
183  */
184 static void
185 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
186                                          Var *var, int levelsup)
187 {
188         int                     netlevelsup;
189         RangeTblEntry *rte;
190         AttrNumber      attnum;
191
192         if (var == NULL || !IsA(var, Var))
193                 return;
194         netlevelsup = var->varlevelsup + levelsup;
195         rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
196         attnum = var->varattno;
197
198         switch (rte->rtekind)
199         {
200                 case RTE_RELATION:
201                         /* It's a table or view, report it */
202                         tle->resorigtbl = rte->relid;
203                         tle->resorigcol = attnum;
204                         break;
205                 case RTE_SUBQUERY:
206                         /* Subselect-in-FROM: copy up from the subselect */
207                         if (attnum != InvalidAttrNumber)
208                         {
209                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
210                                                                                                         attnum);
211
212                                 if (ste == NULL || ste->resjunk)
213                                         elog(ERROR, "subquery %s does not have attribute %d",
214                                                  rte->eref->aliasname, attnum);
215                                 tle->resorigtbl = ste->resorigtbl;
216                                 tle->resorigcol = ste->resorigcol;
217                         }
218                         break;
219                 case RTE_JOIN:
220                         /* Join RTE --- recursively inspect the alias variable */
221                         if (attnum != InvalidAttrNumber)
222                         {
223                                 Var                *aliasvar;
224
225                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
226                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
227                                 markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
228                         }
229                         break;
230                 case RTE_SPECIAL:
231                 case RTE_FUNCTION:
232                         /* not a simple relation, leave it unmarked */
233                         break;
234         }
235 }
236
237
238 /*
239  * updateTargetListEntry()
240  *      This is used in INSERT and UPDATE statements only.      It prepares a
241  *      TargetEntry for assignment to a column of the target table.
242  *      This includes coercing the given value to the target column's type
243  *      (if necessary), and dealing with any subfield names or subscripts
244  *      attached to the target column itself.
245  *
246  * pstate               parse state
247  * tle                  target list entry to be modified
248  * colname              target column name (ie, name of attribute to be assigned to)
249  * attrno               target attribute number
250  * indirection  subscripts/field names for target column, if any
251  * location             error cursor position (should point at column name), or -1
252  */
253 void
254 updateTargetListEntry(ParseState *pstate,
255                                           TargetEntry *tle,
256                                           char *colname,
257                                           int attrno,
258                                           List *indirection,
259                                           int location)
260 {
261         Oid                     type_id;                /* type of value provided */
262         Oid                     attrtype;               /* type of target column */
263         int32           attrtypmod;
264         Relation        rd = pstate->p_target_relation;
265
266         Assert(rd != NULL);
267         if (attrno <= 0)
268                 ereport(ERROR,
269                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
270                                  errmsg("cannot assign to system column \"%s\"",
271                                                 colname),
272                                  parser_errposition(pstate, location)));
273         attrtype = attnumTypeId(rd, attrno);
274         attrtypmod = rd->rd_att->attrs[attrno - 1]->atttypmod;
275
276         /*
277          * If the expression is a DEFAULT placeholder, insert the attribute's
278          * type/typmod into it so that exprType will report the right things. (We
279          * expect that the eventually substituted default expression will in fact
280          * have this type and typmod.)  Also, reject trying to update a subfield
281          * or array element with DEFAULT, since there can't be any default for
282          * portions of a column.
283          */
284         if (tle->expr && IsA(tle->expr, SetToDefault))
285         {
286                 SetToDefault *def = (SetToDefault *) tle->expr;
287
288                 def->typeId = attrtype;
289                 def->typeMod = attrtypmod;
290                 if (indirection)
291                 {
292                         if (IsA(linitial(indirection), A_Indices))
293                                 ereport(ERROR,
294                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
295                                                  errmsg("cannot set an array element to DEFAULT"),
296                                                  parser_errposition(pstate, location)));
297                         else
298                                 ereport(ERROR,
299                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
300                                                  errmsg("cannot set a subfield to DEFAULT"),
301                                                  parser_errposition(pstate, location)));
302                 }
303         }
304
305         /* Now we can use exprType() safely. */
306         type_id = exprType((Node *) tle->expr);
307
308         /*
309          * If there is indirection on the target column, prepare an array or
310          * subfield assignment expression.      This will generate a new column value
311          * that the source value has been inserted into, which can then be placed
312          * in the new tuple constructed by INSERT or UPDATE.
313          */
314         if (indirection)
315         {
316                 Node       *colVar;
317
318                 if (pstate->p_is_insert)
319                 {
320                         /*
321                          * The command is INSERT INTO table (col.something) ... so there
322                          * is not really a source value to work with. Insert a NULL
323                          * constant as the source value.
324                          */
325                         colVar = (Node *) makeNullConst(attrtype);
326                 }
327                 else
328                 {
329                         /*
330                          * Build a Var for the column to be updated.
331                          */
332                         colVar = (Node *) make_var(pstate,
333                                                                            pstate->p_target_rangetblentry,
334                                                                            attrno);
335                 }
336
337                 tle->expr = (Expr *)
338                         transformAssignmentIndirection(pstate,
339                                                                                    colVar,
340                                                                                    colname,
341                                                                                    false,
342                                                                                    attrtype,
343                                                                                    attrtypmod,
344                                                                                    list_head(indirection),
345                                                                                    (Node *) tle->expr,
346                                                                                    location);
347         }
348         else
349         {
350                 /*
351                  * For normal non-qualified target column, do type checking and
352                  * coercion.
353                  */
354                 tle->expr = (Expr *)
355                         coerce_to_target_type(pstate,
356                                                                   (Node *) tle->expr, type_id,
357                                                                   attrtype, attrtypmod,
358                                                                   COERCION_ASSIGNMENT,
359                                                                   COERCE_IMPLICIT_CAST);
360                 if (tle->expr == NULL)
361                         ereport(ERROR,
362                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
363                                          errmsg("column \"%s\" is of type %s"
364                                                         " but expression is of type %s",
365                                                         colname,
366                                                         format_type_be(attrtype),
367                                                         format_type_be(type_id)),
368                                          errhint("You will need to rewrite or cast the expression."),
369                                          parser_errposition(pstate, location)));
370         }
371
372         /*
373          * Set the resno to identify the target column --- the rewriter and
374          * planner depend on this.      We also set the resname to identify the target
375          * column, but this is only for debugging purposes; it should not be
376          * relied on.  (In particular, it might be out of date in a stored rule.)
377          */
378         tle->resno = (AttrNumber) attrno;
379         tle->resname = colname;
380 }
381
382 /*
383  * Process indirection (field selection or subscripting) of the target
384  * column in INSERT/UPDATE.  This routine recurses for multiple levels
385  * of indirection --- but note that several adjacent A_Indices nodes in
386  * the indirection list are treated as a single multidimensional subscript
387  * operation.
388  *
389  * In the initial call, basenode is a Var for the target column in UPDATE,
390  * or a null Const of the target's type in INSERT.  In recursive calls,
391  * basenode is NULL, indicating that a substitute node should be consed up if
392  * needed.
393  *
394  * targetName is the name of the field or subfield we're assigning to, and
395  * targetIsArray is true if we're subscripting it.  These are just for
396  * error reporting.
397  *
398  * targetTypeId and targetTypMod indicate the datatype of the object to
399  * be assigned to (initially the target column, later some subobject).
400  *
401  * indirection is the sublist remaining to process.  When it's NULL, we're
402  * done recursing and can just coerce and return the RHS.
403  *
404  * rhs is the already-transformed value to be assigned; note it has not been
405  * coerced to any particular type.
406  *
407  * location is the cursor error position for any errors.  (Note: this points
408  * to the head of the target clause, eg "foo" in "foo.bar[baz]".  Later we
409  * might want to decorate indirection cells with their own location info,
410  * in which case the location argument could probably be dropped.)
411  */
412 static Node *
413 transformAssignmentIndirection(ParseState *pstate,
414                                                            Node *basenode,
415                                                            const char *targetName,
416                                                            bool targetIsArray,
417                                                            Oid targetTypeId,
418                                                            int32 targetTypMod,
419                                                            ListCell *indirection,
420                                                            Node *rhs,
421                                                            int location)
422 {
423         Node       *result;
424         List       *subscripts = NIL;
425         bool            isSlice = false;
426         ListCell   *i;
427
428         if (indirection && !basenode)
429         {
430                 /* Set up a substitution.  We reuse CaseTestExpr for this. */
431                 CaseTestExpr *ctest = makeNode(CaseTestExpr);
432
433                 ctest->typeId = targetTypeId;
434                 ctest->typeMod = targetTypMod;
435                 basenode = (Node *) ctest;
436         }
437
438         /*
439          * We have to split any field-selection operations apart from
440          * subscripting.  Adjacent A_Indices nodes have to be treated as a single
441          * multidimensional subscript operation.
442          */
443         for_each_cell(i, indirection)
444         {
445                 Node       *n = lfirst(i);
446
447                 if (IsA(n, A_Indices))
448                 {
449                         subscripts = lappend(subscripts, n);
450                         if (((A_Indices *) n)->lidx != NULL)
451                                 isSlice = true;
452                 }
453                 else
454                 {
455                         FieldStore *fstore;
456                         Oid                     typrelid;
457                         AttrNumber      attnum;
458                         Oid                     fieldTypeId;
459                         int32           fieldTypMod;
460
461                         Assert(IsA(n, String));
462
463                         /* process subscripts before this field selection */
464                         if (subscripts)
465                         {
466                                 Oid                     elementTypeId = transformArrayType(targetTypeId);
467                                 Oid                     typeNeeded = isSlice ? targetTypeId : elementTypeId;
468
469                                 /* recurse to create appropriate RHS for array assign */
470                                 rhs = transformAssignmentIndirection(pstate,
471                                                                                                          NULL,
472                                                                                                          targetName,
473                                                                                                          true,
474                                                                                                          typeNeeded,
475                                                                                                          targetTypMod,
476                                                                                                          i,
477                                                                                                          rhs,
478                                                                                                          location);
479                                 /* process subscripts */
480                                 return (Node *) transformArraySubscripts(pstate,
481                                                                                                                  basenode,
482                                                                                                                  targetTypeId,
483                                                                                                                  elementTypeId,
484                                                                                                                  targetTypMod,
485                                                                                                                  subscripts,
486                                                                                                                  rhs);
487                         }
488
489                         /* No subscripts, so can process field selection here */
490
491                         typrelid = typeidTypeRelid(targetTypeId);
492                         if (!typrelid)
493                                 ereport(ERROR,
494                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
495                                                  errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
496                                                                 strVal(n), targetName,
497                                                                 format_type_be(targetTypeId)),
498                                                  parser_errposition(pstate, location)));
499
500                         attnum = get_attnum(typrelid, strVal(n));
501                         if (attnum == InvalidAttrNumber)
502                                 ereport(ERROR,
503                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
504                                                  errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
505                                                                 strVal(n), targetName,
506                                                                 format_type_be(targetTypeId)),
507                                                  parser_errposition(pstate, location)));
508                         if (attnum < 0)
509                                 ereport(ERROR,
510                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
511                                                  errmsg("cannot assign to system column \"%s\"",
512                                                                 strVal(n)),
513                                                  parser_errposition(pstate, location)));
514
515                         get_atttypetypmod(typrelid, attnum,
516                                                           &fieldTypeId, &fieldTypMod);
517
518                         /* recurse to create appropriate RHS for field assign */
519                         rhs = transformAssignmentIndirection(pstate,
520                                                                                                  NULL,
521                                                                                                  strVal(n),
522                                                                                                  false,
523                                                                                                  fieldTypeId,
524                                                                                                  fieldTypMod,
525                                                                                                  lnext(i),
526                                                                                                  rhs,
527                                                                                                  location);
528
529                         /* and build a FieldStore node */
530                         fstore = makeNode(FieldStore);
531                         fstore->arg = (Expr *) basenode;
532                         fstore->newvals = list_make1(rhs);
533                         fstore->fieldnums = list_make1_int(attnum);
534                         fstore->resulttype = targetTypeId;
535
536                         return (Node *) fstore;
537                 }
538         }
539
540         /* process trailing subscripts, if any */
541         if (subscripts)
542         {
543                 Oid                     elementTypeId = transformArrayType(targetTypeId);
544                 Oid                     typeNeeded = isSlice ? targetTypeId : elementTypeId;
545
546                 /* recurse to create appropriate RHS for array assign */
547                 rhs = transformAssignmentIndirection(pstate,
548                                                                                          NULL,
549                                                                                          targetName,
550                                                                                          true,
551                                                                                          typeNeeded,
552                                                                                          targetTypMod,
553                                                                                          NULL,
554                                                                                          rhs,
555                                                                                          location);
556                 /* process subscripts */
557                 return (Node *) transformArraySubscripts(pstate,
558                                                                                                  basenode,
559                                                                                                  targetTypeId,
560                                                                                                  elementTypeId,
561                                                                                                  targetTypMod,
562                                                                                                  subscripts,
563                                                                                                  rhs);
564         }
565
566         /* base case: just coerce RHS to match target type ID */
567
568         result = coerce_to_target_type(pstate,
569                                                                    rhs, exprType(rhs),
570                                                                    targetTypeId, targetTypMod,
571                                                                    COERCION_ASSIGNMENT,
572                                                                    COERCE_IMPLICIT_CAST);
573         if (result == NULL)
574         {
575                 if (targetIsArray)
576                         ereport(ERROR,
577                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
578                                          errmsg("array assignment to \"%s\" requires type %s"
579                                                         " but expression is of type %s",
580                                                         targetName,
581                                                         format_type_be(targetTypeId),
582                                                         format_type_be(exprType(rhs))),
583                                          errhint("You will need to rewrite or cast the expression."),
584                                          parser_errposition(pstate, location)));
585                 else
586                         ereport(ERROR,
587                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
588                                          errmsg("subfield \"%s\" is of type %s"
589                                                         " but expression is of type %s",
590                                                         targetName,
591                                                         format_type_be(targetTypeId),
592                                                         format_type_be(exprType(rhs))),
593                                          errhint("You will need to rewrite or cast the expression."),
594                                          parser_errposition(pstate, location)));
595         }
596
597         return result;
598 }
599
600
601 /*
602  * checkInsertTargets -
603  *        generate a list of INSERT column targets if not supplied, or
604  *        test supplied column names to make sure they are in target table.
605  *        Also return an integer list of the columns' attribute numbers.
606  */
607 List *
608 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
609 {
610         *attrnos = NIL;
611
612         if (cols == NIL)
613         {
614                 /*
615                  * Generate default column list for INSERT.
616                  */
617                 Form_pg_attribute *attr = pstate->p_target_relation->rd_att->attrs;
618                 int                     numcol = pstate->p_target_relation->rd_rel->relnatts;
619                 int                     i;
620
621                 for (i = 0; i < numcol; i++)
622                 {
623                         ResTarget  *col;
624
625                         if (attr[i]->attisdropped)
626                                 continue;
627
628                         col = makeNode(ResTarget);
629                         col->name = pstrdup(NameStr(attr[i]->attname));
630                         col->indirection = NIL;
631                         col->val = NULL;
632                         col->location = -1;
633                         cols = lappend(cols, col);
634                         *attrnos = lappend_int(*attrnos, i + 1);
635                 }
636         }
637         else
638         {
639                 /*
640                  * Do initial validation of user-supplied INSERT column list.
641                  */
642                 Bitmapset  *wholecols = NULL;
643                 Bitmapset  *partialcols = NULL;
644                 ListCell   *tl;
645
646                 foreach(tl, cols)
647                 {
648                         ResTarget  *col = (ResTarget *) lfirst(tl);
649                         char       *name = col->name;
650                         int                     attrno;
651
652                         /* Lookup column name, ereport on failure */
653                         attrno = attnameAttNum(pstate->p_target_relation, name, false);
654                         if (attrno == InvalidAttrNumber)
655                                 ereport(ERROR,
656                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
657                                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
658                                                                 name,
659                                                                 RelationGetRelationName(pstate->p_target_relation)),
660                                                  parser_errposition(pstate, col->location)));
661
662                         /*
663                          * Check for duplicates, but only of whole columns --- we allow
664                          * INSERT INTO foo (col.subcol1, col.subcol2)
665                          */
666                         if (col->indirection == NIL)
667                         {
668                                 /* whole column; must not have any other assignment */
669                                 if (bms_is_member(attrno, wholecols) ||
670                                         bms_is_member(attrno, partialcols))
671                                         ereport(ERROR,
672                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
673                                                          errmsg("column \"%s\" specified more than once",
674                                                                         name),
675                                                          parser_errposition(pstate, col->location)));
676                                 wholecols = bms_add_member(wholecols, attrno);
677                         }
678                         else
679                         {
680                                 /* partial column; must not have any whole assignment */
681                                 if (bms_is_member(attrno, wholecols))
682                                         ereport(ERROR,
683                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
684                                                          errmsg("column \"%s\" specified more than once",
685                                                                         name),
686                                                          parser_errposition(pstate, col->location)));
687                                 partialcols = bms_add_member(partialcols, attrno);
688                         }
689
690                         *attrnos = lappend_int(*attrnos, attrno);
691                 }
692         }
693
694         return cols;
695 }
696
697 /*
698  * ExpandColumnRefStar()
699  *              Transforms foo.* into a list of expressions or targetlist entries.
700  *
701  * This handles the case where '*' appears as the last or only name in a
702  * ColumnRef.  The code is shared between the case of foo.* at the top level
703  * in a SELECT target list (where we want TargetEntry nodes in the result)
704  * and foo.* in a ROW() construct (where we want just bare expressions).
705  */
706 List *
707 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
708                                         bool targetlist)
709 {
710         List       *fields = cref->fields;
711         int                     numnames = list_length(fields);
712
713         if (numnames == 1)
714         {
715                 /*
716                  * Target item is a bare '*', expand all tables
717                  *
718                  * (e.g., SELECT * FROM emp, dept)
719                  *
720                  * Since the grammar only accepts bare '*' at top level of SELECT,
721                  * we need not handle the targetlist==false case here.
722                  */
723                 Assert(targetlist);
724
725                 return ExpandAllTables(pstate);
726         }
727         else
728         {
729                 /*
730                  * Target item is relation.*, expand that table
731                  *
732                  * (e.g., SELECT emp.*, dname FROM emp, dept)
733                  */
734                 char       *schemaname;
735                 char       *relname;
736                 RangeTblEntry *rte;
737                 int                     sublevels_up;
738                 int                     rtindex;
739
740                 switch (numnames)
741                 {
742                         case 2:
743                                 schemaname = NULL;
744                                 relname = strVal(linitial(fields));
745                                 break;
746                         case 3:
747                                 schemaname = strVal(linitial(fields));
748                                 relname = strVal(lsecond(fields));
749                                 break;
750                         case 4:
751                                 {
752                                         char       *name1 = strVal(linitial(fields));
753
754                                         /*
755                                          * We check the catalog name and then ignore it.
756                                          */
757                                         if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
758                                                 ereport(ERROR,
759                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
760                                                                  errmsg("cross-database references are not implemented: %s",
761                                                                                 NameListToString(fields)),
762                                                                  parser_errposition(pstate, cref->location)));
763                                         schemaname = strVal(lsecond(fields));
764                                         relname = strVal(lthird(fields));
765                                         break;
766                                 }
767                         default:
768                                 ereport(ERROR,
769                                                 (errcode(ERRCODE_SYNTAX_ERROR),
770                                 errmsg("improper qualified name (too many dotted names): %s",
771                                            NameListToString(fields)),
772                                                  parser_errposition(pstate, cref->location)));
773                                 schemaname = NULL;              /* keep compiler quiet */
774                                 relname = NULL;
775                                 break;
776                 }
777
778                 rte = refnameRangeTblEntry(pstate, schemaname, relname,
779                                                                    &sublevels_up);
780                 if (rte == NULL)
781                         rte = addImplicitRTE(pstate, makeRangeVar(schemaname, relname),
782                                                                  cref->location);
783
784                 rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
785
786                 if (targetlist)
787                         return expandRelAttrs(pstate, rte, rtindex, sublevels_up);
788                 else
789                 {
790                         List    *vars;
791
792                         expandRTE(rte, rtindex, sublevels_up, false,
793                                           NULL, &vars);
794                         return vars;
795                 }
796         }
797 }
798
799 /*
800  * ExpandAllTables()
801  *              Transforms '*' (in the target list) into a list of targetlist entries.
802  *
803  * tlist entries are generated for each relation appearing in the query's
804  * varnamespace.  We do not consider relnamespace because that would include
805  * input tables of aliasless JOINs, NEW/OLD pseudo-entries, implicit RTEs,
806  * etc.
807  */
808 static List *
809 ExpandAllTables(ParseState *pstate)
810 {
811         List       *target = NIL;
812         ListCell   *l;
813
814         /* Check for SELECT *; */
815         if (!pstate->p_varnamespace)
816                 ereport(ERROR,
817                                 (errcode(ERRCODE_SYNTAX_ERROR),
818                                  errmsg("SELECT * with no tables specified is not valid")));
819
820         foreach(l, pstate->p_varnamespace)
821         {
822                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
823                 int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
824
825                 target = list_concat(target,
826                                                          expandRelAttrs(pstate, rte, rtindex, 0));
827         }
828
829         return target;
830 }
831
832 /*
833  * ExpandIndirectionStar()
834  *              Transforms foo.* into a list of expressions or targetlist entries.
835  *
836  * This handles the case where '*' appears as the last item in A_Indirection.
837  * The code is shared between the case of foo.* at the top level in a SELECT
838  * target list (where we want TargetEntry nodes in the result) and foo.* in
839  * a ROW() construct (where we want just bare expressions).
840  */
841 List *
842 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
843                                           bool targetlist)
844 {
845         List       *result = NIL;
846         Node       *expr;
847         TupleDesc       tupleDesc;
848         int                     numAttrs;
849         int                     i;
850
851         /* Strip off the '*' to create a reference to the rowtype object */
852         ind = copyObject(ind);
853         ind->indirection = list_truncate(ind->indirection,
854                                                                          list_length(ind->indirection) - 1);
855
856         /* And transform that */
857         expr = transformExpr(pstate, (Node *) ind);
858
859         /*
860          * Verify it's a composite type, and get the tupdesc.  We use
861          * get_expr_result_type() because that can handle references to functions
862          * returning anonymous record types.  If that fails, use
863          * lookup_rowtype_tupdesc(), which will almost certainly fail as well, but
864          * it will give an appropriate error message.
865          *
866          * If it's a Var of type RECORD, we have to work even harder: we have to
867          * find what the Var refers to, and pass that to get_expr_result_type.
868          * That task is handled by expandRecordVariable().
869          */
870         if (IsA(expr, Var) &&
871                 ((Var *) expr)->vartype == RECORDOID)
872                 tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
873         else if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
874                 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
875                                                                                                 exprTypmod(expr));
876         Assert(tupleDesc);
877
878         /* Generate a list of references to the individual fields */
879         numAttrs = tupleDesc->natts;
880         for (i = 0; i < numAttrs; i++)
881         {
882                 Form_pg_attribute att = tupleDesc->attrs[i];
883                 Node       *fieldnode;
884
885                 if (att->attisdropped)
886                         continue;
887
888                 /*
889                  * If we got a whole-row Var from the rowtype reference, we can expand
890                  * the fields as simple Vars.  Otherwise we must generate multiple
891                  * copies of the rowtype reference and do FieldSelects.
892                  */
893                 if (IsA(expr, Var) &&
894                         ((Var *) expr)->varattno == InvalidAttrNumber)
895                 {
896                         Var                *var = (Var *) expr;
897
898                         fieldnode = (Node *) makeVar(var->varno,
899                                                                                  i + 1,
900                                                                                  att->atttypid,
901                                                                                  att->atttypmod,
902                                                                                  var->varlevelsup);
903                 }
904                 else
905                 {
906                         FieldSelect *fselect = makeNode(FieldSelect);
907
908                         fselect->arg = (Expr *) copyObject(expr);
909                         fselect->fieldnum = i + 1;
910                         fselect->resulttype = att->atttypid;
911                         fselect->resulttypmod = att->atttypmod;
912
913                         fieldnode = (Node *) fselect;
914                 }
915
916                 if (targetlist)
917                 {
918                         /* add TargetEntry decoration */
919                         TargetEntry *te;
920
921                         te = makeTargetEntry((Expr *) fieldnode,
922                                                                  (AttrNumber) pstate->p_next_resno++,
923                                                                  pstrdup(NameStr(att->attname)),
924                                                                  false);
925                         result = lappend(result, te);
926                 }
927                 else
928                         result = lappend(result, fieldnode);
929         }
930
931         return result;
932 }
933
934 /*
935  * expandRecordVariable
936  *              Get the tuple descriptor for a Var of type RECORD, if possible.
937  *
938  * Since no actual table or view column is allowed to have type RECORD, such
939  * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output.  We
940  * drill down to find the ultimate defining expression and attempt to infer
941  * the tupdesc from it.  We ereport if we can't determine the tupdesc.
942  *
943  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
944  */
945 TupleDesc
946 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
947 {
948         TupleDesc       tupleDesc;
949         int                     netlevelsup;
950         RangeTblEntry *rte;
951         AttrNumber      attnum;
952         Node       *expr;
953
954         /* Check my caller didn't mess up */
955         Assert(IsA(var, Var));
956         Assert(var->vartype == RECORDOID);
957
958         netlevelsup = var->varlevelsup + levelsup;
959         rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
960         attnum = var->varattno;
961
962         if (attnum == InvalidAttrNumber)
963         {
964                 /* Whole-row reference to an RTE, so expand the known fields */
965                 List       *names,
966                                    *vars;
967                 ListCell   *lname,
968                                    *lvar;
969                 int                     i;
970
971                 expandRTE(rte, var->varno, 0, false,
972                                   &names, &vars);
973
974                 tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
975                 i = 1;
976                 forboth(lname, names, lvar, vars)
977                 {
978                         char       *label = strVal(lfirst(lname));
979                         Node       *varnode = (Node *) lfirst(lvar);
980
981                         TupleDescInitEntry(tupleDesc, i,
982                                                            label,
983                                                            exprType(varnode),
984                                                            exprTypmod(varnode),
985                                                            0);
986                         i++;
987                 }
988                 Assert(lname == NULL && lvar == NULL);  /* lists same length? */
989
990                 return tupleDesc;
991         }
992
993         expr = (Node *) var;            /* default if we can't drill down */
994
995         switch (rte->rtekind)
996         {
997                 case RTE_RELATION:
998                 case RTE_SPECIAL:
999
1000                         /*
1001                          * This case should not occur: a column of a table shouldn't have
1002                          * type RECORD.  Fall through and fail (most likely) at the
1003                          * bottom.
1004                          */
1005                         break;
1006                 case RTE_SUBQUERY:
1007                         {
1008                                 /* Subselect-in-FROM: examine sub-select's output expr */
1009                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1010                                                                                                         attnum);
1011
1012                                 if (ste == NULL || ste->resjunk)
1013                                         elog(ERROR, "subquery %s does not have attribute %d",
1014                                                  rte->eref->aliasname, attnum);
1015                                 expr = (Node *) ste->expr;
1016                                 if (IsA(expr, Var))
1017                                 {
1018                                         /*
1019                                          * Recurse into the sub-select to see what its Var refers
1020                                          * to.  We have to build an additional level of ParseState
1021                                          * to keep in step with varlevelsup in the subselect.
1022                                          */
1023                                         ParseState      mypstate;
1024
1025                                         MemSet(&mypstate, 0, sizeof(mypstate));
1026                                         mypstate.parentParseState = pstate;
1027                                         mypstate.p_rtable = rte->subquery->rtable;
1028                                         /* don't bother filling the rest of the fake pstate */
1029
1030                                         return expandRecordVariable(&mypstate, (Var *) expr, 0);
1031                                 }
1032                                 /* else fall through to inspect the expression */
1033                         }
1034                         break;
1035                 case RTE_JOIN:
1036                         /* Join RTE --- recursively inspect the alias variable */
1037                         Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1038                         expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1039                         if (IsA(expr, Var))
1040                                 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1041                         /* else fall through to inspect the expression */
1042                         break;
1043                 case RTE_FUNCTION:
1044
1045                         /*
1046                          * We couldn't get here unless a function is declared with one of
1047                          * its result columns as RECORD, which is not allowed.
1048                          */
1049                         break;
1050         }
1051
1052         /*
1053          * We now have an expression we can't expand any more, so see if
1054          * get_expr_result_type() can do anything with it.      If not, pass to
1055          * lookup_rowtype_tupdesc() which will probably fail, but will give an
1056          * appropriate error message while failing.
1057          */
1058         if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
1059                 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
1060                                                                                                 exprTypmod(expr));
1061
1062         return tupleDesc;
1063 }
1064
1065
1066 /*
1067  * FigureColname -
1068  *        if the name of the resulting column is not specified in the target
1069  *        list, we have to guess a suitable name.  The SQL spec provides some
1070  *        guidance, but not much...
1071  *
1072  * Note that the argument is the *untransformed* parse tree for the target
1073  * item.  This is a shade easier to work with than the transformed tree.
1074  */
1075 char *
1076 FigureColname(Node *node)
1077 {
1078         char       *name = NULL;
1079
1080         FigureColnameInternal(node, &name);
1081         if (name != NULL)
1082                 return name;
1083         /* default result if we can't guess anything */
1084         return "?column?";
1085 }
1086
1087 static int
1088 FigureColnameInternal(Node *node, char **name)
1089 {
1090         int                     strength = 0;
1091
1092         if (node == NULL)
1093                 return strength;
1094
1095         switch (nodeTag(node))
1096         {
1097                 case T_ColumnRef:
1098                         {
1099                                 char       *fname = NULL;
1100                                 ListCell   *l;
1101
1102                                 /* find last field name, if any, ignoring "*" */
1103                                 foreach(l, ((ColumnRef *) node)->fields)
1104                                 {
1105                                         Node       *i = lfirst(l);
1106
1107                                         if (strcmp(strVal(i), "*") != 0)
1108                                                 fname = strVal(i);
1109                                 }
1110                                 if (fname)
1111                                 {
1112                                         *name = fname;
1113                                         return 2;
1114                                 }
1115                         }
1116                         break;
1117                 case T_A_Indirection:
1118                         {
1119                                 A_Indirection *ind = (A_Indirection *) node;
1120                                 char       *fname = NULL;
1121                                 ListCell   *l;
1122
1123                                 /* find last field name, if any, ignoring "*" */
1124                                 foreach(l, ind->indirection)
1125                                 {
1126                                         Node       *i = lfirst(l);
1127
1128                                         if (IsA(i, String) &&
1129                                                 strcmp(strVal(i), "*") != 0)
1130                                                 fname = strVal(i);
1131                                 }
1132                                 if (fname)
1133                                 {
1134                                         *name = fname;
1135                                         return 2;
1136                                 }
1137                                 return FigureColnameInternal(ind->arg, name);
1138                         }
1139                         break;
1140                 case T_FuncCall:
1141                         *name = strVal(llast(((FuncCall *) node)->funcname));
1142                         return 2;
1143                 case T_A_Expr:
1144                         /* make nullif() act like a regular function */
1145                         if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1146                         {
1147                                 *name = "nullif";
1148                                 return 2;
1149                         }
1150                         break;
1151                 case T_A_Const:
1152                         if (((A_Const *) node)->typename != NULL)
1153                         {
1154                                 *name = strVal(llast(((A_Const *) node)->typename->names));
1155                                 return 1;
1156                         }
1157                         break;
1158                 case T_TypeCast:
1159                         strength = FigureColnameInternal(((TypeCast *) node)->arg,
1160                                                                                          name);
1161                         if (strength <= 1)
1162                         {
1163                                 if (((TypeCast *) node)->typename != NULL)
1164                                 {
1165                                         *name = strVal(llast(((TypeCast *) node)->typename->names));
1166                                         return 1;
1167                                 }
1168                         }
1169                         break;
1170                 case T_CaseExpr:
1171                         strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1172                                                                                          name);
1173                         if (strength <= 1)
1174                         {
1175                                 *name = "case";
1176                                 return 1;
1177                         }
1178                         break;
1179                 case T_ArrayExpr:
1180                         /* make ARRAY[] act like a function */
1181                         *name = "array";
1182                         return 2;
1183                 case T_RowExpr:
1184                         /* make ROW() act like a function */
1185                         *name = "row";
1186                         return 2;
1187                 case T_CoalesceExpr:
1188                         /* make coalesce() act like a regular function */
1189                         *name = "coalesce";
1190                         return 2;
1191                 case T_MinMaxExpr:
1192                         /* make greatest/least act like a regular function */
1193                         switch (((MinMaxExpr *) node)->op)
1194                         {
1195                                 case IS_GREATEST:
1196                                         *name = "greatest";
1197                                         return 2;
1198                                 case IS_LEAST:
1199                                         *name = "least";
1200                                         return 2;
1201                         }
1202                         break;
1203                 default:
1204                         break;
1205         }
1206
1207         return strength;
1208 }