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