parse_expr.c 59.6 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * parse_expr.c
 *	  handle expressions in parser
 *
6
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/parser/parse_expr.c,v 1.233 2008/08/30 01:39:14 tgl Exp $
12 13 14 15 16
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"
17

18
#include "catalog/pg_type.h"
Tom Lane's avatar
Tom Lane committed
19
#include "commands/dbcommands.h"
20
#include "miscadmin.h"
21
#include "nodes/makefuncs.h"
22
#include "nodes/nodeFuncs.h"
23
#include "parser/analyze.h"
Bruce Momjian's avatar
Bruce Momjian committed
24
#include "parser/parse_coerce.h"
25 26
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
27
#include "parser/parse_oper.h"
28
#include "parser/parse_relation.h"
29
#include "parser/parse_target.h"
Bruce Momjian's avatar
Bruce Momjian committed
30
#include "parser/parse_type.h"
31
#include "utils/builtins.h"
32
#include "utils/lsyscache.h"
33
#include "utils/xml.h"
34

35

36 37
bool		Transform_null_equals = false;

38 39 40 41 42 43 44 45 46 47
static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
static Node *transformAExprAnd(ParseState *pstate, A_Expr *a);
static Node *transformAExprOr(ParseState *pstate, A_Expr *a);
static Node *transformAExprNot(ParseState *pstate, A_Expr *a);
static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
static Node *transformAExprOf(ParseState *pstate, A_Expr *a);
48
static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
49 50 51
static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
52 53
static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
				   Oid array_type, Oid element_type, int32 typmod);
54 55
static Node *transformRowExpr(ParseState *pstate, RowExpr *r);
static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
56
static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
57 58
static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
59
static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
60
static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
61
static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
62
static Node *transformWholeRowRef(ParseState *pstate, char *schemaname,
63
					 char *relname, int location);
64
static Node *transformIndirection(ParseState *pstate, Node *basenode,
65
					 List *indirection);
66
static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
67
static Node *make_row_comparison_op(ParseState *pstate, List *opname,
Bruce Momjian's avatar
Bruce Momjian committed
68
					   List *largs, List *rargs, int location);
69
static Node *make_row_distinct_op(ParseState *pstate, List *opname,
70
					 RowExpr *lrow, RowExpr *rrow, int location);
71
static Expr *make_distinct_op(ParseState *pstate, List *opname,
72
				 Node *ltree, Node *rtree, int location);
73

74

75 76
/*
 * transformExpr -
77
 *	  Analyze and transform expressions. Type checking and type casting is
78 79 80
 *	  done here. The optimizer and the executor cannot handle the original
 *	  (raw) expressions collected by the parse tree. Hence the transformation
 *	  here.
81 82
 *
 * NOTE: there are various cases in which this routine will get applied to
83 84 85 86 87
 * an already-transformed expression.  Some examples:
 *	1. At least one construct (BETWEEN/AND) puts the same nodes
 *	into two branches of the parse tree; hence, some nodes
 *	are transformed twice.
 *	2. Another way it can happen is that coercion of an operator or
88 89 90 91 92 93 94 95 96 97
 *	function argument to the required type (via coerce_type())
 *	can apply transformExpr to an already-transformed subexpression.
 *	An example here is "SELECT count(*) + 1.0 FROM table".
 * While it might be possible to eliminate these cases, the path of
 * least resistance so far has been to ensure that transformExpr() does
 * no damage if applied to an already-transformed tree.  This is pretty
 * easy for cases where the transformation replaces one node type with
 * another, such as A_Const => Const; we just do nothing when handed
 * a Const.  More care is needed for node types that are used as both
 * input and output of transformExpr; see SubLink for example.
98 99
 */
Node *
100
transformExpr(ParseState *pstate, Node *expr)
101 102 103 104 105 106
{
	Node	   *result = NULL;

	if (expr == NULL)
		return NULL;

107 108
	/* Guard against stack overflow due to overly complex expressions */
	check_stack_depth();
109

110 111
	switch (nodeTag(expr))
	{
112
		case T_ColumnRef:
113 114
			result = transformColumnRef(pstate, (ColumnRef *) expr);
			break;
115

116 117 118
		case T_ParamRef:
			result = transformParamRef(pstate, (ParamRef *) expr);
			break;
119

120 121 122 123 124
		case T_A_Const:
			{
				A_Const    *con = (A_Const *) expr;
				Value	   *val = &con->val;

125
				result = (Node *) make_const(val, con->location);
126 127
				break;
			}
128

129
		case T_A_Indirection:
130
			{
Bruce Momjian's avatar
Bruce Momjian committed
131
				A_Indirection *ind = (A_Indirection *) expr;
132

133
				result = transformExpr(pstate, ind->arg);
134
				result = transformIndirection(pstate, result,
135
											  ind->indirection);
136 137
				break;
			}
138

139 140 141 142 143
		case T_A_ArrayExpr:
			result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
										InvalidOid, InvalidOid, -1);
			break;

144 145 146
		case T_TypeCast:
			{
				TypeCast   *tc = (TypeCast *) expr;
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

				/*
				 * If the subject of the typecast is an ARRAY[] construct
				 * and the target type is an array type, we invoke
				 * transformArrayExpr() directly so that we can pass down
				 * the type information.  This avoids some cases where
				 * transformArrayExpr() might not infer the correct type.
				 */
				if (IsA(tc->arg, A_ArrayExpr))
				{
					Oid			targetType;
					Oid			elementType;
					int32		targetTypmod;

					targetType = typenameTypeId(pstate, tc->typename,
												&targetTypmod);
					elementType = get_element_type(targetType);
					if (OidIsValid(elementType))
					{
						result = transformArrayExpr(pstate,
													(A_ArrayExpr *) tc->arg,
													targetType,
													elementType,
													targetTypmod);
						break;
					}

					/*
					 * Corner case: ARRAY[] cast to a non-array type.
					 * Fall through to do it the standard way.
					 */
				}
179

180
				result = transformTypeCast(pstate, tc);
181 182
				break;
			}
183

184 185 186 187
		case T_A_Expr:
			{
				A_Expr	   *a = (A_Expr *) expr;

188
				switch (a->kind)
189
				{
190
					case AEXPR_OP:
191
						result = transformAExprOp(pstate, a);
192
						break;
193
					case AEXPR_AND:
194
						result = transformAExprAnd(pstate, a);
195
						break;
196
					case AEXPR_OR:
197
						result = transformAExprOr(pstate, a);
198
						break;
199
					case AEXPR_NOT:
200
						result = transformAExprNot(pstate, a);
201
						break;
202
					case AEXPR_OP_ANY:
203
						result = transformAExprOpAny(pstate, a);
204 205
						break;
					case AEXPR_OP_ALL:
206
						result = transformAExprOpAll(pstate, a);
207
						break;
208
					case AEXPR_DISTINCT:
209
						result = transformAExprDistinct(pstate, a);
210
						break;
211
					case AEXPR_NULLIF:
212
						result = transformAExprNullIf(pstate, a);
213
						break;
214
					case AEXPR_OF:
215
						result = transformAExprOf(pstate, a);
216
						break;
217 218 219
					case AEXPR_IN:
						result = transformAExprIn(pstate, a);
						break;
220 221
					default:
						elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
222 223 224
				}
				break;
			}
225

226
		case T_FuncCall:
227 228
			result = transformFuncCall(pstate, (FuncCall *) expr);
			break;
229

230
		case T_SubLink:
231 232
			result = transformSubLink(pstate, (SubLink *) expr);
			break;
233

234
		case T_CaseExpr:
235 236
			result = transformCaseExpr(pstate, (CaseExpr *) expr);
			break;
237

238
		case T_RowExpr:
239 240
			result = transformRowExpr(pstate, (RowExpr *) expr);
			break;
241

242
		case T_CoalesceExpr:
243 244
			result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
			break;
245

246 247 248 249
		case T_MinMaxExpr:
			result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
			break;

250 251 252 253
		case T_XmlExpr:
			result = transformXmlExpr(pstate, (XmlExpr *) expr);
			break;

254 255 256 257
		case T_XmlSerialize:
			result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
			break;

258 259 260 261
		case T_NullTest:
			{
				NullTest   *n = (NullTest *) expr;

262
				n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
263 264 265 266 267 268
				/* the argument can be any type, so don't coerce it */
				result = expr;
				break;
			}

		case T_BooleanTest:
269 270
			result = transformBooleanTest(pstate, (BooleanTest *) expr);
			break;
271

272
		case T_CurrentOfExpr:
273 274
			result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
			break;
275

Bruce Momjian's avatar
Bruce Momjian committed
276 277 278 279 280 281 282 283
			/*********************************************
			 * Quietly accept node types that may be presented when we are
			 * called on an already-transformed tree.
			 *
			 * Do any other node types need to be accepted?  For now we are
			 * taking a conservative approach, and only accepting node
			 * types that are demonstrably necessary to accept.
			 *********************************************/
284 285
		case T_Var:
		case T_Const:
286
		case T_Param:
287 288
		case T_Aggref:
		case T_ArrayRef:
289 290 291
		case T_FuncExpr:
		case T_OpExpr:
		case T_DistinctExpr:
292
		case T_ScalarArrayOpExpr:
293
		case T_NullIfExpr:
294
		case T_BoolExpr:
295
		case T_FieldSelect:
296
		case T_FieldStore:
297
		case T_RelabelType:
298
		case T_CoerceViaIO:
299
		case T_ArrayCoerceExpr:
300
		case T_ConvertRowtypeExpr:
301
		case T_CaseTestExpr:
302 303
		case T_CoerceToDomain:
		case T_CoerceToDomainValue:
304
		case T_SetToDefault:
305 306 307 308
			{
				result = (Node *) expr;
				break;
			}
309

310 311
		default:
			/* should not reach here */
312
			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
313 314 315 316 317 318
			break;
	}

	return result;
}

