parse_expr.c 64.0 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * parse_expr.c
 *	  handle expressions in parser
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
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.248 2009/11/09 02:36:56 tgl Exp $
12 13 14 15 16
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"
17

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

36

37 38
bool		Transform_null_equals = false;

39 40 41 42 43 44 45 46 47 48
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);
49
static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
50 51 52
static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
53 54
static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
				   Oid array_type, Oid element_type, int32 typmod);
55 56
static Node *transformRowExpr(ParseState *pstate, RowExpr *r);
static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
57
static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
58 59
static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
60
static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
61
static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
62
static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
63 64
static Node *transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte,
								  int location);
65
static Node *transformIndirection(ParseState *pstate, Node *basenode,
66
					 List *indirection);
67
static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
68
static Node *make_row_comparison_op(ParseState *pstate, List *opname,
B
Bruce Momjian 已提交
69
					   List *largs, List *rargs, int location);
70
static Node *make_row_distinct_op(ParseState *pstate, List *opname,
71
					 RowExpr *lrow, RowExpr *rrow, int location);
72
static Expr *make_distinct_op(ParseState *pstate, List *opname,
73
				 Node *ltree, Node *rtree, int location);
74

75

76 77
/*
 * transformExpr -
78
 *	  Analyze and transform expressions. Type checking and type casting is
79 80 81
 *	  done here. The optimizer and the executor cannot handle the original
 *	  (raw) expressions collected by the parse tree. Hence the transformation
 *	  here.
82 83
 *
 * NOTE: there are various cases in which this routine will get applied to
84 85 86 87 88
 * 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
89 90 91 92 93 94 95 96 97 98
 *	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.
99 100
 */
Node *
101
transformExpr(ParseState *pstate, Node *expr)
102 103 104 105 106 107
{
	Node	   *result = NULL;

	if (expr == NULL)
		return NULL;

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

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

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

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

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

130
		case T_A_Indirection:
131
			{
B
Bruce Momjian 已提交
132
				A_Indirection *ind = (A_Indirection *) expr;
133

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

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

145 146 147
		case T_TypeCast:
			{
				TypeCast   *tc = (TypeCast *) expr;
148 149

				/*
150 151 152 153
				 * 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
154 155 156 157 158 159 160 161
				 * transformArrayExpr() might not infer the correct type.
				 */
				if (IsA(tc->arg, A_ArrayExpr))
				{
					Oid			targetType;
					Oid			elementType;
					int32		targetTypmod;

162
					targetType = typenameTypeId(pstate, tc->typeName,
163 164 165 166 167 168 169 170 171 172 173 174 175
												&targetTypmod);
					elementType = get_element_type(targetType);
					if (OidIsValid(elementType))
					{
						result = transformArrayExpr(pstate,
													(A_ArrayExpr *) tc->arg,
													targetType,
													elementType,
													targetTypmod);
						break;
					}

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

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

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

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

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

231 232 233 234 235 236 237 238 239
		case T_NamedArgExpr:
			{
				NamedArgExpr *na = (NamedArgExpr *) expr;

				na->arg = (Expr *) transformExpr(pstate, (Node *) na->arg);
				result = expr;
				break;
			}

240
		case T_SubLink:
241 242
			result = transformSubLink(pstate, (SubLink *) expr);
			break;
243

T
Thomas G. Lockhart 已提交
244
		case T_CaseExpr:
245 246
			result = transformCaseExpr(pstate, (CaseExpr *) expr);
			break;
T
Thomas G. Lockhart 已提交
247

248
		case T_RowExpr:
249 250
			result = transformRowExpr(pstate, (RowExpr *) expr);
			break;
251

252
		case T_CoalesceExpr:
253 254
			result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
			break;
255

256 257 258 259
		case T_MinMaxExpr:
			result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
			break;

260 261 262 263
		case T_XmlExpr:
			result = transformXmlExpr(pstate, (XmlExpr *) expr);
			break;

264 265 266 267
		case T_XmlSerialize:
			result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
			break;

268 269 270 271
		case T_NullTest:
			{
				NullTest   *n = (NullTest *) expr;

272
				n->arg = (Expr *) transformExpr(pstate, (Node *) n->arg);
273 274 275 276 277 278
				/* the argument can be any type, so don't coerce it */
				result = expr;
				break;
			}

		case T_BooleanTest:
279 280
			result = transformBooleanTest(pstate, (BooleanTest *) expr);
			break;
281

282
		case T_CurrentOfExpr:
283 284
			result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
			break;
285

B
Bruce Momjian 已提交
286 287 288 289 290 291 292 293
			/*********************************************
			 * 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.
			 *********************************************/
294 295
		case T_Var:
		case T_Const:
296
		case T_Param:
297
		case T_Aggref:
T
Tom Lane 已提交
298
		case T_WindowFunc:
299
		case T_ArrayRef:
300 301 302
		case T_FuncExpr:
		case T_OpExpr:
		case T_DistinctExpr:
303
		case T_ScalarArrayOpExpr:
304
		case T_NullIfExpr:
305
		case T_BoolExpr:
306
		case T_FieldSelect:
307
		case T_FieldStore:
308
		case T_RelabelType:
309
		case T_CoerceViaIO:
310
		case T_ArrayCoerceExpr:
311
		case T_ConvertRowtypeExpr:
312
		case T_CaseTestExpr:
313 314
		case T_CoerceToDomain:
		case T_CoerceToDomainValue:
315
		case T_SetToDefault:
316 317 318 319
			{
				result = (Node *) expr;
				break;
			}
320

321 322
		default:
			/* should not reach here */
323
			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
324 325 326 327 328 329
			break;
	}

	return result;
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
/*
 * helper routine for delivering "column does not exist" error message
 *
 * (Usually we don't have to work this hard, but the general case of field
 * selection from an arbitrary node needs it.)
 */
static void
unknown_attribute(ParseState *pstate, Node *relref, char *attname,
				  int location)
{
	RangeTblEntry *rte;

	if (IsA(relref, Var) &&
		((Var *) relref)->varattno == InvalidAttrNumber)
	{
		/* Reference the RTE by alias not by actual table name */
		rte = GetRTEByRangeTablePosn(pstate,
									 ((Var *) relref)->varno,
									 ((Var *) relref)->varlevelsup);
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_COLUMN),
				 errmsg("column %s.%s does not exist",
						rte->eref->aliasname, attname),
				 parser_errposition(pstate, location)));
	}
	else
	{
		/* Have to do it by reference to the type of the expression */
		Oid			relTypeId = exprType(relref);

		if (ISCOMPLEX(relTypeId))
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("column \"%s\" not found in data type %s",
							attname, format_type_be(relTypeId)),
					 parser_errposition(pstate, location)));
		else if (relTypeId == RECORDOID)
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
			   errmsg("could not identify column \"%s\" in record data type",
					  attname),
					 parser_errposition(pstate, location)));
		else
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("column notation .%s applied to type %s, "
							"which is not a composite type",
							attname, format_type_be(relTypeId)),
					 parser_errposition(pstate, location)));
	}
}

382
static Node *
383
transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
384
{
385 386
	Node	   *result = basenode;
	List	   *subscripts = NIL;
387
	int			location = exprLocation(basenode);
388 389 390 391
	ListCell   *i;

	/*
	 * We have to split any field-selection operations apart from
B
Bruce Momjian 已提交
392 393
	 * subscripting.  Adjacent A_Indices nodes have to be treated as a single
	 * multidimensional subscript operation.
394 395 396
	 */
	foreach(i, indirection)
	{
B
Bruce Momjian 已提交
397
		Node	   *n = lfirst(i);
398 399 400

		if (IsA(n, A_Indices))
			subscripts = lappend(subscripts, n);
401 402 403 404 405
		else if (IsA(n, A_Star))
		{
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("row expansion via \"*\" is not supported here"),
406
					 parser_errposition(pstate, location)));
407
		}
