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