319
static Node *
320
transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
321
{
322 323 324 325 326 327
	Node	   *result = basenode;
	List	   *subscripts = NIL;
	ListCell   *i;

	/*
	 * We have to split any field-selection operations apart from
328 329
	 * subscripting.  Adjacent A_Indices nodes have to be treated as a single
	 * multidimensional subscript operation.
330 331 332
	 */
	foreach(i, indirection)
	{
Bruce Momjian's avatar
Bruce Momjian committed
333
		Node	   *n = lfirst(i);
334 335 336

		if (IsA(n, A_Indices))
			subscripts = lappend(subscripts, n);
337 338 339 340 341 342 343
		else if (IsA(n, A_Star))
		{
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("row expansion via \"*\" is not supported here"),
					 parser_errposition(pstate, exprLocation(basenode))));
		}
344 345 346 347 348 349 350 351
		else
		{
			Assert(IsA(n, String));

			/* process subscripts before this field selection */
			if (subscripts)
				result = (Node *) transformArraySubscripts(pstate,
														   result,
352
														   exprType(result),
353
														   InvalidOid,
354
														   exprTypmod(result),
355 356 357 358 359 360 361
														   subscripts,
														   NULL);
			subscripts = NIL;

			result = ParseFuncOrColumn(pstate,
									   list_make1(n),
									   list_make1(result),
362 363
									   false, false, false,
									   true, -1);
364 365 366 367 368 369 370 371
		}
	}
	/* process trailing subscripts, if any */
	if (subscripts)
		result = (Node *) transformArraySubscripts(pstate,
												   result,
												   exprType(result),
												   InvalidOid,
372
												   exprTypmod(result),
373 374 375 376
												   subscripts,
												   NULL);

	return result;
377
}
378