408 409
		else
		{
410 411
			Node	   *newresult;

412 413 414 415 416 417
			Assert(IsA(n, String));

			/* process subscripts before this field selection */
			if (subscripts)
				result = (Node *) transformArraySubscripts(pstate,
														   result,
B
Bruce Momjian 已提交
418
														   exprType(result),
419
														   InvalidOid,
420
														   exprTypmod(result),
421 422 423 424
														   subscripts,
														   NULL);
			subscripts = NIL;

425 426 427 428 429 430 431 432
			newresult = ParseFuncOrColumn(pstate,
										  list_make1(n),
										  list_make1(result),
										  false, false, false,
										  NULL, true, location);
			if (newresult == NULL)
				unknown_attribute(pstate, result, strVal(n), location);
			result = newresult;
433 434 435 436 437 438 439 440
		}
	}
	/* process trailing subscripts, if any */
	if (subscripts)
		result = (Node *) transformArraySubscripts(pstate,
												   result,
												   exprType(result),
												   InvalidOid,
441
												   exprTypmod(result),
442 443 444 445
												   subscripts,
												   NULL);

	return result;
446
}
447

448 449 450 451 452
/*
 * Transform a ColumnRef.
 *
 * If you find yourself changing this code, see also ExpandColumnRefStar.
 */
453
static Node *
454
transformColumnRef(ParseState *pstate, ColumnRef *cref)
455
{
456 457 458 459 460
	Node	   *node = NULL;
	char	   *nspname = NULL;
	char	   *relname = NULL;
	char	   *colname = NULL;
	RangeTblEntry *rte;
461
	int			levels_up;
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
	enum {
		CRERR_NO_COLUMN,
		CRERR_NO_RTE,
		CRERR_WRONG_DB,
		CRERR_TOO_MANY
	}			crerr = CRERR_NO_COLUMN;

	/*
	 * Give the PreParseColumnRefHook, if any, first shot.  If it returns
	 * non-null then that's all, folks.
	 */
	if (pstate->p_pre_columnref_hook != NULL)
	{
		node = (*pstate->p_pre_columnref_hook) (pstate, cref);
		if (node != NULL)
			return node;
	}
479 480 481 482 483

	/*----------
	 * The allowed syntaxes are:
	 *
	 * A		First try to resolve as unqualified column name;
484 485
	 *			if no luck, try to resolve as unqualified table name (A.*).
	 * A.B		A is an unqualified table name; B is either a
486 487 488
	 *			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.
489
	 * A.*		A is an unqualified table name; means whole-row value.
490 491 492 493 494
	 * 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
495 496 497
	 * 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.
498 499 500 501 502
	 *
	 * Currently, if a catalog name is given then it must equal the current
	 * database name; we check it here and then discard it.
	 *----------
	 */
503
	switch (list_length(cref->fields))
504 505
	{
		case 1:
B
Bruce Momjian 已提交
506
			{
507 508 509
				Node	   *field1 = (Node *) linitial(cref->fields);

				Assert(IsA(field1, String));
510
				colname = strVal(field1);
511

B
Bruce Momjian 已提交
512
				/* Try to identify as an unqualified column */
513
				node = colNameToVar(pstate, colname, false, cref->location);
B
Bruce Momjian 已提交
514 515 516 517

				if (node == NULL)
				{
					/*
518 519
					 * Not known as a column of any range-table entry.
					 *
520 521 522 523
					 * 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.)
524 525
					 */
					if (pstate->p_value_substitute != NULL &&
526
						strcmp(colname, "value") == 0)
527 528
					{
						node = (Node *) copyObject(pstate->p_value_substitute);
529 530 531 532 533 534 535 536

						/*
						 * 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;
537 538 539 540
						break;
					}

					/*
B
Bruce Momjian 已提交
541
					 * Try to find the name as a relation.	Note that only
B
Bruce Momjian 已提交
542 543
					 * relations already entered into the rangetable will be
					 * recognized.
B
Bruce Momjian 已提交
544 545
					 *
					 * This is a hack for backwards compatibility with
B
Bruce Momjian 已提交
546 547
					 * PostQUEL-inspired syntax.  The preferred form now is
					 * "rel.*".
B
Bruce Momjian 已提交
548
					 */
549 550 551 552 553
					rte = refnameRangeTblEntry(pstate, NULL, colname,
											   cref->location,
											   &levels_up);
					if (rte)
						node = transformWholeRowRef(pstate, rte,
554
													cref->location);
B
Bruce Momjian 已提交
555 556 557 558
				}
				break;
			}
		case 2:
559
			{
560 561 562 563
				Node	   *field1 = (Node *) linitial(cref->fields);
				Node	   *field2 = (Node *) lsecond(cref->fields);

				Assert(IsA(field1, String));
564 565 566 567 568 569 570 571 572 573 574
				relname = strVal(field1);

				/* Locate the referenced RTE */
				rte = refnameRangeTblEntry(pstate, nspname, relname,
										   cref->location,
										   &levels_up);
				if (rte == NULL)
				{
					crerr = CRERR_NO_RTE;
					break;
				}
575

B
Bruce Momjian 已提交
576
				/* Whole-row reference? */
577
				if (IsA(field2, A_Star))
578
				{
579
					node = transformWholeRowRef(pstate, rte, cref->location);
B
Bruce Momjian 已提交
580
					break;
581
				}
582

583
				Assert(IsA(field2, String));
584
				colname = strVal(field2);
585

586 587
				/* Try to identify as a column of the RTE */
				node = scanRTEForColumn(pstate, rte, colname, cref->location);
B
Bruce Momjian 已提交
588 589
				if (node == NULL)
				{
590 591
					/* Try it as a function call on the whole row */
					node = transformWholeRowRef(pstate, rte, cref->location);
B
Bruce Momjian 已提交
592
					node = ParseFuncOrColumn(pstate,
593
											 list_make1(makeString(colname)),
594
											 list_make1(node),
595
											 false, false, false,
T
Tom Lane 已提交
596
											 NULL, true, cref->location);
B
Bruce Momjian 已提交
597
				}
598 599 600 601
				break;
			}
		case 3:
			{
602 603 604 605 606
				Node	   *field1 = (Node *) linitial(cref->fields);
				Node	   *field2 = (Node *) lsecond(cref->fields);
				Node	   *field3 = (Node *) lthird(cref->fields);

				Assert(IsA(field1, String));
607
				nspname = strVal(field1);
608
				Assert(IsA(field2, String));
609 610 611 612 613 614 615 616 617 618 619
				relname = strVal(field2);

				/* Locate the referenced RTE */
				rte = refnameRangeTblEntry(pstate, nspname, relname,
										   cref->location,
										   &levels_up);
				if (rte == NULL)
				{
					crerr = CRERR_NO_RTE;
					break;
				}
620

B
Bruce Momjian 已提交
621
				/* Whole-row reference? */
622
				if (IsA(field3, A_Star))
B
Bruce Momjian 已提交
623
				{
624
					node = transformWholeRowRef(pstate, rte, cref->location);
B
Bruce Momjian 已提交
625 626 627
					break;
				}

628
				Assert(IsA(field3, String));
629
				colname = strVal(field3);
630

631 632
				/* Try to identify as a column of the RTE */
				node = scanRTEForColumn(pstate, rte, colname, cref->location);
B
Bruce Momjian 已提交
633 634
				if (node == NULL)
				{
635 636
					/* Try it as a function call on the whole row */
					node = transformWholeRowRef(pstate, rte, cref->location);
B
Bruce Momjian 已提交
637
					node = ParseFuncOrColumn(pstate,
638
											 list_make1(makeString(colname)),
639
											 list_make1(node),
640
											 false, false, false,
T
Tom Lane 已提交
641
											 NULL, true, cref->location);
B
Bruce Momjian 已提交
642 643
				}
				break;
644 645 646
			}
		case 4:
			{
647 648 649 650
				Node	   *field1 = (Node *) linitial(cref->fields);
				Node	   *field2 = (Node *) lsecond(cref->fields);
				Node	   *field3 = (Node *) lthird(cref->fields);
				Node	   *field4 = (Node *) lfourth(cref->fields);
651
				char	   *catname;
652 653

				Assert(IsA(field1, String));
654
				catname = strVal(field1);
655
				Assert(IsA(field2, String));
656
				nspname = strVal(field2);
657
				Assert(IsA(field3, String));
658
				relname = strVal(field3);
659

B
Bruce Momjian 已提交
660 661 662
				/*
				 * We check the catalog name and then ignore it.
				 */
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
				if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
				{
					crerr = CRERR_WRONG_DB;
					break;
				}

				/* Locate the referenced RTE */
				rte = refnameRangeTblEntry(pstate, nspname, relname,
										   cref->location,
										   &levels_up);
				if (rte == NULL)
				{
					crerr = CRERR_NO_RTE;
					break;
				}
B
Bruce Momjian 已提交
678 679

				/* Whole-row reference? */
680
				if (IsA(field4, A_Star))
B
Bruce Momjian 已提交
681
				{
682
					node = transformWholeRowRef(pstate, rte, cref->location);
B
Bruce Momjian 已提交
683 684 685
					break;
				}

686
				Assert(IsA(field4, String));
687
				colname = strVal(field4);
688

689 690
				/* Try to identify as a column of the RTE */
				node = scanRTEForColumn(pstate, rte, colname, cref->location);
B
Bruce Momjian 已提交
691 692
				if (node == NULL)
				{
693 694
					/* Try it as a function call on the whole row */
					node = transformWholeRowRef(pstate, rte, cref->location);
B
Bruce Momjian 已提交
695
					node = ParseFuncOrColumn(pstate,
696
											 list_make1(makeString(colname)),
697
											 list_make1(node),
698
											 false, false, false,
T
Tom Lane 已提交
699
											 NULL, true, cref->location);
B
Bruce Momjian 已提交
700 701
				}
				break;
702 703
			}
		default:
704
			crerr = CRERR_TOO_MANY;			/* too many dotted names */
705
			break;
706 707
	}

708
	/*
709 710 711 712 713 714 715
	 * Now give the PostParseColumnRefHook, if any, a chance.  We pass the
	 * translation-so-far so that it can throw an error if it wishes in the
	 * case that it has a conflicting interpretation of the ColumnRef.
	 * (If it just translates anyway, we'll throw an error, because we can't
	 * undo whatever effects the preceding steps may have had on the pstate.)
	 * If it returns NULL, use the standard translation, or throw a suitable
	 * error if there is none.
716
	 */
717
	if (pstate->p_post_columnref_hook != NULL)
718
	{
719 720 721 722 723 724
		Node   *hookresult;

		hookresult = (*pstate->p_post_columnref_hook) (pstate, cref, node);
		if (node == NULL)
			node = hookresult;
		else if (hookresult != NULL)
725
			ereport(ERROR,
726 727 728 729
					(errcode(ERRCODE_AMBIGUOUS_COLUMN),
					 errmsg("column reference \"%s\" is ambiguous",
							NameListToString(cref->fields)),
					 parser_errposition(pstate, cref->location)));
730
	}
731

732 733 734 735
	/*
	 * Throw error if no translation found.
	 */
	if (node == NULL)
736
	{
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
		switch (crerr)
		{
			case CRERR_NO_COLUMN:
				if (relname)
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
							 errmsg("column %s.%s does not exist",
									relname, colname),
							 parser_errposition(pstate, cref->location)));

				else
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
							 errmsg("column \"%s\" does not exist",
									colname),
							 parser_errposition(pstate, cref->location)));
				break;
			case CRERR_NO_RTE:
				errorMissingRTE(pstate, makeRangeVar(nspname, relname,
													 cref->location));
				break;
			case CRERR_WRONG_DB:
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("cross-database references are not implemented: %s",
								NameListToString(cref->fields)),
						 parser_errposition(pstate, cref->location)));
				break;
			case CRERR_TOO_MANY:
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("improper qualified name (too many dotted names): %s",
								NameListToString(cref->fields)),
						 parser_errposition(pstate, cref->location)));
				break;
		}
