1 /*-------------------------------------------------------------------------
2  *
3  * parse_target.c
4  *	  handle target lists
5  *
6  * Portions Copyright (c) 1996-2019, 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);
38 static Node *transformAssignmentIndirection(ParseState *pstate,
39 											Node *basenode,
40 											const char *targetName,
41 											bool targetIsSubscripting,
42 											Oid targetTypeId,
43 											int32 targetTypMod,
44 											Oid targetCollation,
45 											ListCell *indirection,
46 											Node *rhs,
47 											int location);
48 static Node *transformAssignmentSubscripts(ParseState *pstate,
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);
62 static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
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  */
84 TargetEntry *
transformTargetEntry(ParseState * pstate,Node * node,Node * expr,ParseExprKind exprKind,char * colname,bool resjunk)85 transformTargetEntry(ParseState *pstate,
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 *
transformTargetList(ParseState * pstate,List * targetlist,ParseExprKind exprKind)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.  Also, we don't expect any multiassign constructs within the
223  * list, so there's nothing to do for that.  We use this for ROW() and
224  * VALUES() constructs.
225  *
226  * exprKind is not enough to tell us whether to allow SetToDefault, so
227  * an additional flag is needed for that.
228  */
229 List *
transformExpressionList(ParseState * pstate,List * exprlist,ParseExprKind exprKind,bool allowDefault)230 transformExpressionList(ParseState *pstate, List *exprlist,
231 						ParseExprKind exprKind, bool allowDefault)
232 {
233 	List	   *result = NIL;
234 	ListCell   *lc;
235 
236 	foreach(lc, exprlist)
237 	{
238 		Node	   *e = (Node *) lfirst(lc);
239 
240 		/*
241 		 * Check for "something.*".  Depending on the complexity of the
242 		 * "something", the star could appear as the last field in ColumnRef,
243 		 * or as the last indirection item in A_Indirection.
244 		 */
245 		if (IsA(e, ColumnRef))
246 		{
247 			ColumnRef  *cref = (ColumnRef *) e;
248 
249 			if (IsA(llast(cref->fields), A_Star))
250 			{
251 				/* It is something.*, expand into multiple items */
252 				result = list_concat(result,
253 									 ExpandColumnRefStar(pstate, cref,
254 														 false));
255 				continue;
256 			}
257 		}
258 		else if (IsA(e, A_Indirection))
259 		{
260 			A_Indirection *ind = (A_Indirection *) e;
261 
262 			if (IsA(llast(ind->indirection), A_Star))
263 			{
264 				/* It is something.*, expand into multiple items */
265 				result = list_concat(result,
266 									 ExpandIndirectionStar(pstate, ind,
267 														   false, exprKind));
268 				continue;
269 			}
270 		}
271 
272 		/*
273 		 * Not "something.*", so transform as a single expression.  If it's a
274 		 * SetToDefault node and we should allow that, pass it through
275 		 * unmodified.  (transformExpr will throw the appropriate error if
276 		 * we're disallowing it.)
277 		 */
278 		if (allowDefault && IsA(e, SetToDefault))
279 			 /* do nothing */ ;
280 		else
281 			e = transformExpr(pstate, e, exprKind);
282 
283 		result = lappend(result, e);
284 	}
285 
286 	return result;
287 }
288 
289 
290 /*
291  * resolveTargetListUnknowns()
292  *		Convert any unknown-type targetlist entries to type TEXT.
293  *
294  * We do this after we've exhausted all other ways of identifying the output
295  * column types of a query.
296  */
297 void
resolveTargetListUnknowns(ParseState * pstate,List * targetlist)298 resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
299 {
300 	ListCell   *l;
301 
302 	foreach(l, targetlist)
303 	{
304 		TargetEntry *tle = (TargetEntry *) lfirst(l);
305 		Oid			restype = exprType((Node *) tle->expr);
306 
307 		if (restype == UNKNOWNOID)
308 		{
309 			tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
310 											 restype, TEXTOID, -1,
311 											 COERCION_IMPLICIT,
312 											 COERCE_IMPLICIT_CAST,
313 											 -1);
314 		}
315 	}
316 }
317 
318 
319 /*
320  * markTargetListOrigins()
321  *		Mark targetlist columns that are simple Vars with the source
322  *		table's OID and column number.
323  *
324  * Currently, this is done only for SELECT targetlists and RETURNING lists,
325  * since we only need the info if we are going to send it to the frontend.
326  */
327 void
markTargetListOrigins(ParseState * pstate,List * targetlist)328 markTargetListOrigins(ParseState *pstate, List *targetlist)
329 {
330 	ListCell   *l;
331 
332 	foreach(l, targetlist)
333 	{
334 		TargetEntry *tle = (TargetEntry *) lfirst(l);
335 
336 		markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
337 	}
338 }
339 
340 /*
341  * markTargetListOrigin()
342  *		If 'var' is a Var of a plain relation, mark 'tle' with its origin
343  *
344  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
345  *
346  * This is split out so it can recurse for join references.  Note that we
347  * do not drill down into views, but report the view as the column owner.
348  */
349 static void
markTargetListOrigin(ParseState * pstate,TargetEntry * tle,Var * var,int levelsup)350 markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
351 					 Var *var, int levelsup)
352 {
353 	int			netlevelsup;
354 	RangeTblEntry *rte;
355 	AttrNumber	attnum;
356 
357 	if (var == NULL || !IsA(var, Var))
358 		return;
359 	netlevelsup = var->varlevelsup + levelsup;
360 	rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
361 	attnum = var->varattno;
362 
363 	switch (rte->rtekind)
364 	{
365 		case RTE_RELATION:
366 			/* It's a table or view, report it */
367 			tle->resorigtbl = rte->relid;
368 			tle->resorigcol = attnum;
369 			break;
370 		case RTE_SUBQUERY:
371 			/* Subselect-in-FROM: copy up from the subselect */
372 			if (attnum != InvalidAttrNumber)
373 			{
374 				TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
375 													attnum);
376 
377 				if (ste == NULL || ste->resjunk)
378 					elog(ERROR, "subquery %s does not have attribute %d",
379 						 rte->eref->aliasname, attnum);
380 				tle->resorigtbl = ste->resorigtbl;
381 				tle->resorigcol = ste->resorigcol;
382 			}
383 			break;
384 		case RTE_JOIN:
385 			/* Join RTE --- recursively inspect the alias variable */
386 			if (attnum != InvalidAttrNumber)
387 			{
388 				Var		   *aliasvar;
389 
390 				Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
391 				aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
392 				/* We intentionally don't strip implicit coercions here */
393 				markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
394 			}
395 			break;
396 		case RTE_FUNCTION:
397 		case RTE_VALUES:
398 		case RTE_TABLEFUNC:
399 		case RTE_NAMEDTUPLESTORE:
400 		case RTE_RESULT:
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 *
transformAssignedExpr(ParseState * pstate,Expr * expr,ParseExprKind exprKind,const char * colname,int attrno,List * indirection,int location)455 transformAssignedExpr(ParseState *pstate,
456 					  Expr *expr,
457 					  ParseExprKind exprKind,
458 					  const 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 = TupleDescAttr(rd->rd_att, attrno - 1)->atttypmod;
488 	attrcollation = TupleDescAttr(rd->rd_att, 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 *)
556 			transformAssignmentIndirection(pstate,
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,
579 								  COERCION_ASSIGNMENT,
580 								  COERCE_IMPLICIT_CAST,
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
updateTargetListEntry(ParseState * pstate,TargetEntry * tle,char * colname,int attrno,List * indirection,int location)617 updateTargetListEntry(ParseState *pstate,
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,
627 									  EXPR_KIND_UPDATE_TARGET,
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  * targetIsSubscripting 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 *
transformAssignmentIndirection(ParseState * pstate,Node * basenode,const char * targetName,bool targetIsSubscripting,Oid targetTypeId,int32 targetTypMod,Oid targetCollation,ListCell * indirection,Node * rhs,int location)676 transformAssignmentIndirection(ParseState *pstate,
677 							   Node *basenode,
678 							   const char *targetName,
679 							   bool targetIsSubscripting,
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 		/*
695 		 * Set up a substitution.  We abuse CaseTestExpr for this.  It's safe
696 		 * to do so because the only nodes that will be above the CaseTestExpr
697 		 * in the finished expression will be FieldStore and SubscriptingRef
698 		 * nodes. (There could be other stuff in the tree, but it will be
699 		 * within other child fields of those node types.)
700 		 */
701 		CaseTestExpr *ctest = makeNode(CaseTestExpr);
702 
703 		ctest->typeId = targetTypeId;
704 		ctest->typeMod = targetTypMod;
705 		ctest->collation = targetCollation;
706 		basenode = (Node *) ctest;
707 	}
708 
709 	/*
710 	 * We have to split any field-selection operations apart from
711 	 * subscripting.  Adjacent A_Indices nodes have to be treated as a single
712 	 * multidimensional subscript operation.
713 	 */
714 	for_each_cell(i, indirection)
715 	{
716 		Node	   *n = lfirst(i);
717 
718 		if (IsA(n, A_Indices))
719 		{
720 			subscripts = lappend(subscripts, n);
721 			if (((A_Indices *) n)->is_slice)
722 				isSlice = true;
723 		}
724 		else if (IsA(n, A_Star))
725 		{
726 			ereport(ERROR,
727 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
728 					 errmsg("row expansion via \"*\" is not supported here"),
729 					 parser_errposition(pstate, location)));
730 		}
731 		else
732 		{
733 			FieldStore *fstore;
734 			Oid			baseTypeId;
735 			int32		baseTypeMod;
736 			Oid			typrelid;
737 			AttrNumber	attnum;
738 			Oid			fieldTypeId;
739 			int32		fieldTypMod;
740 			Oid			fieldCollation;
741 
742 			Assert(IsA(n, String));
743 
744 			/* process subscripts before this field selection */
745 			if (subscripts)
746 			{
747 				/* recurse, and then return because we're done */
748 				return transformAssignmentSubscripts(pstate,
749 													 basenode,
750 													 targetName,
751 													 targetTypeId,
752 													 targetTypMod,
753 													 targetCollation,
754 													 subscripts,
755 													 isSlice,
756 													 i,
757 													 rhs,
758 													 location);
759 			}
760 
761 			/* No subscripts, so can process field selection here */
762 
763 			/*
764 			 * Look up the composite type, accounting for possibility that
765 			 * what we are given is a domain over composite.
766 			 */
767 			baseTypeMod = targetTypMod;
768 			baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
769 
770 			typrelid = typeidTypeRelid(baseTypeId);
771 			if (!typrelid)
772 				ereport(ERROR,
773 						(errcode(ERRCODE_DATATYPE_MISMATCH),
774 						 errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
775 								strVal(n), targetName,
776 								format_type_be(targetTypeId)),
777 						 parser_errposition(pstate, location)));
778 
779 			attnum = get_attnum(typrelid, strVal(n));
780 			if (attnum == InvalidAttrNumber)
781 				ereport(ERROR,
782 						(errcode(ERRCODE_UNDEFINED_COLUMN),
783 						 errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
784 								strVal(n), targetName,
785 								format_type_be(targetTypeId)),
786 						 parser_errposition(pstate, location)));
787 			if (attnum < 0)
788 				ereport(ERROR,
789 						(errcode(ERRCODE_UNDEFINED_COLUMN),
790 						 errmsg("cannot assign to system column \"%s\"",
791 								strVal(n)),
792 						 parser_errposition(pstate, location)));
793 
794 			get_atttypetypmodcoll(typrelid, attnum,
795 								  &fieldTypeId, &fieldTypMod, &fieldCollation);
796 
797 			/* recurse to create appropriate RHS for field assign */
798 			rhs = transformAssignmentIndirection(pstate,
799 												 NULL,
800 												 strVal(n),
801 												 false,
802 												 fieldTypeId,
803 												 fieldTypMod,
804 												 fieldCollation,
805 												 lnext(i),
806 												 rhs,
807 												 location);
808 
809 			/* and build a FieldStore node */
810 			fstore = makeNode(FieldStore);
811 			fstore->arg = (Expr *) basenode;
812 			fstore->newvals = list_make1(rhs);
813 			fstore->fieldnums = list_make1_int(attnum);
814 			fstore->resulttype = baseTypeId;
815 
816 			/* If target is a domain, apply constraints */
817 			if (baseTypeId != targetTypeId)
818 				return coerce_to_domain((Node *) fstore,
819 										baseTypeId, baseTypeMod,
820 										targetTypeId,
821 										COERCION_IMPLICIT,
822 										COERCE_IMPLICIT_CAST,
823 										location,
824 										false);
825 
826 			return (Node *) fstore;
827 		}
828 	}
829 
830 	/* process trailing subscripts, if any */
831 	if (subscripts)
832 	{
833 		/* recurse, and then return because we're done */
834 		return transformAssignmentSubscripts(pstate,
835 											 basenode,
836 											 targetName,
837 											 targetTypeId,
838 											 targetTypMod,
839 											 targetCollation,
840 											 subscripts,
841 											 isSlice,
842 											 NULL,
843 											 rhs,
844 											 location);
845 	}
846 
847 	/* base case: just coerce RHS to match target type ID */
848 
849 	result = coerce_to_target_type(pstate,
850 								   rhs, exprType(rhs),
851 								   targetTypeId, targetTypMod,
852 								   COERCION_ASSIGNMENT,
853 								   COERCE_IMPLICIT_CAST,
854 								   -1);
855 	if (result == NULL)
856 	{
857 		if (targetIsSubscripting)
858 			ereport(ERROR,
859 					(errcode(ERRCODE_DATATYPE_MISMATCH),
860 					 errmsg("array assignment to \"%s\" requires type %s"
861 							" but expression is of type %s",
862 							targetName,
863 							format_type_be(targetTypeId),
864 							format_type_be(exprType(rhs))),
865 					 errhint("You will need to rewrite or cast the expression."),
866 					 parser_errposition(pstate, location)));
867 		else
868 			ereport(ERROR,
869 					(errcode(ERRCODE_DATATYPE_MISMATCH),
870 					 errmsg("subfield \"%s\" is of type %s"
871 							" but expression is of type %s",
872 							targetName,
873 							format_type_be(targetTypeId),
874 							format_type_be(exprType(rhs))),
875 					 errhint("You will need to rewrite or cast the expression."),
876 					 parser_errposition(pstate, location)));
877 	}
878 
879 	return result;
880 }
881 
882 /*
883  * helper for transformAssignmentIndirection: process container assignment
884  */
885 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)886 transformAssignmentSubscripts(ParseState *pstate,
887 							  Node *basenode,
888 							  const char *targetName,
889 							  Oid targetTypeId,
890 							  int32 targetTypMod,
891 							  Oid targetCollation,
892 							  List *subscripts,
893 							  bool isSlice,
894 							  ListCell *next_indirection,
895 							  Node *rhs,
896 							  int location)
897 {
898 	Node	   *result;
899 	Oid			containerType;
900 	int32		containerTypMod;
901 	Oid			elementTypeId;
902 	Oid			typeNeeded;
903 	Oid			collationNeeded;
904 
905 	Assert(subscripts != NIL);
906 
907 	/* Identify the actual array type and element type involved */
908 	containerType = targetTypeId;
909 	containerTypMod = targetTypMod;
910 	elementTypeId = transformContainerType(&containerType, &containerTypMod);
911 
912 	/* Identify type that RHS must provide */
913 	typeNeeded = isSlice ? containerType : elementTypeId;
914 
915 	/*
916 	 * container normally has same collation as elements, but there's an
917 	 * exception: we might be subscripting a domain over a container type. In
918 	 * that case use collation of the base type.
919 	 */
920 	if (containerType == targetTypeId)
921 		collationNeeded = targetCollation;
922 	else
923 		collationNeeded = get_typcollation(containerType);
924 
925 	/* recurse to create appropriate RHS for container assign */
926 	rhs = transformAssignmentIndirection(pstate,
927 										 NULL,
928 										 targetName,
929 										 true,
930 										 typeNeeded,
931 										 containerTypMod,
932 										 collationNeeded,
933 										 next_indirection,
934 										 rhs,
935 										 location);
936 
937 	/* process subscripts */
938 	result = (Node *) transformContainerSubscripts(pstate,
939 												   basenode,
940 												   containerType,
941 												   elementTypeId,
942 												   containerTypMod,
943 												   subscripts,
944 												   rhs);
945 
946 	/* If target was a domain over container, need to coerce up to the domain */
947 	if (containerType != targetTypeId)
948 	{
949 		Oid			resulttype = exprType(result);
950 
951 		result = coerce_to_target_type(pstate,
952 									   result, resulttype,
953 									   targetTypeId, targetTypMod,
954 									   COERCION_ASSIGNMENT,
955 									   COERCE_IMPLICIT_CAST,
956 									   -1);
957 		/* can fail if we had int2vector/oidvector, but not for true domains */
958 		if (result == NULL)
959 			ereport(ERROR,
960 					(errcode(ERRCODE_CANNOT_COERCE),
961 					 errmsg("cannot cast type %s to %s",
962 							format_type_be(resulttype),
963 							format_type_be(targetTypeId)),
964 					 parser_errposition(pstate, location)));
965 	}
966 
967 	return result;
968 }
969 
970 
971 /*
972  * checkInsertTargets -
973  *	  generate a list of INSERT column targets if not supplied, or
974  *	  test supplied column names to make sure they are in target table.
975  *	  Also return an integer list of the columns' attribute numbers.
976  */
977 List *
checkInsertTargets(ParseState * pstate,List * cols,List ** attrnos)978 checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
979 {
980 	*attrnos = NIL;
981 
982 	if (cols == NIL)
983 	{
984 		/*
985 		 * Generate default column list for INSERT.
986 		 */
987 		int			numcol = RelationGetNumberOfAttributes(pstate->p_target_relation);
988 
989 		int			i;
990 
991 		for (i = 0; i < numcol; i++)
992 		{
993 			ResTarget  *col;
994 			Form_pg_attribute attr;
995 
996 			attr = TupleDescAttr(pstate->p_target_relation->rd_att, i);
997 
998 			if (attr->attisdropped)
999 				continue;
1000 
1001 			col = makeNode(ResTarget);
1002 			col->name = pstrdup(NameStr(attr->attname));
1003 			col->indirection = NIL;
1004 			col->val = NULL;
1005 			col->location = -1;
1006 			cols = lappend(cols, col);
1007 			*attrnos = lappend_int(*attrnos, i + 1);
1008 		}
1009 	}
1010 	else
1011 	{
1012 		/*
1013 		 * Do initial validation of user-supplied INSERT column list.
1014 		 */
1015 		Bitmapset  *wholecols = NULL;
1016 		Bitmapset  *partialcols = NULL;
1017 		ListCell   *tl;
1018 
1019 		foreach(tl, cols)
1020 		{
1021 			ResTarget  *col = (ResTarget *) lfirst(tl);
1022 			char	   *name = col->name;
1023 			int			attrno;
1024 
1025 			/* Lookup column name, ereport on failure */
1026 			attrno = attnameAttNum(pstate->p_target_relation, name, false);
1027 			if (attrno == InvalidAttrNumber)
1028 				ereport(ERROR,
1029 						(errcode(ERRCODE_UNDEFINED_COLUMN),
1030 						 errmsg("column \"%s\" of relation \"%s\" does not exist",
1031 								name,
1032 								RelationGetRelationName(pstate->p_target_relation)),
1033 						 parser_errposition(pstate, col->location)));
1034 
1035 			/*
1036 			 * Check for duplicates, but only of whole columns --- we allow
1037 			 * INSERT INTO foo (col.subcol1, col.subcol2)
1038 			 */
1039 			if (col->indirection == NIL)
1040 			{
1041 				/* whole column; must not have any other assignment */
1042 				if (bms_is_member(attrno, wholecols) ||
1043 					bms_is_member(attrno, partialcols))
1044 					ereport(ERROR,
1045 							(errcode(ERRCODE_DUPLICATE_COLUMN),
1046 							 errmsg("column \"%s\" specified more than once",
1047 									name),
1048 							 parser_errposition(pstate, col->location)));
1049 				wholecols = bms_add_member(wholecols, attrno);
1050 			}
1051 			else
1052 			{
1053 				/* partial column; must not have any whole assignment */
1054 				if (bms_is_member(attrno, wholecols))
1055 					ereport(ERROR,
1056 							(errcode(ERRCODE_DUPLICATE_COLUMN),
1057 							 errmsg("column \"%s\" specified more than once",
1058 									name),
1059 							 parser_errposition(pstate, col->location)));
1060 				partialcols = bms_add_member(partialcols, attrno);
1061 			}
1062 
1063 			*attrnos = lappend_int(*attrnos, attrno);
1064 		}
1065 	}
1066 
1067 	return cols;
1068 }
1069 
1070 /*
1071  * ExpandColumnRefStar()
1072  *		Transforms foo.* into a list of expressions or targetlist entries.
1073  *
1074  * This handles the case where '*' appears as the last or only item in a
1075  * ColumnRef.  The code is shared between the case of foo.* at the top level
1076  * in a SELECT target list (where we want TargetEntry nodes in the result)
1077  * and foo.* in a ROW() or VALUES() construct (where we want just bare
1078  * expressions).
1079  *
1080  * The referenced columns are marked as requiring SELECT access.
1081  */
1082 static List *
ExpandColumnRefStar(ParseState * pstate,ColumnRef * cref,bool make_target_entry)1083 ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
1084 					bool make_target_entry)
1085 {
1086 	List	   *fields = cref->fields;
1087 	int			numnames = list_length(fields);
1088 
1089 	if (numnames == 1)
1090 	{
1091 		/*
1092 		 * Target item is a bare '*', expand all tables
1093 		 *
1094 		 * (e.g., SELECT * FROM emp, dept)
1095 		 *
1096 		 * Since the grammar only accepts bare '*' at top level of SELECT, we
1097 		 * need not handle the make_target_entry==false case here.
1098 		 */
1099 		Assert(make_target_entry);
1100 		return ExpandAllTables(pstate, cref->location);
1101 	}
1102 	else
1103 	{
1104 		/*
1105 		 * Target item is relation.*, expand that table
1106 		 *
1107 		 * (e.g., SELECT emp.*, dname FROM emp, dept)
1108 		 *
1109 		 * Note: this code is a lot like transformColumnRef; it's tempting to
1110 		 * call that instead and then replace the resulting whole-row Var with
1111 		 * a list of Vars.  However, that would leave us with the RTE's
1112 		 * selectedCols bitmap showing the whole row as needing select
1113 		 * permission, as well as the individual columns.  That would be
1114 		 * incorrect (since columns added later shouldn't need select
1115 		 * permissions).  We could try to remove the whole-row permission bit
1116 		 * after the fact, but duplicating code is less messy.
1117 		 */
1118 		char	   *nspname = NULL;
1119 		char	   *relname = NULL;
1120 		RangeTblEntry *rte = NULL;
1121 		int			levels_up;
1122 		enum
1123 		{
1124 			CRSERR_NO_RTE,
1125 			CRSERR_WRONG_DB,
1126 			CRSERR_TOO_MANY
1127 		}			crserr = CRSERR_NO_RTE;
1128 
1129 		/*
1130 		 * Give the PreParseColumnRefHook, if any, first shot.  If it returns
1131 		 * non-null then we should use that expression.
1132 		 */
1133 		if (pstate->p_pre_columnref_hook != NULL)
1134 		{
1135 			Node	   *node;
1136 
1137 			node = pstate->p_pre_columnref_hook(pstate, cref);
1138 			if (node != NULL)
1139 				return ExpandRowReference(pstate, node, make_target_entry);
1140 		}
1141 
1142 		switch (numnames)
1143 		{
1144 			case 2:
1145 				relname = strVal(linitial(fields));
1146 				rte = refnameRangeTblEntry(pstate, nspname, relname,
1147 										   cref->location,
1148 										   &levels_up);
1149 				break;
1150 			case 3:
1151 				nspname = strVal(linitial(fields));
1152 				relname = strVal(lsecond(fields));
1153 				rte = refnameRangeTblEntry(pstate, nspname, relname,
1154 										   cref->location,
1155 										   &levels_up);
1156 				break;
1157 			case 4:
1158 				{
1159 					char	   *catname = strVal(linitial(fields));
1160 
1161 					/*
1162 					 * We check the catalog name and then ignore it.
1163 					 */
1164 					if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1165 					{
1166 						crserr = CRSERR_WRONG_DB;
1167 						break;
1168 					}
1169 					nspname = strVal(lsecond(fields));
1170 					relname = strVal(lthird(fields));
1171 					rte = refnameRangeTblEntry(pstate, nspname, relname,
1172 											   cref->location,
1173 											   &levels_up);
1174 					break;
1175 				}
1176 			default:
1177 				crserr = CRSERR_TOO_MANY;
1178 				break;
1179 		}
1180 
1181 		/*
1182 		 * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1183 		 * bit by passing the RangeTblEntry, not a Var, as the planned
1184 		 * translation.  (A single Var wouldn't be strictly correct anyway.
1185 		 * This convention allows hooks that really care to know what is
1186 		 * happening.)
1187 		 */
1188 		if (pstate->p_post_columnref_hook != NULL)
1189 		{
1190 			Node	   *node;
1191 
1192 			node = pstate->p_post_columnref_hook(pstate, cref,
1193 												 (Node *) rte);
1194 			if (node != NULL)
1195 			{
1196 				if (rte != NULL)
1197 					ereport(ERROR,
1198 							(errcode(ERRCODE_AMBIGUOUS_COLUMN),
1199 							 errmsg("column reference \"%s\" is ambiguous",
1200 									NameListToString(cref->fields)),
1201 							 parser_errposition(pstate, cref->location)));
1202 				return ExpandRowReference(pstate, node, make_target_entry);
1203 			}
1204 		}
1205 
1206 		/*
1207 		 * Throw error if no translation found.
1208 		 */
1209 		if (rte == NULL)
1210 		{
1211 			switch (crserr)
1212 			{
1213 				case CRSERR_NO_RTE:
1214 					errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1215 														 cref->location));
1216 					break;
1217 				case CRSERR_WRONG_DB:
1218 					ereport(ERROR,
1219 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1220 							 errmsg("cross-database references are not implemented: %s",
1221 									NameListToString(cref->fields)),
1222 							 parser_errposition(pstate, cref->location)));
1223 					break;
1224 				case CRSERR_TOO_MANY:
1225 					ereport(ERROR,
1226 							(errcode(ERRCODE_SYNTAX_ERROR),
1227 							 errmsg("improper qualified name (too many dotted names): %s",
1228 									NameListToString(cref->fields)),
1229 							 parser_errposition(pstate, cref->location)));
1230 					break;
1231 			}
1232 		}
1233 
1234 		/*
1235 		 * OK, expand the RTE into fields.
1236 		 */
1237 		return ExpandSingleTable(pstate, rte, cref->location, make_target_entry);
1238 	}
1239 }
1240 
1241 /*
1242  * ExpandAllTables()
1243  *		Transforms '*' (in the target list) into a list of targetlist entries.
1244  *
1245  * tlist entries are generated for each relation visible for unqualified
1246  * column name access.  We do not consider qualified-name-only entries because
1247  * that would include input tables of aliasless JOINs, NEW/OLD pseudo-entries,
1248  * etc.
1249  *
1250  * The referenced relations/columns are marked as requiring SELECT access.
1251  */
1252 static List *
ExpandAllTables(ParseState * pstate,int location)1253 ExpandAllTables(ParseState *pstate, int location)
1254 {
1255 	List	   *target = NIL;
1256 	bool		found_table = false;
1257 	ListCell   *l;
1258 
1259 	foreach(l, pstate->p_namespace)
1260 	{
1261 		ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1262 		RangeTblEntry *rte = nsitem->p_rte;
1263 
1264 		/* Ignore table-only items */
1265 		if (!nsitem->p_cols_visible)
1266 			continue;
1267 		/* Should not have any lateral-only items when parsing targetlist */
1268 		Assert(!nsitem->p_lateral_only);
1269 		/* Remember we found a p_cols_visible item */
1270 		found_table = true;
1271 
1272 		target = list_concat(target,
1273 							 expandRelAttrs(pstate,
1274 											rte,
1275 											RTERangeTablePosn(pstate, rte,
1276 															  NULL),
1277 											0,
1278 											location));
1279 	}
1280 
1281 	/*
1282 	 * Check for "SELECT *;".  We do it this way, rather than checking for
1283 	 * target == NIL, because we want to allow SELECT * FROM a zero_column
1284 	 * table.
1285 	 */
1286 	if (!found_table)
1287 		ereport(ERROR,
1288 				(errcode(ERRCODE_SYNTAX_ERROR),
1289 				 errmsg("SELECT * with no tables specified is not valid"),
1290 				 parser_errposition(pstate, location)));
1291 
1292 	return target;
1293 }
1294 
1295 /*
1296  * ExpandIndirectionStar()
1297  *		Transforms foo.* into a list of expressions or targetlist entries.
1298  *
1299  * This handles the case where '*' appears as the last item in A_Indirection.
1300  * The code is shared between the case of foo.* at the top level in a SELECT
1301  * target list (where we want TargetEntry nodes in the result) and foo.* in
1302  * a ROW() or VALUES() construct (where we want just bare expressions).
1303  * For robustness, we use a separate "make_target_entry" flag to control
1304  * this rather than relying on exprKind.
1305  */
1306 static List *
ExpandIndirectionStar(ParseState * pstate,A_Indirection * ind,bool make_target_entry,ParseExprKind exprKind)1307 ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
1308 					  bool make_target_entry, ParseExprKind exprKind)
1309 {
1310 	Node	   *expr;
1311 
1312 	/* Strip off the '*' to create a reference to the rowtype object */
1313 	ind = copyObject(ind);
1314 	ind->indirection = list_truncate(ind->indirection,
1315 									 list_length(ind->indirection) - 1);
1316 
1317 	/* And transform that */
1318 	expr = transformExpr(pstate, (Node *) ind, exprKind);
1319 
1320 	/* Expand the rowtype expression into individual fields */
1321 	return ExpandRowReference(pstate, expr, make_target_entry);
1322 }
1323 
1324 /*
1325  * ExpandSingleTable()
1326  *		Transforms foo.* into a list of expressions or targetlist entries.
1327  *
1328  * This handles the case where foo has been determined to be a simple
1329  * reference to an RTE, so we can just generate Vars for the expressions.
1330  *
1331  * The referenced columns are marked as requiring SELECT access.
1332  */
1333 static List *
ExpandSingleTable(ParseState * pstate,RangeTblEntry * rte,int location,bool make_target_entry)1334 ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
1335 				  int location, bool make_target_entry)
1336 {
1337 	int			sublevels_up;
1338 	int			rtindex;
1339 
1340 	rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1341 
1342 	if (make_target_entry)
1343 	{
1344 		/* expandRelAttrs handles permissions marking */
1345 		return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1346 							  location);
1347 	}
1348 	else
1349 	{
1350 		List	   *vars;
1351 		ListCell   *l;
1352 
1353 		expandRTE(rte, rtindex, sublevels_up, location, false,
1354 				  NULL, &vars);
1355 
1356 		/*
1357 		 * Require read access to the table.  This is normally redundant with
1358 		 * the markVarForSelectPriv calls below, but not if the table has zero
1359 		 * columns.
1360 		 */
1361 		rte->requiredPerms |= ACL_SELECT;
1362 
1363 		/* Require read access to each column */
1364 		foreach(l, vars)
1365 		{
1366 			Var		   *var = (Var *) lfirst(l);
1367 
1368 			markVarForSelectPriv(pstate, var, rte);
1369 		}
1370 
1371 		return vars;
1372 	}
1373 }
1374 
1375 /*
1376  * ExpandRowReference()
1377  *		Transforms foo.* into a list of expressions or targetlist entries.
1378  *
1379  * This handles the case where foo is an arbitrary expression of composite
1380  * type.
1381  */
1382 static List *
ExpandRowReference(ParseState * pstate,Node * expr,bool make_target_entry)1383 ExpandRowReference(ParseState *pstate, Node *expr,
1384 				   bool make_target_entry)
1385 {
1386 	List	   *result = NIL;
1387 	TupleDesc	tupleDesc;
1388 	int			numAttrs;
1389 	int			i;
1390 
1391 	/*
1392 	 * If the rowtype expression is a whole-row Var, we can expand the fields
1393 	 * as simple Vars.  Note: if the RTE is a relation, this case leaves us
1394 	 * with the RTE's selectedCols bitmap showing the whole row as needing
1395 	 * select permission, as well as the individual columns.  However, we can
1396 	 * only get here for weird notations like (table.*).*, so it's not worth
1397 	 * trying to clean up --- arguably, the permissions marking is correct
1398 	 * anyway for such cases.
1399 	 */
1400 	if (IsA(expr, Var) &&
1401 		((Var *) expr)->varattno == InvalidAttrNumber)
1402 	{
1403 		Var		   *var = (Var *) expr;
1404 		RangeTblEntry *rte;
1405 
1406 		rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1407 		return ExpandSingleTable(pstate, rte, var->location, make_target_entry);
1408 	}
1409 
1410 	/*
1411 	 * Otherwise we have to do it the hard way.  Our current implementation is
1412 	 * to generate multiple copies of the expression and do FieldSelects.
1413 	 * (This can be pretty inefficient if the expression involves nontrivial
1414 	 * computation :-(.)
1415 	 *
1416 	 * Verify it's a composite type, and get the tupdesc.
1417 	 * get_expr_result_tupdesc() handles this conveniently.
1418 	 *
1419 	 * If it's a Var of type RECORD, we have to work even harder: we have to
1420 	 * find what the Var refers to, and pass that to get_expr_result_tupdesc.
1421 	 * That task is handled by expandRecordVariable().
1422 	 */
1423 	if (IsA(expr, Var) &&
1424 		((Var *) expr)->vartype == RECORDOID)
1425 		tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1426 	else
1427 		tupleDesc = get_expr_result_tupdesc(expr, false);
1428 	Assert(tupleDesc);
1429 
1430 	/* Generate a list of references to the individual fields */
1431 	numAttrs = tupleDesc->natts;
1432 	for (i = 0; i < numAttrs; i++)
1433 	{
1434 		Form_pg_attribute att = TupleDescAttr(tupleDesc, i);
1435 		FieldSelect *fselect;
1436 
1437 		if (att->attisdropped)
1438 			continue;
1439 
1440 		fselect = makeNode(FieldSelect);
1441 		fselect->arg = (Expr *) copyObject(expr);
1442 		fselect->fieldnum = i + 1;
1443 		fselect->resulttype = att->atttypid;
1444 		fselect->resulttypmod = att->atttypmod;
1445 		/* save attribute's collation for parse_collate.c */
1446 		fselect->resultcollid = att->attcollation;
1447 
1448 		if (make_target_entry)
1449 		{
1450 			/* add TargetEntry decoration */
1451 			TargetEntry *te;
1452 
1453 			te = makeTargetEntry((Expr *) fselect,
1454 								 (AttrNumber) pstate->p_next_resno++,
1455 								 pstrdup(NameStr(att->attname)),
1456 								 false);
1457 			result = lappend(result, te);
1458 		}
1459 		else
1460 			result = lappend(result, fselect);
1461 	}
1462 
1463 	return result;
1464 }
1465 
1466 /*
1467  * expandRecordVariable
1468  *		Get the tuple descriptor for a Var of type RECORD, if possible.
1469  *
1470  * Since no actual table or view column is allowed to have type RECORD, such
1471  * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output.  We
1472  * drill down to find the ultimate defining expression and attempt to infer
1473  * the tupdesc from it.  We ereport if we can't determine the tupdesc.
1474  *
1475  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
1476  */
1477 TupleDesc
expandRecordVariable(ParseState * pstate,Var * var,int levelsup)1478 expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
1479 {
1480 	TupleDesc	tupleDesc;
1481 	int			netlevelsup;
1482 	RangeTblEntry *rte;
1483 	AttrNumber	attnum;
1484 	Node	   *expr;
1485 
1486 	/* Check my caller didn't mess up */
1487 	Assert(IsA(var, Var));
1488 	Assert(var->vartype == RECORDOID);
1489 
1490 	netlevelsup = var->varlevelsup + levelsup;
1491 	rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1492 	attnum = var->varattno;
1493 
1494 	if (attnum == InvalidAttrNumber)
1495 	{
1496 		/* Whole-row reference to an RTE, so expand the known fields */
1497 		List	   *names,
1498 				   *vars;
1499 		ListCell   *lname,
1500 				   *lvar;
1501 		int			i;
1502 
1503 		expandRTE(rte, var->varno, 0, var->location, false,
1504 				  &names, &vars);
1505 
1506 		tupleDesc = CreateTemplateTupleDesc(list_length(vars));
1507 		i = 1;
1508 		forboth(lname, names, lvar, vars)
1509 		{
1510 			char	   *label = strVal(lfirst(lname));
1511 			Node	   *varnode = (Node *) lfirst(lvar);
1512 
1513 			TupleDescInitEntry(tupleDesc, i,
1514 							   label,
1515 							   exprType(varnode),
1516 							   exprTypmod(varnode),
1517 							   0);
1518 			TupleDescInitEntryCollation(tupleDesc, i,
1519 										exprCollation(varnode));
1520 			i++;
1521 		}
1522 		Assert(lname == NULL && lvar == NULL);	/* lists same length? */
1523 
1524 		return tupleDesc;
1525 	}
1526 
1527 	expr = (Node *) var;		/* default if we can't drill down */
1528 
1529 	switch (rte->rtekind)
1530 	{
1531 		case RTE_RELATION:
1532 		case RTE_VALUES:
1533 		case RTE_NAMEDTUPLESTORE:
1534 		case RTE_RESULT:
1535 
1536 			/*
1537 			 * This case should not occur: a column of a table, values list,
1538 			 * or ENR shouldn't have type RECORD.  Fall through and fail (most
1539 			 * likely) at the bottom.
1540 			 */
1541 			break;
1542 		case RTE_SUBQUERY:
1543 			{
1544 				/* Subselect-in-FROM: examine sub-select's output expr */
1545 				TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1546 													attnum);
1547 
1548 				if (ste == NULL || ste->resjunk)
1549 					elog(ERROR, "subquery %s does not have attribute %d",
1550 						 rte->eref->aliasname, attnum);
1551 				expr = (Node *) ste->expr;
1552 				if (IsA(expr, Var))
1553 				{
1554 					/*
1555 					 * Recurse into the sub-select to see what its Var refers
1556 					 * to.  We have to build an additional level of ParseState
1557 					 * to keep in step with varlevelsup in the subselect.
1558 					 */
1559 					ParseState	mypstate;
1560 
1561 					MemSet(&mypstate, 0, sizeof(mypstate));
1562 					mypstate.parentParseState = pstate;
1563 					mypstate.p_rtable = rte->subquery->rtable;
1564 					/* don't bother filling the rest of the fake pstate */
1565 
1566 					return expandRecordVariable(&mypstate, (Var *) expr, 0);
1567 				}
1568 				/* else fall through to inspect the expression */
1569 			}
1570 			break;
1571 		case RTE_JOIN:
1572 			/* Join RTE --- recursively inspect the alias variable */
1573 			Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1574 			expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1575 			Assert(expr != NULL);
1576 			/* We intentionally don't strip implicit coercions here */
1577 			if (IsA(expr, Var))
1578 				return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1579 			/* else fall through to inspect the expression */
1580 			break;
1581 		case RTE_FUNCTION:
1582 
1583 			/*
1584 			 * We couldn't get here unless a function is declared with one of
1585 			 * its result columns as RECORD, which is not allowed.
1586 			 */
1587 			break;
1588 		case RTE_TABLEFUNC:
1589 
1590 			/*
1591 			 * Table function cannot have columns with RECORD type.
1592 			 */
1593 			break;
1594 		case RTE_CTE:
1595 			/* CTE reference: examine subquery's output expr */
1596 			if (!rte->self_reference)
1597 			{
1598 				CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1599 				TargetEntry *ste;
1600 
1601 				ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1602 				if (ste == NULL || ste->resjunk)
1603 					elog(ERROR, "subquery %s does not have attribute %d",
1604 						 rte->eref->aliasname, attnum);
1605 				expr = (Node *) ste->expr;
1606 				if (IsA(expr, Var))
1607 				{
1608 					/*
1609 					 * Recurse into the CTE to see what its Var refers to. We
1610 					 * have to build an additional level of ParseState to keep
1611 					 * in step with varlevelsup in the CTE; furthermore it
1612 					 * could be an outer CTE.
1613 					 */
1614 					ParseState	mypstate;
1615 					Index		levelsup;
1616 
1617 					MemSet(&mypstate, 0, sizeof(mypstate));
1618 					/* this loop must work, since GetCTEForRTE did */
1619 					for (levelsup = 0;
1620 						 levelsup < rte->ctelevelsup + netlevelsup;
1621 						 levelsup++)
1622 						pstate = pstate->parentParseState;
1623 					mypstate.parentParseState = pstate;
1624 					mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1625 					/* don't bother filling the rest of the fake pstate */
1626 
1627 					return expandRecordVariable(&mypstate, (Var *) expr, 0);
1628 				}
1629 				/* else fall through to inspect the expression */
1630 			}
1631 			break;
1632 	}
1633 
1634 	/*
1635 	 * We now have an expression we can't expand any more, so see if
1636 	 * get_expr_result_tupdesc() can do anything with it.
1637 	 */
1638 	return get_expr_result_tupdesc(expr, false);
1639 }
1640 
1641 
1642 /*
1643  * FigureColname -
1644  *	  if the name of the resulting column is not specified in the target
1645  *	  list, we have to guess a suitable name.  The SQL spec provides some
1646  *	  guidance, but not much...
1647  *
1648  * Note that the argument is the *untransformed* parse tree for the target
1649  * item.  This is a shade easier to work with than the transformed tree.
1650  */
1651 char *
FigureColname(Node * node)1652 FigureColname(Node *node)
1653 {
1654 	char	   *name = NULL;
1655 
1656 	(void) FigureColnameInternal(node, &name);
1657 	if (name != NULL)
1658 		return name;
1659 	/* default result if we can't guess anything */
1660 	return "?column?";
1661 }
1662 
1663 /*
1664  * FigureIndexColname -
1665  *	  choose the name for an expression column in an index
1666  *
1667  * This is actually just like FigureColname, except we return NULL if
1668  * we can't pick a good name.
1669  */
1670 char *
FigureIndexColname(Node * node)1671 FigureIndexColname(Node *node)
1672 {
1673 	char	   *name = NULL;
1674 
1675 	(void) FigureColnameInternal(node, &name);
1676 	return name;
1677 }
1678 
1679 /*
1680  * FigureColnameInternal -
1681  *	  internal workhorse for FigureColname
1682  *
1683  * Return value indicates strength of confidence in result:
1684  *		0 - no information
1685  *		1 - second-best name choice
1686  *		2 - good name choice
1687  * The return value is actually only used internally.
1688  * If the result isn't zero, *name is set to the chosen name.
1689  */
1690 static int
FigureColnameInternal(Node * node,char ** name)1691 FigureColnameInternal(Node *node, char **name)
1692 {
1693 	int			strength = 0;
1694 
1695 	if (node == NULL)
1696 		return strength;
1697 
1698 	switch (nodeTag(node))
1699 	{
1700 		case T_ColumnRef:
1701 			{
1702 				char	   *fname = NULL;
1703 				ListCell   *l;
1704 
1705 				/* find last field name, if any, ignoring "*" */
1706 				foreach(l, ((ColumnRef *) node)->fields)
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 			}
1719 			break;
1720 		case T_A_Indirection:
1721 			{
1722 				A_Indirection *ind = (A_Indirection *) node;
1723 				char	   *fname = NULL;
1724 				ListCell   *l;
1725 
1726 				/* find last field name, if any, ignoring "*" and subscripts */
1727 				foreach(l, ind->indirection)
1728 				{
1729 					Node	   *i = lfirst(l);
1730 
1731 					if (IsA(i, String))
1732 						fname = strVal(i);
1733 				}
1734 				if (fname)
1735 				{
1736 					*name = fname;
1737 					return 2;
1738 				}
1739 				return FigureColnameInternal(ind->arg, name);
1740 			}
1741 			break;
1742 		case T_FuncCall:
1743 			*name = strVal(llast(((FuncCall *) node)->funcname));
1744 			return 2;
1745 		case T_A_Expr:
1746 			if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1747 			{
1748 				/* make nullif() act like a regular function */
1749 				*name = "nullif";
1750 				return 2;
1751 			}
1752 			if (((A_Expr *) node)->kind == AEXPR_PAREN)
1753 			{
1754 				/* look through dummy parenthesis node */
1755 				return FigureColnameInternal(((A_Expr *) node)->lexpr, name);
1756 			}
1757 			break;
1758 		case T_TypeCast:
1759 			strength = FigureColnameInternal(((TypeCast *) node)->arg,
1760 											 name);
1761 			if (strength <= 1)
1762 			{
1763 				if (((TypeCast *) node)->typeName != NULL)
1764 				{
1765 					*name = strVal(llast(((TypeCast *) node)->typeName->names));
1766 					return 1;
1767 				}
1768 			}
1769 			break;
1770 		case T_CollateClause:
1771 			return FigureColnameInternal(((CollateClause *) node)->arg, name);
1772 		case T_GroupingFunc:
1773 			/* make GROUPING() act like a regular function */
1774 			*name = "grouping";
1775 			return 2;
1776 		case T_SubLink:
1777 			switch (((SubLink *) node)->subLinkType)
1778 			{
1779 				case EXISTS_SUBLINK:
1780 					*name = "exists";
1781 					return 2;
1782 				case ARRAY_SUBLINK:
1783 					*name = "array";
1784 					return 2;
1785 				case EXPR_SUBLINK:
1786 					{
1787 						/* Get column name of the subquery's single target */
1788 						SubLink    *sublink = (SubLink *) node;
1789 						Query	   *query = (Query *) sublink->subselect;
1790 
1791 						/*
1792 						 * The subquery has probably already been transformed,
1793 						 * but let's be careful and check that.  (The reason
1794 						 * we can see a transformed subquery here is that
1795 						 * transformSubLink is lazy and modifies the SubLink
1796 						 * node in-place.)
1797 						 */
1798 						if (IsA(query, Query))
1799 						{
1800 							TargetEntry *te = (TargetEntry *) linitial(query->targetList);
1801 
1802 							if (te->resname)
1803 							{
1804 								*name = te->resname;
1805 								return 2;
1806 							}
1807 						}
1808 					}
1809 					break;
1810 					/* As with other operator-like nodes, these have no names */
1811 				case MULTIEXPR_SUBLINK:
1812 				case ALL_SUBLINK:
1813 				case ANY_SUBLINK:
1814 				case ROWCOMPARE_SUBLINK:
1815 				case CTE_SUBLINK:
1816 					break;
1817 			}
1818 			break;
1819 		case T_CaseExpr:
1820 			strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1821 											 name);
1822 			if (strength <= 1)
1823 			{
1824 				*name = "case";
1825 				return 1;
1826 			}
1827 			break;
1828 		case T_A_ArrayExpr:
1829 			/* make ARRAY[] act like a function */
1830 			*name = "array";
1831 			return 2;
1832 		case T_RowExpr:
1833 			/* make ROW() act like a function */
1834 			*name = "row";
1835 			return 2;
1836 		case T_CoalesceExpr:
1837 			/* make coalesce() act like a regular function */
1838 			*name = "coalesce";
1839 			return 2;
1840 		case T_MinMaxExpr:
1841 			/* make greatest/least act like a regular function */
1842 			switch (((MinMaxExpr *) node)->op)
1843 			{
1844 				case IS_GREATEST:
1845 					*name = "greatest";
1846 					return 2;
1847 				case IS_LEAST:
1848 					*name = "least";
1849 					return 2;
1850 			}
1851 			break;
1852 		case T_SQLValueFunction:
1853 			/* make these act like a function or variable */
1854 			switch (((SQLValueFunction *) node)->op)
1855 			{
1856 				case SVFOP_CURRENT_DATE:
1857 					*name = "current_date";
1858 					return 2;
1859 				case SVFOP_CURRENT_TIME:
1860 				case SVFOP_CURRENT_TIME_N:
1861 					*name = "current_time";
1862 					return 2;
1863 				case SVFOP_CURRENT_TIMESTAMP:
1864 				case SVFOP_CURRENT_TIMESTAMP_N:
1865 					*name = "current_timestamp";
1866 					return 2;
1867 				case SVFOP_LOCALTIME:
1868 				case SVFOP_LOCALTIME_N:
1869 					*name = "localtime";
1870 					return 2;
1871 				case SVFOP_LOCALTIMESTAMP:
1872 				case SVFOP_LOCALTIMESTAMP_N:
1873 					*name = "localtimestamp";
1874 					return 2;
1875 				case SVFOP_CURRENT_ROLE:
1876 					*name = "current_role";
1877 					return 2;
1878 				case SVFOP_CURRENT_USER:
1879 					*name = "current_user";
1880 					return 2;
1881 				case SVFOP_USER:
1882 					*name = "user";
1883 					return 2;
1884 				case SVFOP_SESSION_USER:
1885 					*name = "session_user";
1886 					return 2;
1887 				case SVFOP_CURRENT_CATALOG:
1888 					*name = "current_catalog";
1889 					return 2;
1890 				case SVFOP_CURRENT_SCHEMA:
1891 					*name = "current_schema";
1892 					return 2;
1893 			}
1894 			break;
1895 		case T_XmlExpr:
1896 			/* make SQL/XML functions act like a regular function */
1897 			switch (((XmlExpr *) node)->op)
1898 			{
1899 				case IS_XMLCONCAT:
1900 					*name = "xmlconcat";
1901 					return 2;
1902 				case IS_XMLELEMENT:
1903 					*name = "xmlelement";
1904 					return 2;
1905 				case IS_XMLFOREST:
1906 					*name = "xmlforest";
1907 					return 2;
1908 				case IS_XMLPARSE:
1909 					*name = "xmlparse";
1910 					return 2;
1911 				case IS_XMLPI:
1912 					*name = "xmlpi";
1913 					return 2;
1914 				case IS_XMLROOT:
1915 					*name = "xmlroot";
1916 					return 2;
1917 				case IS_XMLSERIALIZE:
1918 					*name = "xmlserialize";
1919 					return 2;
1920 				case IS_DOCUMENT:
1921 					/* nothing */
1922 					break;
1923 			}
1924 			break;
1925 		case T_XmlSerialize:
1926 			*name = "xmlserialize";
1927 			return 2;
1928 		default:
1929 			break;
1930 	}
1931 
1932 	return strength;
1933 }
1934