379
static Node *
380
transformColumnRef(ParseState *pstate, ColumnRef *cref)
381
{
382
	int			numnames = list_length(cref->fields);
383
	Node	   *node;
384
	int			levels_up;
385 386 387 388 389

	/*----------
	 * The allowed syntaxes are:
	 *
	 * A		First try to resolve as unqualified column name;
390 391
	 *			if no luck, try to resolve as unqualified table name (A.*).
	 * A.B		A is an unqualified table name; B is either a
392 393 394
	 *			column or function name (trying column name first).
	 * A.B.C	schema A, table B, col or func name C.
	 * A.B.C.D	catalog A, schema B, table C, col or func D.
395
	 * A.*		A is an unqualified table name; means whole-row value.
396 397 398 399 400
	 * A.B.*	whole-row value of table B in schema A.
	 * A.B.C.*	whole-row value of table C in schema B in catalog A.
	 *
	 * We do not need to cope with bare "*"; that will only be accepted by
	 * the grammar at the top level of a SELECT list, and transformTargetList
401 402 403
	 * will take care of it before it ever gets here.  Also, "A.*" etc will
	 * be expanded by transformTargetList if they appear at SELECT top level,
	 * so here we are only going to see them as function or operator inputs.
404 405 406 407 408 409 410 411
	 *
	 * Currently, if a catalog name is given then it must equal the current
	 * database name; we check it here and then discard it.
	 *----------
	 */
	switch (numnames)
	{
		case 1:
Bruce Momjian's avatar
Bruce Momjian committed
412
			{
413 414 415 416 417
				Node	   *field1 = (Node *) linitial(cref->fields);
				char	   *name1;

				Assert(IsA(field1, String));
				name1 = strVal(field1);
418

Bruce Momjian's avatar
Bruce Momjian committed
419
				/* Try to identify as an unqualified column */
420
				node = colNameToVar(pstate, name1, false, cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
421 422 423 424

				if (node == NULL)
				{
					/*
425 426
					 * Not known as a column of any range-table entry.
					 *
427 428 429 430
					 * Consider the possibility that it's VALUE in a domain
					 * check expression.  (We handle VALUE as a name, not a
					 * keyword, to avoid breaking a lot of applications that
					 * have used VALUE as a column name in the past.)
431 432
					 */
					if (pstate->p_value_substitute != NULL &&
433
						strcmp(name1, "value") == 0)
434 435
					{
						node = (Node *) copyObject(pstate->p_value_substitute);
436 437 438 439 440 441 442 443

						/*
						 * Try to propagate location knowledge.  This should
						 * be extended if p_value_substitute can ever take on
						 * other node types.
						 */
						if (IsA(node, CoerceToDomainValue))
							((CoerceToDomainValue *) node)->location = cref->location;
444 445 446 447
						break;
					}

					/*
Bruce Momjian's avatar
Bruce Momjian committed
448
					 * Try to find the name as a relation.	Note that only
449 450
					 * relations already entered into the rangetable will be
					 * recognized.
Bruce Momjian's avatar
Bruce Momjian committed
451 452
					 *
					 * This is a hack for backwards compatibility with
453 454
					 * PostQUEL-inspired syntax.  The preferred form now is
					 * "rel.*".
Bruce Momjian's avatar
Bruce Momjian committed
455
					 */
456
					if (refnameRangeTblEntry(pstate, NULL, name1,
Bruce Momjian's avatar
Bruce Momjian committed
457
											 &levels_up) != NULL)
458
						node = transformWholeRowRef(pstate, NULL, name1,
459
													cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
460
					else
461 462
						ereport(ERROR,
								(errcode(ERRCODE_UNDEFINED_COLUMN),
463
								 errmsg("column \"%s\" does not exist",
464
										name1),
465
								 parser_errposition(pstate, cref->location)));
Bruce Momjian's avatar
Bruce Momjian committed
466 467 468 469
				}
				break;
			}
		case 2:
470
			{
471 472 473 474 475 476 477
				Node	   *field1 = (Node *) linitial(cref->fields);
				Node	   *field2 = (Node *) lsecond(cref->fields);
				char	   *name1;
				char	   *name2;

				Assert(IsA(field1, String));
				name1 = strVal(field1);
478

Bruce Momjian's avatar
Bruce Momjian committed
479
				/* Whole-row reference? */
480
				if (IsA(field2, A_Star))
481
				{
482 483
					node = transformWholeRowRef(pstate, NULL, name1,
												cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
484
					break;
485
				}
486

487 488 489
				Assert(IsA(field2, String));
				name2 = strVal(field2);

Bruce Momjian's avatar
Bruce Momjian committed
490
				/* Try to identify as a once-qualified column */
491 492
				node = qualifiedNameToVar(pstate, NULL, name1, name2, true,
										  cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
493 494 495
				if (node == NULL)
				{
					/*
496 497
					 * Not known as a column of any range-table entry, so try
					 * it as a function call.  Here, we will create an
Bruce Momjian's avatar
Bruce Momjian committed
498 499
					 * implicit RTE for tables not already entered.
					 */
500 501
					node = transformWholeRowRef(pstate, NULL, name1,
												cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
502
					node = ParseFuncOrColumn(pstate,
503
											 list_make1(makeString(name2)),
504
											 list_make1(node),
505 506
											 false, false, false,
											 true, cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
507
				}
508 509 510 511
				break;
			}
		case 3:
			{
512 513 514 515 516 517 518 519 520 521 522
				Node	   *field1 = (Node *) linitial(cref->fields);
				Node	   *field2 = (Node *) lsecond(cref->fields);
				Node	   *field3 = (Node *) lthird(cref->fields);
				char	   *name1;
				char	   *name2;
				char	   *name3;

				Assert(IsA(field1, String));
				name1 = strVal(field1);
				Assert(IsA(field2, String));
				name2 = strVal(field2);
523

Bruce Momjian's avatar
Bruce Momjian committed
524
				/* Whole-row reference? */
525
				if (IsA(field3, A_Star))
Bruce Momjian's avatar
Bruce Momjian committed
526
				{
527 528
					node = transformWholeRowRef(pstate, name1, name2,
												cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
529 530 531
					break;
				}

532 533 534
				Assert(IsA(field3, String));
				name3 = strVal(field3);

Bruce Momjian's avatar
Bruce Momjian committed
535
				/* Try to identify as a twice-qualified column */
536 537
				node = qualifiedNameToVar(pstate, name1, name2, name3, true,
										  cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
538 539 540
				if (node == NULL)
				{
					/* Try it as a function call */
541 542
					node = transformWholeRowRef(pstate, name1, name2,
												cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
543
					node = ParseFuncOrColumn(pstate,
544
											 list_make1(makeString(name3)),
545
											 list_make1(node),
546 547
											 false, false, false,
											 true, cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
548 549
				}
				break;
550 551 552
			}
		case 4:
			{
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
				Node	   *field1 = (Node *) linitial(cref->fields);
				Node	   *field2 = (Node *) lsecond(cref->fields);
				Node	   *field3 = (Node *) lthird(cref->fields);
				Node	   *field4 = (Node *) lfourth(cref->fields);
				char	   *name1;
				char	   *name2;
				char	   *name3;
				char	   *name4;

				Assert(IsA(field1, String));
				name1 = strVal(field1);
				Assert(IsA(field2, String));
				name2 = strVal(field2);
				Assert(IsA(field3, String));
				name3 = strVal(field3);
568

Bruce Momjian's avatar
Bruce Momjian committed
569 570 571
				/*
				 * We check the catalog name and then ignore it.
				 */
572
				if (strcmp(name1, get_database_name(MyDatabaseId)) != 0)
573 574
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
575
							 errmsg("cross-database references are not implemented: %s",
576 577
									NameListToString(cref->fields)),
							 parser_errposition(pstate, cref->location)));
Bruce Momjian's avatar
Bruce Momjian committed
578 579

				/* Whole-row reference? */
580
				if (IsA(field4, A_Star))
Bruce Momjian's avatar
Bruce Momjian committed
581
				{
582 583
					node = transformWholeRowRef(pstate, name2, name3,
												cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
584 585 586
					break;
				}

587 588 589
				Assert(IsA(field4, String));
				name4 = strVal(field4);

Bruce Momjian's avatar
Bruce Momjian committed
590
				/* Try to identify as a twice-qualified column */
591 592
				node = qualifiedNameToVar(pstate, name2, name3, name4, true,
										  cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
593 594 595
				if (node == NULL)
				{
					/* Try it as a function call */
596 597
					node = transformWholeRowRef(pstate, name2, name3,
												cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
598
					node = ParseFuncOrColumn(pstate,
599
											 list_make1(makeString(name4)),
600
											 list_make1(node),
601 602
											 false, false, false,
											 true, cref->location);
Bruce Momjian's avatar
Bruce Momjian committed
603 604
				}
				break;
605 606
			}
		default:
607 608
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
609
				errmsg("improper qualified name (too many dotted names): %s",
610 611
					   NameListToString(cref->fields)),
					 parser_errposition(pstate, cref->location)));
612 613
			node = NULL;		/* keep compiler quiet */
			break;
614 615
	}

616
	return node;
617 618
}

619 620 621 622 623 624
/*
 * Locate the parameter type info for the given parameter number, and
 * return a pointer to it.
 */
static Oid *
find_param_type(ParseState *pstate, int paramno)
625
{
Bruce Momjian's avatar
Bruce Momjian committed
626
	Oid		   *result;
627 628 629 630

	/*
	 * Find topmost ParseState, which is where paramtype info lives.
	 */
631 632
	while (pstate->parentParseState != NULL)
		pstate = pstate->parentParseState;
633 634

	/* Check parameter number is in range */
635
	if (paramno <= 0)			/* probably can't happen? */
636 637 638
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_PARAMETER),
				 errmsg("there is no parameter $%d", paramno)));
639
	if (paramno > pstate->p_numparams)
640
	{
641
		if (!pstate->p_variableparams)
642 643 644 645 646
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_PARAMETER),
					 errmsg("there is no parameter $%d",
							paramno)));
		/* Okay to enlarge param array */
647 648 649
		if (pstate->p_paramtypes)
			pstate->p_paramtypes = (Oid *) repalloc(pstate->p_paramtypes,
													paramno * sizeof(Oid));
650
		else
651
			pstate->p_paramtypes = (Oid *) palloc(paramno * sizeof(Oid));
652
		/* Zero out the previously-unreferenced slots */
653
		MemSet(pstate->p_paramtypes + pstate->p_numparams,
654
			   0,
655 656
			   (paramno - pstate->p_numparams) * sizeof(Oid));
		pstate->p_numparams = paramno;
657
	}
658 659 660 661

	result = &pstate->p_paramtypes[paramno - 1];

	if (pstate->p_variableparams)
662 663
	{
		/* If not seen before, initialize to UNKNOWN type */
664 665
		if (*result == InvalidOid)
			*result = UNKNOWNOID;
666 667
	}

668 669 670 671 672 673 674 675 676 677
	return result;
}

static Node *
transformParamRef(ParseState *pstate, ParamRef *pref)
{
	int			paramno = pref->number;
	Oid		   *pptype = find_param_type(pstate, paramno);
	Param	   *param;

678
	param = makeNode(Param);
679 680
	param->paramkind = PARAM_EXTERN;
	param->paramid = paramno;
681
	param->paramtype = *pptype;
682
	param->paramtypmod = -1;
683
	param->location = pref->location;
684 685 686 687

	return (Node *) param;
}

688 689 690 691 692 693
/* Test whether an a_expr is a plain NULL constant or not */
static bool
exprIsNullConstant(Node *arg)
{
	if (arg && IsA(arg, A_Const))
	{
Bruce Momjian's avatar
Bruce Momjian committed
694
		A_Const    *con = (A_Const *) arg;
695

696
		if (con->val.type == T_Null)
697 698 699 700 701
			return true;
	}
	return false;
}

702 703 704 705 706 707 708 709
static Node *
transformAExprOp(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = a->lexpr;
	Node	   *rexpr = a->rexpr;
	Node	   *result;

	/*
710 711 712
	 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
	 * standards-broken products (like Microsoft's).  Turn these into IS NULL
	 * exprs.
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
	 */
	if (Transform_null_equals &&
		list_length(a->name) == 1 &&
		strcmp(strVal(linitial(a->name)), "=") == 0 &&
		(exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)))
	{
		NullTest   *n = makeNode(NullTest);

		n->nulltesttype = IS_NULL;

		if (exprIsNullConstant(lexpr))
			n->arg = (Expr *) rexpr;
		else
			n->arg = (Expr *) lexpr;

		result = transformExpr(pstate, (Node *) n);
	}
	else if (lexpr && IsA(lexpr, RowExpr) &&
			 rexpr && IsA(rexpr, SubLink) &&
			 ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
	{
		/*
735
		 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
736 737
		 * grammar did this, but now that a row construct is allowed anywhere
		 * in expressions, it's easier to do it here.
738 739 740
		 */
		SubLink    *s = (SubLink *) rexpr;

741 742
		s->subLinkType = ROWCOMPARE_SUBLINK;
		s->testexpr = lexpr;
743
		s->operName = a->name;
744
		s->location = a->location;
745 746 747 748 749 750
		result = transformExpr(pstate, (Node *) s);
	}
	else if (lexpr && IsA(lexpr, RowExpr) &&
			 rexpr && IsA(rexpr, RowExpr))
	{
		/* "row op row" */
751 752 753 754 755
		lexpr = transformExpr(pstate, lexpr);
		rexpr = transformExpr(pstate, rexpr);
		Assert(IsA(lexpr, RowExpr));
		Assert(IsA(rexpr, RowExpr));

756 757 758
		result = make_row_comparison_op(pstate,
										a->name,
										((RowExpr *) lexpr)->args,
759 760
										((RowExpr *) rexpr)->args,
										a->location);
761 762 763 764 765 766 767 768 769 770
	}
	else
	{
		/* Ordinary scalar operator */
		lexpr = transformExpr(pstate, lexpr);
		rexpr = transformExpr(pstate, rexpr);

		result = (Node *) make_op(pstate,
								  a->name,
								  lexpr,
771 772
								  rexpr,
								  a->location);
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
	}

	return result;
}

static Node *
transformAExprAnd(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);

	lexpr = coerce_to_boolean(pstate, lexpr, "AND");
	rexpr = coerce_to_boolean(pstate, rexpr, "AND");

	return (Node *) makeBoolExpr(AND_EXPR,
788 789
								 list_make2(lexpr, rexpr),
								 a->location);
790 791 792 793 794 795 796 797 798 799 800 801
}

static Node *
transformAExprOr(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);

	lexpr = coerce_to_boolean(pstate, lexpr, "OR");
	rexpr = coerce_to_boolean(pstate, rexpr, "OR");

	return (Node *) makeBoolExpr(OR_EXPR,
802 803
								 list_make2(lexpr, rexpr),
								 a->location);
804 805 806 807 808 809 810 811 812 813
}

static Node *
transformAExprNot(ParseState *pstate, A_Expr *a)
{
	Node	   *rexpr = transformExpr(pstate, a->rexpr);

	rexpr = coerce_to_boolean(pstate, rexpr, "NOT");

	return (Node *) makeBoolExpr(NOT_EXPR,
814 815
								 list_make1(rexpr),
								 a->location);
816 817 818 819 820 821 822 823 824 825 826 827
}

static Node *
transformAExprOpAny(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);

	return (Node *) make_scalar_array_op(pstate,
										 a->name,
										 true,
										 lexpr,
828 829
										 rexpr,
										 a->location);
830 831 832 833 834 835 836 837 838 839 840 841
}

static Node *
transformAExprOpAll(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);

	return (Node *) make_scalar_array_op(pstate,
										 a->name,
										 false,
										 lexpr,
842 843
										 rexpr,
										 a->location);
844 845 846 847 848
}

static Node *
transformAExprDistinct(ParseState *pstate, A_Expr *a)
{
849 850
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);
851 852 853 854 855 856

	if (lexpr && IsA(lexpr, RowExpr) &&
		rexpr && IsA(rexpr, RowExpr))
	{
		/* "row op row" */
		return make_row_distinct_op(pstate, a->name,
857
									(RowExpr *) lexpr,
858 859
									(RowExpr *) rexpr,
									a->location);
860 861 862 863 864 865 866
	}
	else
	{
		/* Ordinary scalar operator */
		return (Node *) make_distinct_op(pstate,
										 a->name,
										 lexpr,
867 868
										 rexpr,
										 a->location);
869 870 871 872 873 874 875 876 877 878 879 880 881
	}
}

