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