773 774
	}

775
	return node;
776 777 778 779 780
}

static Node *
transformParamRef(ParseState *pstate, ParamRef *pref)
{
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
	Node	   *result;

	/*
	 * The core parser knows nothing about Params.  If a hook is supplied,
	 * call it.  If not, or if the hook returns NULL, throw a generic error.
	 */
	if (pstate->p_paramref_hook != NULL)
		result = (*pstate->p_paramref_hook) (pstate, pref);
	else
		result = NULL;

	if (result == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_PARAMETER),
				 errmsg("there is no parameter $%d", pref->number),
				 parser_errposition(pstate, pref->location)));

	return result;
799 800
}

801 802 803 804 805 806
/* Test whether an a_expr is a plain NULL constant or not */
static bool
exprIsNullConstant(Node *arg)
{
	if (arg && IsA(arg, A_Const))
	{
B
Bruce Momjian 已提交
807
		A_Const    *con = (A_Const *) arg;
808

A
Alvaro Herrera 已提交
809
		if (con->val.type == T_Null)
810 811 812 813 814
			return true;
	}
	return false;
}

815 816 817 818 819 820 821 822
static Node *
transformAExprOp(ParseState *pstate, A_Expr *a)
{
	Node	   *lexpr = a->lexpr;
	Node	   *rexpr = a->rexpr;
	Node	   *result;

	/*
B
Bruce Momjian 已提交
823 824 825
	 * Special-case "foo = NULL" and "NULL = foo" for compatibility with
	 * standards-broken products (like Microsoft's).  Turn these into IS NULL
	 * exprs.
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
	 */
	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)
	{
		/*
848
		 * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
B
Bruce Momjian 已提交
849 850
		 * grammar did this, but now that a row construct is allowed anywhere
		 * in expressions, it's easier to do it here.
851 852 853
		 */
		SubLink    *s = (SubLink *) rexpr;

854 855
		s->subLinkType = ROWCOMPARE_SUBLINK;
		s->testexpr = lexpr;
856
		s->operName = a->name;
857
		s->location = a->location;
858 859 860 861 862 863
		result = transformExpr(pstate, (Node *) s);
	}
	else if (lexpr && IsA(lexpr, RowExpr) &&
			 rexpr && IsA(rexpr, RowExpr))
	{
		/* "row op row" */
864 865 866 867 868
		lexpr = transformExpr(pstate, lexpr);
		rexpr = transformExpr(pstate, rexpr);
		Assert(IsA(lexpr, RowExpr));
		Assert(IsA(rexpr, RowExpr));

869 870 871
		result = make_row_comparison_op(pstate,
										a->name,
										((RowExpr *) lexpr)->args,
872 873
										((RowExpr *) rexpr)->args,
										a->location);
874 875 876 877 878 879 880 881 882 883
	}
	else
	{
		/* Ordinary scalar operator */
		lexpr = transformExpr(pstate, lexpr);
		rexpr = transformExpr(pstate, rexpr);

		result = (Node *) make_op(pstate,
								  a->name,
								  lexpr,
884 885
								  rexpr,
								  a->location);
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
	}

	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,