static Node *
transformAExprNullIf(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);
	Node	   *result;

	result = (Node *) make_op(pstate,
							  a->name,
							  lexpr,
882 883
							  rexpr,
							  a->location);
884 885 886
	if (((OpExpr *) result)->opresulttype != BOOLOID)
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
887 888
				 errmsg("NULLIF requires = operator to yield boolean"),
				 parser_errposition(pstate, a->location)));
889 890 891 892 893 894 895 896 897 898 899 900 901

	/*
	 * We rely on NullIfExpr and OpExpr being the same struct
	 */
	NodeSetTag(result, T_NullIfExpr);

	return result;
}

static Node *
transformAExprOf(ParseState *pstate, A_Expr *a)
{
	/*
Bruce Momjian's avatar
Bruce Momjian committed
902 903
	 * Checking an expression for match to a list of type names. Will result
	 * in a boolean constant node.
904
	 */
905
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
906
	Const	   *result;
907 908 909 910 911 912 913 914
	ListCell   *telem;
	Oid			ltype,
				rtype;
	bool		matched = false;

	ltype = exprType(lexpr);
	foreach(telem, (List *) a->rexpr)
	{
915
		rtype = typenameTypeId(pstate, lfirst(telem), NULL);
916 917 918 919 920 921
		matched = (rtype == ltype);
		if (matched)
			break;
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
922
	 * We have two forms: equals or not equals. Flip the sense of the result
923
	 * for not equals.
924
	 */
925
	if (strcmp(strVal(linitial(a->name)), "<>") == 0)
926 927
		matched = (!matched);

928 929 930 931 932 933
	result = (Const *) makeBoolConst(matched, false);

	/* Make the result have the original input's parse location */
	result->location = exprLocation((Node *) a);

	return (Node *) result;
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
}

static Node *
transformAExprIn(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr;
	List	   *rexprs;
	bool		useOr;
	bool		haveRowExpr;
	Node	   *result;
	ListCell   *l;

	/*
	 * If the operator is <>, combine with AND not OR.
	 */
	if (strcmp(strVal(linitial(a->name)), "<>") == 0)
		useOr = false;
	else
		useOr = true;

	/*
Bruce Momjian's avatar
Bruce Momjian committed
955 956 957 958
	 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
	 * possible if the inputs are all scalars (no RowExprs) and there is a
	 * suitable array type available.  If not, we fall back to a boolean
	 * condition tree with multiple copies of the lefthand expression.
959 960 961 962 963 964 965 966 967
	 *
	 * First step: transform all the inputs, and detect whether any are
	 * RowExprs.
	 */
	lexpr = transformExpr(pstate, a->lexpr);
	haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
	rexprs = NIL;
	foreach(l, (List *) a->rexpr)
	{
Bruce Momjian's avatar
Bruce Momjian committed
968
		Node	   *rexpr = transformExpr(pstate, lfirst(l));
969 970 971 972

		haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
		rexprs = lappend(rexprs, rexpr);
	}
973

974
	/*
Bruce Momjian's avatar
Bruce Momjian committed
975 976 977 978
	 * If not forced by presence of RowExpr, try to resolve a common scalar
	 * type for all the expressions, and see if it has an array type. (But if
	 * there's only one righthand expression, we may as well just fall through
	 * and generate a simple = comparison.)
979 980 981
	 */
	if (!haveRowExpr && list_length(rexprs) != 1)
	{
982
		List	   *allexprs;
983 984 985 986
		Oid			scalar_type;
		Oid			array_type;

		/*
Bruce Momjian's avatar
Bruce Momjian committed
987 988 989
		 * Select a common type for the array elements.  Note that since the
		 * LHS' type is first in the list, it will be preferred when there is
		 * doubt (eg, when all the RHS items are unknown literals).
990 991
		 *
		 * Note: use list_concat here not lcons, to avoid damaging rexprs.
992
		 */
993 994
		allexprs = list_concat(list_make1(lexpr), rexprs);
		scalar_type = select_common_type(pstate, allexprs, "IN", NULL);
995 996 997 998 999 1000

		/* Do we have an array type to use? */
		array_type = get_array_type(scalar_type);
		if (array_type != InvalidOid)
		{
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1001 1002
			 * OK: coerce all the right-hand inputs to the common type and
			 * build an ArrayExpr for them.
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
			 */
			List	   *aexprs;
			ArrayExpr  *newa;

			aexprs = NIL;
			foreach(l, rexprs)
			{
				Node	   *rexpr = (Node *) lfirst(l);

				rexpr = coerce_to_common_type(pstate, rexpr,
											  scalar_type,
											  "IN");
				aexprs = lappend(aexprs, rexpr);
			}
			newa = makeNode(ArrayExpr);
			newa->array_typeid = array_type;
			newa->element_typeid = scalar_type;
			newa->elements = aexprs;
			newa->multidims = false;
1022
			newa->location = -1;
1023 1024 1025 1026 1027

			return (Node *) make_scalar_array_op(pstate,
												 a->name,
												 useOr,
												 lexpr,
1028 1029
												 (Node *) newa,
												 a->location);
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
		}
	}

	/*
	 * Must do it the hard way, ie, with a boolean expression tree.
	 */
	result = NULL;
	foreach(l, rexprs)
	{
		Node	   *rexpr = (Node *) lfirst(l);
		Node	   *cmp;

		if (haveRowExpr)
		{
			if (!IsA(lexpr, RowExpr) ||
				!IsA(rexpr, RowExpr))
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1048
				   errmsg("arguments of row IN must all be row expressions"),
1049
						 parser_errposition(pstate, a->location)));
1050 1051
			cmp = make_row_comparison_op(pstate,
										 a->name,
Bruce Momjian's avatar
Bruce Momjian committed
1052
							  (List *) copyObject(((RowExpr *) lexpr)->args),
1053 1054
										 ((RowExpr *) rexpr)->args,
										 a->location);
1055 1056 1057 1058 1059
		}
		else
			cmp = (Node *) make_op(pstate,
								   a->name,
								   copyObject(lexpr),
1060 1061
								   rexpr,
								   a->location);
1062 1063 1064 1065 1066 1067

		cmp = coerce_to_boolean(pstate, cmp, "IN");
		if (result == NULL)
			result = cmp;
		else
			result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1068 1069
										   list_make2(result, cmp),
										   a->location);
1070 1071 1072
	}

	return result;
1073 1074 1075 1076 1077 1078 1079 1080
}

static Node *
transformFuncCall(ParseState *pstate, FuncCall *fn)
{
	List	   *targs;
	ListCell   *args;

1081 1082 1083
	/* Transform the list of arguments ... */
	targs = NIL;
	foreach(args, fn->args)
1084
	{
1085 1086
		targs = lappend(targs, transformExpr(pstate,
											 (Node *) lfirst(args)));
1087 1088
	}

1089
	/* ... and hand off to ParseFuncOrColumn */
1090 1091 1092 1093 1094
	return ParseFuncOrColumn(pstate,
							 fn->funcname,
							 targs,
							 fn->agg_star,
							 fn->agg_distinct,
1095
							 fn->func_variadic,
1096 1097
							 false,
							 fn->location);
1098 1099 1100 1101 1102 1103 1104 1105 1106
}

static Node *
transformCaseExpr(ParseState *pstate, CaseExpr *c)
{
	CaseExpr   *newc;
	Node	   *arg;
	CaseTestExpr *placeholder;
	List	   *newargs;
1107
	List	   *resultexprs;
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
	ListCell   *l;
	Node	   *defresult;
	Oid			ptype;

	/* If we already transformed this node, do nothing */
	if (OidIsValid(c->casetype))
		return (Node *) c;

	newc = makeNode(CaseExpr);

	/* transform the test expression, if any */
	arg = transformExpr(pstate, (Node *) c->arg);

	/* generate placeholder for test expression */
	if (arg)
	{
		/*
1125 1126 1127 1128 1129
		 * If test expression is an untyped literal, force it to text. We have
		 * to do something now because we won't be able to do this coercion on
		 * the placeholder.  This is not as flexible as what was done in 7.4
		 * and before, but it's good enough to handle the sort of silly coding
		 * commonly seen.
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
		 */
		if (exprType(arg) == UNKNOWNOID)
			arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");

		placeholder = makeNode(CaseTestExpr);
		placeholder->typeId = exprType(arg);
		placeholder->typeMod = exprTypmod(arg);
	}
	else
		placeholder = NULL;

	newc->arg = (Expr *) arg;

	/* transform the list of arguments */
	newargs = NIL;
1145
	resultexprs = NIL;
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	foreach(l, c->args)
	{
		CaseWhen   *w = (CaseWhen *) lfirst(l);
		CaseWhen   *neww = makeNode(CaseWhen);
		Node	   *warg;

		Assert(IsA(w, CaseWhen));

		warg = (Node *) w->expr;
		if (placeholder)
		{
			/* shorthand form was specified, so expand... */
			warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
											 (Node *) placeholder,
1160
											 warg,
1161
											 w->location);
1162 1163 1164 1165 1166 1167 1168 1169 1170
		}
		neww->expr = (Expr *) transformExpr(pstate, warg);

		neww->expr = (Expr *) coerce_to_boolean(pstate,
												(Node *) neww->expr,
												"CASE/WHEN");

		warg = (Node *) w->result;
		neww->result = (Expr *) transformExpr(pstate, warg);
1171
		neww->location = w->location;
1172 1173

		newargs = lappend(newargs, neww);
1174
		resultexprs = lappend(resultexprs, neww->result);
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
	}

	newc->args = newargs;

	/* transform the default clause */
	defresult = (Node *) c->defresult;
	if (defresult == NULL)
	{
		A_Const    *n = makeNode(A_Const);

		n->val.type = T_Null;
1186
		n->location = -1;
1187 1188 1189 1190 1191 1192
		defresult = (Node *) n;
	}
	newc->defresult = (Expr *) transformExpr(pstate, defresult);

	/*
	 * Note: default result is considered the most significant type in
1193 1194
	 * determining preferred type. This is how the code worked before, but it
	 * seems a little bogus to me --- tgl
1195
	 */
