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