901 902
								 list_make2(lexpr, rexpr),
								 a->location);
903 904 905 906 907 908 909 910 911 912 913 914
}

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,
915 916
								 list_make2(lexpr, rexpr),
								 a->location);
917 918 919 920 921 922 923 924 925 926
}

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,
927 928
								 list_make1(rexpr),
								 a->location);
929 930 931 932 933 934 935 936 937 938 939 940
}

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,
941 942
										 rexpr,
										 a->location);
943 944 945 946 947 948 949 950 951 952 953 954
}

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,
955 956
										 rexpr,
										 a->location);
957 958 959 960 961
}

static Node *
transformAExprDistinct(ParseState *pstate, A_Expr *a)
{
962 963
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
	Node	   *rexpr = transformExpr(pstate, a->rexpr);
964 965 966 967 968 969

	if (lexpr && IsA(lexpr, RowExpr) &&
		rexpr && IsA(rexpr, RowExpr))
	{
		/* "row op row" */
		return make_row_distinct_op(pstate, a->name,
970
									(RowExpr *) lexpr,
971 972
									(RowExpr *) rexpr,
									a->location);
973 974 975 976 977 978 979
	}
	else
	{
		/* Ordinary scalar operator */
		return (Node *) make_distinct_op(pstate,
										 a->name,
										 lexpr,
980 981
										 rexpr,
										 a->location);
982 983 984 985 986 987 988 989 990 991 992 993 994
	}
}

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,
995 996
							  rexpr,
							  a->location);
997 998 999
	if (((OpExpr *) result)->opresulttype != BOOLOID)
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
1000 1001
				 errmsg("NULLIF requires = operator to yield boolean"),
				 parser_errposition(pstate, a->location)));
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

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

	return result;
}

static Node *
transformAExprOf(ParseState *pstate, A_Expr *a)
{
	/*
B
Bruce Momjian 已提交
1015 1016
	 * Checking an expression for match to a list of type names. Will result
	 * in a boolean constant node.
1017
	 */
1018
	Node	   *lexpr = transformExpr(pstate, a->lexpr);
1019
	Const	   *result;
1020 1021 1022 1023 1024 1025 1026 1027
	ListCell   *telem;
	Oid			ltype,
				rtype;
	bool		matched = false;

	ltype = exprType(lexpr);
	foreach(telem, (List *) a->rexpr)
	{
1028
		rtype = typenameTypeId(pstate, lfirst(telem), NULL);
1029 1030 1031 1032 1033 1034
		matched = (rtype == ltype);
		if (matched)
			break;
	}

	/*
B
Bruce Momjian 已提交
1035
	 * We have two forms: equals or not equals. Flip the sense of the result
B
Bruce Momjian 已提交
1036
	 * for not equals.
1037
	 */
1038
	if (strcmp(strVal(linitial(a->name)), "<>") == 0)
1039 1040
		matched = (!matched);

1041 1042 1043 1044 1045 1046
	result = (Const *) makeBoolConst(matched, false);

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

	return (Node *) result;
1047 1048 1049 1050 1051
}

static Node *
transformAExprIn(ParseState *pstate, A_Expr *a)
{
1052
	Node	   *result = NULL;
1053 1054
	Node	   *lexpr;
	List	   *rexprs;
1055 1056
	List	   *rvars;
	List	   *rnonvars;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
	bool		useOr;
	bool		haveRowExpr;
	ListCell   *l;

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

	/*
B
Bruce Momjian 已提交
1070 1071 1072
	 * 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
1073 1074 1075 1076
	 * condition tree with multiple copies of the lefthand expression. Also,
	 * any IN-list items that contain Vars are handled as separate boolean
	 * conditions, because that gives the planner more scope for optimization
	 * on such clauses.
1077 1078
	 *
	 * First step: transform all the inputs, and detect whether any are
1079
	 * RowExprs or contain Vars.
1080 1081 1082
	 */
	lexpr = transformExpr(pstate, a->lexpr);
	haveRowExpr = (lexpr && IsA(lexpr, RowExpr));
1083
	rexprs = rvars = rnonvars = NIL;
1084 1085
	foreach(l, (List *) a->rexpr)
	{
B
Bruce Momjian 已提交
1086
		Node	   *rexpr = transformExpr(pstate, lfirst(l));
1087 1088 1089

		haveRowExpr |= (rexpr && IsA(rexpr, RowExpr));
		rexprs = lappend(rexprs, rexpr);
1090 1091 1092 1093
		if (contain_vars_of_level(rexpr, 0))
			rvars = lappend(rvars, rexpr);
		else
			rnonvars = lappend(rnonvars, rexpr);
1094
	}
1095

1096
	/*
1097 1098
	 * ScalarArrayOpExpr is only going to be useful if there's more than one
	 * non-Var righthand item.	Also, it won't work for RowExprs.
1099
	 */
1100
	if (!haveRowExpr && list_length(rnonvars) > 1)
1101
	{
1102
		List	   *allexprs;
1103 1104 1105 1106
		Oid			scalar_type;
		Oid			array_type;

		/*
1107
		 * Try to select a common type for the array elements.	Note that
1108 1109
		 * 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).
1110
		 *
1111
		 * Note: use list_concat here not lcons, to avoid damaging rnonvars.
1112
		 */
1113
		allexprs = list_concat(list_make1(lexpr), rnonvars);
1114
		scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
1115 1116

		/* Do we have an array type to use? */
1117 1118 1119 1120
		if (OidIsValid(scalar_type))
			array_type = get_array_type(scalar_type);
		else
			array_type = InvalidOid;
1121 1122 1123
		if (array_type != InvalidOid)
		{
			/*
1124 1125
			 * OK: coerce all the right-hand non-Var inputs to the common type
			 * and build an ArrayExpr for them.
1126 1127 1128 1129 1130
			 */
			List	   *aexprs;
			ArrayExpr  *newa;

			aexprs = NIL;
1131
			foreach(l, rnonvars)
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
			{
				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;
1145
			newa->location = -1;
1146

1147 1148 1149 1150 1151 1152 1153 1154 1155
			result = (Node *) make_scalar_array_op(pstate,
												   a->name,
												   useOr,
												   lexpr,
												   (Node *) newa,
												   a->location);

			/* Consider only the Vars (if any) in the loop below */
			rexprs = rvars;
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
		}
	}

	/*
	 * Must do it the hard way, ie, with a boolean expression tree.
	 */
	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),
B
Bruce Momjian 已提交
1173
				   errmsg("arguments of row IN must all be row expressions"),
1174
						 parser_errposition(pstate, a->location)));
1175 1176
			cmp = make_row_comparison_op(pstate,
										 a->name,
B
Bruce Momjian 已提交
1177
							  (List *) copyObject(((RowExpr *) lexpr)->args),
1178 1179
										 ((RowExpr *) rexpr)->args,
										 a->location);
1180 1181 1182 1183 1184
		}
		else
			cmp = (Node *) make_op(pstate,
								   a->name,
								   copyObject(lexpr),
1185 1186
								   rexpr,
								   a->location);
1187 1188 1189 1190 1191 1192

		cmp = coerce_to_boolean(pstate, cmp, "IN");
		if (result == NULL)
			result = cmp;
		else
			result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
1193 1194
										   list_make2(result, cmp),
										   a->location);
1195 1196 1197
	}

	return result;
1198 1199 1200 1201 1202 1203 1204 1205
}

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

1206 1207 1208
	/* Transform the list of arguments ... */
	targs = NIL;
	foreach(args, fn->args)
1209
	{
1210 1211
		targs = lappend(targs, transformExpr(pstate,
											 (Node *) lfirst(args)));
1212 1213
	}