1196
	resultexprs = lcons(newc->defresult, resultexprs);
1197

1198
	ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
	Assert(OidIsValid(ptype));
	newc->casetype = ptype;

	/* Convert default result clause, if necessary */
	newc->defresult = (Expr *)
		coerce_to_common_type(pstate,
							  (Node *) newc->defresult,
							  ptype,
							  "CASE/ELSE");

	/* Convert when-clause results, if necessary */
	foreach(l, newc->args)
	{
		CaseWhen   *w = (CaseWhen *) lfirst(l);

		w->result = (Expr *)
			coerce_to_common_type(pstate,
								  (Node *) w->result,
								  ptype,
								  "CASE/WHEN");
	}

1221 1222
	newc->location = c->location;

1223 1224 1225 1226 1227 1228 1229
	return (Node *) newc;
}

static Node *
transformSubLink(ParseState *pstate, SubLink *sublink)
{
	Node	   *result = (Node *) sublink;
1230
	Query	   *qtree;
1231 1232 1233 1234 1235 1236

	/* If we already transformed this node, do nothing */
	if (IsA(sublink->subselect, Query))
		return result;

	pstate->p_hasSubLinks = true;
1237
	qtree = parse_sub_analyze(sublink->subselect, pstate);
1238
	if (qtree->commandType != CMD_SELECT ||
1239 1240
		qtree->utilityStmt != NULL ||
		qtree->intoClause != NULL)
1241 1242 1243 1244 1245 1246
		elog(ERROR, "bad query in sub-select");
	sublink->subselect = (Node *) qtree;

	if (sublink->subLinkType == EXISTS_SUBLINK)
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1247 1248
		 * EXISTS needs no test expression or combining operator. These fields
		 * should be null already, but make sure.
1249
		 */
1250
		sublink->testexpr = NULL;
1251 1252 1253 1254 1255 1256 1257 1258
		sublink->operName = NIL;
	}
	else if (sublink->subLinkType == EXPR_SUBLINK ||
			 sublink->subLinkType == ARRAY_SUBLINK)
	{
		ListCell   *tlist_item = list_head(qtree->targetList);

		/*
1259 1260
		 * Make sure the subselect delivers a single column (ignoring resjunk
		 * targets).
1261 1262
		 */
		if (tlist_item == NULL ||
1263
			((TargetEntry *) lfirst(tlist_item))->resjunk)
1264 1265
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
1266 1267
					 errmsg("subquery must return a column"),
					 parser_errposition(pstate, sublink->location)));
1268 1269
		while ((tlist_item = lnext(tlist_item)) != NULL)
		{
1270
			if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1271 1272
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
1273 1274
						 errmsg("subquery must return only one column"),
						 parser_errposition(pstate, sublink->location)));
1275 1276 1277
		}

		/*
Bruce Momjian's avatar
Bruce Momjian committed
1278 1279
		 * EXPR and ARRAY need no test expression or combining operator. These
		 * fields should be null already, but make sure.
1280
		 */
1281
		sublink->testexpr = NULL;
1282 1283 1284 1285
		sublink->operName = NIL;
	}
	else
	{
1286 1287 1288 1289
		/* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
		Node	   *lefthand;
		List	   *left_list;
		List	   *right_list;
1290 1291 1292
		ListCell   *l;

		/*
1293
		 * Transform lefthand expression, and convert to a list
1294
		 */
1295 1296 1297
		lefthand = transformExpr(pstate, sublink->testexpr);
		if (lefthand && IsA(lefthand, RowExpr))
			left_list = ((RowExpr *) lefthand)->args;
1298
		else
1299
			left_list = list_make1(lefthand);
1300 1301

		/*
Bruce Momjian's avatar
Bruce Momjian committed
1302 1303
		 * Build a list of PARAM_SUBLINK nodes representing the output columns
		 * of the subquery.
1304
		 */
1305 1306
		right_list = NIL;
		foreach(l, qtree->targetList)
1307 1308
		{
			TargetEntry *tent = (TargetEntry *) lfirst(l);
1309
			Param	   *param;
1310

1311
			if (tent->resjunk)
1312 1313
				continue;

1314 1315
			param = makeNode(Param);
			param->paramkind = PARAM_SUBLINK;
1316
			param->paramid = tent->resno;
1317
			param->paramtype = exprType((Node *) tent->expr);
1318
			param->paramtypmod = exprTypmod((Node *) tent->expr);
1319
			param->location = -1;
1320

1321
			right_list = lappend(right_list, param);
1322
		}
1323 1324

		/*
Bruce Momjian's avatar
Bruce Momjian committed
1325 1326 1327
		 * We could rely on make_row_comparison_op to complain if the list
		 * lengths differ, but we prefer to generate a more specific error
		 * message.
1328 1329 1330 1331
		 */
		if (list_length(left_list) < list_length(right_list))
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
1332 1333
					 errmsg("subquery has too many columns"),
					 parser_errposition(pstate, sublink->location)));
1334
		if (list_length(left_list) > list_length(right_list))
1335 1336
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
1337 1338
					 errmsg("subquery has too few columns"),
					 parser_errposition(pstate, sublink->location)));
1339

1340 1341 1342 1343 1344 1345 1346
		/*
		 * Identify the combining operator(s) and generate a suitable
		 * row-comparison expression.
		 */
		sublink->testexpr = make_row_comparison_op(pstate,
												   sublink->operName,
												   left_list,
1347
												   right_list,
1348
												   sublink->location);
1349 1350 1351 1352 1353
	}

	return result;
}

1354 1355 1356 1357 1358 1359 1360
/*
 * transformArrayExpr
 *
 * If the caller specifies the target type, the resulting array will
 * be of exactly that type.  Otherwise we try to infer a common type
 * for the elements using select_common_type().
 */
1361
static Node *
1362 1363
transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
				   Oid array_type, Oid element_type, int32 typmod)
1364 1365 1366 1367 1368
{
	ArrayExpr  *newa = makeNode(ArrayExpr);
	List	   *newelems = NIL;
	List	   *newcoercedelems = NIL;
	ListCell   *element;
1369 1370
	Oid			coerce_type;
	bool		coerce_hard;
1371

1372 1373 1374 1375 1376 1377 1378
	/* 
	 * Transform the element expressions 
	 *
	 * Assume that the array is one-dimensional unless we find an
	 * array-type element expression.
	 */ 
	newa->multidims = false;
1379 1380 1381 1382
	foreach(element, a->elements)
	{
		Node	   *e = (Node *) lfirst(element);
		Node	   *newe;
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395

		/*
		 * If an element is itself an A_ArrayExpr, recurse directly so that
		 * we can pass down any target type we were given.
		 */
		if (IsA(e, A_ArrayExpr))
		{
			newe = transformArrayExpr(pstate,
									  (A_ArrayExpr *) e,
									  array_type,
									  element_type,
									  typmod);
			/* we certainly have an array here */
1396
			Assert(array_type == InvalidOid || array_type == exprType(newe));
1397 1398 1399 1400 1401 1402 1403 1404 1405
			newa->multidims = true;
		}
		else
		{
			newe = transformExpr(pstate, e);
			/*
			 * Check for sub-array expressions, if we haven't already
			 * found one.
			 */
1406
			if (!newa->multidims && type_is_array(exprType(newe)))
1407 1408
				newa->multidims = true;
		}
1409 1410 1411 1412

		newelems = lappend(newelems, newe);
	}

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
	/* 
	 * Select a target type for the elements.
	 *
	 * If we haven't been given a target array type, we must try to deduce a
	 * common type based on the types of the individual elements present.
	 */
	if (OidIsValid(array_type))
	{
		/* Caller must ensure array_type matches element_type */
		Assert(OidIsValid(element_type));
		coerce_type = (newa->multidims ? array_type : element_type);
		coerce_hard = true;
	}
	else
	{
		/* Can't handle an empty array without a target type */
1429
		if (newelems == NIL)
1430 1431 1432 1433
			ereport(ERROR,
					(errcode(ERRCODE_INDETERMINATE_DATATYPE),
					 errmsg("cannot determine type of empty array"),
					 errhint("Explicitly cast to the desired type, "
1434 1435
							 "for example ARRAY[]::integer[]."),
					 parser_errposition(pstate, a->location)));
1436 1437

		/* Select a common type for the elements */
1438
		coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461

		if (newa->multidims)
		{
			array_type = coerce_type;
			element_type = get_element_type(array_type);
			if (!OidIsValid(element_type))
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_OBJECT),
						 errmsg("could not find element type for data type %s",
								format_type_be(array_type))));
		}
		else
		{
			element_type = coerce_type;
			array_type = get_array_type(element_type);
			if (!OidIsValid(array_type))
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_OBJECT),
						 errmsg("could not find array type for data type %s",
								format_type_be(element_type))));
		}
		coerce_hard = false;
	}
