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