1214
	/* ... and hand off to ParseFuncOrColumn */
1215 1216 1217 1218 1219
	return ParseFuncOrColumn(pstate,
							 fn->funcname,
							 targs,
							 fn->agg_star,
							 fn->agg_distinct,
1220
							 fn->func_variadic,
T
Tom Lane 已提交
1221
							 fn->over,
1222 1223
							 false,
							 fn->location);
1224 1225 1226 1227 1228 1229 1230 1231 1232
}

static Node *
transformCaseExpr(ParseState *pstate, CaseExpr *c)
{
	CaseExpr   *newc;
	Node	   *arg;
	CaseTestExpr *placeholder;
	List	   *newargs;
1233
	List	   *resultexprs;
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
	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)
	{
		/*
B
Bruce Momjian 已提交
1251 1252 1253 1254 1255
		 * 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.
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
		 */
		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;
1271
	resultexprs = NIL;
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
	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,
1286
											 warg,
1287
											 w->location);
1288 1289 1290 1291 1292 1293 1294 1295 1296
		}
		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);
1297
		neww->location = w->location;
1298 1299

		newargs = lappend(newargs, neww);
1300
		resultexprs = lappend(resultexprs, neww->result);
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	}

	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;
1312
		n->location = -1;
1313 1314 1315 1316 1317 1318
		defresult = (Node *) n;
	}
	newc->defresult = (Expr *) transformExpr(pstate, defresult);

	/*
	 * Note: default result is considered the most significant type in
B
Bruce Momjian 已提交
1319 1320
	 * determining preferred type. This is how the code worked before, but it
	 * seems a little bogus to me --- tgl
1321
	 */
1322
	resultexprs = lcons(newc->defresult, resultexprs);
1323

1324
	ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
	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");
	}

1347 1348
	newc->location = c->location;

1349 1350 1351 1352 1353 1354 1355
	return (Node *) newc;
}

static Node *
transformSubLink(ParseState *pstate, SubLink *sublink)
{
	Node	   *result = (Node *) sublink;
1356
	Query	   *qtree;
1357 1358 1359 1360 1361 1362

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

	pstate->p_hasSubLinks = true;
1363
	qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false);
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377

	/*
	 * Check that we got something reasonable.	Many of these conditions are
	 * impossible given restrictions of the grammar, but check 'em anyway.
	 */
	if (!IsA(qtree, Query) ||
		qtree->commandType != CMD_SELECT ||
		qtree->utilityStmt != NULL)
		elog(ERROR, "unexpected non-SELECT command in SubLink");
	if (qtree->intoClause)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("subquery cannot have SELECT INTO"),
				 parser_errposition(pstate,
1378
								 exprLocation((Node *) qtree->intoClause))));
1379

1380 1381 1382 1383 1384
	sublink->subselect = (Node *) qtree;

	if (sublink->subLinkType == EXISTS_SUBLINK)
	{
		/*
B
Bruce Momjian 已提交
1385 1386
		 * EXISTS needs no test expression or combining operator. These fields
		 * should be null already, but make sure.
1387
		 */
1388
		sublink->testexpr = NULL;
1389 1390 1391 1392 1393 1394 1395 1396
		sublink->operName = NIL;
	}
	else if (sublink->subLinkType == EXPR_SUBLINK ||
			 sublink->subLinkType == ARRAY_SUBLINK)
	{
		ListCell   *tlist_item = list_head(qtree->targetList);

		/*
B
Bruce Momjian 已提交
1397 1398
		 * Make sure the subselect delivers a single column (ignoring resjunk
		 * targets).
1399 1400
		 */
		if (tlist_item == NULL ||
1401
			((TargetEntry *) lfirst(tlist_item))->resjunk)
1402 1403
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
1404 1405
					 errmsg("subquery must return a column"),
					 parser_errposition(pstate, sublink->location)));
1406 1407
		while ((tlist_item = lnext(tlist_item)) != NULL)
		{
1408
			if (!((TargetEntry *) lfirst(tlist_item))->resjunk)
1409 1410
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
1411 1412
						 errmsg("subquery must return only one column"),
						 parser_errposition(pstate, sublink->location)));
1413 1414 1415
		}

		/*
B
Bruce Momjian 已提交
1416 1417
		 * EXPR and ARRAY need no test expression or combining operator. These
		 * fields should be null already, but make sure.
1418
		 */
1419
		sublink->testexpr = NULL;
1420 1421 1422 1423
		sublink->operName = NIL;
	}
	else
	{
1424 1425 1426 1427
		/* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
		Node	   *lefthand;
		List	   *left_list;
		List	   *right_list;
1428 1429 1430
		ListCell   *l;

		/*
1431
		 * Transform lefthand expression, and convert to a list
1432
		 */
1433 1434 1435
		lefthand = transformExpr(pstate, sublink->testexpr);
		if (lefthand && IsA(lefthand, RowExpr))
			left_list = ((RowExpr *) lefthand)->args;
1436
		else
1437
			left_list = list_make1(lefthand);
1438 1439

		/*
B
Bruce Momjian 已提交
1440 1441
		 * Build a list of PARAM_SUBLINK nodes representing the output columns
		 * of the subquery.
1442
		 */
1443 1444
		right_list = NIL;
		foreach(l, qtree->targetList)
1445 1446
		{
			TargetEntry *tent = (TargetEntry *) lfirst(l);
1447
			Param	   *param;
1448

1449
			if (tent->resjunk)
1450 1451
				continue;

1452 1453
			param = makeNode(Param);
			param->paramkind = PARAM_SUBLINK;
1454
			param->paramid = tent->resno;
1455
			param->paramtype = exprType((Node *) tent->expr);
1456
			param->paramtypmod = exprTypmod((Node *) tent->expr);
1457
			param->location = -1;
1458

1459
			right_list = lappend(right_list, param);
1460
		}
1461 1462

		/*
B
Bruce Momjian 已提交
1463 1464 1465
		 * 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.
1466 1467 1468 1469
		 */
		if (list_length(left_list) < list_length(right_list))
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
1470 1471
					 errmsg("subquery has too many columns"),
					 parser_errposition(pstate, sublink->location)));
1472
		if (list_length(left_list) > list_length(right_list))
1473 1474
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
1475 1476
					 errmsg("subquery has too few columns"),
					 parser_errposition(pstate, sublink->location)));
1477

1478 1479 1480 1481 1482 1483 1484
		/*
		 * Identify the combining operator(s) and generate a suitable
		 * row-comparison expression.
		 */
		sublink->testexpr = make_row_comparison_op(pstate,
												   sublink->operName,
												   left_list,
1485
												   right_list,
1486
												   sublink->location);
1487 1488 1489 1490 1491
	}

	return result;
}

1492 1493 1494 1495 1496 1497 1498
/*
 * 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().
 */
1499
static Node *
1500 1501
transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
				   Oid array_type, Oid element_type, int32 typmod)