1462

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
	/*
	 * Coerce elements to target type 
	 *
	 * If the array has been explicitly cast, then the elements are in turn
	 * explicitly coerced.
	 *
	 * If the array's type was merely derived from the common type of its
	 * elements, then the elements are implicitly coerced to the common type.
	 * This is consistent with other uses of select_common_type().
	 */ 
1473 1474 1475 1476 1477
	foreach(element, newelems)
	{
		Node	   *e = (Node *) lfirst(element);
		Node	   *newe;

1478 1479 1480 1481 1482 1483 1484
		if (coerce_hard)
		{
			newe = coerce_to_target_type(pstate, e, 
										 exprType(e),
										 coerce_type, 
										 typmod,
										 COERCION_EXPLICIT,
1485 1486
										 COERCE_EXPLICIT_CAST,
										 -1);
1487 1488 1489 1490 1491
			if (newe == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_CANNOT_COERCE),
						 errmsg("cannot cast type %s to %s",
								format_type_be(exprType(e)),
1492 1493
								format_type_be(coerce_type)),
						 parser_errposition(pstate, exprLocation(e))));
1494 1495 1496 1497 1498
		}
		else
			newe = coerce_to_common_type(pstate, e,
										 coerce_type,
										 "ARRAY");
1499 1500 1501 1502 1503 1504
		newcoercedelems = lappend(newcoercedelems, newe);
	}

	newa->array_typeid = array_type;
	newa->element_typeid = element_type;
	newa->elements = newcoercedelems;
1505
	newa->location = a->location;
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515

	return (Node *) newa;
}

static Node *
transformRowExpr(ParseState *pstate, RowExpr *r)
{
	RowExpr    *newr = makeNode(RowExpr);

	/* Transform the field expressions */
1516
	newr->args = transformExpressionList(pstate, r->args);
1517 1518 1519 1520

	/* Barring later casting, we consider the type RECORD */
	newr->row_typeid = RECORDOID;
	newr->row_format = COERCE_IMPLICIT_CAST;
1521
	newr->location = r->location;
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

	return (Node *) newr;
}

static Node *
transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
{
	CoalesceExpr *newc = makeNode(CoalesceExpr);
	List	   *newargs = NIL;
	List	   *newcoercedargs = NIL;
	ListCell   *args;

	foreach(args, c->args)
	{
		Node	   *e = (Node *) lfirst(args);
		Node	   *newe;

		newe = transformExpr(pstate, e);
		newargs = lappend(newargs, newe);
	}

1543
	newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557

	/* Convert arguments if necessary */
	foreach(args, newargs)
	{
		Node	   *e = (Node *) lfirst(args);
		Node	   *newe;

		newe = coerce_to_common_type(pstate, e,
									 newc->coalescetype,
									 "COALESCE");
		newcoercedargs = lappend(newcoercedargs, newe);
	}

	newc->args = newcoercedargs;
1558
	newc->location = c->location;
1559 1560 1561
	return (Node *) newc;
}

1562 1563 1564 1565 1566 1567
static Node *
transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
{
	MinMaxExpr *newm = makeNode(MinMaxExpr);
	List	   *newargs = NIL;
	List	   *newcoercedargs = NIL;
1568
	const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
	ListCell   *args;

	newm->op = m->op;
	foreach(args, m->args)
	{
		Node	   *e = (Node *) lfirst(args);
		Node	   *newe;

		newe = transformExpr(pstate, e);
		newargs = lappend(newargs, newe);
	}

1581
	newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1582 1583 1584 1585 1586 1587 1588 1589 1590

	/* Convert arguments if necessary */
	foreach(args, newargs)
	{
		Node	   *e = (Node *) lfirst(args);
		Node	   *newe;

		newe = coerce_to_common_type(pstate, e,
									 newm->minmaxtype,
1591
									 funcname);
1592 1593 1594 1595
		newcoercedargs = lappend(newcoercedargs, newe);
	}

	newm->args = newcoercedargs;
1596
	newm->location = m->location;
1597 1598 1599
	return (Node *) newm;
}

1600
static Node *
1601
transformXmlExpr(ParseState *pstate, XmlExpr *x)
1602
{
Bruce Momjian's avatar
Bruce Momjian committed
1603 1604
	XmlExpr    *newx = makeNode(XmlExpr);
	ListCell   *lc;
1605 1606 1607 1608
	int			i;

	newx->op = x->op;
	if (x->name)
1609
		newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1610 1611
	else
		newx->name = NULL;
1612 1613
	newx->xmloption = x->xmloption;
	newx->location = x->location;
1614 1615

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1616
	 * gram.y built the named args as a list of ResTarget.	Transform each,
1617 1618 1619 1620 1621 1622 1623
	 * and break the names out as a separate list.
	 */
	newx->named_args = NIL;
	newx->arg_names = NIL;

	foreach(lc, x->named_args)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1624 1625 1626
		ResTarget  *r = (ResTarget *) lfirst(lc);
		Node	   *expr;
		char	   *argname;
1627 1628 1629 1630 1631 1632

		Assert(IsA(r, ResTarget));

		expr = transformExpr(pstate, r->val);

		if (r->name)
1633
			argname = map_sql_identifier_to_xml_name(r->name, false, false);
1634 1635
		else if (IsA(r->val, ColumnRef))
			argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1636
													 true, false);
1637 1638 1639 1640 1641
		else
		{
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 x->op == IS_XMLELEMENT
1642 1643 1644
					 ? errmsg("unnamed XML attribute value must be a column reference")
					 : errmsg("unnamed XML element value must be a column reference"),
					 parser_errposition(pstate, r->location)));
1645 1646 1647
			argname = NULL;		/* keep compiler quiet */
		}

1648 1649
		/* reject duplicate argnames in XMLELEMENT only */
		if (x->op == IS_XMLELEMENT)
1650
		{
Bruce Momjian's avatar
Bruce Momjian committed
1651
			ListCell   *lc2;
1652

1653
			foreach(lc2, newx->arg_names)
1654
			{
1655
				if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1656 1657
					ereport(ERROR,
							(errcode(ERRCODE_SYNTAX_ERROR),
1658 1659 1660
							 errmsg("XML attribute name \"%s\" appears more than once",
									argname),
							 parser_errposition(pstate, r->location)));
1661 1662
			}
		}
1663 1664 1665

		newx->named_args = lappend(newx->named_args, expr);
		newx->arg_names = lappend(newx->arg_names, makeString(argname));
1666 1667
	}

1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
	/* The other arguments are of varying types depending on the function */
	newx->args = NIL;
	i = 0;
	foreach(lc, x->args)
	{
		Node	   *e = (Node *) lfirst(lc);
		Node	   *newe;

		newe = transformExpr(pstate, e);
		switch (x->op)
		{
			case IS_XMLCONCAT:
				newe = coerce_to_specific_type(pstate, newe, XMLOID,
											   "XMLCONCAT");
				break;
Peter Eisentraut's avatar
Peter Eisentraut committed
1683 1684 1685
			case IS_XMLELEMENT:
				/* no coercion necessary */
				break;
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
			case IS_XMLFOREST:
				newe = coerce_to_specific_type(pstate, newe, XMLOID,
											   "XMLFOREST");
				break;
			case IS_XMLPARSE:
				if (i == 0)
					newe = coerce_to_specific_type(pstate, newe, TEXTOID,
												   "XMLPARSE");
				else
					newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
				break;
			case IS_XMLPI:
				newe = coerce_to_specific_type(pstate, newe, TEXTOID,
											   "XMLPI");
				break;
			case IS_XMLROOT:
				if (i == 0)
					newe = coerce_to_specific_type(pstate, newe, XMLOID,
												   "XMLROOT");
				else if (i == 1)
					newe = coerce_to_specific_type(pstate, newe, TEXTOID,
												   "XMLROOT");
				else
1709 1710
					newe = coerce_to_specific_type(pstate, newe, INT4OID,
												   "XMLROOT");
1711
				break;
1712 1713
			case IS_XMLSERIALIZE:
				/* not handled here */
1714
				Assert(false);
1715
				break;
1716 1717 1718 1719
			case IS_DOCUMENT:
				newe = coerce_to_specific_type(pstate, newe, XMLOID,
											   "IS DOCUMENT");
				break;
1720 1721 1722 1723
		}
		newx->args = lappend(newx->args, newe);
		i++;
	}
1724

1725 1726 1727
	return (Node *) newx;
}

