1 /*-------------------------------------------------------------------------
2  *
3  * parse_expr.c
4  *	  handle expressions in parser
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/parser/parse_expr.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include "catalog/pg_type.h"
19 #include "commands/dbcommands.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/tlist.h"
24 #include "optimizer/var.h"
25 #include "parser/analyze.h"
26 #include "parser/parse_clause.h"
27 #include "parser/parse_coerce.h"
28 #include "parser/parse_collate.h"
29 #include "parser/parse_expr.h"
30 #include "parser/parse_func.h"
31 #include "parser/parse_oper.h"
32 #include "parser/parse_relation.h"
33 #include "parser/parse_target.h"
34 #include "parser/parse_type.h"
35 #include "parser/parse_agg.h"
36 #include "utils/builtins.h"
37 #include "utils/lsyscache.h"
38 #include "utils/xml.h"
39 
40 
41 /* GUC parameters */
42 bool		operator_precedence_warning = false;
43 bool		Transform_null_equals = false;
44 
45 /*
46  * Node-type groups for operator precedence warnings
47  * We use zero for everything not otherwise classified
48  */
49 #define PREC_GROUP_POSTFIX_IS	1		/* postfix IS tests (NullTest, etc) */
50 #define PREC_GROUP_INFIX_IS		2		/* infix IS (IS DISTINCT FROM, etc) */
51 #define PREC_GROUP_LESS			3		/* < > */
52 #define PREC_GROUP_EQUAL		4		/* = */
53 #define PREC_GROUP_LESS_EQUAL	5		/* <= >= <> */
54 #define PREC_GROUP_LIKE			6		/* LIKE ILIKE SIMILAR */
55 #define PREC_GROUP_BETWEEN		7		/* BETWEEN */
56 #define PREC_GROUP_IN			8		/* IN */
57 #define PREC_GROUP_NOT_LIKE		9		/* NOT LIKE/ILIKE/SIMILAR */
58 #define PREC_GROUP_NOT_BETWEEN	10		/* NOT BETWEEN */
59 #define PREC_GROUP_NOT_IN		11		/* NOT IN */
60 #define PREC_GROUP_POSTFIX_OP	12		/* generic postfix operators */
61 #define PREC_GROUP_INFIX_OP		13		/* generic infix operators */
62 #define PREC_GROUP_PREFIX_OP	14		/* generic prefix operators */
63 
64 /*
65  * Map precedence groupings to old precedence ordering
66  *
67  * Old precedence order:
68  * 1. NOT
69  * 2. =
70  * 3. < >
71  * 4. LIKE ILIKE SIMILAR
72  * 5. BETWEEN
73  * 6. IN
74  * 7. generic postfix Op
75  * 8. generic Op, including <= => <>
76  * 9. generic prefix Op
77  * 10. IS tests (NullTest, BooleanTest, etc)
78  *
79  * NOT BETWEEN etc map to BETWEEN etc when considered as being on the left,
80  * but to NOT when considered as being on the right, because of the buggy
81  * precedence handling of those productions in the old grammar.
82  */
83 static const int oldprecedence_l[] = {
84 	0, 10, 10, 3, 2, 8, 4, 5, 6, 4, 5, 6, 7, 8, 9
85 };
86 static const int oldprecedence_r[] = {
87 	0, 10, 10, 3, 2, 8, 4, 5, 6, 1, 1, 1, 7, 8, 9
88 };
89 
90 static Node *transformExprRecurse(ParseState *pstate, Node *expr);
91 static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
92 static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
93 static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
94 static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
95 static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
96 static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
97 static Node *transformAExprOf(ParseState *pstate, A_Expr *a);
98 static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
99 static Node *transformAExprBetween(ParseState *pstate, A_Expr *a);
100 static Node *transformBoolExpr(ParseState *pstate, BoolExpr *a);
101 static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
102 static Node *transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref);
103 static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
104 static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
105 static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
106 				   Oid array_type, Oid element_type, int32 typmod);
107 static Node *transformRowExpr(ParseState *pstate, RowExpr *r);
108 static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
109 static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
110 static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
111 static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
112 static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
113 static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
114 static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
115 static Node *transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte,
116 					 int location);
117 static Node *transformIndirection(ParseState *pstate, Node *basenode,
118 					 List *indirection);
119 static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
120 static Node *transformCollateClause(ParseState *pstate, CollateClause *c);
121 static Node *make_row_comparison_op(ParseState *pstate, List *opname,
122 					   List *largs, List *rargs, int location);
123 static Node *make_row_distinct_op(ParseState *pstate, List *opname,
124 					 RowExpr *lrow, RowExpr *rrow, int location);
125 static Expr *make_distinct_op(ParseState *pstate, List *opname,
126 				 Node *ltree, Node *rtree, int location);
127 static Node *make_nulltest_from_distinct(ParseState *pstate,
128 							A_Expr *distincta, Node *arg);
129 static int	operator_precedence_group(Node *node, const char **nodename);
130 static void emit_precedence_warnings(ParseState *pstate,
131 						 int opgroup, const char *opname,
132 						 Node *lchild, Node *rchild,
133 						 int location);
134 
135 
136 /*
137  * transformExpr -
138  *	  Analyze and transform expressions. Type checking and type casting is
139  *	  done here.  This processing converts the raw grammar output into
140  *	  expression trees with fully determined semantics.
141  */
142 Node *
transformExpr(ParseState * pstate,Node * expr,ParseExprKind exprKind)143 transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
144 {
145 	Node	   *result;
146 	ParseExprKind sv_expr_kind;
147 
148 	/* Save and restore identity of expression type we're parsing */
149 	Assert(exprKind != EXPR_KIND_NONE);
150 	sv_expr_kind = pstate->p_expr_kind;
151 	pstate->p_expr_kind = exprKind;
152 
153 	result = transformExprRecurse(pstate, expr);
154 
155 	pstate->p_expr_kind = sv_expr_kind;
156 
157 	return result;
158 }
159 
160 static Node *
transformExprRecurse(ParseState * pstate,Node * expr)161 transformExprRecurse(ParseState *pstate, Node *expr)
162 {
163 	Node	   *result;
164 
165 	if (expr == NULL)
166 		return NULL;
167 
168 	/* Guard against stack overflow due to overly complex expressions */
169 	check_stack_depth();
170 
171 	switch (nodeTag(expr))
172 	{
173 		case T_ColumnRef:
174 			result = transformColumnRef(pstate, (ColumnRef *) expr);
175 			break;
176 
177 		case T_ParamRef:
178 			result = transformParamRef(pstate, (ParamRef *) expr);
179 			break;
180 
181 		case T_A_Const:
182 			{
183 				A_Const    *con = (A_Const *) expr;
184 				Value	   *val = &con->val;
185 
186 				result = (Node *) make_const(pstate, val, con->location);
187 				break;
188 			}
189 
190 		case T_A_Indirection:
191 			{
192 				A_Indirection *ind = (A_Indirection *) expr;
193 
194 				result = transformExprRecurse(pstate, ind->arg);
195 				result = transformIndirection(pstate, result,
196 											  ind->indirection);
197 				break;
198 			}
199 
200 		case T_A_ArrayExpr:
201 			result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
202 										InvalidOid, InvalidOid, -1);
203 			break;
204 
205 		case T_TypeCast:
206 			result = transformTypeCast(pstate, (TypeCast *) expr);
207 			break;
208 
209 		case T_CollateClause:
210 			result = transformCollateClause(pstate, (CollateClause *) expr);
211 			break;
212 
213 		case T_A_Expr:
214 			{
215 				A_Expr	   *a = (A_Expr *) expr;
216 
217 				switch (a->kind)
218 				{
219 					case AEXPR_OP:
220 						result = transformAExprOp(pstate, a);
221 						break;
222 					case AEXPR_OP_ANY:
223 						result = transformAExprOpAny(pstate, a);
224 						break;
225 					case AEXPR_OP_ALL:
226 						result = transformAExprOpAll(pstate, a);
227 						break;
228 					case AEXPR_DISTINCT:
229 					case AEXPR_NOT_DISTINCT:
230 						result = transformAExprDistinct(pstate, a);
231 						break;
232 					case AEXPR_NULLIF:
233 						result = transformAExprNullIf(pstate, a);
234 						break;
235 					case AEXPR_OF:
236 						result = transformAExprOf(pstate, a);
237 						break;
238 					case AEXPR_IN:
239 						result = transformAExprIn(pstate, a);
240 						break;
241 					case AEXPR_LIKE:
242 					case AEXPR_ILIKE:
243 					case AEXPR_SIMILAR:
244 						/* we can transform these just like AEXPR_OP */
245 						result = transformAExprOp(pstate, a);
246 						break;
247 					case AEXPR_BETWEEN:
248 					case AEXPR_NOT_BETWEEN:
249 					case AEXPR_BETWEEN_SYM:
250 					case AEXPR_NOT_BETWEEN_SYM:
251 						result = transformAExprBetween(pstate, a);
252 						break;
253 					case AEXPR_PAREN:
254 						result = transformExprRecurse(pstate, a->lexpr);
255 						break;
256 					default:
257 						elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
258 						result = NULL;	/* keep compiler quiet */
259 						break;
260 				}
261 				break;
262 			}
263 
264 		case T_BoolExpr:
265 			result = transformBoolExpr(pstate, (BoolExpr *) expr);
266 			break;
267 
268 		case T_FuncCall:
269 			result = transformFuncCall(pstate, (FuncCall *) expr);
270 			break;
271 
272 		case T_MultiAssignRef:
273 			result = transformMultiAssignRef(pstate, (MultiAssignRef *) expr);
274 			break;
275 
276 		case T_GroupingFunc:
277 			result = transformGroupingFunc(pstate, (GroupingFunc *) expr);
278 			break;
279 
280 		case T_NamedArgExpr:
281 			{
282 				NamedArgExpr *na = (NamedArgExpr *) expr;
283 
284 				na->arg = (Expr *) transformExprRecurse(pstate, (Node *) na->arg);
285 				result = expr;
286 				break;
287 			}
288 
289 		case T_SubLink:
290 			result = transformSubLink(pstate, (SubLink *) expr);
291 			break;
292 
293 		case T_CaseExpr:
294 			result = transformCaseExpr(pstate, (CaseExpr *) expr);
295 			break;
296 
297 		case T_RowExpr:
298 			result = transformRowExpr(pstate, (RowExpr *) expr);
299 			break;
300 
301 		case T_CoalesceExpr:
302 			result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
303 			break;
304 
305 		case T_MinMaxExpr:
306 			result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
307 			break;
308 
309 		case T_XmlExpr:
310 			result = transformXmlExpr(pstate, (XmlExpr *) expr);
311 			break;
312 
313 		case T_XmlSerialize:
314 			result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
315 			break;
316 
317 		case T_NullTest:
318 			{
319 				NullTest   *n = (NullTest *) expr;
320 
321 				if (operator_precedence_warning)
322 					emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
323 											 (Node *) n->arg, NULL,
324 											 n->location);
325 
326 				n->arg = (Expr *) transformExprRecurse(pstate, (Node *) n->arg);
327 				/* the argument can be any type, so don't coerce it */
328 				n->argisrow = type_is_rowtype(exprType((Node *) n->arg));
329 				result = expr;
330 				break;
331 			}
332 
333 		case T_BooleanTest:
334 			result = transformBooleanTest(pstate, (BooleanTest *) expr);
335 			break;
336 
337 		case T_CurrentOfExpr:
338 			result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
339 			break;
340 
341 			/*
342 			 * CaseTestExpr and SetToDefault don't require any processing;
343 			 * they are only injected into parse trees in fully-formed state.
344 			 *
345 			 * Ordinarily we should not see a Var here, but it is convenient
346 			 * for transformJoinUsingClause() to create untransformed operator
347 			 * trees containing already-transformed Vars.  The best
348 			 * alternative would be to deconstruct and reconstruct column
349 			 * references, which seems expensively pointless.  So allow it.
350 			 */
351 		case T_CaseTestExpr:
352 		case T_SetToDefault:
353 		case T_Var:
354 			{
355 				result = (Node *) expr;
356 				break;
357 			}
358 
359 		default:
360 			/* should not reach here */
361 			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
362 			result = NULL;		/* keep compiler quiet */
363 			break;
364 	}
365 
366 	return result;
367 }
368 
369 /*
370  * helper routine for delivering "column does not exist" error message
371  *
372  * (Usually we don't have to work this hard, but the general case of field
373  * selection from an arbitrary node needs it.)
374  */
375 static void
unknown_attribute(ParseState * pstate,Node * relref,char * attname,int location)376 unknown_attribute(ParseState *pstate, Node *relref, char *attname,
377 				  int location)
378 {
379 	RangeTblEntry *rte;
380 
381 	if (IsA(relref, Var) &&
382 		((Var *) relref)->varattno == InvalidAttrNumber)
383 	{
384 		/* Reference the RTE by alias not by actual table name */
385 		rte = GetRTEByRangeTablePosn(pstate,
386 									 ((Var *) relref)->varno,
387 									 ((Var *) relref)->varlevelsup);
388 		ereport(ERROR,
389 				(errcode(ERRCODE_UNDEFINED_COLUMN),
390 				 errmsg("column %s.%s does not exist",
391 						rte->eref->aliasname, attname),
392 				 parser_errposition(pstate, location)));
393 	}
394 	else
395 	{
396 		/* Have to do it by reference to the type of the expression */
397 		Oid			relTypeId = exprType(relref);
398 
399 		if (ISCOMPLEX(relTypeId))
400 			ereport(ERROR,
401 					(errcode(ERRCODE_UNDEFINED_COLUMN),
402 					 errmsg("column \"%s\" not found in data type %s",
403 							attname, format_type_be(relTypeId)),
404 					 parser_errposition(pstate, location)));
405 		else if (relTypeId == RECORDOID)
406 			ereport(ERROR,
407 					(errcode(ERRCODE_UNDEFINED_COLUMN),
408 			   errmsg("could not identify column \"%s\" in record data type",
409 					  attname),
410 					 parser_errposition(pstate, location)));
411 		else
412 			ereport(ERROR,
413 					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
414 					 errmsg("column notation .%s applied to type %s, "
415 							"which is not a composite type",
416 							attname, format_type_be(relTypeId)),
417 					 parser_errposition(pstate, location)));
418 	}
419 }
420 
421 static Node *
transformIndirection(ParseState * pstate,Node * basenode,List * indirection)422 transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
423 {
424 	Node	   *result = basenode;
425 	List	   *subscripts = NIL;
426 	int			location = exprLocation(basenode);
427 	ListCell   *i;
428 
429 	/*
430 	 * We have to split any field-selection operations apart from
431 	 * subscripting.  Adjacent A_Indices nodes have to be treated as a single
432 	 * multidimensional subscript operation.
433 	 */
434 	foreach(i, indirection)
435 	{
436 		Node	   *n = lfirst(i);
437 
438 		if (IsA(n, A_Indices))
439 			subscripts = lappend(subscripts, n);
440 		else if (IsA(n, A_Star))
441 		{
442 			ereport(ERROR,
443 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
444 					 errmsg("row expansion via \"*\" is not supported here"),
445 					 parser_errposition(pstate, location)));
446 		}
447 		else
448 		{
449 			Node	   *newresult;
450 
451 			Assert(IsA(n, String));
452 
453 			/* process subscripts before this field selection */
454 			if (subscripts)
455 				result = (Node *) transformArraySubscripts(pstate,
456 														   result,
457 														   exprType(result),
458 														   InvalidOid,
459 														   exprTypmod(result),
460 														   subscripts,
461 														   NULL);
462 			subscripts = NIL;
463 
464 			newresult = ParseFuncOrColumn(pstate,
465 										  list_make1(n),
466 										  list_make1(result),
467 										  NULL,
468 										  location);
469 			if (newresult == NULL)
470 				unknown_attribute(pstate, result, strVal(n), location);
471 			result = newresult;
472 		}
473 	}
474 	/* process trailing subscripts, if any */
475 	if (subscripts)
476 		result = (Node *) transformArraySubscripts(pstate,
477 												   result,
478 												   exprType(result),
479 												   InvalidOid,
480 												   exprTypmod(result),
481 												   subscripts,
482 												   NULL);
483 
484 	return result;
485 }
486 
487 /*
488  * Transform a ColumnRef.
489  *
490  * If you find yourself changing this code, see also ExpandColumnRefStar.
491  */
492 static Node *
transformColumnRef(ParseState * pstate,ColumnRef * cref)493 transformColumnRef(ParseState *pstate, ColumnRef *cref)
494 {
495 	Node	   *node = NULL;
496 	char	   *nspname = NULL;
497 	char	   *relname = NULL;
498 	char	   *colname = NULL;
499 	RangeTblEntry *rte;
500 	int			levels_up;
501 	enum
502 	{
503 		CRERR_NO_COLUMN,
504 		CRERR_NO_RTE,
505 		CRERR_WRONG_DB,
506 		CRERR_TOO_MANY
507 	}			crerr = CRERR_NO_COLUMN;
508 
509 	/*
510 	 * Give the PreParseColumnRefHook, if any, first shot.  If it returns
511 	 * non-null then that's all, folks.
512 	 */
513 	if (pstate->p_pre_columnref_hook != NULL)
514 	{
515 		node = (*pstate->p_pre_columnref_hook) (pstate, cref);
516 		if (node != NULL)
517 			return node;
518 	}
519 
520 	/*----------
521 	 * The allowed syntaxes are:
522 	 *
523 	 * A		First try to resolve as unqualified column name;
524 	 *			if no luck, try to resolve as unqualified table name (A.*).
525 	 * A.B		A is an unqualified table name; B is either a
526 	 *			column or function name (trying column name first).
527 	 * A.B.C	schema A, table B, col or func name C.
528 	 * A.B.C.D	catalog A, schema B, table C, col or func D.
529 	 * A.*		A is an unqualified table name; means whole-row value.
530 	 * A.B.*	whole-row value of table B in schema A.
531 	 * A.B.C.*	whole-row value of table C in schema B in catalog A.
532 	 *
533 	 * We do not need to cope with bare "*"; that will only be accepted by
534 	 * the grammar at the top level of a SELECT list, and transformTargetList
535 	 * will take care of it before it ever gets here.  Also, "A.*" etc will
536 	 * be expanded by transformTargetList if they appear at SELECT top level,
537 	 * so here we are only going to see them as function or operator inputs.
538 	 *
539 	 * Currently, if a catalog name is given then it must equal the current
540 	 * database name; we check it here and then discard it.
541 	 *----------
542 	 */
543 	switch (list_length(cref->fields))
544 	{
545 		case 1:
546 			{
547 				Node	   *field1 = (Node *) linitial(cref->fields);
548 
549 				Assert(IsA(field1, String));
550 				colname = strVal(field1);
551 
552 				/* Try to identify as an unqualified column */
553 				node = colNameToVar(pstate, colname, false, cref->location);
554 
555 				if (node == NULL)
556 				{
557 					/*
558 					 * Not known as a column of any range-table entry.
559 					 *
560 					 * Consider the possibility that it's VALUE in a domain
561 					 * check expression.  (We handle VALUE as a name, not a
562 					 * keyword, to avoid breaking a lot of applications that
563 					 * have used VALUE as a column name in the past.)
564 					 */
565 					if (pstate->p_value_substitute != NULL &&
566 						strcmp(colname, "value") == 0)
567 					{
568 						node = (Node *) copyObject(pstate->p_value_substitute);
569 
570 						/*
571 						 * Try to propagate location knowledge.  This should
572 						 * be extended if p_value_substitute can ever take on
573 						 * other node types.
574 						 */
575 						if (IsA(node, CoerceToDomainValue))
576 							((CoerceToDomainValue *) node)->location = cref->location;
577 						break;
578 					}
579 
580 					/*
581 					 * Try to find the name as a relation.  Note that only
582 					 * relations already entered into the rangetable will be
583 					 * recognized.
584 					 *
585 					 * This is a hack for backwards compatibility with
586 					 * PostQUEL-inspired syntax.  The preferred form now is
587 					 * "rel.*".
588 					 */
589 					rte = refnameRangeTblEntry(pstate, NULL, colname,
590 											   cref->location,
591 											   &levels_up);
592 					if (rte)
593 						node = transformWholeRowRef(pstate, rte,
594 													cref->location);
595 				}
596 				break;
597 			}
598 		case 2:
599 			{
600 				Node	   *field1 = (Node *) linitial(cref->fields);
601 				Node	   *field2 = (Node *) lsecond(cref->fields);
602 
603 				Assert(IsA(field1, String));
604 				relname = strVal(field1);
605 
606 				/* Locate the referenced RTE */
607 				rte = refnameRangeTblEntry(pstate, nspname, relname,
608 										   cref->location,
609 										   &levels_up);
610 				if (rte == NULL)
611 				{
612 					crerr = CRERR_NO_RTE;
613 					break;
614 				}
615 
616 				/* Whole-row reference? */
617 				if (IsA(field2, A_Star))
618 				{
619 					node = transformWholeRowRef(pstate, rte, cref->location);
620 					break;
621 				}
622 
623 				Assert(IsA(field2, String));
624 				colname = strVal(field2);
625 
626 				/* Try to identify as a column of the RTE */
627 				node = scanRTEForColumn(pstate, rte, colname, cref->location,
628 										0, NULL);
629 				if (node == NULL)
630 				{
631 					/* Try it as a function call on the whole row */
632 					node = transformWholeRowRef(pstate, rte, cref->location);
633 					node = ParseFuncOrColumn(pstate,
634 											 list_make1(makeString(colname)),
635 											 list_make1(node),
636 											 NULL,
637 											 cref->location);
638 				}
639 				break;
640 			}
641 		case 3:
642 			{
643 				Node	   *field1 = (Node *) linitial(cref->fields);
644 				Node	   *field2 = (Node *) lsecond(cref->fields);
645 				Node	   *field3 = (Node *) lthird(cref->fields);
646 
647 				Assert(IsA(field1, String));
648 				nspname = strVal(field1);
649 				Assert(IsA(field2, String));
650 				relname = strVal(field2);
651 
652 				/* Locate the referenced RTE */
653 				rte = refnameRangeTblEntry(pstate, nspname, relname,
654 										   cref->location,
655 										   &levels_up);
656 				if (rte == NULL)
657 				{
658 					crerr = CRERR_NO_RTE;
659 					break;
660 				}
661 
662 				/* Whole-row reference? */
663 				if (IsA(field3, A_Star))
664 				{
665 					node = transformWholeRowRef(pstate, rte, cref->location);
666 					break;
667 				}
668 
669 				Assert(IsA(field3, String));
670 				colname = strVal(field3);
671 
672 				/* Try to identify as a column of the RTE */
673 				node = scanRTEForColumn(pstate, rte, colname, cref->location,
674 										0, NULL);
675 				if (node == NULL)
676 				{
677 					/* Try it as a function call on the whole row */
678 					node = transformWholeRowRef(pstate, rte, cref->location);
679 					node = ParseFuncOrColumn(pstate,
680 											 list_make1(makeString(colname)),
681 											 list_make1(node),
682 											 NULL,
683 											 cref->location);
684 				}
685 				break;
686 			}
687 		case 4:
688 			{
689 				Node	   *field1 = (Node *) linitial(cref->fields);
690 				Node	   *field2 = (Node *) lsecond(cref->fields);
691 				Node	   *field3 = (Node *) lthird(cref->fields);
692 				Node	   *field4 = (Node *) lfourth(cref->fields);
693 				char	   *catname;
694 
695 				Assert(IsA(field1, String));
696 				catname = strVal(field1);
697 				Assert(IsA(field2, String));
698 				nspname = strVal(field2);
699 				Assert(IsA(field3, String));
700 				relname = strVal(field3);
701 
702 				/*
703 				 * We check the catalog name and then ignore it.
704 				 */
705 				if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
706 				{
707 					crerr = CRERR_WRONG_DB;
708 					break;
709 				}
710 
711 				/* Locate the referenced RTE */
712 				rte = refnameRangeTblEntry(pstate, nspname, relname,
713 										   cref->location,
714 										   &levels_up);
715 				if (rte == NULL)
716 				{
717 					crerr = CRERR_NO_RTE;
718 					break;
719 				}
720 
721 				/* Whole-row reference? */
722 				if (IsA(field4, A_Star))
723 				{
724 					node = transformWholeRowRef(pstate, rte, cref->location);
725 					break;
726 				}
727 
728 				Assert(IsA(field4, String));
729 				colname = strVal(field4);
730 
731 				/* Try to identify as a column of the RTE */
732 				node = scanRTEForColumn(pstate, rte, colname, cref->location,
733 										0, NULL);
734 				if (node == NULL)
735 				{
736 					/* Try it as a function call on the whole row */
737 					node = transformWholeRowRef(pstate, rte, cref->location);
738 					node = ParseFuncOrColumn(pstate,
739 											 list_make1(makeString(colname)),
740 											 list_make1(node),
741 											 NULL,
742 											 cref->location);
743 				}
744 				break;
745 			}
746 		default:
747 			crerr = CRERR_TOO_MANY;		/* too many dotted names */
748 			break;
749 	}
750 
751 	/*
752 	 * Now give the PostParseColumnRefHook, if any, a chance.  We pass the
753 	 * translation-so-far so that it can throw an error if it wishes in the
754 	 * case that it has a conflicting interpretation of the ColumnRef. (If it
755 	 * just translates anyway, we'll throw an error, because we can't undo
756 	 * whatever effects the preceding steps may have had on the pstate.) If it
757 	 * returns NULL, use the standard translation, or throw a suitable error
758 	 * if there is none.
759 	 */
760 	if (pstate->p_post_columnref_hook != NULL)
761 	{
762 		Node	   *hookresult;
763 
764 		hookresult = (*pstate->p_post_columnref_hook) (pstate, cref, node);
765 		if (node == NULL)
766 			node = hookresult;
767 		else if (hookresult != NULL)
768 			ereport(ERROR,
769 					(errcode(ERRCODE_AMBIGUOUS_COLUMN),
770 					 errmsg("column reference \"%s\" is ambiguous",
771 							NameListToString(cref->fields)),
772 					 parser_errposition(pstate, cref->location)));
773 	}
774 
775 	/*
776 	 * Throw error if no translation found.
777 	 */
778 	if (node == NULL)
779 	{
780 		switch (crerr)
781 		{
782 			case CRERR_NO_COLUMN:
783 				errorMissingColumn(pstate, relname, colname, cref->location);
784 				break;
785 			case CRERR_NO_RTE:
786 				errorMissingRTE(pstate, makeRangeVar(nspname, relname,
787 													 cref->location));
788 				break;
789 			case CRERR_WRONG_DB:
790 				ereport(ERROR,
791 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
792 				  errmsg("cross-database references are not implemented: %s",
793 						 NameListToString(cref->fields)),
794 						 parser_errposition(pstate, cref->location)));
795 				break;
796 			case CRERR_TOO_MANY:
797 				ereport(ERROR,
798 						(errcode(ERRCODE_SYNTAX_ERROR),
799 				errmsg("improper qualified name (too many dotted names): %s",
800 					   NameListToString(cref->fields)),
801 						 parser_errposition(pstate, cref->location)));
802 				break;
803 		}
804 	}
805 
806 	return node;
807 }
808 
809 static Node *
transformParamRef(ParseState * pstate,ParamRef * pref)810 transformParamRef(ParseState *pstate, ParamRef *pref)
811 {
812 	Node	   *result;
813 
814 	/*
815 	 * The core parser knows nothing about Params.  If a hook is supplied,
816 	 * call it.  If not, or if the hook returns NULL, throw a generic error.
817 	 */
818 	if (pstate->p_paramref_hook != NULL)
819 		result = (*pstate->p_paramref_hook) (pstate, pref);
820 	else
821 		result = NULL;
822 
823 	if (result == NULL)
824 		ereport(ERROR,
825 				(errcode(ERRCODE_UNDEFINED_PARAMETER),
826 				 errmsg("there is no parameter $%d", pref->number),
827 				 parser_errposition(pstate, pref->location)));
828 
829 	return result;
830 }
831 
832 /* Test whether an a_expr is a plain NULL constant or not */
833 static bool
exprIsNullConstant(Node * arg)834 exprIsNullConstant(Node *arg)
835 {
836 	if (arg && IsA(arg, A_Const))
837 	{
838 		A_Const    *con = (A_Const *) arg;
839 
840 		if (con->val.type == T_Null)
841 			return true;
842 	}
843 	return false;
844 }
845 
846 static Node *
transformAExprOp(ParseState * pstate,A_Expr * a)847 transformAExprOp(ParseState *pstate, A_Expr *a)
848 {
849 	Node	   *lexpr = a->lexpr;
850 	Node	   *rexpr = a->rexpr;
851 	Node	   *result;
852 
853 	if (operator_precedence_warning)
854 	{
855 		int			opgroup;
856 		const char *opname;
857 
858 		opgroup = operator_precedence_group((Node *) a, &opname);
859 		if (opgroup > 0)
860 			emit_precedence_warnings(pstate, opgroup, opname,
861 									 lexpr, rexpr,
862 									 a->location);
863 
864 		/* Look through AEXPR_PAREN nodes so they don't affect tests below */
865 		while (lexpr && IsA(lexpr, A_Expr) &&
866 			   ((A_Expr *) lexpr)->kind == AEXPR_PAREN)
867 			lexpr = ((A_Expr *) lexpr)->lexpr;
868 		while (rexpr && IsA(rexpr, A_Expr) &&
869 			   ((A_Expr *) rexpr)->kind == AEXPR_PAREN)
870 			rexpr = ((A_Expr *) rexpr)->lexpr;
871 	}
872 
873 	/*
874 	 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
875 	 * standards-broken products (like Microsoft's).  Turn these into IS NULL
876 	 * exprs. (If either side is a CaseTestExpr, then the expression was
877 	 * generated internally from a CASE-WHEN expression, and
878 	 * transform_null_equals does not apply.)
879 	 */
880 	if (Transform_null_equals &&
881 		list_length(a->name) == 1 &&
882 		strcmp(strVal(linitial(a->name)), "=") == 0 &&
883 		(exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)) &&
884 		(!IsA(lexpr, CaseTestExpr) &&!IsA(rexpr, CaseTestExpr)))
885 	{
886 		NullTest   *n = makeNode(NullTest);
887 
888 		n->nulltesttype = IS_NULL;
889 		n->location = a->location;
890 
891 		if (exprIsNullConstant(lexpr))
892 			n->arg = (Expr *) rexpr;
893 		else
894 			n->arg = (Expr *) lexpr;
895 
896 		result = transformExprRecurse(pstate, (Node *) n);
897 	}
898 	else if (lexpr && IsA(lexpr, RowExpr) &&
899 			 rexpr && IsA(rexpr, SubLink) &&
900 			 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
901 	{
902 		/*
903 		 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
904 		 * grammar did this, but now that a row construct is allowed anywhere
905 		 * in expressions, it's easier to do it here.
906 		 */
907 		SubLink    *s = (SubLink *) rexpr;
908 
909 		s->subLinkType = ROWCOMPARE_SUBLINK;
910 		s->testexpr = lexpr;
911 		s->operName = a->name;
912 		s->location = a->location;
913 		result = transformExprRecurse(pstate, (Node *) s);
914 	}
915 	else if (lexpr && IsA(lexpr, RowExpr) &&
916 			 rexpr && IsA(rexpr, RowExpr))
917 	{
918 		/* ROW() op ROW() is handled specially */
919 		lexpr = transformExprRecurse(pstate, lexpr);
920 		rexpr = transformExprRecurse(pstate, rexpr);
921 		Assert(IsA(lexpr, RowExpr));
922 		Assert(IsA(rexpr, RowExpr));
923 
924 		result = make_row_comparison_op(pstate,
925 										a->name,
926 										((RowExpr *) lexpr)->args,
927 										((RowExpr *) rexpr)->args,
928 										a->location);
929 	}
930 	else
931 	{
932 		/* Ordinary scalar operator */
933 		lexpr = transformExprRecurse(pstate, lexpr);
934 		rexpr = transformExprRecurse(pstate, rexpr);
935 
936 		result = (Node *) make_op(pstate,
937 								  a->name,
938 								  lexpr,
939 								  rexpr,
940 								  a->location);
941 	}
942 
943 	return result;
944 }
945 
946 static Node *
transformAExprOpAny(ParseState * pstate,A_Expr * a)947 transformAExprOpAny(ParseState *pstate, A_Expr *a)
948 {
949 	Node	   *lexpr = a->lexpr;
950 	Node	   *rexpr = a->rexpr;
951 
952 	if (operator_precedence_warning)
953 		emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_OP,
954 								 strVal(llast(a->name)),
955 								 lexpr, NULL,
956 								 a->location);
957 
958 	lexpr = transformExprRecurse(pstate, lexpr);
959 	rexpr = transformExprRecurse(pstate, rexpr);
960 
961 	return (Node *) make_scalar_array_op(pstate,
962 										 a->name,
963 										 true,
964 										 lexpr,
965 										 rexpr,
966 										 a->location);
967 }
968 
969 static Node *
transformAExprOpAll(ParseState * pstate,A_Expr * a)970 transformAExprOpAll(ParseState *pstate, A_Expr *a)
971 {
972 	Node	   *lexpr = a->lexpr;
973 	Node	   *rexpr = a->rexpr;
974 
975 	if (operator_precedence_warning)
976 		emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_OP,
977 								 strVal(llast(a->name)),
978 								 lexpr, NULL,
979 								 a->location);
980 
981 	lexpr = transformExprRecurse(pstate, lexpr);
982 	rexpr = transformExprRecurse(pstate, rexpr);
983 
984 	return (Node *) make_scalar_array_op(pstate,
985 										 a->name,
986 										 false,
987 										 lexpr,
988 										 rexpr,
989 										 a->location);
990 }
991 
992 static Node *
transformAExprDistinct(ParseState * pstate,A_Expr * a)993 transformAExprDistinct(ParseState *pstate, A_Expr *a)
994 {
995 	Node	   *lexpr = a->lexpr;
996 	Node	   *rexpr = a->rexpr;
997 	Node	   *result;
998 
999 	if (operator_precedence_warning)
1000 		emit_precedence_warnings(pstate, PREC_GROUP_INFIX_IS, "IS",
1001 								 lexpr, rexpr,
1002 								 a->location);
1003 
1004 	/*
1005 	 * If either input is an undecorated NULL literal, transform to a NullTest
1006 	 * on the other input. That's simpler to process than a full DistinctExpr,
1007 	 * and it avoids needing to require that the datatype have an = operator.
1008 	 */
1009 	if (exprIsNullConstant(rexpr))
1010 		return make_nulltest_from_distinct(pstate, a, lexpr);
1011 	if (exprIsNullConstant(lexpr))
1012 		return make_nulltest_from_distinct(pstate, a, rexpr);
1013 
1014 	lexpr = transformExprRecurse(pstate, lexpr);
1015 	rexpr = transformExprRecurse(pstate, rexpr);
1016 
1017 	if (lexpr && IsA(lexpr, RowExpr) &&
1018 		rexpr && IsA(rexpr, RowExpr))
1019 	{
1020 		/* ROW() op ROW() is handled specially */
1021 		result = make_row_distinct_op(pstate, a->name,
1022 									  (RowExpr *) lexpr,
1023 									  (RowExpr *) rexpr,
1024 									  a->location);
1025 	}
1026 	else
1027 	{
1028 		/* Ordinary scalar operator */
1029 		result = (Node *) make_distinct_op(pstate,
1030 										   a->name,
1031 										   lexpr,
1032 										   rexpr,
1033 										   a->location);
1034 	}
1035 
1036 	/*
1037 	 * If it's NOT DISTINCT, we first build a DistinctExpr and then stick a
1038 	 * NOT on top.
1039 	 */
1040 	if (a->kind == AEXPR_NOT_DISTINCT)
1041 		result = (Node *) makeBoolExpr(NOT_EXPR,
1042 									   list_make1(result),
1043 									   a->location);
1044 
1045 	return result;
1046 }
1047 
1048 static Node *
transformAExprNullIf(ParseState * pstate,A_Expr * a)1049 transformAExprNullIf(ParseState *pstate, A_Expr *a)
1050 {
1051 	Node	   *lexpr = transformExprRecurse(pstate, a->lexpr);
1052 	Node	   *rexpr = transformExprRecurse(pstate, a->rexpr);
1053 	OpExpr	   *result;
1054 
1055 	result = (OpExpr *) make_op(pstate,
1056 								a->name,
1057 								lexpr,
1058 								rexpr,
1059 								a->location);
1060 
1061 	/*
1062 	 * The comparison operator itself should yield boolean ...
1063 	 */
1064 	if (result->opresulttype != BOOLOID)
1065 		ereport(ERROR,
1066 				(errcode(ERRCODE_DATATYPE_MISMATCH),
1067 				 errmsg("NULLIF requires = operator to yield boolean"),
1068 				 parser_errposition(pstate, a->location)));
1069 
1070 	/*
1071 	 * ... but the NullIfExpr will yield the first operand's type.
1072 	 */
1073 	result->opresulttype = exprType((Node *) linitial(result->args));
1074 
1075 	/*
1076 	 * We rely on NullIfExpr and OpExpr being the same struct
1077 	 */
1078 	NodeSetTag(result, T_NullIfExpr);
1079 
1080 	return (Node *) result;
1081 }
1082 
1083 /*
1084  * Checking an expression for match to a list of type names. Will result
1085  * in a boolean constant node.
1086  */
1087 static Node *
transformAExprOf(ParseState * pstate,A_Expr * a)1088 transformAExprOf(ParseState *pstate, A_Expr *a)
1089 {
1090 	Node	   *lexpr = a->lexpr;
1091 	Const	   *result;
1092 	ListCell   *telem;
1093 	Oid			ltype,
1094 				rtype;
1095 	bool		matched = false;
1096 
1097 	if (operator_precedence_warning)
1098 		emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
1099 								 lexpr, NULL,
1100 								 a->location);
1101 
1102 	lexpr = transformExprRecurse(pstate, lexpr);
1103 
1104 	ltype = exprType(lexpr);
1105 	foreach(telem, (List *) a->rexpr)
1106 	{
1107 		rtype = typenameTypeId(pstate, lfirst(telem));
1108 		matched = (rtype == ltype);
1109 		if (matched)
1110 			break;
1111 	}
1112 
1113 	/*
1114 	 * We have two forms: equals or not equals. Flip the sense of the result
1115 	 * for not equals.
1116 	 */
1117 	if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1118 		matched = (!matched);
1119 
1120 	result = (Const *) makeBoolConst(matched, false);
1121 
1122 	/* Make the result have the original input's parse location */
1123 	result->location = exprLocation((Node *) a);
1124 
1125 	return (Node *) result;
1126 }
1127 
1128 static Node *
transformAExprIn(ParseState * pstate,A_Expr * a)1129 transformAExprIn(ParseState *pstate, A_Expr *a)
1130 {
1131 	Node	   *result = NULL;
1132 	Node	   *lexpr;
1133 	List	   *rexprs;
1134 	List	   *rvars;
1135 	List	   *rnonvars;
1136 	bool		useOr;
1137 	ListCell   *l;
1138 
1139 	/*
1140 	 * If the operator is <>, combine with AND not OR.
1141 	 */
1142 	if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1143 		useOr = false;
1144 	else
1145 		useOr = true;
1146 
1147 	if (operator_precedence_warning)
1148 		emit_precedence_warnings(pstate,
1149 								 useOr ? PREC_GROUP_IN : PREC_GROUP_NOT_IN,
1150 								 "IN",
1151 								 a->lexpr, NULL,
1152 								 a->location);
1153 
1154 	/*
1155 	 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
1156 	 * possible if there is a suitable array type available.  If not, we fall
1157 	 * back to a boolean condition tree with multiple copies of the lefthand
1158 	 * expression.  Also, any IN-list items that contain Vars are handled as
1159 	 * separate boolean conditions, because that gives the planner more scope
1160 	 * for optimization on such clauses.
1161 	 *
1162 	 * First step: transform all the inputs, and detect whether any contain
1163 	 * Vars.
1164 	 */
1165 	lexpr = transformExprRecurse(pstate, a->lexpr);
1166 	rexprs = rvars = rnonvars = NIL;
1167 	foreach(l, (List *) a->rexpr)
1168 	{
1169 		Node	   *rexpr = transformExprRecurse(pstate, lfirst(l));
1170 
1171 		rexprs = lappend(rexprs, rexpr);
1172 		if (contain_vars_of_level(rexpr, 0))
1173 			rvars = lappend(rvars, rexpr);
1174 		else
1175 			rnonvars = lappend(rnonvars, rexpr);
1176 	}
1177 
1178 	/*
1179 	 * ScalarArrayOpExpr is only going to be useful if there's more than one
1180 	 * non-Var righthand item.
1181 	 */
1182 	if (list_length(rnonvars) > 1)
1183 	{
1184 		List	   *allexprs;
1185 		Oid			scalar_type;
1186 		Oid			array_type;
1187 
1188 		/*
1189 		 * Try to select a common type for the array elements.  Note that
1190 		 * since the LHS' type is first in the list, it will be preferred when
1191 		 * there is doubt (eg, when all the RHS items are unknown literals).
1192 		 *
1193 		 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1194 		 */
1195 		allexprs = list_concat(list_make1(lexpr), rnonvars);
1196 		scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1197 
1198 		/*
1199 		 * Do we have an array type to use?  Aside from the case where there
1200 		 * isn't one, we don't risk using ScalarArrayOpExpr when the common
1201 		 * type is RECORD, because the RowExpr comparison logic below can cope
1202 		 * with some cases of non-identical row types.
1203 		 */
1204 		if (OidIsValid(scalar_type) && scalar_type != RECORDOID)
1205 			array_type = get_array_type(scalar_type);
1206 		else
1207 			array_type = InvalidOid;
1208 		if (array_type != InvalidOid)
1209 		{
1210 			/*
1211 			 * OK: coerce all the right-hand non-Var inputs to the common type
1212 			 * and build an ArrayExpr for them.
1213 			 */
1214 			List	   *aexprs;
1215 			ArrayExpr  *newa;
1216 
1217 			aexprs = NIL;
1218 			foreach(l, rnonvars)
1219 			{
1220 				Node	   *rexpr = (Node *) lfirst(l);
1221 
1222 				rexpr = coerce_to_common_type(pstate, rexpr,
1223 											  scalar_type,
1224 											  "IN");
1225 				aexprs = lappend(aexprs, rexpr);
1226 			}
1227 			newa = makeNode(ArrayExpr);
1228 			newa->array_typeid = array_type;
1229 			/* array_collid will be set by parse_collate.c */
1230 			newa->element_typeid = scalar_type;
1231 			newa->elements = aexprs;
1232 			newa->multidims = false;
1233 			newa->location = -1;
1234 
1235 			result = (Node *) make_scalar_array_op(pstate,
1236 												   a->name,
1237 												   useOr,
1238 												   lexpr,
1239 												   (Node *) newa,
1240 												   a->location);
1241 
1242 			/* Consider only the Vars (if any) in the loop below */
1243 			rexprs = rvars;
1244 		}
1245 	}
1246 
1247 	/*
1248 	 * Must do it the hard way, ie, with a boolean expression tree.
1249 	 */
1250 	foreach(l, rexprs)
1251 	{
1252 		Node	   *rexpr = (Node *) lfirst(l);
1253 		Node	   *cmp;
1254 
1255 		if (IsA(lexpr, RowExpr) &&
1256 			IsA(rexpr, RowExpr))
1257 		{
1258 			/* ROW() op ROW() is handled specially */
1259 			cmp = make_row_comparison_op(pstate,
1260 										 a->name,
1261 							  (List *) copyObject(((RowExpr *) lexpr)->args),
1262 										 ((RowExpr *) rexpr)->args,
1263 										 a->location);
1264 		}
1265 		else
1266 		{
1267 			/* Ordinary scalar operator */
1268 			cmp = (Node *) make_op(pstate,
1269 								   a->name,
1270 								   copyObject(lexpr),
1271 								   rexpr,
1272 								   a->location);
1273 		}
1274 
1275 		cmp = coerce_to_boolean(pstate, cmp, "IN");
1276 		if (result == NULL)
1277 			result = cmp;
1278 		else
1279 			result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1280 										   list_make2(result, cmp),
1281 										   a->location);
1282 	}
1283 
1284 	return result;
1285 }
1286 
1287 static Node *
transformAExprBetween(ParseState * pstate,A_Expr * a)1288 transformAExprBetween(ParseState *pstate, A_Expr *a)
1289 {
1290 	Node	   *aexpr;
1291 	Node	   *bexpr;
1292 	Node	   *cexpr;
1293 	Node	   *result;
1294 	Node	   *sub1;
1295 	Node	   *sub2;
1296 	List	   *args;
1297 
1298 	/* Deconstruct A_Expr into three subexprs */
1299 	aexpr = a->lexpr;
1300 	Assert(IsA(a->rexpr, List));
1301 	args = (List *) a->rexpr;
1302 	Assert(list_length(args) == 2);
1303 	bexpr = (Node *) linitial(args);
1304 	cexpr = (Node *) lsecond(args);
1305 
1306 	if (operator_precedence_warning)
1307 	{
1308 		int			opgroup;
1309 		const char *opname;
1310 
1311 		opgroup = operator_precedence_group((Node *) a, &opname);
1312 		emit_precedence_warnings(pstate, opgroup, opname,
1313 								 aexpr, cexpr,
1314 								 a->location);
1315 		/* We can ignore bexpr thanks to syntactic restrictions */
1316 		/* Wrap subexpressions to prevent extra warnings */
1317 		aexpr = (Node *) makeA_Expr(AEXPR_PAREN, NIL, aexpr, NULL, -1);
1318 		bexpr = (Node *) makeA_Expr(AEXPR_PAREN, NIL, bexpr, NULL, -1);
1319 		cexpr = (Node *) makeA_Expr(AEXPR_PAREN, NIL, cexpr, NULL, -1);
1320 	}
1321 
1322 	/*
1323 	 * Build the equivalent comparison expression.  Make copies of
1324 	 * multiply-referenced subexpressions for safety.  (XXX this is really
1325 	 * wrong since it results in multiple runtime evaluations of what may be
1326 	 * volatile expressions ...)
1327 	 *
1328 	 * Ideally we would not use hard-wired operators here but instead use
1329 	 * opclasses.  However, mixed data types and other issues make this
1330 	 * difficult:
1331 	 * http://archives.postgresql.org/pgsql-hackers/2008-08/msg01142.php
1332 	 */
1333 	switch (a->kind)
1334 	{
1335 		case AEXPR_BETWEEN:
1336 			args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
1337 											   aexpr, bexpr,
1338 											   a->location),
1339 							  makeSimpleA_Expr(AEXPR_OP, "<=",
1340 											   copyObject(aexpr), cexpr,
1341 											   a->location));
1342 			result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1343 			break;
1344 		case AEXPR_NOT_BETWEEN:
1345 			args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
1346 											   aexpr, bexpr,
1347 											   a->location),
1348 							  makeSimpleA_Expr(AEXPR_OP, ">",
1349 											   copyObject(aexpr), cexpr,
1350 											   a->location));
1351 			result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1352 			break;
1353 		case AEXPR_BETWEEN_SYM:
1354 			args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
1355 											   aexpr, bexpr,
1356 											   a->location),
1357 							  makeSimpleA_Expr(AEXPR_OP, "<=",
1358 											   copyObject(aexpr), cexpr,
1359 											   a->location));
1360 			sub1 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1361 			args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
1362 										copyObject(aexpr), copyObject(cexpr),
1363 											   a->location),
1364 							  makeSimpleA_Expr(AEXPR_OP, "<=",
1365 										copyObject(aexpr), copyObject(bexpr),
1366 											   a->location));
1367 			sub2 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1368 			args = list_make2(sub1, sub2);
1369 			result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1370 			break;
1371 		case AEXPR_NOT_BETWEEN_SYM:
1372 			args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
1373 											   aexpr, bexpr,
1374 											   a->location),
1375 							  makeSimpleA_Expr(AEXPR_OP, ">",
1376 											   copyObject(aexpr), cexpr,
1377 											   a->location));
1378 			sub1 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1379 			args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
1380 										copyObject(aexpr), copyObject(cexpr),
1381 											   a->location),
1382 							  makeSimpleA_Expr(AEXPR_OP, ">",
1383 										copyObject(aexpr), copyObject(bexpr),
1384 											   a->location));
1385 			sub2 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
1386 			args = list_make2(sub1, sub2);
1387 			result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
1388 			break;
1389 		default:
1390 			elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
1391 			result = NULL;		/* keep compiler quiet */
1392 			break;
1393 	}
1394 
1395 	return transformExprRecurse(pstate, result);
1396 }
1397 
1398 static Node *
transformBoolExpr(ParseState * pstate,BoolExpr * a)1399 transformBoolExpr(ParseState *pstate, BoolExpr *a)
1400 {
1401 	List	   *args = NIL;
1402 	const char *opname;
1403 	ListCell   *lc;
1404 
1405 	switch (a->boolop)
1406 	{
1407 		case AND_EXPR:
1408 			opname = "AND";
1409 			break;
1410 		case OR_EXPR:
1411 			opname = "OR";
1412 			break;
1413 		case NOT_EXPR:
1414 			opname = "NOT";
1415 			break;
1416 		default:
1417 			elog(ERROR, "unrecognized boolop: %d", (int) a->boolop);
1418 			opname = NULL;		/* keep compiler quiet */
1419 			break;
1420 	}
1421 
1422 	foreach(lc, a->args)
1423 	{
1424 		Node	   *arg = (Node *) lfirst(lc);
1425 
1426 		arg = transformExprRecurse(pstate, arg);
1427 		arg = coerce_to_boolean(pstate, arg, opname);
1428 		args = lappend(args, arg);
1429 	}
1430 
1431 	return (Node *) makeBoolExpr(a->boolop, args, a->location);
1432 }
1433 
1434 static Node *
transformFuncCall(ParseState * pstate,FuncCall * fn)1435 transformFuncCall(ParseState *pstate, FuncCall *fn)
1436 {
1437 	List	   *targs;
1438 	ListCell   *args;
1439 
1440 	/* Transform the list of arguments ... */
1441 	targs = NIL;
1442 	foreach(args, fn->args)
1443 	{
1444 		targs = lappend(targs, transformExprRecurse(pstate,
1445 													(Node *) lfirst(args)));
1446 	}
1447 
1448 	/*
1449 	 * When WITHIN GROUP is used, we treat its ORDER BY expressions as
1450 	 * additional arguments to the function, for purposes of function lookup
1451 	 * and argument type coercion.  So, transform each such expression and add
1452 	 * them to the targs list.  We don't explicitly mark where each argument
1453 	 * came from, but ParseFuncOrColumn can tell what's what by reference to
1454 	 * list_length(fn->agg_order).
1455 	 */
1456 	if (fn->agg_within_group)
1457 	{
1458 		Assert(fn->agg_order != NIL);
1459 		foreach(args, fn->agg_order)
1460 		{
1461 			SortBy	   *arg = (SortBy *) lfirst(args);
1462 
1463 			targs = lappend(targs, transformExpr(pstate, arg->node,
1464 												 EXPR_KIND_ORDER_BY));
1465 		}
1466 	}
1467 
1468 	/* ... and hand off to ParseFuncOrColumn */
1469 	return ParseFuncOrColumn(pstate,
1470 							 fn->funcname,
1471 							 targs,
1472 							 fn,
1473 							 fn->location);
1474 }
1475 
1476 static Node *
transformMultiAssignRef(ParseState * pstate,MultiAssignRef * maref)1477 transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref)
1478 {
1479 	SubLink    *sublink;
1480 	Query	   *qtree;
1481 	TargetEntry *tle;
1482 	Param	   *param;
1483 
1484 	/* We should only see this in first-stage processing of UPDATE tlists */
1485 	Assert(pstate->p_expr_kind == EXPR_KIND_UPDATE_SOURCE);
1486 
1487 	/* We only need to transform the source if this is the first column */
1488 	if (maref->colno == 1)
1489 	{
1490 		sublink = (SubLink *) transformExprRecurse(pstate, maref->source);
1491 		/* Currently, the grammar only allows a SubLink as source */
1492 		Assert(IsA(sublink, SubLink));
1493 		Assert(sublink->subLinkType == MULTIEXPR_SUBLINK);
1494 		qtree = (Query *) sublink->subselect;
1495 		Assert(IsA(qtree, Query));
1496 
1497 		/* Check subquery returns required number of columns */
1498 		if (count_nonjunk_tlist_entries(qtree->targetList) != maref->ncolumns)
1499 			ereport(ERROR,
1500 					(errcode(ERRCODE_SYNTAX_ERROR),
1501 				 errmsg("number of columns does not match number of values"),
1502 					 parser_errposition(pstate, sublink->location)));
1503 
1504 		/*
1505 		 * Build a resjunk tlist item containing the MULTIEXPR SubLink, and
1506 		 * add it to pstate->p_multiassign_exprs, whence it will later get
1507 		 * appended to the completed targetlist.  We needn't worry about
1508 		 * selecting a resno for it; transformUpdateStmt will do that.
1509 		 */
1510 		tle = makeTargetEntry((Expr *) sublink, 0, NULL, true);
1511 		pstate->p_multiassign_exprs = lappend(pstate->p_multiassign_exprs, tle);
1512 
1513 		/*
1514 		 * Assign a unique-within-this-targetlist ID to the MULTIEXPR SubLink.
1515 		 * We can just use its position in the p_multiassign_exprs list.
1516 		 */
1517 		sublink->subLinkId = list_length(pstate->p_multiassign_exprs);
1518 	}
1519 	else
1520 	{
1521 		/*
1522 		 * Second or later column in a multiassignment.  Re-fetch the
1523 		 * transformed query, which we assume is still the last entry in
1524 		 * p_multiassign_exprs.
1525 		 */
1526 		Assert(pstate->p_multiassign_exprs != NIL);
1527 		tle = (TargetEntry *) llast(pstate->p_multiassign_exprs);
1528 		sublink = (SubLink *) tle->expr;
1529 		Assert(IsA(sublink, SubLink));
1530 		Assert(sublink->subLinkType == MULTIEXPR_SUBLINK);
1531 		qtree = (Query *) sublink->subselect;
1532 		Assert(IsA(qtree, Query));
1533 	}
1534 
1535 	/* Build a Param representing the appropriate subquery output column */
1536 	tle = (TargetEntry *) list_nth(qtree->targetList, maref->colno - 1);
1537 	Assert(!tle->resjunk);
1538 
1539 	param = makeNode(Param);
1540 	param->paramkind = PARAM_MULTIEXPR;
1541 	param->paramid = (sublink->subLinkId << 16) | maref->colno;
1542 	param->paramtype = exprType((Node *) tle->expr);
1543 	param->paramtypmod = exprTypmod((Node *) tle->expr);
1544 	param->paramcollid = exprCollation((Node *) tle->expr);
1545 	param->location = exprLocation((Node *) tle->expr);
1546 
1547 	return (Node *) param;
1548 }
1549 
1550 static Node *
transformCaseExpr(ParseState * pstate,CaseExpr * c)1551 transformCaseExpr(ParseState *pstate, CaseExpr *c)
1552 {
1553 	CaseExpr   *newc;
1554 	Node	   *arg;
1555 	CaseTestExpr *placeholder;
1556 	List	   *newargs;
1557 	List	   *resultexprs;
1558 	ListCell   *l;
1559 	Node	   *defresult;
1560 	Oid			ptype;
1561 
1562 	newc = makeNode(CaseExpr);
1563 
1564 	/* transform the test expression, if any */
1565 	arg = transformExprRecurse(pstate, (Node *) c->arg);
1566 
1567 	/* generate placeholder for test expression */
1568 	if (arg)
1569 	{
1570 		/*
1571 		 * If test expression is an untyped literal, force it to text. We have
1572 		 * to do something now because we won't be able to do this coercion on
1573 		 * the placeholder.  This is not as flexible as what was done in 7.4
1574 		 * and before, but it's good enough to handle the sort of silly coding
1575 		 * commonly seen.
1576 		 */
1577 		if (exprType(arg) == UNKNOWNOID)
1578 			arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
1579 
1580 		/*
1581 		 * Run collation assignment on the test expression so that we know
1582 		 * what collation to mark the placeholder with.  In principle we could
1583 		 * leave it to parse_collate.c to do that later, but propagating the
1584 		 * result to the CaseTestExpr would be unnecessarily complicated.
1585 		 */
1586 		assign_expr_collations(pstate, arg);
1587 
1588 		placeholder = makeNode(CaseTestExpr);
1589 		placeholder->typeId = exprType(arg);
1590 		placeholder->typeMod = exprTypmod(arg);
1591 		placeholder->collation = exprCollation(arg);
1592 	}
1593 	else
1594 		placeholder = NULL;
1595 
1596 	newc->arg = (Expr *) arg;
1597 
1598 	/* transform the list of arguments */
1599 	newargs = NIL;
1600 	resultexprs = NIL;
1601 	foreach(l, c->args)
1602 	{
1603 		CaseWhen   *w = (CaseWhen *) lfirst(l);
1604 		CaseWhen   *neww = makeNode(CaseWhen);
1605 		Node	   *warg;
1606 
1607 		Assert(IsA(w, CaseWhen));
1608 
1609 		warg = (Node *) w->expr;
1610 		if (placeholder)
1611 		{
1612 			/* shorthand form was specified, so expand... */
1613 			warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
1614 											 (Node *) placeholder,
1615 											 warg,
1616 											 w->location);
1617 		}
1618 		neww->expr = (Expr *) transformExprRecurse(pstate, warg);
1619 
1620 		neww->expr = (Expr *) coerce_to_boolean(pstate,
1621 												(Node *) neww->expr,
1622 												"CASE/WHEN");
1623 
1624 		warg = (Node *) w->result;
1625 		neww->result = (Expr *) transformExprRecurse(pstate, warg);
1626 		neww->location = w->location;
1627 
1628 		newargs = lappend(newargs, neww);
1629 		resultexprs = lappend(resultexprs, neww->result);
1630 	}
1631 
1632 	newc->args = newargs;
1633 
1634 	/* transform the default clause */
1635 	defresult = (Node *) c->defresult;
1636 	if (defresult == NULL)
1637 	{
1638 		A_Const    *n = makeNode(A_Const);
1639 
1640 		n->val.type = T_Null;
1641 		n->location = -1;
1642 		defresult = (Node *) n;
1643 	}
1644 	newc->defresult = (Expr *) transformExprRecurse(pstate, defresult);
1645 
1646 	/*
1647 	 * Note: default result is considered the most significant type in
1648 	 * determining preferred type. This is how the code worked before, but it
1649 	 * seems a little bogus to me --- tgl
1650 	 */
1651 	resultexprs = lcons(newc->defresult, resultexprs);
1652 
1653 	ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1654 	Assert(OidIsValid(ptype));
1655 	newc->casetype = ptype;
1656 	/* casecollid will be set by parse_collate.c */
1657 
1658 	/* Convert default result clause, if necessary */
1659 	newc->defresult = (Expr *)
1660 		coerce_to_common_type(pstate,
1661 							  (Node *) newc->defresult,
1662 							  ptype,
1663 							  "CASE/ELSE");
1664 
1665 	/* Convert when-clause results, if necessary */
1666 	foreach(l, newc->args)
1667 	{
1668 		CaseWhen   *w = (CaseWhen *) lfirst(l);
1669 
1670 		w->result = (Expr *)
1671 			coerce_to_common_type(pstate,
1672 								  (Node *) w->result,
1673 								  ptype,
1674 								  "CASE/WHEN");
1675 	}
1676 
1677 	newc->location = c->location;
1678 
1679 	return (Node *) newc;
1680 }
1681 
1682 static Node *
transformSubLink(ParseState * pstate,SubLink * sublink)1683 transformSubLink(ParseState *pstate, SubLink *sublink)
1684 {
1685 	Node	   *result = (Node *) sublink;
1686 	Query	   *qtree;
1687 	const char *err;
1688 
1689 	/*
1690 	 * Check to see if the sublink is in an invalid place within the query. We
1691 	 * allow sublinks everywhere in SELECT/INSERT/UPDATE/DELETE, but generally
1692 	 * not in utility statements.
1693 	 */
1694 	err = NULL;
1695 	switch (pstate->p_expr_kind)
1696 	{
1697 		case EXPR_KIND_NONE:
1698 			Assert(false);		/* can't happen */
1699 			break;
1700 		case EXPR_KIND_OTHER:
1701 			/* Accept sublink here; caller must throw error if wanted */
1702 			break;
1703 		case EXPR_KIND_JOIN_ON:
1704 		case EXPR_KIND_JOIN_USING:
1705 		case EXPR_KIND_FROM_SUBSELECT:
1706 		case EXPR_KIND_FROM_FUNCTION:
1707 		case EXPR_KIND_WHERE:
1708 		case EXPR_KIND_POLICY:
1709 		case EXPR_KIND_HAVING:
1710 		case EXPR_KIND_FILTER:
1711 		case EXPR_KIND_WINDOW_PARTITION:
1712 		case EXPR_KIND_WINDOW_ORDER:
1713 		case EXPR_KIND_WINDOW_FRAME_RANGE:
1714 		case EXPR_KIND_WINDOW_FRAME_ROWS:
1715 		case EXPR_KIND_SELECT_TARGET:
1716 		case EXPR_KIND_INSERT_TARGET:
1717 		case EXPR_KIND_UPDATE_SOURCE:
1718 		case EXPR_KIND_UPDATE_TARGET:
1719 		case EXPR_KIND_GROUP_BY:
1720 		case EXPR_KIND_ORDER_BY:
1721 		case EXPR_KIND_DISTINCT_ON:
1722 		case EXPR_KIND_LIMIT:
1723 		case EXPR_KIND_OFFSET:
1724 		case EXPR_KIND_RETURNING:
1725 		case EXPR_KIND_VALUES:
1726 			/* okay */
1727 			break;
1728 		case EXPR_KIND_CHECK_CONSTRAINT:
1729 		case EXPR_KIND_DOMAIN_CHECK:
1730 			err = _("cannot use subquery in check constraint");
1731 			break;
1732 		case EXPR_KIND_COLUMN_DEFAULT:
1733 		case EXPR_KIND_FUNCTION_DEFAULT:
1734 			err = _("cannot use subquery in DEFAULT expression");
1735 			break;
1736 		case EXPR_KIND_INDEX_EXPRESSION:
1737 			err = _("cannot use subquery in index expression");
1738 			break;
1739 		case EXPR_KIND_INDEX_PREDICATE:
1740 			err = _("cannot use subquery in index predicate");
1741 			break;
1742 		case EXPR_KIND_ALTER_COL_TRANSFORM:
1743 			err = _("cannot use subquery in transform expression");
1744 			break;
1745 		case EXPR_KIND_EXECUTE_PARAMETER:
1746 			err = _("cannot use subquery in EXECUTE parameter");
1747 			break;
1748 		case EXPR_KIND_TRIGGER_WHEN:
1749 			err = _("cannot use subquery in trigger WHEN condition");
1750 			break;
1751 
1752 			/*
1753 			 * There is intentionally no default: case here, so that the
1754 			 * compiler will warn if we add a new ParseExprKind without
1755 			 * extending this switch.  If we do see an unrecognized value at
1756 			 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
1757 			 * which is sane anyway.
1758 			 */
1759 	}
1760 	if (err)
1761 		ereport(ERROR,
1762 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1763 				 errmsg_internal("%s", err),
1764 				 parser_errposition(pstate, sublink->location)));
1765 
1766 	pstate->p_hasSubLinks = true;
1767 
1768 	/*
1769 	 * OK, let's transform the sub-SELECT.
1770 	 */
1771 	qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false);
1772 
1773 	/*
1774 	 * Check that we got something reasonable.  Many of these conditions are
1775 	 * impossible given restrictions of the grammar, but check 'em anyway.
1776 	 */
1777 	if (!IsA(qtree, Query) ||
1778 		qtree->commandType != CMD_SELECT ||
1779 		qtree->utilityStmt != NULL)
1780 		elog(ERROR, "unexpected non-SELECT command in SubLink");
1781 
1782 	sublink->subselect = (Node *) qtree;
1783 
1784 	if (sublink->subLinkType == EXISTS_SUBLINK)
1785 	{
1786 		/*
1787 		 * EXISTS needs no test expression or combining operator. These fields
1788 		 * should be null already, but make sure.
1789 		 */
1790 		sublink->testexpr = NULL;
1791 		sublink->operName = NIL;
1792 	}
1793 	else if (sublink->subLinkType == EXPR_SUBLINK ||
1794 			 sublink->subLinkType == ARRAY_SUBLINK)
1795 	{
1796 		/*
1797 		 * Make sure the subselect delivers a single column (ignoring resjunk
1798 		 * targets).
1799 		 */
1800 		if (count_nonjunk_tlist_entries(qtree->targetList) != 1)
1801 			ereport(ERROR,
1802 					(errcode(ERRCODE_SYNTAX_ERROR),
1803 					 errmsg("subquery must return only one column"),
1804 					 parser_errposition(pstate, sublink->location)));
1805 
1806 		/*
1807 		 * EXPR and ARRAY need no test expression or combining operator. These
1808 		 * fields should be null already, but make sure.
1809 		 */
1810 		sublink->testexpr = NULL;
1811 		sublink->operName = NIL;
1812 	}
1813 	else if (sublink->subLinkType == MULTIEXPR_SUBLINK)
1814 	{
1815 		/* Same as EXPR case, except no restriction on number of columns */
1816 		sublink->testexpr = NULL;
1817 		sublink->operName = NIL;
1818 	}
1819 	else
1820 	{
1821 		/* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
1822 		Node	   *lefthand;
1823 		List	   *left_list;
1824 		List	   *right_list;
1825 		ListCell   *l;
1826 
1827 		if (operator_precedence_warning)
1828 		{
1829 			if (sublink->operName == NIL)
1830 				emit_precedence_warnings(pstate, PREC_GROUP_IN, "IN",
1831 										 sublink->testexpr, NULL,
1832 										 sublink->location);
1833 			else
1834 				emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_OP,
1835 										 strVal(llast(sublink->operName)),
1836 										 sublink->testexpr, NULL,
1837 										 sublink->location);
1838 		}
1839 
1840 		/*
1841 		 * If the source was "x IN (select)", convert to "x = ANY (select)".
1842 		 */
1843 		if (sublink->operName == NIL)
1844 			sublink->operName = list_make1(makeString("="));
1845 
1846 		/*
1847 		 * Transform lefthand expression, and convert to a list
1848 		 */
1849 		lefthand = transformExprRecurse(pstate, sublink->testexpr);
1850 		if (lefthand && IsA(lefthand, RowExpr))
1851 			left_list = ((RowExpr *) lefthand)->args;
1852 		else
1853 			left_list = list_make1(lefthand);
1854 
1855 		/*
1856 		 * Build a list of PARAM_SUBLINK nodes representing the output columns
1857 		 * of the subquery.
1858 		 */
1859 		right_list = NIL;
1860 		foreach(l, qtree->targetList)
1861 		{
1862 			TargetEntry *tent = (TargetEntry *) lfirst(l);
1863 			Param	   *param;
1864 
1865 			if (tent->resjunk)
1866 				continue;
1867 
1868 			param = makeNode(Param);
1869 			param->paramkind = PARAM_SUBLINK;
1870 			param->paramid = tent->resno;
1871 			param->paramtype = exprType((Node *) tent->expr);
1872 			param->paramtypmod = exprTypmod((Node *) tent->expr);
1873 			param->paramcollid = exprCollation((Node *) tent->expr);
1874 			param->location = -1;
1875 
1876 			right_list = lappend(right_list, param);
1877 		}
1878 
1879 		/*
1880 		 * We could rely on make_row_comparison_op to complain if the list
1881 		 * lengths differ, but we prefer to generate a more specific error
1882 		 * message.
1883 		 */
1884 		if (list_length(left_list) < list_length(right_list))
1885 			ereport(ERROR,
1886 					(errcode(ERRCODE_SYNTAX_ERROR),
1887 					 errmsg("subquery has too many columns"),
1888 					 parser_errposition(pstate, sublink->location)));
1889 		if (list_length(left_list) > list_length(right_list))
1890 			ereport(ERROR,
1891 					(errcode(ERRCODE_SYNTAX_ERROR),
1892 					 errmsg("subquery has too few columns"),
1893 					 parser_errposition(pstate, sublink->location)));
1894 
1895 		/*
1896 		 * Identify the combining operator(s) and generate a suitable
1897 		 * row-comparison expression.
1898 		 */
1899 		sublink->testexpr = make_row_comparison_op(pstate,
1900 												   sublink->operName,
1901 												   left_list,
1902 												   right_list,
1903 												   sublink->location);
1904 	}
1905 
1906 	return result;
1907 }
1908 
1909 /*
1910  * transformArrayExpr
1911  *
1912  * If the caller specifies the target type, the resulting array will
1913  * be of exactly that type.  Otherwise we try to infer a common type
1914  * for the elements using select_common_type().
1915  */
1916 static Node *
transformArrayExpr(ParseState * pstate,A_ArrayExpr * a,Oid array_type,Oid element_type,int32 typmod)1917 transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
1918 				   Oid array_type, Oid element_type, int32 typmod)
1919 {
1920 	ArrayExpr  *newa = makeNode(ArrayExpr);
1921 	List	   *newelems = NIL;
1922 	List	   *newcoercedelems = NIL;
1923 	ListCell   *element;
1924 	Oid			coerce_type;
1925 	bool		coerce_hard;
1926 
1927 	/*
1928 	 * Transform the element expressions
1929 	 *
1930 	 * Assume that the array is one-dimensional unless we find an array-type
1931 	 * element expression.
1932 	 */
1933 	newa->multidims = false;
1934 	foreach(element, a->elements)
1935 	{
1936 		Node	   *e = (Node *) lfirst(element);
1937 		Node	   *newe;
1938 
1939 		/* Look through AEXPR_PAREN nodes so they don't affect test below */
1940 		while (e && IsA(e, A_Expr) &&
1941 			   ((A_Expr *) e)->kind == AEXPR_PAREN)
1942 			e = ((A_Expr *) e)->lexpr;
1943 
1944 		/*
1945 		 * If an element is itself an A_ArrayExpr, recurse directly so that we
1946 		 * can pass down any target type we were given.
1947 		 */
1948 		if (IsA(e, A_ArrayExpr))
1949 		{
1950 			newe = transformArrayExpr(pstate,
1951 									  (A_ArrayExpr *) e,
1952 									  array_type,
1953 									  element_type,
1954 									  typmod);
1955 			/* we certainly have an array here */
1956 			Assert(array_type == InvalidOid || array_type == exprType(newe));
1957 			newa->multidims = true;
1958 		}
1959 		else
1960 		{
1961 			newe = transformExprRecurse(pstate, e);
1962 
1963 			/*
1964 			 * Check for sub-array expressions, if we haven't already found
1965 			 * one.
1966 			 */
1967 			if (!newa->multidims && type_is_array(exprType(newe)))
1968 				newa->multidims = true;
1969 		}
1970 
1971 		newelems = lappend(newelems, newe);
1972 	}
1973 
1974 	/*
1975 	 * Select a target type for the elements.
1976 	 *
1977 	 * If we haven't been given a target array type, we must try to deduce a
1978 	 * common type based on the types of the individual elements present.
1979 	 */
1980 	if (OidIsValid(array_type))
1981 	{
1982 		/* Caller must ensure array_type matches element_type */
1983 		Assert(OidIsValid(element_type));
1984 		coerce_type = (newa->multidims ? array_type : element_type);
1985 		coerce_hard = true;
1986 	}
1987 	else
1988 	{
1989 		/* Can't handle an empty array without a target type */
1990 		if (newelems == NIL)
1991 			ereport(ERROR,
1992 					(errcode(ERRCODE_INDETERMINATE_DATATYPE),
1993 					 errmsg("cannot determine type of empty array"),
1994 					 errhint("Explicitly cast to the desired type, "
1995 							 "for example ARRAY[]::integer[]."),
1996 					 parser_errposition(pstate, a->location)));
1997 
1998 		/* Select a common type for the elements */
1999 		coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
2000 
2001 		if (newa->multidims)
2002 		{
2003 			array_type = coerce_type;
2004 			element_type = get_element_type(array_type);
2005 			if (!OidIsValid(element_type))
2006 				ereport(ERROR,
2007 						(errcode(ERRCODE_UNDEFINED_OBJECT),
2008 					   errmsg("could not find element type for data type %s",
2009 							  format_type_be(array_type)),
2010 						 parser_errposition(pstate, a->location)));
2011 		}
2012 		else
2013 		{
2014 			element_type = coerce_type;
2015 			array_type = get_array_type(element_type);
2016 			if (!OidIsValid(array_type))
2017 				ereport(ERROR,
2018 						(errcode(ERRCODE_UNDEFINED_OBJECT),
2019 						 errmsg("could not find array type for data type %s",
2020 								format_type_be(element_type)),
2021 						 parser_errposition(pstate, a->location)));
2022 		}
2023 		coerce_hard = false;
2024 	}
2025 
2026 	/*
2027 	 * Coerce elements to target type
2028 	 *
2029 	 * If the array has been explicitly cast, then the elements are in turn
2030 	 * explicitly coerced.
2031 	 *
2032 	 * If the array's type was merely derived from the common type of its
2033 	 * elements, then the elements are implicitly coerced to the common type.
2034 	 * This is consistent with other uses of select_common_type().
2035 	 */
2036 	foreach(element, newelems)
2037 	{
2038 		Node	   *e = (Node *) lfirst(element);
2039 		Node	   *newe;
2040 
2041 		if (coerce_hard)
2042 		{
2043 			newe = coerce_to_target_type(pstate, e,
2044 										 exprType(e),
2045 										 coerce_type,
2046 										 typmod,
2047 										 COERCION_EXPLICIT,
2048 										 COERCE_EXPLICIT_CAST,
2049 										 -1);
2050 			if (newe == NULL)
2051 				ereport(ERROR,
2052 						(errcode(ERRCODE_CANNOT_COERCE),
2053 						 errmsg("cannot cast type %s to %s",
2054 								format_type_be(exprType(e)),
2055 								format_type_be(coerce_type)),
2056 						 parser_errposition(pstate, exprLocation(e))));
2057 		}
2058 		else
2059 			newe = coerce_to_common_type(pstate, e,
2060 										 coerce_type,
2061 										 "ARRAY");
2062 		newcoercedelems = lappend(newcoercedelems, newe);
2063 	}
2064 
2065 	newa->array_typeid = array_type;
2066 	/* array_collid will be set by parse_collate.c */
2067 	newa->element_typeid = element_type;
2068 	newa->elements = newcoercedelems;
2069 	newa->location = a->location;
2070 
2071 	return (Node *) newa;
2072 }
2073 
2074 static Node *
transformRowExpr(ParseState * pstate,RowExpr * r)2075 transformRowExpr(ParseState *pstate, RowExpr *r)
2076 {
2077 	RowExpr    *newr;
2078 	char		fname[16];
2079 	int			fnum;
2080 	ListCell   *lc;
2081 
2082 	newr = makeNode(RowExpr);
2083 
2084 	/* Transform the field expressions */
2085 	newr->args = transformExpressionList(pstate, r->args, pstate->p_expr_kind);
2086 
2087 	/* Barring later casting, we consider the type RECORD */
2088 	newr->row_typeid = RECORDOID;
2089 	newr->row_format = COERCE_IMPLICIT_CAST;
2090 
2091 	/* ROW() has anonymous columns, so invent some field names */
2092 	newr->colnames = NIL;
2093 	fnum = 1;
2094 	foreach(lc, newr->args)
2095 	{
2096 		snprintf(fname, sizeof(fname), "f%d", fnum++);
2097 		newr->colnames = lappend(newr->colnames, makeString(pstrdup(fname)));
2098 	}
2099 
2100 	newr->location = r->location;
2101 
2102 	return (Node *) newr;
2103 }
2104 
2105 static Node *
transformCoalesceExpr(ParseState * pstate,CoalesceExpr * c)2106 transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
2107 {
2108 	CoalesceExpr *newc = makeNode(CoalesceExpr);
2109 	List	   *newargs = NIL;
2110 	List	   *newcoercedargs = NIL;
2111 	ListCell   *args;
2112 
2113 	foreach(args, c->args)
2114 	{
2115 		Node	   *e = (Node *) lfirst(args);
2116 		Node	   *newe;
2117 
2118 		newe = transformExprRecurse(pstate, e);
2119 		newargs = lappend(newargs, newe);
2120 	}
2121 
2122 	newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
2123 	/* coalescecollid will be set by parse_collate.c */
2124 
2125 	/* Convert arguments if necessary */
2126 	foreach(args, newargs)
2127 	{
2128 		Node	   *e = (Node *) lfirst(args);
2129 		Node	   *newe;
2130 
2131 		newe = coerce_to_common_type(pstate, e,
2132 									 newc->coalescetype,
2133 									 "COALESCE");
2134 		newcoercedargs = lappend(newcoercedargs, newe);
2135 	}
2136 
2137 	newc->args = newcoercedargs;
2138 	newc->location = c->location;
2139 	return (Node *) newc;
2140 }
2141 
2142 static Node *
transformMinMaxExpr(ParseState * pstate,MinMaxExpr * m)2143 transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
2144 {
2145 	MinMaxExpr *newm = makeNode(MinMaxExpr);
2146 	List	   *newargs = NIL;
2147 	List	   *newcoercedargs = NIL;
2148 	const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
2149 	ListCell   *args;
2150 
2151 	newm->op = m->op;
2152 	foreach(args, m->args)
2153 	{
2154 		Node	   *e = (Node *) lfirst(args);
2155 		Node	   *newe;
2156 
2157 		newe = transformExprRecurse(pstate, e);
2158 		newargs = lappend(newargs, newe);
2159 	}
2160 
2161 	newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
2162 	/* minmaxcollid and inputcollid will be set by parse_collate.c */
2163 
2164 	/* Convert arguments if necessary */
2165 	foreach(args, newargs)
2166 	{
2167 		Node	   *e = (Node *) lfirst(args);
2168 		Node	   *newe;
2169 
2170 		newe = coerce_to_common_type(pstate, e,
2171 									 newm->minmaxtype,
2172 									 funcname);
2173 		newcoercedargs = lappend(newcoercedargs, newe);
2174 	}
2175 
2176 	newm->args = newcoercedargs;
2177 	newm->location = m->location;
2178 	return (Node *) newm;
2179 }
2180 
2181 static Node *
transformXmlExpr(ParseState * pstate,XmlExpr * x)2182 transformXmlExpr(ParseState *pstate, XmlExpr *x)
2183 {
2184 	XmlExpr    *newx;
2185 	ListCell   *lc;
2186 	int			i;
2187 
2188 	if (operator_precedence_warning && x->op == IS_DOCUMENT)
2189 		emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
2190 								 (Node *) linitial(x->args), NULL,
2191 								 x->location);
2192 
2193 	newx = makeNode(XmlExpr);
2194 	newx->op = x->op;
2195 	if (x->name)
2196 		newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
2197 	else
2198 		newx->name = NULL;
2199 	newx->xmloption = x->xmloption;
2200 	newx->type = XMLOID;		/* this just marks the node as transformed */
2201 	newx->typmod = -1;
2202 	newx->location = x->location;
2203 
2204 	/*
2205 	 * gram.y built the named args as a list of ResTarget.  Transform each,
2206 	 * and break the names out as a separate list.
2207 	 */
2208 	newx->named_args = NIL;
2209 	newx->arg_names = NIL;
2210 
2211 	foreach(lc, x->named_args)
2212 	{
2213 		ResTarget  *r = (ResTarget *) lfirst(lc);
2214 		Node	   *expr;
2215 		char	   *argname;
2216 
2217 		Assert(IsA(r, ResTarget));
2218 
2219 		expr = transformExprRecurse(pstate, r->val);
2220 
2221 		if (r->name)
2222 			argname = map_sql_identifier_to_xml_name(r->name, false, false);
2223 		else if (IsA(r->val, ColumnRef))
2224 			argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
2225 													 true, false);
2226 		else
2227 		{
2228 			ereport(ERROR,
2229 					(errcode(ERRCODE_SYNTAX_ERROR),
2230 					 x->op == IS_XMLELEMENT
2231 			? errmsg("unnamed XML attribute value must be a column reference")
2232 			: errmsg("unnamed XML element value must be a column reference"),
2233 					 parser_errposition(pstate, r->location)));
2234 			argname = NULL;		/* keep compiler quiet */
2235 		}
2236 
2237 		/* reject duplicate argnames in XMLELEMENT only */
2238 		if (x->op == IS_XMLELEMENT)
2239 		{
2240 			ListCell   *lc2;
2241 
2242 			foreach(lc2, newx->arg_names)
2243 			{
2244 				if (strcmp(argname, strVal(lfirst(lc2))) == 0)
2245 					ereport(ERROR,
2246 							(errcode(ERRCODE_SYNTAX_ERROR),
2247 					errmsg("XML attribute name \"%s\" appears more than once",
2248 						   argname),
2249 							 parser_errposition(pstate, r->location)));
2250 			}
2251 		}
2252 
2253 		newx->named_args = lappend(newx->named_args, expr);
2254 		newx->arg_names = lappend(newx->arg_names, makeString(argname));
2255 	}
2256 
2257 	/* The other arguments are of varying types depending on the function */
2258 	newx->args = NIL;
2259 	i = 0;
2260 	foreach(lc, x->args)
2261 	{
2262 		Node	   *e = (Node *) lfirst(lc);
2263 		Node	   *newe;
2264 
2265 		newe = transformExprRecurse(pstate, e);
2266 		switch (x->op)
2267 		{
2268 			case IS_XMLCONCAT:
2269 				newe = coerce_to_specific_type(pstate, newe, XMLOID,
2270 											   "XMLCONCAT");
2271 				break;
2272 			case IS_XMLELEMENT:
2273 				/* no coercion necessary */
2274 				break;
2275 			case IS_XMLFOREST:
2276 				newe = coerce_to_specific_type(pstate, newe, XMLOID,
2277 											   "XMLFOREST");
2278 				break;
2279 			case IS_XMLPARSE:
2280 				if (i == 0)
2281 					newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2282 												   "XMLPARSE");
2283 				else
2284 					newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
2285 				break;
2286 			case IS_XMLPI:
2287 				newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2288 											   "XMLPI");
2289 				break;
2290 			case IS_XMLROOT:
2291 				if (i == 0)
2292 					newe = coerce_to_specific_type(pstate, newe, XMLOID,
2293 												   "XMLROOT");
2294 				else if (i == 1)
2295 					newe = coerce_to_specific_type(pstate, newe, TEXTOID,
2296 												   "XMLROOT");
2297 				else
2298 					newe = coerce_to_specific_type(pstate, newe, INT4OID,
2299 												   "XMLROOT");
2300 				break;
2301 			case IS_XMLSERIALIZE:
2302 				/* not handled here */
2303 				Assert(false);
2304 				break;
2305 			case IS_DOCUMENT:
2306 				newe = coerce_to_specific_type(pstate, newe, XMLOID,
2307 											   "IS DOCUMENT");
2308 				break;
2309 		}
2310 		newx->args = lappend(newx->args, newe);
2311 		i++;
2312 	}
2313 
2314 	return (Node *) newx;
2315 }
2316 
2317 static Node *
transformXmlSerialize(ParseState * pstate,XmlSerialize * xs)2318 transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
2319 {
2320 	Node	   *result;
2321 	XmlExpr    *xexpr;
2322 	Oid			targetType;
2323 	int32		targetTypmod;
2324 
2325 	xexpr = makeNode(XmlExpr);
2326 	xexpr->op = IS_XMLSERIALIZE;
2327 	xexpr->args = list_make1(coerce_to_specific_type(pstate,
2328 									  transformExprRecurse(pstate, xs->expr),
2329 													 XMLOID,
2330 													 "XMLSERIALIZE"));
2331 
2332 	typenameTypeIdAndMod(pstate, xs->typeName, &targetType, &targetTypmod);
2333 
2334 	xexpr->xmloption = xs->xmloption;
2335 	xexpr->location = xs->location;
2336 	/* We actually only need these to be able to parse back the expression. */
2337 	xexpr->type = targetType;
2338 	xexpr->typmod = targetTypmod;
2339 
2340 	/*
2341 	 * The actual target type is determined this way.  SQL allows char and
2342 	 * varchar as target types.  We allow anything that can be cast implicitly
2343 	 * from text.  This way, user-defined text-like data types automatically
2344 	 * fit in.
2345 	 */
2346 	result = coerce_to_target_type(pstate, (Node *) xexpr,
2347 								   TEXTOID, targetType, targetTypmod,
2348 								   COERCION_IMPLICIT,
2349 								   COERCE_IMPLICIT_CAST,
2350 								   -1);
2351 	if (result == NULL)
2352 		ereport(ERROR,
2353 				(errcode(ERRCODE_CANNOT_COERCE),
2354 				 errmsg("cannot cast XMLSERIALIZE result to %s",
2355 						format_type_be(targetType)),
2356 				 parser_errposition(pstate, xexpr->location)));
2357 	return result;
2358 }
2359 
2360 static Node *
transformBooleanTest(ParseState * pstate,BooleanTest * b)2361 transformBooleanTest(ParseState *pstate, BooleanTest *b)
2362 {
2363 	const char *clausename;
2364 
2365 	if (operator_precedence_warning)
2366 		emit_precedence_warnings(pstate, PREC_GROUP_POSTFIX_IS, "IS",
2367 								 (Node *) b->arg, NULL,
2368 								 b->location);
2369 
2370 	switch (b->booltesttype)
2371 	{
2372 		case IS_TRUE:
2373 			clausename = "IS TRUE";
2374 			break;
2375 		case IS_NOT_TRUE:
2376 			clausename = "IS NOT TRUE";
2377 			break;
2378 		case IS_FALSE:
2379 			clausename = "IS FALSE";
2380 			break;
2381 		case IS_NOT_FALSE:
2382 			clausename = "IS NOT FALSE";
2383 			break;
2384 		case IS_UNKNOWN:
2385 			clausename = "IS UNKNOWN";
2386 			break;
2387 		case IS_NOT_UNKNOWN:
2388 			clausename = "IS NOT UNKNOWN";
2389 			break;
2390 		default:
2391 			elog(ERROR, "unrecognized booltesttype: %d",
2392 				 (int) b->booltesttype);
2393 			clausename = NULL;	/* keep compiler quiet */
2394 	}
2395 
2396 	b->arg = (Expr *) transformExprRecurse(pstate, (Node *) b->arg);
2397 
2398 	b->arg = (Expr *) coerce_to_boolean(pstate,
2399 										(Node *) b->arg,
2400 										clausename);
2401 
2402 	return (Node *) b;
2403 }
2404 
2405 static Node *
transformCurrentOfExpr(ParseState * pstate,CurrentOfExpr * cexpr)2406 transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
2407 {
2408 	int			sublevels_up;
2409 
2410 	/* CURRENT OF can only appear at top level of UPDATE/DELETE */
2411 	Assert(pstate->p_target_rangetblentry != NULL);
2412 	cexpr->cvarno = RTERangeTablePosn(pstate,
2413 									  pstate->p_target_rangetblentry,
2414 									  &sublevels_up);
2415 	Assert(sublevels_up == 0);
2416 
2417 	/*
2418 	 * Check to see if the cursor name matches a parameter of type REFCURSOR.
2419 	 * If so, replace the raw name reference with a parameter reference. (This
2420 	 * is a hack for the convenience of plpgsql.)
2421 	 */
2422 	if (cexpr->cursor_name != NULL)		/* in case already transformed */
2423 	{
2424 		ColumnRef  *cref = makeNode(ColumnRef);
2425 		Node	   *node = NULL;
2426 
2427 		/* Build an unqualified ColumnRef with the given name */
2428 		cref->fields = list_make1(makeString(cexpr->cursor_name));
2429 		cref->location = -1;
2430 
2431 		/* See if there is a translation available from a parser hook */
2432 		if (pstate->p_pre_columnref_hook != NULL)
2433 			node = (*pstate->p_pre_columnref_hook) (pstate, cref);
2434 		if (node == NULL && pstate->p_post_columnref_hook != NULL)
2435 			node = (*pstate->p_post_columnref_hook) (pstate, cref, NULL);
2436 
2437 		/*
2438 		 * XXX Should we throw an error if we get a translation that isn't a
2439 		 * refcursor Param?  For now it seems best to silently ignore false
2440 		 * matches.
2441 		 */
2442 		if (node != NULL && IsA(node, Param))
2443 		{
2444 			Param	   *p = (Param *) node;
2445 
2446 			if (p->paramkind == PARAM_EXTERN &&
2447 				p->paramtype == REFCURSOROID)
2448 			{
2449 				/* Matches, so convert CURRENT OF to a param reference */
2450 				cexpr->cursor_name = NULL;
2451 				cexpr->cursor_param = p->paramid;
2452 			}
2453 		}
2454 	}
2455 
2456 	return (Node *) cexpr;
2457 }
2458 
2459 /*
2460  * Construct a whole-row reference to represent the notation "relation.*".
2461  */
2462 static Node *
transformWholeRowRef(ParseState * pstate,RangeTblEntry * rte,int location)2463 transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte, int location)
2464 {
2465 	Var		   *result;
2466 	int			vnum;
2467 	int			sublevels_up;
2468 
2469 	/* Find the RTE's rangetable location */
2470 	vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
2471 
2472 	/*
2473 	 * Build the appropriate referencing node.  Note that if the RTE is a
2474 	 * function returning scalar, we create just a plain reference to the
2475 	 * function value, not a composite containing a single column.  This is
2476 	 * pretty inconsistent at first sight, but it's what we've done
2477 	 * historically.  One argument for it is that "rel" and "rel.*" mean the
2478 	 * same thing for composite relations, so why not for scalar functions...
2479 	 */
2480 	result = makeWholeRowVar(rte, vnum, sublevels_up, true);
2481 
2482 	/* location is not filled in by makeWholeRowVar */
2483 	result->location = location;
2484 
2485 	/* mark relation as requiring whole-row SELECT access */
2486 	markVarForSelectPriv(pstate, result, rte);
2487 
2488 	return (Node *) result;
2489 }
2490 
2491 /*
2492  * Handle an explicit CAST construct.
2493  *
2494  * Transform the argument, look up the type name, and apply any necessary
2495  * coercion function(s).
2496  */
2497 static Node *
transformTypeCast(ParseState * pstate,TypeCast * tc)2498 transformTypeCast(ParseState *pstate, TypeCast *tc)
2499 {
2500 	Node	   *result;
2501 	Node	   *arg = tc->arg;
2502 	Node	   *expr;
2503 	Oid			inputType;
2504 	Oid			targetType;
2505 	int32		targetTypmod;
2506 	int			location;
2507 
2508 	/* Look up the type name first */
2509 	typenameTypeIdAndMod(pstate, tc->typeName, &targetType, &targetTypmod);
2510 
2511 	/*
2512 	 * Look through any AEXPR_PAREN nodes that may have been inserted thanks
2513 	 * to operator_precedence_warning.  Otherwise, ARRAY[]::foo[] behaves
2514 	 * differently from (ARRAY[])::foo[].
2515 	 */
2516 	while (arg && IsA(arg, A_Expr) &&
2517 		   ((A_Expr *) arg)->kind == AEXPR_PAREN)
2518 		arg = ((A_Expr *) arg)->lexpr;
2519 
2520 	/*
2521 	 * If the subject of the typecast is an ARRAY[] construct and the target
2522 	 * type is an array type, we invoke transformArrayExpr() directly so that
2523 	 * we can pass down the type information.  This avoids some cases where
2524 	 * transformArrayExpr() might not infer the correct type.  Otherwise, just
2525 	 * transform the argument normally.
2526 	 */
2527 	if (IsA(arg, A_ArrayExpr))
2528 	{
2529 		Oid			targetBaseType;
2530 		int32		targetBaseTypmod;
2531 		Oid			elementType;
2532 
2533 		/*
2534 		 * If target is a domain over array, work with the base array type
2535 		 * here.  Below, we'll cast the array type to the domain.  In the
2536 		 * usual case that the target is not a domain, the remaining steps
2537 		 * will be a no-op.
2538 		 */
2539 		targetBaseTypmod = targetTypmod;
2540 		targetBaseType = getBaseTypeAndTypmod(targetType, &targetBaseTypmod);
2541 		elementType = get_element_type(targetBaseType);
2542 		if (OidIsValid(elementType))
2543 		{
2544 			expr = transformArrayExpr(pstate,
2545 									  (A_ArrayExpr *) arg,
2546 									  targetBaseType,
2547 									  elementType,
2548 									  targetBaseTypmod);
2549 		}
2550 		else
2551 			expr = transformExprRecurse(pstate, arg);
2552 	}
2553 	else
2554 		expr = transformExprRecurse(pstate, arg);
2555 
2556 	inputType = exprType(expr);
2557 	if (inputType == InvalidOid)
2558 		return expr;			/* do nothing if NULL input */
2559 
2560 	/*
2561 	 * Location of the coercion is preferentially the location of the :: or
2562 	 * CAST symbol, but if there is none then use the location of the type
2563 	 * name (this can happen in TypeName 'string' syntax, for instance).
2564 	 */
2565 	location = tc->location;
2566 	if (location < 0)
2567 		location = tc->typeName->location;
2568 
2569 	result = coerce_to_target_type(pstate, expr, inputType,
2570 								   targetType, targetTypmod,
2571 								   COERCION_EXPLICIT,
2572 								   COERCE_EXPLICIT_CAST,
2573 								   location);
2574 	if (result == NULL)
2575 		ereport(ERROR,
2576 				(errcode(ERRCODE_CANNOT_COERCE),
2577 				 errmsg("cannot cast type %s to %s",
2578 						format_type_be(inputType),
2579 						format_type_be(targetType)),
2580 				 parser_coercion_errposition(pstate, location, expr)));
2581 
2582 	return result;
2583 }
2584 
2585 /*
2586  * Handle an explicit COLLATE clause.
2587  *
2588  * Transform the argument, and look up the collation name.
2589  */
2590 static Node *
transformCollateClause(ParseState * pstate,CollateClause * c)2591 transformCollateClause(ParseState *pstate, CollateClause *c)
2592 {
2593 	CollateExpr *newc;
2594 	Oid			argtype;
2595 
2596 	newc = makeNode(CollateExpr);
2597 	newc->arg = (Expr *) transformExprRecurse(pstate, c->arg);
2598 
2599 	argtype = exprType((Node *) newc->arg);
2600 
2601 	/*
2602 	 * The unknown type is not collatable, but coerce_type() takes care of it
2603 	 * separately, so we'll let it go here.
2604 	 */
2605 	if (!type_is_collatable(argtype) && argtype != UNKNOWNOID)
2606 		ereport(ERROR,
2607 				(errcode(ERRCODE_DATATYPE_MISMATCH),
2608 				 errmsg("collations are not supported by type %s",
2609 						format_type_be(argtype)),
2610 				 parser_errposition(pstate, c->location)));
2611 
2612 	newc->collOid = LookupCollation(pstate, c->collname, c->location);
2613 	newc->location = c->location;
2614 
2615 	return (Node *) newc;
2616 }
2617 
2618 /*
2619  * Transform a "row compare-op row" construct
2620  *
2621  * The inputs are lists of already-transformed expressions.
2622  * As with coerce_type, pstate may be NULL if no special unknown-Param
2623  * processing is wanted.
2624  *
2625  * The output may be a single OpExpr, an AND or OR combination of OpExprs,
2626  * or a RowCompareExpr.  In all cases it is guaranteed to return boolean.
2627  * The AND, OR, and RowCompareExpr cases further imply things about the
2628  * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2629  */
2630 static Node *
make_row_comparison_op(ParseState * pstate,List * opname,List * largs,List * rargs,int location)2631 make_row_comparison_op(ParseState *pstate, List *opname,
2632 					   List *largs, List *rargs, int location)
2633 {
2634 	RowCompareExpr *rcexpr;
2635 	RowCompareType rctype;
2636 	List	   *opexprs;
2637 	List	   *opnos;
2638 	List	   *opfamilies;
2639 	ListCell   *l,
2640 			   *r;
2641 	List	  **opinfo_lists;
2642 	Bitmapset  *strats;
2643 	int			nopers;
2644 	int			i;
2645 
2646 	nopers = list_length(largs);
2647 	if (nopers != list_length(rargs))
2648 		ereport(ERROR,
2649 				(errcode(ERRCODE_SYNTAX_ERROR),
2650 				 errmsg("unequal number of entries in row expressions"),
2651 				 parser_errposition(pstate, location)));
2652 
2653 	/*
2654 	 * We can't compare zero-length rows because there is no principled basis
2655 	 * for figuring out what the operator is.
2656 	 */
2657 	if (nopers == 0)
2658 		ereport(ERROR,
2659 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2660 				 errmsg("cannot compare rows of zero length"),
2661 				 parser_errposition(pstate, location)));
2662 
2663 	/*
2664 	 * Identify all the pairwise operators, using make_op so that behavior is
2665 	 * the same as in the simple scalar case.
2666 	 */
2667 	opexprs = NIL;
2668 	forboth(l, largs, r, rargs)
2669 	{
2670 		Node	   *larg = (Node *) lfirst(l);
2671 		Node	   *rarg = (Node *) lfirst(r);
2672 		OpExpr	   *cmp;
2673 
2674 		cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2675 		Assert(IsA(cmp, OpExpr));
2676 
2677 		/*
2678 		 * We don't use coerce_to_boolean here because we insist on the
2679 		 * operator yielding boolean directly, not via coercion.  If it
2680 		 * doesn't yield bool it won't be in any index opfamilies...
2681 		 */
2682 		if (cmp->opresulttype != BOOLOID)
2683 			ereport(ERROR,
2684 					(errcode(ERRCODE_DATATYPE_MISMATCH),
2685 				   errmsg("row comparison operator must yield type boolean, "
2686 						  "not type %s",
2687 						  format_type_be(cmp->opresulttype)),
2688 					 parser_errposition(pstate, location)));
2689 		if (expression_returns_set((Node *) cmp))
2690 			ereport(ERROR,
2691 					(errcode(ERRCODE_DATATYPE_MISMATCH),
2692 					 errmsg("row comparison operator must not return a set"),
2693 					 parser_errposition(pstate, location)));
2694 		opexprs = lappend(opexprs, cmp);
2695 	}
2696 
2697 	/*
2698 	 * If rows are length 1, just return the single operator.  In this case we
2699 	 * don't insist on identifying btree semantics for the operator (but we
2700 	 * still require it to return boolean).
2701 	 */
2702 	if (nopers == 1)
2703 		return (Node *) linitial(opexprs);
2704 
2705 	/*
2706 	 * Now we must determine which row comparison semantics (= <> < <= > >=)
2707 	 * apply to this set of operators.  We look for btree opfamilies
2708 	 * containing the operators, and see which interpretations (strategy
2709 	 * numbers) exist for each operator.
2710 	 */
2711 	opinfo_lists = (List **) palloc(nopers * sizeof(List *));
2712 	strats = NULL;
2713 	i = 0;
2714 	foreach(l, opexprs)
2715 	{
2716 		Oid			opno = ((OpExpr *) lfirst(l))->opno;
2717 		Bitmapset  *this_strats;
2718 		ListCell   *j;
2719 
2720 		opinfo_lists[i] = get_op_btree_interpretation(opno);
2721 
2722 		/*
2723 		 * convert strategy numbers into a Bitmapset to make the intersection
2724 		 * calculation easy.
2725 		 */
2726 		this_strats = NULL;
2727 		foreach(j, opinfo_lists[i])
2728 		{
2729 			OpBtreeInterpretation *opinfo = lfirst(j);
2730 
2731 			this_strats = bms_add_member(this_strats, opinfo->strategy);
2732 		}
2733 		if (i == 0)
2734 			strats = this_strats;
2735 		else
2736 			strats = bms_int_members(strats, this_strats);
2737 		i++;
2738 	}
2739 
2740 	/*
2741 	 * If there are multiple common interpretations, we may use any one of
2742 	 * them ... this coding arbitrarily picks the lowest btree strategy
2743 	 * number.
2744 	 */
2745 	i = bms_first_member(strats);
2746 	if (i < 0)
2747 	{
2748 		/* No common interpretation, so fail */
2749 		ereport(ERROR,
2750 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2751 				 errmsg("could not determine interpretation of row comparison operator %s",
2752 						strVal(llast(opname))),
2753 				 errhint("Row comparison operators must be associated with btree operator families."),
2754 				 parser_errposition(pstate, location)));
2755 	}
2756 	rctype = (RowCompareType) i;
2757 
2758 	/*
2759 	 * For = and <> cases, we just combine the pairwise operators with AND or
2760 	 * OR respectively.
2761 	 */
2762 	if (rctype == ROWCOMPARE_EQ)
2763 		return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2764 	if (rctype == ROWCOMPARE_NE)
2765 		return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2766 
2767 	/*
2768 	 * Otherwise we need to choose exactly which opfamily to associate with
2769 	 * each operator.
2770 	 */
2771 	opfamilies = NIL;
2772 	for (i = 0; i < nopers; i++)
2773 	{
2774 		Oid			opfamily = InvalidOid;
2775 		ListCell   *j;
2776 
2777 		foreach(j, opinfo_lists[i])
2778 		{
2779 			OpBtreeInterpretation *opinfo = lfirst(j);
2780 
2781 			if (opinfo->strategy == rctype)
2782 			{
2783 				opfamily = opinfo->opfamily_id;
2784 				break;
2785 			}
2786 		}
2787 		if (OidIsValid(opfamily))
2788 			opfamilies = lappend_oid(opfamilies, opfamily);
2789 		else	/* should not happen */
2790 			ereport(ERROR,
2791 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2792 					 errmsg("could not determine interpretation of row comparison operator %s",
2793 							strVal(llast(opname))),
2794 			   errdetail("There are multiple equally-plausible candidates."),
2795 					 parser_errposition(pstate, location)));
2796 	}
2797 
2798 	/*
2799 	 * Now deconstruct the OpExprs and create a RowCompareExpr.
2800 	 *
2801 	 * Note: can't just reuse the passed largs/rargs lists, because of
2802 	 * possibility that make_op inserted coercion operations.
2803 	 */
2804 	opnos = NIL;
2805 	largs = NIL;
2806 	rargs = NIL;
2807 	foreach(l, opexprs)
2808 	{
2809 		OpExpr	   *cmp = (OpExpr *) lfirst(l);
2810 
2811 		opnos = lappend_oid(opnos, cmp->opno);
2812 		largs = lappend(largs, linitial(cmp->args));
2813 		rargs = lappend(rargs, lsecond(cmp->args));
2814 	}
2815 
2816 	rcexpr = makeNode(RowCompareExpr);
2817 	rcexpr->rctype = rctype;
2818 	rcexpr->opnos = opnos;
2819 	rcexpr->opfamilies = opfamilies;
2820 	rcexpr->inputcollids = NIL; /* assign_expr_collations will fix this */
2821 	rcexpr->largs = largs;
2822 	rcexpr->rargs = rargs;
2823 
2824 	return (Node *) rcexpr;
2825 }
2826 
2827 /*
2828  * Transform a "row IS DISTINCT FROM row" construct
2829  *
2830  * The input RowExprs are already transformed
2831  */
2832 static Node *
make_row_distinct_op(ParseState * pstate,List * opname,RowExpr * lrow,RowExpr * rrow,int location)2833 make_row_distinct_op(ParseState *pstate, List *opname,
2834 					 RowExpr *lrow, RowExpr *rrow,
2835 					 int location)
2836 {
2837 	Node	   *result = NULL;
2838 	List	   *largs = lrow->args;
2839 	List	   *rargs = rrow->args;
2840 	ListCell   *l,
2841 			   *r;
2842 
2843 	if (list_length(largs) != list_length(rargs))
2844 		ereport(ERROR,
2845 				(errcode(ERRCODE_SYNTAX_ERROR),
2846 				 errmsg("unequal number of entries in row expressions"),
2847 				 parser_errposition(pstate, location)));
2848 
2849 	forboth(l, largs, r, rargs)
2850 	{
2851 		Node	   *larg = (Node *) lfirst(l);
2852 		Node	   *rarg = (Node *) lfirst(r);
2853 		Node	   *cmp;
2854 
2855 		cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2856 		if (result == NULL)
2857 			result = cmp;
2858 		else
2859 			result = (Node *) makeBoolExpr(OR_EXPR,
2860 										   list_make2(result, cmp),
2861 										   location);
2862 	}
2863 
2864 	if (result == NULL)
2865 	{
2866 		/* zero-length rows?  Generate constant FALSE */
2867 		result = makeBoolConst(false, false);
2868 	}
2869 
2870 	return result;
2871 }
2872 
2873 /*
2874  * make the node for an IS DISTINCT FROM operator
2875  */
2876 static Expr *
make_distinct_op(ParseState * pstate,List * opname,Node * ltree,Node * rtree,int location)2877 make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
2878 				 int location)
2879 {
2880 	Expr	   *result;
2881 
2882 	result = make_op(pstate, opname, ltree, rtree, location);
2883 	if (((OpExpr *) result)->opresulttype != BOOLOID)
2884 		ereport(ERROR,
2885 				(errcode(ERRCODE_DATATYPE_MISMATCH),
2886 			 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2887 				 parser_errposition(pstate, location)));
2888 
2889 	/*
2890 	 * We rely on DistinctExpr and OpExpr being same struct
2891 	 */
2892 	NodeSetTag(result, T_DistinctExpr);
2893 
2894 	return result;
2895 }
2896 
2897 /*
2898  * Produce a NullTest node from an IS [NOT] DISTINCT FROM NULL construct
2899  *
2900  * "arg" is the untransformed other argument
2901  */
2902 static Node *
make_nulltest_from_distinct(ParseState * pstate,A_Expr * distincta,Node * arg)2903 make_nulltest_from_distinct(ParseState *pstate, A_Expr *distincta, Node *arg)
2904 {
2905 	NullTest   *nt = makeNode(NullTest);
2906 
2907 	nt->arg = (Expr *) transformExprRecurse(pstate, arg);
2908 	/* the argument can be any type, so don't coerce it */
2909 	if (distincta->kind == AEXPR_NOT_DISTINCT)
2910 		nt->nulltesttype = IS_NULL;
2911 	else
2912 		nt->nulltesttype = IS_NOT_NULL;
2913 	/* argisrow = false is correct whether or not arg is composite */
2914 	nt->argisrow = false;
2915 	nt->location = distincta->location;
2916 	return (Node *) nt;
2917 }
2918 
2919 /*
2920  * Identify node's group for operator precedence warnings
2921  *
2922  * For items in nonzero groups, also return a suitable node name into *nodename
2923  *
2924  * Note: group zero is used for nodes that are higher or lower precedence
2925  * than everything that changed precedence; we need never issue warnings
2926  * related to such nodes.
2927  */
2928 static int
operator_precedence_group(Node * node,const char ** nodename)2929 operator_precedence_group(Node *node, const char **nodename)
2930 {
2931 	int			group = 0;
2932 
2933 	*nodename = NULL;
2934 	if (node == NULL)
2935 		return 0;
2936 
2937 	if (IsA(node, A_Expr))
2938 	{
2939 		A_Expr	   *aexpr = (A_Expr *) node;
2940 
2941 		if (aexpr->kind == AEXPR_OP &&
2942 			aexpr->lexpr != NULL &&
2943 			aexpr->rexpr != NULL)
2944 		{
2945 			/* binary operator */
2946 			if (list_length(aexpr->name) == 1)
2947 			{
2948 				*nodename = strVal(linitial(aexpr->name));
2949 				/* Ignore if op was always higher priority than IS-tests */
2950 				if (strcmp(*nodename, "+") == 0 ||
2951 					strcmp(*nodename, "-") == 0 ||
2952 					strcmp(*nodename, "*") == 0 ||
2953 					strcmp(*nodename, "/") == 0 ||
2954 					strcmp(*nodename, "%") == 0 ||
2955 					strcmp(*nodename, "^") == 0)
2956 					group = 0;
2957 				else if (strcmp(*nodename, "<") == 0 ||
2958 						 strcmp(*nodename, ">") == 0)
2959 					group = PREC_GROUP_LESS;
2960 				else if (strcmp(*nodename, "=") == 0)
2961 					group = PREC_GROUP_EQUAL;
2962 				else if (strcmp(*nodename, "<=") == 0 ||
2963 						 strcmp(*nodename, ">=") == 0 ||
2964 						 strcmp(*nodename, "<>") == 0)
2965 					group = PREC_GROUP_LESS_EQUAL;
2966 				else
2967 					group = PREC_GROUP_INFIX_OP;
2968 			}
2969 			else
2970 			{
2971 				/* schema-qualified operator syntax */
2972 				*nodename = "OPERATOR()";
2973 				group = PREC_GROUP_INFIX_OP;
2974 			}
2975 		}
2976 		else if (aexpr->kind == AEXPR_OP &&
2977 				 aexpr->lexpr == NULL &&
2978 				 aexpr->rexpr != NULL)
2979 		{
2980 			/* prefix operator */
2981 			if (list_length(aexpr->name) == 1)
2982 			{
2983 				*nodename = strVal(linitial(aexpr->name));
2984 				/* Ignore if op was always higher priority than IS-tests */
2985 				if (strcmp(*nodename, "+") == 0 ||
2986 					strcmp(*nodename, "-") == 0)
2987 					group = 0;
2988 				else
2989 					group = PREC_GROUP_PREFIX_OP;
2990 			}
2991 			else
2992 			{
2993 				/* schema-qualified operator syntax */
2994 				*nodename = "OPERATOR()";
2995 				group = PREC_GROUP_PREFIX_OP;
2996 			}
2997 		}
2998 		else if (aexpr->kind == AEXPR_OP &&
2999 				 aexpr->lexpr != NULL &&
3000 				 aexpr->rexpr == NULL)
3001 		{
3002 			/* postfix operator */
3003 			if (list_length(aexpr->name) == 1)
3004 			{
3005 				*nodename = strVal(linitial(aexpr->name));
3006 				group = PREC_GROUP_POSTFIX_OP;
3007 			}
3008 			else
3009 			{
3010 				/* schema-qualified operator syntax */
3011 				*nodename = "OPERATOR()";
3012 				group = PREC_GROUP_POSTFIX_OP;
3013 			}
3014 		}
3015 		else if (aexpr->kind == AEXPR_OP_ANY ||
3016 				 aexpr->kind == AEXPR_OP_ALL)
3017 		{
3018 			*nodename = strVal(llast(aexpr->name));
3019 			group = PREC_GROUP_POSTFIX_OP;
3020 		}
3021 		else if (aexpr->kind == AEXPR_DISTINCT ||
3022 				 aexpr->kind == AEXPR_NOT_DISTINCT)
3023 		{
3024 			*nodename = "IS";
3025 			group = PREC_GROUP_INFIX_IS;
3026 		}
3027 		else if (aexpr->kind == AEXPR_OF)
3028 		{
3029 			*nodename = "IS";
3030 			group = PREC_GROUP_POSTFIX_IS;
3031 		}
3032 		else if (aexpr->kind == AEXPR_IN)
3033 		{
3034 			*nodename = "IN";
3035 			if (strcmp(strVal(linitial(aexpr->name)), "=") == 0)
3036 				group = PREC_GROUP_IN;
3037 			else
3038 				group = PREC_GROUP_NOT_IN;
3039 		}
3040 		else if (aexpr->kind == AEXPR_LIKE)
3041 		{
3042 			*nodename = "LIKE";
3043 			if (strcmp(strVal(linitial(aexpr->name)), "~~") == 0)
3044 				group = PREC_GROUP_LIKE;
3045 			else
3046 				group = PREC_GROUP_NOT_LIKE;
3047 		}
3048 		else if (aexpr->kind == AEXPR_ILIKE)
3049 		{
3050 			*nodename = "ILIKE";
3051 			if (strcmp(strVal(linitial(aexpr->name)), "~~*") == 0)
3052 				group = PREC_GROUP_LIKE;
3053 			else
3054 				group = PREC_GROUP_NOT_LIKE;
3055 		}
3056 		else if (aexpr->kind == AEXPR_SIMILAR)
3057 		{
3058 			*nodename = "SIMILAR";
3059 			if (strcmp(strVal(linitial(aexpr->name)), "~") == 0)
3060 				group = PREC_GROUP_LIKE;
3061 			else
3062 				group = PREC_GROUP_NOT_LIKE;
3063 		}
3064 		else if (aexpr->kind == AEXPR_BETWEEN ||
3065 				 aexpr->kind == AEXPR_BETWEEN_SYM)
3066 		{
3067 			Assert(list_length(aexpr->name) == 1);
3068 			*nodename = strVal(linitial(aexpr->name));
3069 			group = PREC_GROUP_BETWEEN;
3070 		}
3071 		else if (aexpr->kind == AEXPR_NOT_BETWEEN ||
3072 				 aexpr->kind == AEXPR_NOT_BETWEEN_SYM)
3073 		{
3074 			Assert(list_length(aexpr->name) == 1);
3075 			*nodename = strVal(linitial(aexpr->name));
3076 			group = PREC_GROUP_NOT_BETWEEN;
3077 		}
3078 	}
3079 	else if (IsA(node, NullTest) ||
3080 			 IsA(node, BooleanTest))
3081 	{
3082 		*nodename = "IS";
3083 		group = PREC_GROUP_POSTFIX_IS;
3084 	}
3085 	else if (IsA(node, XmlExpr))
3086 	{
3087 		XmlExpr    *x = (XmlExpr *) node;
3088 
3089 		if (x->op == IS_DOCUMENT)
3090 		{
3091 			*nodename = "IS";
3092 			group = PREC_GROUP_POSTFIX_IS;
3093 		}
3094 	}
3095 	else if (IsA(node, SubLink))
3096 	{
3097 		SubLink    *s = (SubLink *) node;
3098 
3099 		if (s->subLinkType == ANY_SUBLINK ||
3100 			s->subLinkType == ALL_SUBLINK)
3101 		{
3102 			if (s->operName == NIL)
3103 			{
3104 				*nodename = "IN";
3105 				group = PREC_GROUP_IN;
3106 			}
3107 			else
3108 			{
3109 				*nodename = strVal(llast(s->operName));
3110 				group = PREC_GROUP_POSTFIX_OP;
3111 			}
3112 		}
3113 	}
3114 	else if (IsA(node, BoolExpr))
3115 	{
3116 		/*
3117 		 * Must dig into NOTs to see if it's IS NOT DOCUMENT or NOT IN.  This
3118 		 * opens us to possibly misrecognizing, eg, NOT (x IS DOCUMENT) as a
3119 		 * problematic construct.  We can tell the difference by checking
3120 		 * whether the parse locations of the two nodes are identical.
3121 		 *
3122 		 * Note that when we are comparing the child node to its own children,
3123 		 * we will not know that it was a NOT.  Fortunately, that doesn't
3124 		 * matter for these cases.
3125 		 */
3126 		BoolExpr   *b = (BoolExpr *) node;
3127 
3128 		if (b->boolop == NOT_EXPR)
3129 		{
3130 			Node	   *child = (Node *) linitial(b->args);
3131 
3132 			if (IsA(child, XmlExpr))
3133 			{
3134 				XmlExpr    *x = (XmlExpr *) child;
3135 
3136 				if (x->op == IS_DOCUMENT &&
3137 					x->location == b->location)
3138 				{
3139 					*nodename = "IS";
3140 					group = PREC_GROUP_POSTFIX_IS;
3141 				}
3142 			}
3143 			else if (IsA(child, SubLink))
3144 			{
3145 				SubLink    *s = (SubLink *) child;
3146 
3147 				if (s->subLinkType == ANY_SUBLINK && s->operName == NIL &&
3148 					s->location == b->location)
3149 				{
3150 					*nodename = "IN";
3151 					group = PREC_GROUP_NOT_IN;
3152 				}
3153 			}
3154 		}
3155 	}
3156 	return group;
3157 }
3158 
3159 /*
3160  * helper routine for delivering 9.4-to-9.5 operator precedence warnings
3161  *
3162  * opgroup/opname/location represent some parent node
3163  * lchild, rchild are its left and right children (either could be NULL)
3164  *
3165  * This should be called before transforming the child nodes, since if a
3166  * precedence-driven parsing change has occurred in a query that used to work,
3167  * it's quite possible that we'll get a semantic failure while analyzing the
3168  * child expression.  We want to produce the warning before that happens.
3169  * In any case, operator_precedence_group() expects untransformed input.
3170  */
3171 static void
emit_precedence_warnings(ParseState * pstate,int opgroup,const char * opname,Node * lchild,Node * rchild,int location)3172 emit_precedence_warnings(ParseState *pstate,
3173 						 int opgroup, const char *opname,
3174 						 Node *lchild, Node *rchild,
3175 						 int location)
3176 {
3177 	int			cgroup;
3178 	const char *copname;
3179 
3180 	Assert(opgroup > 0);
3181 
3182 	/*
3183 	 * Complain if left child, which should be same or higher precedence
3184 	 * according to current rules, used to be lower precedence.
3185 	 *
3186 	 * Exception to precedence rules: if left child is IN or NOT IN or a
3187 	 * postfix operator, the grouping is syntactically forced regardless of
3188 	 * precedence.
3189 	 */
3190 	cgroup = operator_precedence_group(lchild, &copname);
3191 	if (cgroup > 0)
3192 	{
3193 		if (oldprecedence_l[cgroup] < oldprecedence_r[opgroup] &&
3194 			cgroup != PREC_GROUP_IN &&
3195 			cgroup != PREC_GROUP_NOT_IN &&
3196 			cgroup != PREC_GROUP_POSTFIX_OP &&
3197 			cgroup != PREC_GROUP_POSTFIX_IS)
3198 			ereport(WARNING,
3199 					(errmsg("operator precedence change: %s is now lower precedence than %s",
3200 							opname, copname),
3201 					 parser_errposition(pstate, location)));
3202 	}
3203 
3204 	/*
3205 	 * Complain if right child, which should be higher precedence according to
3206 	 * current rules, used to be same or lower precedence.
3207 	 *
3208 	 * Exception to precedence rules: if right child is a prefix operator, the
3209 	 * grouping is syntactically forced regardless of precedence.
3210 	 */
3211 	cgroup = operator_precedence_group(rchild, &copname);
3212 	if (cgroup > 0)
3213 	{
3214 		if (oldprecedence_r[cgroup] <= oldprecedence_l[opgroup] &&
3215 			cgroup != PREC_GROUP_PREFIX_OP)
3216 			ereport(WARNING,
3217 					(errmsg("operator precedence change: %s is now lower precedence than %s",
3218 							opname, copname),
3219 					 parser_errposition(pstate, location)));
3220 	}
3221 }
3222 
3223 /*
3224  * Produce a string identifying an expression by kind.
3225  *
3226  * Note: when practical, use a simple SQL keyword for the result.  If that
3227  * doesn't work well, check call sites to see whether custom error message
3228  * strings are required.
3229  */
3230 const char *
ParseExprKindName(ParseExprKind exprKind)3231 ParseExprKindName(ParseExprKind exprKind)
3232 {
3233 	switch (exprKind)
3234 	{
3235 		case EXPR_KIND_NONE:
3236 			return "invalid expression context";
3237 		case EXPR_KIND_OTHER:
3238 			return "extension expression";
3239 		case EXPR_KIND_JOIN_ON:
3240 			return "JOIN/ON";
3241 		case EXPR_KIND_JOIN_USING:
3242 			return "JOIN/USING";
3243 		case EXPR_KIND_FROM_SUBSELECT:
3244 			return "sub-SELECT in FROM";
3245 		case EXPR_KIND_FROM_FUNCTION:
3246 			return "function in FROM";
3247 		case EXPR_KIND_WHERE:
3248 			return "WHERE";
3249 		case EXPR_KIND_POLICY:
3250 			return "POLICY";
3251 		case EXPR_KIND_HAVING:
3252 			return "HAVING";
3253 		case EXPR_KIND_FILTER:
3254 			return "FILTER";
3255 		case EXPR_KIND_WINDOW_PARTITION:
3256 			return "window PARTITION BY";
3257 		case EXPR_KIND_WINDOW_ORDER:
3258 			return "window ORDER BY";
3259 		case EXPR_KIND_WINDOW_FRAME_RANGE:
3260 			return "window RANGE";
3261 		case EXPR_KIND_WINDOW_FRAME_ROWS:
3262 			return "window ROWS";
3263 		case EXPR_KIND_SELECT_TARGET:
3264 			return "SELECT";
3265 		case EXPR_KIND_INSERT_TARGET:
3266 			return "INSERT";
3267 		case EXPR_KIND_UPDATE_SOURCE:
3268 		case EXPR_KIND_UPDATE_TARGET:
3269 			return "UPDATE";
3270 		case EXPR_KIND_GROUP_BY:
3271 			return "GROUP BY";
3272 		case EXPR_KIND_ORDER_BY:
3273 			return "ORDER BY";
3274 		case EXPR_KIND_DISTINCT_ON:
3275 			return "DISTINCT ON";
3276 		case EXPR_KIND_LIMIT:
3277 			return "LIMIT";
3278 		case EXPR_KIND_OFFSET:
3279 			return "OFFSET";
3280 		case EXPR_KIND_RETURNING:
3281 			return "RETURNING";
3282 		case EXPR_KIND_VALUES:
3283 			return "VALUES";
3284 		case EXPR_KIND_CHECK_CONSTRAINT:
3285 		case EXPR_KIND_DOMAIN_CHECK:
3286 			return "CHECK";
3287 		case EXPR_KIND_COLUMN_DEFAULT:
3288 		case EXPR_KIND_FUNCTION_DEFAULT:
3289 			return "DEFAULT";
3290 		case EXPR_KIND_INDEX_EXPRESSION:
3291 			return "index expression";
3292 		case EXPR_KIND_INDEX_PREDICATE:
3293 			return "index predicate";
3294 		case EXPR_KIND_ALTER_COL_TRANSFORM:
3295 			return "USING";
3296 		case EXPR_KIND_EXECUTE_PARAMETER:
3297 			return "EXECUTE";
3298 		case EXPR_KIND_TRIGGER_WHEN:
3299 			return "WHEN";
3300 
3301 			/*
3302 			 * There is intentionally no default: case here, so that the
3303 			 * compiler will warn if we add a new ParseExprKind without
3304 			 * extending this switch.  If we do see an unrecognized value at
3305 			 * runtime, we'll fall through to the "unrecognized" return.
3306 			 */
3307 	}
3308 	return "unrecognized expression kind";
3309 }
3310