1502 1503 1504 1505 1506
{
	ArrayExpr  *newa = makeNode(ArrayExpr);
	List	   *newelems = NIL;
	List	   *newcoercedelems = NIL;
	ListCell   *element;
1507 1508
	Oid			coerce_type;
	bool		coerce_hard;
1509

1510 1511
	/*
	 * Transform the element expressions
1512
	 *
1513 1514 1515
	 * Assume that the array is one-dimensional unless we find an array-type
	 * element expression.
	 */
1516
	newa->multidims = false;
1517 1518 1519 1520
	foreach(element, a->elements)
	{
		Node	   *e = (Node *) lfirst(element);
		Node	   *newe;
1521 1522

		/*
1523 1524
		 * If an element is itself an A_ArrayExpr, recurse directly so that we
		 * can pass down any target type we were given.
1525 1526 1527 1528 1529 1530 1531 1532 1533
		 */
		if (IsA(e, A_ArrayExpr))
		{
			newe = transformArrayExpr(pstate,
									  (A_ArrayExpr *) e,
									  array_type,
									  element_type,
									  typmod);
			/* we certainly have an array here */
1534
			Assert(array_type == InvalidOid || array_type == exprType(newe));
1535 1536 1537 1538 1539
			newa->multidims = true;
		}
		else
		{
			newe = transformExpr(pstate, e);
1540

1541
			/*
1542 1543
			 * Check for sub-array expressions, if we haven't already found
			 * one.
1544
			 */
1545
			if (!newa->multidims && type_is_array(exprType(newe)))
1546 1547
				newa->multidims = true;
		}
1548 1549 1550 1551

		newelems = lappend(newelems, newe);
	}

1552
	/*
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
	 * 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 */
1568
		if (newelems == NIL)
1569 1570 1571 1572
			ereport(ERROR,
					(errcode(ERRCODE_INDETERMINATE_DATATYPE),
					 errmsg("cannot determine type of empty array"),
					 errhint("Explicitly cast to the desired type, "
1573 1574
							 "for example ARRAY[]::integer[]."),
					 parser_errposition(pstate, a->location)));
1575 1576

		/* Select a common type for the elements */
1577
		coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
1578 1579 1580 1581 1582 1583 1584 1585

		if (newa->multidims)
		{
			array_type = coerce_type;
			element_type = get_element_type(array_type);
			if (!OidIsValid(element_type))
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_OBJECT),
1586 1587
					   errmsg("could not find element type for data type %s",
							  format_type_be(array_type)),
1588
						 parser_errposition(pstate, a->location)));
1589 1590 1591 1592 1593 1594 1595 1596 1597
		}
		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",
1598 1599
								format_type_be(element_type)),
						 parser_errposition(pstate, a->location)));
1600 1601 1602
		}
		coerce_hard = false;
	}
1603

1604
	/*
1605
	 * Coerce elements to target type
1606 1607 1608 1609 1610 1611 1612
	 *
	 * 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().
1613
	 */
1614 1615 1616 1617 1618
	foreach(element, newelems)
	{
		Node	   *e = (Node *) lfirst(element);
		Node	   *newe;

1619 1620
		if (coerce_hard)
		{
1621
			newe = coerce_to_target_type(pstate, e,
1622
										 exprType(e),
1623
										 coerce_type,
1624 1625
										 typmod,
										 COERCION_EXPLICIT,
1626 1627
										 COERCE_EXPLICIT_CAST,
										 -1);
1628 1629 1630 1631 1632
			if (newe == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_CANNOT_COERCE),
						 errmsg("cannot cast type %s to %s",
								format_type_be(exprType(e)),
1633 1634
								format_type_be(coerce_type)),
						 parser_errposition(pstate, exprLocation(e))));
1635 1636 1637 1638 1639
		}
		else
			newe = coerce_to_common_type(pstate, e,
										 coerce_type,
										 "ARRAY");
1640 1641 1642 1643 1644 1645
		newcoercedelems = lappend(newcoercedelems, newe);
	}

	newa->array_typeid = array_type;
	newa->element_typeid = element_type;
	newa->elements = newcoercedelems;
1646
	newa->location = a->location;
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656

	return (Node *) newa;
}

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

	/* Transform the field expressions */
1657
	newr->args = transformExpressionList(pstate, r->args);
1658 1659 1660 1661

	/* Barring later casting, we consider the type RECORD */
	newr->row_typeid = RECORDOID;
	newr->row_format = COERCE_IMPLICIT_CAST;
1662
	newr->colnames = NIL;		/* ROW() has anonymous columns */
1663
	newr->location = r->location;
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684

	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);
	}

1685
	newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

	/* 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;
1700
	newc->location = c->location;
1701 1702 1703
	return (Node *) newc;
}

1704 1705 1706 1707 1708 1709
static Node *
transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
{
	MinMaxExpr *newm = makeNode(MinMaxExpr);
	List	   *newargs = NIL;
	List	   *newcoercedargs = NIL;
1710
	const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
	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);
	}

1723
	newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
1724 1725 1726 1727 1728 1729 1730 1731 1732

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

		newe = coerce_to_common_type(pstate, e,
									 newm->minmaxtype,
1733
									 funcname);
1734 1735 1736 1737
		newcoercedargs = lappend(newcoercedargs, newe);
	}

	newm->args = newcoercedargs;
1738
	newm->location = m->location;
1739 1740 1741
	return (Node *) newm;
}

1742
static Node *
1743
transformXmlExpr(ParseState *pstate, XmlExpr *x)
1744
{
B
Bruce Momjian 已提交
1745 1746
	XmlExpr    *newx = makeNode(XmlExpr);
	ListCell   *lc;
1747 1748 1749 1750
	int			i;

	newx->op = x->op;
	if (x->name)
1751
		newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
1752 1753
	else
		newx->name = NULL;
1754 1755
	newx->xmloption = x->xmloption;
	newx->location = x->location;
1756 1757

	/*
B
Bruce Momjian 已提交
1758
	 * gram.y built the named args as a list of ResTarget.	Transform each,
1759 1760 1761 1762 1763 1764 1765
	 * and break the names out as a separate list.
	 */
	newx->named_args = NIL;
	newx->arg_names = NIL;

	foreach(lc, x->named_args)
	{
B
Bruce Momjian 已提交
1766 1767 1768
		ResTarget  *r = (ResTarget *) lfirst(lc);
		Node	   *expr;
		char	   *argname;
1769 1770 1771 1772 1773 1774

		Assert(IsA(r, ResTarget));

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

		if (r->name)
1775
			argname = map_sql_identifier_to_xml_name(r->name, false, false);
1776 1777
		else if (IsA(r->val, ColumnRef))
			argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
1778
													 true, false);
1779 1780 1781 1782 1783
		else
		{
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 x->op == IS_XMLELEMENT
1784 1785
			? errmsg("unnamed XML attribute value must be a column reference")
			: errmsg("unnamed XML element value must be a column reference"),
1786
					 parser_errposition(pstate, r->location)));
1787 1788 1789
			argname = NULL;		/* keep compiler quiet */
		}

1790 1791
		/* reject duplicate argnames in XMLELEMENT only */
		if (x->op == IS_XMLELEMENT)
1792
		{
B
Bruce Momjian 已提交
1793
			ListCell   *lc2;
1794

1795
			foreach(lc2, newx->arg_names)
1796
			{
1797
				if (strcmp(argname, strVal(lfirst(lc2))) == 0)
1798 1799
					ereport(ERROR,
							(errcode(ERRCODE_SYNTAX_ERROR),
1800 1801
					errmsg("XML attribute name \"%s\" appears more than once",
						   argname),
1802
							 parser_errposition(pstate, r->location)));
1803 1804
			}
		}
1805 1806 1807

		newx->named_args = lappend(newx->named_args, expr);
		newx->arg_names = lappend(newx->arg_names, makeString(argname));
1808 1809
	}

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
	/* 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;
P
Peter Eisentraut 已提交
1825 1826 1827
			case IS_XMLELEMENT:
				/* no coercion necessary */
				break;
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
			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
1851 1852
					newe = coerce_to_specific_type(pstate, newe, INT4OID,
												   "XMLROOT");
1853
				break;
1854 1855
			case IS_XMLSERIALIZE:
				/* not handled here */
1856
				Assert(false);
1857
				break;
1858 1859 1860 1861
			case IS_DOCUMENT:
				newe = coerce_to_specific_type(pstate, newe, XMLOID,
											   "IS DOCUMENT");
				break;