1728
static Node *
1729
transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1730
{
1731 1732
	Node	   *result;
	XmlExpr    *xexpr;
1733 1734 1735 1736 1737 1738
	Oid			targetType;
	int32		targetTypmod;

	xexpr = makeNode(XmlExpr);
	xexpr->op = IS_XMLSERIALIZE;
	xexpr->args = list_make1(coerce_to_specific_type(pstate,
Bruce Momjian's avatar
Bruce Momjian committed
1739
											 transformExpr(pstate, xs->expr),
1740 1741 1742
													 XMLOID,
													 "XMLSERIALIZE"));

1743
	targetType = typenameTypeId(pstate, xs->typename, &targetTypmod);
1744 1745

	xexpr->xmloption = xs->xmloption;
1746
	xexpr->location = xs->location;
1747 1748 1749 1750 1751
	/* We actually only need these to be able to parse back the expression. */
	xexpr->type = targetType;
	xexpr->typmod = targetTypmod;

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1752 1753 1754 1755
	 * The actual target type is determined this way.  SQL allows char and
	 * varchar as target types.  We allow anything that can be cast implicitly
	 * from text.  This way, user-defined text-like data types automatically
	 * fit in.
1756
	 */
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
	result = coerce_to_target_type(pstate, (Node *) xexpr,
								   TEXTOID, targetType, targetTypmod,
								   COERCION_IMPLICIT,
								   COERCE_IMPLICIT_CAST,
								   -1);
	if (result == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_CANNOT_COERCE),
				 errmsg("cannot cast XMLSERIALIZE result to %s",
						format_type_be(targetType)),
				 parser_errposition(pstate, xexpr->location)));
	return result;
1769 1770
}

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
static Node *
transformBooleanTest(ParseState *pstate, BooleanTest *b)
{
	const char *clausename;

	switch (b->booltesttype)
	{
		case IS_TRUE:
			clausename = "IS TRUE";
			break;
		case IS_NOT_TRUE:
			clausename = "IS NOT TRUE";
			break;
		case IS_FALSE:
			clausename = "IS FALSE";
			break;
		case IS_NOT_FALSE:
			clausename = "IS NOT FALSE";
			break;
		case IS_UNKNOWN:
			clausename = "IS UNKNOWN";
			break;
		case IS_NOT_UNKNOWN:
			clausename = "IS NOT UNKNOWN";
			break;
		default:
			elog(ERROR, "unrecognized booltesttype: %d",
				 (int) b->booltesttype);
1799
			clausename = NULL;	/* keep compiler quiet */
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
	}

	b->arg = (Expr *) transformExpr(pstate, (Node *) b->arg);

	b->arg = (Expr *) coerce_to_boolean(pstate,
										(Node *) b->arg,
										clausename);

	return (Node *) b;
}

1811
static Node *
1812
transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1813
{
Bruce Momjian's avatar
Bruce Momjian committed
1814
	int			sublevels_up;
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847

	/* CURRENT OF can only appear at top level of UPDATE/DELETE */
	Assert(pstate->p_target_rangetblentry != NULL);
	cexpr->cvarno = RTERangeTablePosn(pstate,
									  pstate->p_target_rangetblentry,
									  &sublevels_up);
	Assert(sublevels_up == 0);

	/* If a parameter is used, it must be of type REFCURSOR */
	if (cexpr->cursor_name == NULL)
	{
		Oid		   *pptype = find_param_type(pstate, cexpr->cursor_param);

		if (pstate->p_variableparams && *pptype == UNKNOWNOID)
		{
			/* resolve unknown param type as REFCURSOR */
			*pptype = REFCURSOROID;
		}
		else if (*pptype != REFCURSOROID)
		{
			ereport(ERROR,
					(errcode(ERRCODE_AMBIGUOUS_PARAMETER),
					 errmsg("inconsistent types deduced for parameter $%d",
							cexpr->cursor_param),
					 errdetail("%s versus %s",
							   format_type_be(*pptype),
							   format_type_be(REFCURSOROID))));
		}
	}

	return (Node *) cexpr;
}

1848 1849 1850
/*
 * Construct a whole-row reference to represent the notation "relation.*".
 *
1851
 * A whole-row reference is a Var with varno set to the correct range
1852 1853 1854 1855 1856 1857
 * table entry, and varattno == 0 to signal that it references the whole
 * tuple.  (Use of zero here is unclean, since it could easily be confused
 * with error cases, but it's not worth changing now.)  The vartype indicates
 * a rowtype; either a named composite type, or RECORD.
 */
static Node *
1858 1859
transformWholeRowRef(ParseState *pstate, char *schemaname, char *relname,
					 int location)
1860
{
1861
	Var		   *result;
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
	RangeTblEntry *rte;
	int			vnum;
	int			sublevels_up;
	Oid			toid;

	/* Look up the referenced RTE, creating it if needed */

	rte = refnameRangeTblEntry(pstate, schemaname, relname,
							   &sublevels_up);

	if (rte == NULL)
1873 1874
		rte = addImplicitRTE(pstate, makeRangeVar(schemaname, relname),
							 location);
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887

	vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);

	/* Build the appropriate referencing node */

	switch (rte->rtekind)
	{
		case RTE_RELATION:
			/* relation: the rowtype is a named composite type */
			toid = get_rel_type_id(rte->relid);
			if (!OidIsValid(toid))
				elog(ERROR, "could not find type OID for relation %u",
					 rte->relid);
1888 1889 1890 1891 1892
			result = makeVar(vnum,
							 InvalidAttrNumber,
							 toid,
							 -1,
							 sublevels_up);
1893 1894 1895
			break;
		case RTE_FUNCTION:
			toid = exprType(rte->funcexpr);
1896
			if (type_is_rowtype(toid))
1897 1898
			{
				/* func returns composite; same as relation case */
1899 1900 1901 1902 1903
				result = makeVar(vnum,
								 InvalidAttrNumber,
								 toid,
								 -1,
								 sublevels_up);
1904 1905 1906 1907 1908 1909 1910 1911 1912
			}
			else
			{
				/*
				 * func returns scalar; instead of making a whole-row Var,
				 * just reference the function's scalar output.  (XXX this
				 * seems a tad inconsistent, especially if "f.*" was
				 * explicitly written ...)
				 */
1913 1914 1915 1916 1917
				result = makeVar(vnum,
								 1,
								 toid,
								 -1,
								 sublevels_up);
1918 1919
			}
			break;
1920 1921 1922
		case RTE_VALUES:
			toid = RECORDOID;
			/* returns composite; same as relation case */
1923 1924 1925 1926 1927
			result = makeVar(vnum,
							 InvalidAttrNumber,
							 toid,
							 -1,
							 sublevels_up);
1928
			break;
1929
		default:
Bruce Momjian's avatar
Bruce Momjian committed
1930

1931
			/*
1932 1933 1934 1935
			 * RTE is a join or subselect.	We represent this as a whole-row
			 * Var of RECORD type.	(Note that in most cases the Var will be
			 * expanded to a RowExpr during planning, but that is not our
			 * concern here.)
1936
			 */
1937 1938 1939 1940 1941
			result = makeVar(vnum,
							 InvalidAttrNumber,
							 RECORDOID,
							 -1,
							 sublevels_up);
1942 1943 1944
			break;
	}

1945 1946 1947 1948
	/* location is not filled in by makeVar */
	result->location = location;

	return (Node *) result;
1949 1950
}

1951
/*
1952
 * Handle an explicit CAST construct.
1953
 *
1954 1955
 * Transform the argument, then look up the type name and apply any necessary
 * coercion function(s).
1956 1957
 */
static Node *
1958
transformTypeCast(ParseState *pstate, TypeCast *tc)
1959
{
1960 1961
	Node	   *result;
	Node	   *expr = transformExpr(pstate, tc->arg);
1962 1963
	Oid			inputType = exprType(expr);
	Oid			targetType;
1964
	int32		targetTypmod;
1965
	int			location;
1966

1967
	targetType = typenameTypeId(pstate, tc->typename, &targetTypmod);
1968 1969 1970 1971

	if (inputType == InvalidOid)
		return expr;			/* do nothing if NULL input */

1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
	/*
	 * Location of the coercion is preferentially the location of the :: or
	 * CAST symbol, but if there is none then use the location of the type
	 * name (this can happen in TypeName 'string' syntax, for instance).
	 */
	location = tc->location;
	if (location < 0)
		location = tc->typename->location;

	result = coerce_to_target_type(pstate, expr, inputType,
								   targetType, targetTypmod,
								   COERCION_EXPLICIT,
								   COERCE_EXPLICIT_CAST,
								   location);
	if (result == NULL)
1987 1988 1989 1990
		ereport(ERROR,
				(errcode(ERRCODE_CANNOT_COERCE),
				 errmsg("cannot cast type %s to %s",
						format_type_be(inputType),
1991
						format_type_be(targetType)),
1992
				 parser_coercion_errposition(pstate, location, expr)));
1993

1994
	return result;
1995
}
1996 1997

/*
1998
 * Transform a "row compare-op row" construct
1999
 *
2000 2001 2002 2003 2004 2005 2006 2007
 * The inputs are lists of already-transformed expressions.
 * As with coerce_type, pstate may be NULL if no special unknown-Param
 * processing is wanted.
 *
 * The output may be a single OpExpr, an AND or OR combination of OpExprs,
 * or a RowCompareExpr.  In all cases it is guaranteed to return boolean.
 * The AND, OR, and RowCompareExpr cases further imply things about the
 * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
2008 2009
 */
static Node *
2010
make_row_comparison_op(ParseState *pstate, List *opname,
2011
					   List *largs, List *rargs, int location)
2012
{
2013 2014 2015 2016
	RowCompareExpr *rcexpr;
	RowCompareType rctype;
	List	   *opexprs;
	List	   *opnos;
2017
	List	   *opfamilies;
2018 2019
	ListCell   *l,
			   *r;
2020
	List	  **opfamily_lists;
2021 2022 2023 2024 2025 2026 2027
	List	  **opstrat_lists;
	Bitmapset  *strats;
	int			nopers;
	int			i;

	nopers = list_length(largs);
	if (nopers != list_length(rargs))
2028 2029
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
2030 2031
				 errmsg("unequal number of entries in row expressions"),
				 parser_errposition(pstate, location)));
