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