1862 1863 1864 1865
		}
		newx->args = lappend(newx->args, newe);
		i++;
	}
1866

1867 1868 1869
	return (Node *) newx;
}

1870
static Node *
1871
transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
1872
{
1873 1874
	Node	   *result;
	XmlExpr    *xexpr;
1875 1876 1877 1878 1879 1880
	Oid			targetType;
	int32		targetTypmod;

	xexpr = makeNode(XmlExpr);
	xexpr->op = IS_XMLSERIALIZE;
	xexpr->args = list_make1(coerce_to_specific_type(pstate,
B
Bruce Momjian 已提交
1881
											 transformExpr(pstate, xs->expr),
1882 1883 1884
													 XMLOID,
													 "XMLSERIALIZE"));

1885
	targetType = typenameTypeId(pstate, xs->typeName, &targetTypmod);
1886 1887

	xexpr->xmloption = xs->xmloption;
1888
	xexpr->location = xs->location;
1889 1890 1891 1892 1893
	/* We actually only need these to be able to parse back the expression. */
	xexpr->type = targetType;
	xexpr->typmod = targetTypmod;

	/*
B
Bruce Momjian 已提交
1894 1895 1896 1897
	 * 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.
1898
	 */
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
	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;
1911 1912
}

1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
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);
B
Bruce Momjian 已提交
1941
			clausename = NULL;	/* keep compiler quiet */
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
	}

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

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

	return (Node *) b;
}

1953
static Node *
1954
transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
1955
{
B
Bruce Momjian 已提交
1956
	int			sublevels_up;
1957 1958 1959 1960 1961 1962 1963 1964

	/* 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);

1965
	/*
1966 1967 1968
	 * Check to see if the cursor name matches a parameter of type REFCURSOR.
	 * If so, replace the raw name reference with a parameter reference.
	 * (This is a hack for the convenience of plpgsql.)
1969
	 */
1970
	if (cexpr->cursor_name != NULL)			/* in case already transformed */
1971
	{
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
		ColumnRef  *cref = makeNode(ColumnRef);
		Node	   *node = NULL;

		/* Build an unqualified ColumnRef with the given name */
		cref->fields = list_make1(makeString(cexpr->cursor_name));
		cref->location = -1;

		/* See if there is a translation available from a parser hook */
		if (pstate->p_pre_columnref_hook != NULL)
			node = (*pstate->p_pre_columnref_hook) (pstate, cref);
		if (node == NULL && pstate->p_post_columnref_hook != NULL)
			node = (*pstate->p_post_columnref_hook) (pstate, cref, NULL);

		/*
		 * XXX Should we throw an error if we get a translation that isn't
		 * a refcursor Param?  For now it seems best to silently ignore
		 * false matches.
		 */
		if (node != NULL && IsA(node, Param))
		{
			Param  *p = (Param *) node;

			if (p->paramkind == PARAM_EXTERN &&
				p->paramtype == REFCURSOROID)
			{
				/* Matches, so convert CURRENT OF to a param reference */
				cexpr->cursor_name = NULL;
				cexpr->cursor_param = p->paramid;
			}
		}
2002 2003 2004 2005 2006
	}

	return (Node *) cexpr;
}

2007 2008 2009
/*
 * Construct a whole-row reference to represent the notation "relation.*".
 *
2010
 * A whole-row reference is a Var with varno set to the correct range
2011 2012 2013 2014 2015 2016
 * 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 *
2017
transformWholeRowRef(ParseState *pstate, RangeTblEntry *rte, int location)
2018
{
2019
	Var		   *result;
2020 2021 2022 2023
	int			vnum;
	int			sublevels_up;
	Oid			toid;

2024
	/* Find the RTE's rangetable location */
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037

	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);
2038 2039 2040 2041 2042
			result = makeVar(vnum,
							 InvalidAttrNumber,
							 toid,
							 -1,
							 sublevels_up);
2043 2044 2045
			break;
		case RTE_FUNCTION:
			toid = exprType(rte->funcexpr);
2046
			if (type_is_rowtype(toid))
2047 2048
			{
				/* func returns composite; same as relation case */
2049 2050 2051 2052 2053
				result = makeVar(vnum,
								 InvalidAttrNumber,
								 toid,
								 -1,
								 sublevels_up);
2054 2055 2056 2057 2058 2059 2060 2061 2062
			}
			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 ...)
				 */
2063 2064 2065 2066 2067
				result = makeVar(vnum,
								 1,
								 toid,
								 -1,
								 sublevels_up);
2068 2069
			}
			break;
2070 2071 2072
		case RTE_VALUES:
			toid = RECORDOID;
			/* returns composite; same as relation case */
2073 2074 2075 2076 2077
			result = makeVar(vnum,
							 InvalidAttrNumber,
							 toid,
							 -1,
							 sublevels_up);
2078
			break;
2079
		default:
B
Bruce Momjian 已提交
2080

2081
			/*
B
Bruce Momjian 已提交
2082 2083 2084 2085
			 * 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.)
2086
			 */
2087 2088 2089 2090 2091
			result = makeVar(vnum,
							 InvalidAttrNumber,
							 RECORDOID,
							 -1,
							 sublevels_up);
2092 2093 2094
			break;
	}

2095 2096 2097
	/* location is not filled in by makeVar */
	result->location = location;

2098 2099 2100
	/* mark relation as requiring whole-row SELECT access */
	markVarForSelectPriv(pstate, result, rte);

2101
	return (Node *) result;
2102 2103
}

2104
/*
2105
 * Handle an explicit CAST construct.
2106
 *
2107 2108
 * Transform the argument, then look up the type name and apply any necessary
 * coercion function(s).
2109 2110
 */
static Node *
2111
transformTypeCast(ParseState *pstate, TypeCast *tc)
2112
{
2113 2114
	Node	   *result;
	Node	   *expr = transformExpr(pstate, tc->arg);
2115 2116
	Oid			inputType = exprType(expr);
	Oid			targetType;
2117
	int32		targetTypmod;
2118
	int			location;
2119

2120
	targetType = typenameTypeId(pstate, tc->typeName, &targetTypmod);
2121 2122 2123 2124

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

2125 2126 2127 2128 2129 2130 2131
	/*
	 * 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)
2132
		location = tc->typeName->location;
2133 2134 2135 2136 2137 2138 2139

	result = coerce_to_target_type(pstate, expr, inputType,
								   targetType, targetTypmod,
								   COERCION_EXPLICIT,
								   COERCE_EXPLICIT_CAST,
								   location);
	if (result == NULL)
2140 2141 2142 2143
		ereport(ERROR,
				(errcode(ERRCODE_CANNOT_COERCE),
				 errmsg("cannot cast type %s to %s",
						format_type_be(inputType),
2144
						format_type_be(targetType)),
2145
				 parser_coercion_errposition(pstate, location, expr)));
2146

2147
	return result;
2148
}
2149 2150

/*
2151
 * Transform a "row compare-op row" construct
2152
 *
2153 2154 2155 2156 2157 2158 2159 2160
 * 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 < <= > >=).
2161 2162
 */
static Node *
2163
make_row_comparison_op(ParseState *pstate, List *opname,
2164
					   List *largs, List *rargs, int location)
2165
{
2166 2167 2168 2169
	RowCompareExpr *rcexpr;
	RowCompareType rctype;
	List	   *opexprs;
	List	   *opnos;
2170
	List	   *opfamilies;
2171 2172
	ListCell   *l,
			   *r;
2173
	List	  **opfamily_lists;
2174 2175 2176 2177 2178 2179 2180
	List	  **opstrat_lists;
	Bitmapset  *strats;
	int			nopers;
	int			i;

	nopers = list_length(largs);
	if (nopers != list_length(rargs))
2181 2182
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
2183 2184
				 errmsg("unequal number of entries in row expressions"),
				 parser_errposition(pstate, location)));