2032 2033

	/*
Bruce Momjian's avatar
Bruce Momjian committed
2034 2035
	 * We can't compare zero-length rows because there is no principled basis
	 * for figuring out what the operator is.
2036
	 */
2037
	if (nopers == 0)
2038 2039
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2040 2041
				 errmsg("cannot compare rows of zero length"),
				 parser_errposition(pstate, location)));
2042

2043
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2044 2045
	 * Identify all the pairwise operators, using make_op so that behavior is
	 * the same as in the simple scalar case.
2046 2047
	 */
	opexprs = NIL;
2048
	forboth(l, largs, r, rargs)
2049
	{
Bruce Momjian's avatar
Bruce Momjian committed
2050 2051
		Node	   *larg = (Node *) lfirst(l);
		Node	   *rarg = (Node *) lfirst(r);
2052
		OpExpr	   *cmp;
2053

2054
		cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2055 2056 2057 2058 2059
		Assert(IsA(cmp, OpExpr));

		/*
		 * We don't use coerce_to_boolean here because we insist on the
		 * operator yielding boolean directly, not via coercion.  If it
2060
		 * doesn't yield bool it won't be in any index opfamilies...
2061 2062 2063 2064
		 */
		if (cmp->opresulttype != BOOLOID)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
Bruce Momjian's avatar
Bruce Momjian committed
2065 2066 2067
				   errmsg("row comparison operator must yield type boolean, "
						  "not type %s",
						  format_type_be(cmp->opresulttype)),
2068
					 parser_errposition(pstate, location)));
2069 2070 2071
		if (expression_returns_set((Node *) cmp))
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
2072 2073
					 errmsg("row comparison operator must not return a set"),
					 parser_errposition(pstate, location)));
2074 2075 2076 2077
		opexprs = lappend(opexprs, cmp);
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
2078 2079 2080
	 * If rows are length 1, just return the single operator.  In this case we
	 * don't insist on identifying btree semantics for the operator (but we
	 * still require it to return boolean).
2081 2082 2083 2084 2085 2086
	 */
	if (nopers == 1)
		return (Node *) linitial(opexprs);

	/*
	 * Now we must determine which row comparison semantics (= <> < <= > >=)
Bruce Momjian's avatar
Bruce Momjian committed
2087 2088 2089
	 * apply to this set of operators.	We look for btree opfamilies
	 * containing the operators, and see which interpretations (strategy
	 * numbers) exist for each operator.
2090
	 */
2091
	opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2092 2093 2094 2095 2096
	opstrat_lists = (List **) palloc(nopers * sizeof(List *));
	strats = NULL;
	i = 0;
	foreach(l, opexprs)
	{
2097
		Oid			opno = ((OpExpr *) lfirst(l))->opno;
Bruce Momjian's avatar
Bruce Momjian committed
2098
		Bitmapset  *this_strats;
2099 2100
		ListCell   *j;

2101 2102
		get_op_btree_interpretation(opno,
									&opfamily_lists[i], &opstrat_lists[i]);
Bruce Momjian's avatar
Bruce Momjian committed
2103

2104
		/*
Bruce Momjian's avatar
Bruce Momjian committed
2105 2106
		 * convert strategy number list to a Bitmapset to make the
		 * intersection calculation easy.
2107 2108 2109 2110 2111 2112 2113 2114
		 */
		this_strats = NULL;
		foreach(j, opstrat_lists[i])
		{
			this_strats = bms_add_member(this_strats, lfirst_int(j));
		}
		if (i == 0)
			strats = this_strats;
2115
		else
2116 2117
			strats = bms_int_members(strats, this_strats);
		i++;
2118 2119
	}

2120 2121 2122 2123 2124 2125 2126
	/*
	 * If there are multiple common interpretations, we may use any one of
	 * them ... this coding arbitrarily picks the lowest btree strategy
	 * number.
	 */
	i = bms_first_member(strats);
	if (i < 0)
2127
	{
2128 2129 2130 2131 2132 2133 2134
		/* No common interpretation, so fail */
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("could not determine interpretation of row comparison operator %s",
						strVal(llast(opname))),
				 errhint("Row comparison operators must be associated with btree operator families."),
				 parser_errposition(pstate, location)));
2135
	}
2136
	rctype = (RowCompareType) i;
2137 2138

	/*
Bruce Momjian's avatar
Bruce Momjian committed
2139 2140
	 * For = and <> cases, we just combine the pairwise operators with AND or
	 * OR respectively.
2141 2142
	 *
	 * Note: this is presently the only place where the parser generates
Bruce Momjian's avatar
Bruce Momjian committed
2143 2144
	 * BoolExpr with more than two arguments.  Should be OK since the rest of
	 * the system thinks BoolExpr is N-argument anyway.
2145 2146
	 */
	if (rctype == ROWCOMPARE_EQ)
2147
		return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2148
	if (rctype == ROWCOMPARE_NE)
2149
		return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2150 2151

	/*
2152
	 * Otherwise we need to choose exactly which opfamily to associate with
Bruce Momjian's avatar
Bruce Momjian committed
2153
	 * each operator.
2154
	 */
2155
	opfamilies = NIL;
2156 2157
	for (i = 0; i < nopers; i++)
	{
2158
		Oid			opfamily = InvalidOid;
2159

2160
		forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2161
		{
Bruce Momjian's avatar
Bruce Momjian committed
2162
			int			opstrat = lfirst_int(r);
2163 2164 2165

			if (opstrat == rctype)
			{
2166 2167
				opfamily = lfirst_oid(l);
				break;
2168 2169
			}
		}
2170 2171
		if (OidIsValid(opfamily))
			opfamilies = lappend_oid(opfamilies, opfamily);
Bruce Momjian's avatar
Bruce Momjian committed
2172
		else	/* should not happen */
2173 2174 2175 2176
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("could not determine interpretation of row comparison operator %s",
							strVal(llast(opname))),
Bruce Momjian's avatar
Bruce Momjian committed
2177
			   errdetail("There are multiple equally-plausible candidates."),
2178
					 parser_errposition(pstate, location)));
2179 2180
	}

2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
	/*
	 * Now deconstruct the OpExprs and create a RowCompareExpr.
	 *
	 * Note: can't just reuse the passed largs/rargs lists, because of
	 * possibility that make_op inserted coercion operations.
	 */
	opnos = NIL;
	largs = NIL;
	rargs = NIL;
	foreach(l, opexprs)
	{
		OpExpr	   *cmp = (OpExpr *) lfirst(l);

		opnos = lappend_oid(opnos, cmp->opno);
		largs = lappend(largs, linitial(cmp->args));
		rargs = lappend(rargs, lsecond(cmp->args));
	}

	rcexpr = makeNode(RowCompareExpr);
	rcexpr->rctype = rctype;
	rcexpr->opnos = opnos;
2202
	rcexpr->opfamilies = opfamilies;
2203 2204 2205 2206
	rcexpr->largs = largs;
	rcexpr->rargs = rargs;

	return (Node *) rcexpr;
2207 2208 2209 2210
}

/*
 * Transform a "row IS DISTINCT FROM row" construct
2211 2212
 *
 * The input RowExprs are already transformed
2213 2214 2215
 */
static Node *
make_row_distinct_op(ParseState *pstate, List *opname,
2216 2217
					 RowExpr *lrow, RowExpr *rrow,
					 int location)
2218 2219
{
	Node	   *result = NULL;
2220 2221
	List	   *largs = lrow->args;
	List	   *rargs = rrow->args;
2222 2223
	ListCell   *l,
			   *r;
2224

2225
	if (list_length(largs) != list_length(rargs))
2226 2227
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
2228 2229
				 errmsg("unequal number of entries in row expressions"),
				 parser_errposition(pstate, location)));
2230

2231
	forboth(l, largs, r, rargs)
2232
	{
Bruce Momjian's avatar
Bruce Momjian committed
2233 2234 2235
		Node	   *larg = (Node *) lfirst(l);
		Node	   *rarg = (Node *) lfirst(r);
		Node	   *cmp;
2236

2237
		cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2238 2239 2240 2241
		if (result == NULL)
			result = cmp;
		else
			result = (Node *) makeBoolExpr(OR_EXPR,
2242 2243
										   list_make2(result, cmp),
										   location);
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
	}

	if (result == NULL)
	{
		/* zero-length rows?  Generate constant FALSE */
		result = makeBoolConst(false, false);
	}

	return result;
}

/*
 * make the node for an IS DISTINCT FROM operator
 */
static Expr *
2259 2260
make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
				 int location)
2261
{
Bruce Momjian's avatar
Bruce Momjian committed
2262
	Expr	   *result;
2263

2264
	result = make_op(pstate, opname, ltree, rtree, location);
2265 2266 2267
	if (((OpExpr *) result)->opresulttype != BOOLOID)
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
Bruce Momjian's avatar
Bruce Momjian committed
2268
			 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2269
				 parser_errposition(pstate, location)));
Bruce Momjian's avatar
Bruce Momjian committed
2270

2271
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2272
	 * We rely on DistinctExpr and OpExpr being same struct
2273 2274 2275 2276 2277
	 */
	NodeSetTag(result, T_DistinctExpr);

	return result;
}