2185 2186

	/*
B
Bruce Momjian 已提交
2187 2188
	 * We can't compare zero-length rows because there is no principled basis
	 * for figuring out what the operator is.
2189
	 */
2190
	if (nopers == 0)
2191 2192
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2193 2194
				 errmsg("cannot compare rows of zero length"),
				 parser_errposition(pstate, location)));
2195

2196
	/*
B
Bruce Momjian 已提交
2197 2198
	 * Identify all the pairwise operators, using make_op so that behavior is
	 * the same as in the simple scalar case.
2199 2200
	 */
	opexprs = NIL;
2201
	forboth(l, largs, r, rargs)
2202
	{
B
Bruce Momjian 已提交
2203 2204
		Node	   *larg = (Node *) lfirst(l);
		Node	   *rarg = (Node *) lfirst(r);
2205
		OpExpr	   *cmp;
2206

2207
		cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
2208 2209 2210 2211 2212
		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
2213
		 * doesn't yield bool it won't be in any index opfamilies...
2214 2215 2216 2217
		 */
		if (cmp->opresulttype != BOOLOID)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
B
Bruce Momjian 已提交
2218 2219 2220
				   errmsg("row comparison operator must yield type boolean, "
						  "not type %s",
						  format_type_be(cmp->opresulttype)),
2221
					 parser_errposition(pstate, location)));
2222 2223 2224
		if (expression_returns_set((Node *) cmp))
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
2225 2226
					 errmsg("row comparison operator must not return a set"),
					 parser_errposition(pstate, location)));
2227 2228 2229 2230
		opexprs = lappend(opexprs, cmp);
	}

	/*
B
Bruce Momjian 已提交
2231 2232 2233
	 * 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).
2234 2235 2236 2237 2238 2239
	 */
	if (nopers == 1)
		return (Node *) linitial(opexprs);

	/*
	 * Now we must determine which row comparison semantics (= <> < <= > >=)
B
Bruce Momjian 已提交
2240 2241 2242
	 * apply to this set of operators.	We look for btree opfamilies
	 * containing the operators, and see which interpretations (strategy
	 * numbers) exist for each operator.
2243
	 */
2244
	opfamily_lists = (List **) palloc(nopers * sizeof(List *));
2245 2246 2247 2248 2249
	opstrat_lists = (List **) palloc(nopers * sizeof(List *));
	strats = NULL;
	i = 0;
	foreach(l, opexprs)
	{
2250
		Oid			opno = ((OpExpr *) lfirst(l))->opno;
B
Bruce Momjian 已提交
2251
		Bitmapset  *this_strats;
2252 2253
		ListCell   *j;

2254 2255
		get_op_btree_interpretation(opno,
									&opfamily_lists[i], &opstrat_lists[i]);
B
Bruce Momjian 已提交
2256

2257
		/*
B
Bruce Momjian 已提交
2258 2259
		 * convert strategy number list to a Bitmapset to make the
		 * intersection calculation easy.
2260 2261 2262 2263 2264 2265 2266 2267
		 */
		this_strats = NULL;
		foreach(j, opstrat_lists[i])
		{
			this_strats = bms_add_member(this_strats, lfirst_int(j));
		}
		if (i == 0)
			strats = this_strats;
2268
		else
2269 2270
			strats = bms_int_members(strats, this_strats);
		i++;
2271 2272
	}

2273 2274 2275 2276 2277 2278 2279
	/*
	 * 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)
2280
	{
2281 2282 2283 2284 2285 2286 2287
		/* 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)));
2288
	}
2289
	rctype = (RowCompareType) i;
2290 2291

	/*
B
Bruce Momjian 已提交
2292 2293
	 * For = and <> cases, we just combine the pairwise operators with AND or
	 * OR respectively.
2294 2295
	 *
	 * Note: this is presently the only place where the parser generates
B
Bruce Momjian 已提交
2296 2297
	 * BoolExpr with more than two arguments.  Should be OK since the rest of
	 * the system thinks BoolExpr is N-argument anyway.
2298 2299
	 */
	if (rctype == ROWCOMPARE_EQ)
2300
		return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
2301
	if (rctype == ROWCOMPARE_NE)
2302
		return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
2303 2304

	/*
2305
	 * Otherwise we need to choose exactly which opfamily to associate with
B
Bruce Momjian 已提交
2306
	 * each operator.
2307
	 */
2308
	opfamilies = NIL;
2309 2310
	for (i = 0; i < nopers; i++)
	{
2311
		Oid			opfamily = InvalidOid;
2312

2313
		forboth(l, opfamily_lists[i], r, opstrat_lists[i])
2314
		{
B
Bruce Momjian 已提交
2315
			int			opstrat = lfirst_int(r);
2316 2317 2318

			if (opstrat == rctype)
			{
2319 2320
				opfamily = lfirst_oid(l);
				break;
2321 2322
			}
		}
2323 2324
		if (OidIsValid(opfamily))
			opfamilies = lappend_oid(opfamilies, opfamily);
B
Bruce Momjian 已提交
2325
		else	/* should not happen */
2326 2327 2328 2329
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("could not determine interpretation of row comparison operator %s",
							strVal(llast(opname))),
B
Bruce Momjian 已提交
2330
			   errdetail("There are multiple equally-plausible candidates."),
2331
					 parser_errposition(pstate, location)));
2332 2333
	}

2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
	/*
	 * 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;
2355
	rcexpr->opfamilies = opfamilies;
2356 2357 2358 2359
	rcexpr->largs = largs;
	rcexpr->rargs = rargs;

	return (Node *) rcexpr;
2360 2361 2362 2363
}

/*
 * Transform a "row IS DISTINCT FROM row" construct
2364 2365
 *
 * The input RowExprs are already transformed
2366 2367 2368
 */
static Node *
make_row_distinct_op(ParseState *pstate, List *opname,
2369 2370
					 RowExpr *lrow, RowExpr *rrow,
					 int location)
2371 2372
{
	Node	   *result = NULL;
2373 2374
	List	   *largs = lrow->args;
	List	   *rargs = rrow->args;
2375 2376
	ListCell   *l,
			   *r;
2377

2378
	if (list_length(largs) != list_length(rargs))
2379 2380
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
2381 2382
				 errmsg("unequal number of entries in row expressions"),
				 parser_errposition(pstate, location)));
2383

2384
	forboth(l, largs, r, rargs)
2385
	{
B
Bruce Momjian 已提交
2386 2387 2388
		Node	   *larg = (Node *) lfirst(l);
		Node	   *rarg = (Node *) lfirst(r);
		Node	   *cmp;
2389

2390
		cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
2391 2392 2393 2394
		if (result == NULL)
			result = cmp;
		else
			result = (Node *) makeBoolExpr(OR_EXPR,
2395 2396
										   list_make2(result, cmp),
										   location);
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
	}

	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 *
2412 2413
make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
				 int location)
2414
{
B
Bruce Momjian 已提交
2415
	Expr	   *result;
2416

2417
	result = make_op(pstate, opname, ltree, rtree, location);
2418 2419 2420
	if (((OpExpr *) result)->opresulttype != BOOLOID)
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
B
Bruce Momjian 已提交
2421
			 errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
2422
				 parser_errposition(pstate, location)));
B
Bruce Momjian 已提交
2423

2424
	/*
B
Bruce Momjian 已提交
2425
	 * We rely on DistinctExpr and OpExpr being same struct
2426 2427 2428 2429 2430
	 */
	NodeSetTag(result, T_DistinctExpr);

	return result;
}