parse_expr.c 27.3 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * parse_expr.c
 *	  handle expressions in parser
 *
6
 * Portions Copyright (c) 1996-2001, 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
Bruce Momjian's avatar
Bruce Momjian committed
11
 *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_expr.c,v 1.106 2002/03/06 20:34:52 momjian Exp $
12 13 14 15 16
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"
17 18

#include "catalog/pg_operator.h"
19
#include "catalog/pg_proc.h"
20 21
#include "nodes/makefuncs.h"
#include "nodes/params.h"
22
#include "parser/analyze.h"
23
#include "parser/gramparse.h"
24
#include "parser/parse.h"
Bruce Momjian's avatar
Bruce Momjian committed
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 30
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
Bruce Momjian's avatar
Bruce Momjian committed
31
#include "parser/parse_type.h"
32
#include "utils/builtins.h"
33
#include "utils/syscache.h"
34

35

36
int			max_expr_depth = DEFAULT_MAX_EXPR_DEPTH;
37 38
static int	expr_depth_counter = 0;

39 40
bool		Transform_null_equals = false;

41 42
static Node *parser_typecast_constant(Value *expr, TypeName *typename);
static Node *parser_typecast_expression(ParseState *pstate,
43
						   Node *expr, TypeName *typename);
44 45 46
static Node *transformAttr(ParseState *pstate, Attr *att, int precedence);
static Node *transformIdent(ParseState *pstate, Ident *ident, int precedence);
static Node *transformIndirection(ParseState *pstate, Node *basenode,
47
					 List *indirection);
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62

/*
 * Initialize for parsing a new query.
 *
 * We reset the expression depth counter here, in case it was left nonzero
 * due to elog()'ing out of the last parsing operation.
 */
void
parse_expr_init(void)
{
	expr_depth_counter = 0;
}


63 64
/*
 * transformExpr -
65
 *	  Analyze and transform expressions. Type checking and type casting is
66 67 68
 *	  done here. The optimizer and the executor cannot handle the original
 *	  (raw) expressions collected by the parse tree. Hence the transformation
 *	  here.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
 *
 * NOTE: there are various cases in which this routine will get applied to
 * 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
 *	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.
86 87 88 89 90 91 92 93 94
 */
Node *
transformExpr(ParseState *pstate, Node *expr, int precedence)
{
	Node	   *result = NULL;

	if (expr == NULL)
		return NULL;

95
	/*
96 97
	 * Guard against an overly complex expression leading to coredump due
	 * to stack overflow here, or in later recursive routines that
98 99 100 101 102 103 104 105
	 * traverse expression trees.  Note that this is very unlikely to
	 * happen except with pathological queries; but we don't want someone
	 * to be able to crash the backend quite that easily...
	 */
	if (++expr_depth_counter > max_expr_depth)
		elog(ERROR, "Expression too complex: nesting depth exceeds max_expr_depth = %d",
			 max_expr_depth);

106 107 108 109
	switch (nodeTag(expr))
	{
		case T_Attr:
			{
110
				result = transformAttr(pstate, (Attr *) expr, precedence);
111 112 113 114 115 116 117 118
				break;
			}
		case T_A_Const:
			{
				A_Const    *con = (A_Const *) expr;
				Value	   *val = &con->val;

				if (con->typename != NULL)
119
					result = parser_typecast_constant(val, con->typename);
120 121 122 123 124 125 126
				else
					result = (Node *) make_const(val);
				break;
			}
		case T_ParamNo:
			{
				ParamNo    *pno = (ParamNo *) expr;
127 128
				int			paramno = pno->number;
				Oid			toid = param_type(paramno);
129
				Param	   *param = makeNode(Param);
130 131

				if (!OidIsValid(toid))
132
					elog(ERROR, "Parameter '$%d' is out of range", paramno);
133 134 135
				param->paramkind = PARAM_NUM;
				param->paramid = (AttrNumber) paramno;
				param->paramname = "<unnamed>";
136
				param->paramtype = toid;
137
				result = transformIndirection(pstate, (Node *) param,
138
											  pno->indirection);
139 140 141 142
				/* cope with typecast applied to param */
				if (pno->typename != NULL)
					result = parser_typecast_expression(pstate, result,
														pno->typename);
143 144 145 146 147 148 149 150
				break;
			}
		case T_TypeCast:
			{
				TypeCast   *tc = (TypeCast *) expr;
				Node	   *arg = transformExpr(pstate, tc->arg, precedence);

				result = parser_typecast_expression(pstate, arg, tc->typename);
151 152 153 154 155 156 157 158 159 160
				break;
			}
		case T_A_Expr:
			{
				A_Expr	   *a = (A_Expr *) expr;

				switch (a->oper)
				{
					case OP:
						{
161
							/*
162 163 164 165
							 * Special-case "foo = NULL" and "NULL = foo"
							 * for compatibility with standards-broken
							 * products (like Microsoft's).  Turn these
							 * into IS NULL exprs.
166
							 */
Tom Lane's avatar
Tom Lane committed
167 168 169 170
							if (Transform_null_equals &&
								strcmp(a->opname, "=") == 0 &&
								(exprIsNullConstant(a->lexpr) ||
								 exprIsNullConstant(a->rexpr)))
171
							{
172 173
								NullTest   *n = makeNode(NullTest);

174 175 176 177 178 179 180
								n->nulltesttype = IS_NULL;

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

Tom Lane's avatar
Tom Lane committed
181 182 183
								result = transformExpr(pstate,
													   (Node *) n,
													   precedence);
184 185 186 187
							}
							else
							{
								Node	   *lexpr = transformExpr(pstate,
188 189
																a->lexpr,
															 precedence);
190
								Node	   *rexpr = transformExpr(pstate,
191 192
																a->rexpr,
															 precedence);
193

Tom Lane's avatar
Tom Lane committed
194 195 196
								result = (Node *) make_op(a->opname,
														  lexpr,
														  rexpr);
197
							}
198 199 200 201
						}
						break;
					case AND:
						{
202 203 204 205 206 207
							Node	   *lexpr = transformExpr(pstate,
															  a->lexpr,
															  precedence);
							Node	   *rexpr = transformExpr(pstate,
															  a->rexpr,
															  precedence);
208 209
							Expr	   *expr = makeNode(Expr);

210
							if (!coerce_to_boolean(pstate, &lexpr))
211
								elog(ERROR, "left-hand side of AND is type '%s', not '%s'",
212 213
									 format_type_be(exprType(lexpr)),
									 format_type_be(BOOLOID));
214

215
							if (!coerce_to_boolean(pstate, &rexpr))
216
								elog(ERROR, "right-hand side of AND is type '%s', not '%s'",
217 218
									 format_type_be(exprType(rexpr)),
									 format_type_be(BOOLOID));
219

220 221
							expr->typeOid = BOOLOID;
							expr->opType = AND_EXPR;
222
							expr->args = makeList2(lexpr, rexpr);
223 224 225 226 227
							result = (Node *) expr;
						}
						break;
					case OR:
						{
228 229 230 231 232 233
							Node	   *lexpr = transformExpr(pstate,
															  a->lexpr,
															  precedence);
							Node	   *rexpr = transformExpr(pstate,
															  a->rexpr,
															  precedence);
234 235
							Expr	   *expr = makeNode(Expr);

236
							if (!coerce_to_boolean(pstate, &lexpr))
237
								elog(ERROR, "left-hand side of OR is type '%s', not '%s'",
238 239
									 format_type_be(exprType(lexpr)),
									 format_type_be(BOOLOID));
240

241
							if (!coerce_to_boolean(pstate, &rexpr))
242
								elog(ERROR, "right-hand side of OR is type '%s', not '%s'",
243 244
									 format_type_be(exprType(rexpr)),
									 format_type_be(BOOLOID));
245

246 247
							expr->typeOid = BOOLOID;
							expr->opType = OR_EXPR;
248
							expr->args = makeList2(lexpr, rexpr);
249 250 251 252 253
							result = (Node *) expr;
						}
						break;
					case NOT:
						{
254 255 256
							Node	   *rexpr = transformExpr(pstate,
															  a->rexpr,
															  precedence);
257 258
							Expr	   *expr = makeNode(Expr);

259
							if (!coerce_to_boolean(pstate, &rexpr))
260
								elog(ERROR, "argument to NOT is type '%s', not '%s'",
261 262
									 format_type_be(exprType(rexpr)),
									 format_type_be(BOOLOID));
263

264 265
							expr->typeOid = BOOLOID;
							expr->opType = NOT_EXPR;
266
							expr->args = makeList1(rexpr);
267 268 269 270 271 272 273 274
							result = (Node *) expr;
						}
						break;
				}
				break;
			}
		case T_Ident:
			{
275
				result = transformIdent(pstate, (Ident *) expr, precedence);
276 277 278 279 280 281 282 283 284
				break;
			}
		case T_FuncCall:
			{
				FuncCall   *fn = (FuncCall *) expr;
				List	   *args;

				/* transform the list of arguments */
				foreach(args, fn->args)
285 286 287
					lfirst(args) = transformExpr(pstate,
												 (Node *) lfirst(args),
												 precedence);
288
				result = ParseFuncOrColumn(pstate,
289 290
										   fn->funcname,
										   fn->args,
291 292
										   fn->agg_star,
										   fn->agg_distinct,
293
										   precedence);
294 295
				break;
			}
296 297
		case T_SubLink:
			{
298
				SubLink    *sublink = (SubLink *) expr;
299 300
				List	   *qtrees;
				Query	   *qtree;
Bruce Momjian's avatar
Bruce Momjian committed
301

302 303 304 305 306 307
				/* If we already transformed this node, do nothing */
				if (IsA(sublink->subselect, Query))
				{
					result = expr;
					break;
				}
Bruce Momjian's avatar
Bruce Momjian committed
308
				pstate->p_hasSubLinks = true;
309
				qtrees = parse_analyze(sublink->subselect, pstate);
310
				if (length(qtrees) != 1)
311
					elog(ERROR, "Bad query in subselect");
312 313 314
				qtree = (Query *) lfirst(qtrees);
				if (qtree->commandType != CMD_SELECT ||
					qtree->resultRelation != 0)
315
					elog(ERROR, "Bad query in subselect");
316
				sublink->subselect = (Node *) qtree;
317

318 319
				if (sublink->subLinkType == EXISTS_SUBLINK)
				{
320 321
					/*
					 * EXISTS needs no lefthand or combining operator.
322 323 324 325 326
					 * These fields should be NIL already, but make sure.
					 */
					sublink->lefthand = NIL;
					sublink->oper = NIL;
				}
327 328 329 330
				else if (sublink->subLinkType == EXPR_SUBLINK)
				{
					List	   *tlist = qtree->targetList;

331 332
					/*
					 * Make sure the subselect delivers a single column
333 334 335 336
					 * (ignoring resjunk targets).
					 */
					if (tlist == NIL ||
						((TargetEntry *) lfirst(tlist))->resdom->resjunk)
337
						elog(ERROR, "Subselect must have a field");
338 339
					while ((tlist = lnext(tlist)) != NIL)
					{
340
						if (!((TargetEntry *) lfirst(tlist))->resdom->resjunk)
341
							elog(ERROR, "Subselect must have only one field");
342
					}
343 344 345 346

					/*
					 * EXPR needs no lefthand or combining operator. These
					 * fields should be NIL already, but make sure.
347 348 349 350
					 */
					sublink->lefthand = NIL;
					sublink->oper = NIL;
				}
351
				else
352
				{
353
					/* ALL, ANY, or MULTIEXPR: generate operator list */
354 355
					List	   *left_list = sublink->lefthand;
					List	   *right_list = qtree->targetList;
356
					char	   *op;
357
					List	   *elist;
Bruce Momjian's avatar
Bruce Momjian committed
358

359 360 361
					foreach(elist, left_list)
						lfirst(elist) = transformExpr(pstate, lfirst(elist),
													  precedence);
362

363 364 365 366
					Assert(IsA(sublink->oper, A_Expr));
					op = ((A_Expr *) sublink->oper)->opname;
					sublink->oper = NIL;

367 368
					/* Combining operators other than =/<> is dubious... */
					if (length(left_list) != 1 &&
369
						strcmp(op, "=") != 0 && strcmp(op, "<>") != 0)
370
						elog(ERROR, "Row comparison cannot use '%s'",
371
							 op);
372

373 374 375 376 377 378
					/*
					 * Scan subquery's targetlist to find values that will
					 * be matched against lefthand values.	We need to
					 * ignore resjunk targets, so doing the outer
					 * iteration over right_list is easier than doing it
					 * over left_list.
379 380
					 */
					while (right_list != NIL)
Bruce Momjian's avatar
Bruce Momjian committed
381
					{
382 383
						TargetEntry *tent = (TargetEntry *) lfirst(right_list);
						Node	   *lexpr;
384 385 386
						Operator	optup;
						Form_pg_operator opform;
						Oper	   *newop;
Bruce Momjian's avatar
Bruce Momjian committed
387

388
						right_list = lnext(right_list);
389 390 391 392
						if (tent->resdom->resjunk)
							continue;

						if (left_list == NIL)
393
							elog(ERROR, "Subselect has too many fields");
394 395 396
						lexpr = lfirst(left_list);
						left_list = lnext(left_list);

397
						/*
398 399 400
						 * It's OK to use oper() not compatible_oper()
						 * here, because make_subplan() will insert type
						 * coercion calls if needed.
401
						 */
402 403 404
						optup = oper(op,
									 exprType(lexpr),
									 exprType(tent->expr),
405
									 false);
406 407
						opform = (Form_pg_operator) GETSTRUCT(optup);

408
						if (opform->oprresult != BOOLOID)
409 410 411 412
							elog(ERROR, "'%s' result type of '%s' must return '%s'"
								 " to be used with quantified predicate subquery",
								 op, typeidTypeName(opform->oprresult),
								 typeidTypeName(BOOLOID));
413

414 415
						newop = makeOper(oprid(optup),	/* opno */
										 InvalidOid,	/* opid */
416
										 opform->oprresult);
417
						sublink->oper = lappend(sublink->oper, newop);
418
						ReleaseSysCache(optup);
Bruce Momjian's avatar
Bruce Momjian committed
419
					}
420
					if (left_list != NIL)
421
						elog(ERROR, "Subselect has too few fields");
422
				}
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
423
				result = (Node *) expr;
424 425
				break;
			}
426

427 428 429
		case T_CaseExpr:
			{
				CaseExpr   *c = (CaseExpr *) expr;
430 431
				CaseExpr   *newc = makeNode(CaseExpr);
				List	   *newargs = NIL;
432
				List	   *typeids = NIL;
433
				List	   *args;
434
				Node	   *defresult;
435 436 437 438 439
				Oid			ptype;

				/* transform the list of arguments */
				foreach(args, c->args)
				{
440 441 442 443 444 445 446
					CaseWhen   *w = (CaseWhen *) lfirst(args);
					CaseWhen   *neww = makeNode(CaseWhen);
					Node	   *warg;

					Assert(IsA(w, CaseWhen));

					warg = w->expr;
447 448
					if (c->arg != NULL)
					{
449
						/* shorthand form was specified, so expand... */
Bruce Momjian's avatar
Bruce Momjian committed
450 451
						A_Expr	   *a = makeNode(A_Expr);

452 453 454
						a->oper = OP;
						a->opname = "=";
						a->lexpr = c->arg;
455 456
						a->rexpr = warg;
						warg = (Node *) a;
457
					}
458 459
					neww->expr = transformExpr(pstate, warg, precedence);

460
					if (!coerce_to_boolean(pstate, &neww->expr))
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
						elog(ERROR, "WHEN clause must have a boolean result");

					/*
					 * result is NULL for NULLIF() construct - thomas
					 * 1998-11-11
					 */
					warg = w->result;
					if (warg == NULL)
					{
						A_Const    *n = makeNode(A_Const);

						n->val.type = T_Null;
						warg = (Node *) n;
					}
					neww->result = transformExpr(pstate, warg, precedence);

					newargs = lappend(newargs, neww);
					typeids = lappendi(typeids, exprType(neww->result));
479 480
				}

481 482
				newc->args = newargs;

Bruce Momjian's avatar
Bruce Momjian committed
483 484
				/*
				 * It's not shorthand anymore, so drop the implicit
485 486
				 * argument. This is necessary to keep any re-application
				 * of transformExpr from doing the wrong thing.
487
				 */
488
				newc->arg = NULL;
489 490

				/* transform the default clause */
491 492
				defresult = c->defresult;
				if (defresult == NULL)
493
				{
Bruce Momjian's avatar
Bruce Momjian committed
494 495
					A_Const    *n = makeNode(A_Const);

496
					n->val.type = T_Null;
497
					defresult = (Node *) n;
498
				}
499
				newc->defresult = transformExpr(pstate, defresult, precedence);
500

501 502
				/*
				 * Note: default result is considered the most significant
503 504 505
				 * type in determining preferred type.	This is how the
				 * code worked before, but it seems a little bogus to me
				 * --- tgl
506
				 */
507
				typeids = lconsi(exprType(newc->defresult), typeids);
508

509
				ptype = select_common_type(typeids, "CASE");
510
				newc->casetype = ptype;
511

512
				/* Convert default result clause, if necessary */
513 514 515 516
				newc->defresult = coerce_to_common_type(pstate,
														newc->defresult,
														ptype,
														"CASE/ELSE");
517

518
				/* Convert when-clause results, if necessary */
519
				foreach(args, newc->args)
520
				{
521
					CaseWhen   *w = (CaseWhen *) lfirst(args);
522

523 524 525 526
					w->result = coerce_to_common_type(pstate,
													  w->result,
													  ptype,
													  "CASE/WHEN");
527
				}
528 529

				result = (Node *) newc;
530 531 532
				break;
			}

533 534 535 536 537 538 539 540 541 542 543 544
		case T_NullTest:
			{
				NullTest   *n = (NullTest *) expr;

				n->arg = transformExpr(pstate, n->arg, precedence);
				/* the argument can be any type, so don't coerce it */
				result = expr;
				break;
			}

		case T_BooleanTest:
			{
545
				BooleanTest *b = (BooleanTest *) expr;
546 547 548

				b->arg = transformExpr(pstate, b->arg, precedence);

549
				if (!coerce_to_boolean(pstate, &b->arg))
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
				{
					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, "transformExpr: unexpected booltesttype %d",
								 (int) b->booltesttype);
576
							clausename = NULL;	/* keep compiler quiet */
577 578 579 580 581 582 583 584 585
					}

					elog(ERROR, "Argument of %s must be boolean",
						 clausename);
				}
				result = expr;
				break;
			}

586 587 588 589 590 591 592 593
			/*
			 * 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.
			 */
594 595 596
		case T_Expr:
		case T_Var:
		case T_Const:
597
		case T_Param:
598 599
		case T_Aggref:
		case T_ArrayRef:
600
		case T_FieldSelect:
601
		case T_RelabelType:
602 603 604 605
			{
				result = (Node *) expr;
				break;
			}
606

607 608
		default:
			/* should not reach here */
609 610
			elog(ERROR, "transformExpr: does not know how to transform node %d"
				 " (internal error)", nodeTag(expr));
611 612 613
			break;
	}

614 615
	expr_depth_counter--;

616 617 618
	return result;
}

619
static Node *
620
transformIndirection(ParseState *pstate, Node *basenode, List *indirection)
621
{
622 623
	if (indirection == NIL)
		return basenode;
624 625
	return (Node *) transformArraySubscripts(pstate,
											 basenode, exprType(basenode),
626
											 indirection, false, NULL);
627
}
628

629 630 631 632 633
static Node *
transformAttr(ParseState *pstate, Attr *att, int precedence)
{
	Node	   *basenode;

634
	basenode = ParseNestedFuncOrColumn(pstate, att, precedence);
635
	return transformIndirection(pstate, basenode, att->indirection);
636 637 638 639 640 641
}

static Node *
transformIdent(ParseState *pstate, Ident *ident, int precedence)
{
	Node	   *result = NULL;
642
	int			sublevels_up;
643

644 645 646 647
	/*
	 * try to find the ident as a relation ... but not if subscripts
	 * appear
	 */
648
	if (ident->indirection == NIL &&
649
	 refnameRangeOrJoinEntry(pstate, ident->name, &sublevels_up) != NULL)
650 651
	{
		ident->isRel = TRUE;
652
		result = (Node *) ident;
653 654
	}

655
	if (result == NULL || precedence == EXPR_COLUMN_FIRST)
656
	{
657
		/* try to find the ident as a column */
658
		Node	   *var = colnameToVar(pstate, ident->name);
659 660

		if (var != NULL)
661 662
		{
			ident->isRel = FALSE;
663
			result = transformIndirection(pstate, var, ident->indirection);
664
		}
665 666 667
	}

	if (result == NULL)
668
		elog(ERROR, "Attribute '%s' not found", ident->name);
669 670 671 672 673 674 675 676 677 678 679

	return result;
}

/*
 *	exprType -
 *	  returns the Oid of the type of the expression. (Used for typechecking.)
 */
Oid
exprType(Node *expr)
{
680
	Oid			type = (Oid) InvalidOid;
681

682 683 684
	if (!expr)
		return type;

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
	switch (nodeTag(expr))
	{
		case T_Func:
			type = ((Func *) expr)->functype;
			break;
		case T_Iter:
			type = ((Iter *) expr)->itertype;
			break;
		case T_Var:
			type = ((Var *) expr)->vartype;
			break;
		case T_Expr:
			type = ((Expr *) expr)->typeOid;
			break;
		case T_Const:
			type = ((Const *) expr)->consttype;
			break;
		case T_ArrayRef:
			type = ((ArrayRef *) expr)->refelemtype;
			break;
Bruce Momjian's avatar
Bruce Momjian committed
705 706
		case T_Aggref:
			type = ((Aggref *) expr)->aggtype;
707 708 709 710
			break;
		case T_Param:
			type = ((Param *) expr)->paramtype;
			break;
711 712 713
		case T_FieldSelect:
			type = ((FieldSelect *) expr)->resulttype;
			break;
714 715 716
		case T_RelabelType:
			type = ((RelabelType *) expr)->resulttype;
			break;
717
		case T_SubLink:
718
			{
Bruce Momjian's avatar
Bruce Momjian committed
719 720
				SubLink    *sublink = (SubLink *) expr;

721 722
				if (sublink->subLinkType == EXPR_SUBLINK)
				{
723 724 725 726
					/* get the type of the subselect's first target column */
					Query	   *qtree = (Query *) sublink->subselect;
					TargetEntry *tent;

727
					if (!qtree || !IsA(qtree, Query))
728
						elog(ERROR, "Cannot get type for untransformed sublink");
729 730
					tent = (TargetEntry *) lfirst(qtree->targetList);
					type = tent->resdom->restype;
731 732 733 734 735 736 737
				}
				else
				{
					/* for all other sublink types, result is boolean */
					type = BOOLOID;
				}
			}
738
			break;
739 740 741 742 743 744
		case T_CaseExpr:
			type = ((CaseExpr *) expr)->casetype;
			break;
		case T_CaseWhen:
			type = exprType(((CaseWhen *) expr)->result);
			break;
745 746 747 748 749 750
		case T_NullTest:
			type = BOOLOID;
			break;
		case T_BooleanTest:
			type = BOOLOID;
			break;
751
		case T_Ident:
752
			/* XXX is this right? */
753 754 755
			type = UNKNOWNOID;
			break;
		default:
756
			elog(ERROR, "Do not know how to get type for %d node",
757 758 759 760 761 762
				 nodeTag(expr));
			break;
	}
	return type;
}

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
/*
 *	exprTypmod -
 *	  returns the type-specific attrmod of the expression, if it can be
 *	  determined.  In most cases, it can't and we return -1.
 */
int32
exprTypmod(Node *expr)
{
	if (!expr)
		return -1;

	switch (nodeTag(expr))
	{
		case T_Var:
			return ((Var *) expr)->vartypmod;
		case T_Const:
			{
				/* Be smart about string constants... */
781 782
				Const	   *con = (Const *) expr;

783 784 785
				switch (con->consttype)
				{
					case BPCHAROID:
786
						if (!con->constisnull)
787 788 789 790 791 792 793
							return VARSIZE(DatumGetPointer(con->constvalue));
						break;
					default:
						break;
				}
			}
			break;
794 795
		case T_Expr:
			{
796
				int32		coercedTypmod;
797 798 799 800 801 802

				/* Be smart about length-coercion functions... */
				if (exprIsLengthCoercion(expr, &coercedTypmod))
					return coercedTypmod;
			}
			break;
803 804 805
		case T_FieldSelect:
			return ((FieldSelect *) expr)->resulttypmod;
			break;
806 807 808
		case T_RelabelType:
			return ((RelabelType *) expr)->resulttypmod;
			break;
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
		case T_CaseExpr:
			{
				/*
				 * If all the alternatives agree on type/typmod, return
				 * that typmod, else use -1
				 */
				CaseExpr   *cexpr = (CaseExpr *) expr;
				Oid			casetype = cexpr->casetype;
				int32		typmod;
				List	   *arg;

				if (!cexpr->defresult)
					return -1;
				if (exprType(cexpr->defresult) != casetype)
					return -1;
				typmod = exprTypmod(cexpr->defresult);
				if (typmod < 0)
					return -1;	/* no point in trying harder */
				foreach(arg, cexpr->args)
				{
					CaseWhen   *w = (CaseWhen *) lfirst(arg);

					Assert(IsA(w, CaseWhen));
					if (exprType(w->result) != casetype)
						return -1;
					if (exprTypmod(w->result) != typmod)
						return -1;
				}
				return typmod;
			}
			break;
840 841 842 843 844 845
		default:
			break;
	}
	return -1;
}

846 847 848 849 850 851 852 853 854 855 856
/*
 * exprIsLengthCoercion
 *		Detect whether an expression tree is an application of a datatype's
 *		typmod-coercion function.  Optionally extract the result's typmod.
 *
 * If coercedTypmod is not NULL, the typmod is stored there if the expression
 * is a length-coercion function, else -1 is stored there.
 *
 * We assume that a two-argument function named for a datatype, whose
 * output and first argument types are that datatype, and whose second
 * input is an int32 constant, represents a forced length coercion.
857
 *
858 859 860 861 862 863 864 865
 * XXX It'd be better if the parsetree retained some explicit indication
 * of the coercion, so we didn't need these heuristics.
 */
bool
exprIsLengthCoercion(Node *expr, int32 *coercedTypmod)
{
	Func	   *func;
	Const	   *second_arg;
866 867
	HeapTuple	procTuple;
	HeapTuple	typeTuple;
868 869 870 871 872 873 874 875
	Form_pg_proc procStruct;
	Form_pg_type typeStruct;

	if (coercedTypmod != NULL)
		*coercedTypmod = -1;	/* default result on failure */

	/* Is it a function-call at all? */
	if (expr == NULL ||
876
		!IsA(expr, Expr) ||
877 878 879 880 881 882 883
		((Expr *) expr)->opType != FUNC_EXPR)
		return false;
	func = (Func *) (((Expr *) expr)->oper);
	Assert(IsA(func, Func));

	/*
	 * If it's not a two-argument function with the second argument being
884 885
	 * an int4 constant, it can't have been created from a length
	 * coercion.
886 887 888 889
	 */
	if (length(((Expr *) expr)->args) != 2)
		return false;
	second_arg = (Const *) lsecond(((Expr *) expr)->args);
890
	if (!IsA(second_arg, Const) ||
891 892 893 894 895 896 897
		second_arg->consttype != INT4OID ||
		second_arg->constisnull)
		return false;

	/*
	 * Lookup the function in pg_proc
	 */
898 899 900 901
	procTuple = SearchSysCache(PROCOID,
							   ObjectIdGetDatum(func->funcid),
							   0, 0, 0);
	if (!HeapTupleIsValid(procTuple))
902
		elog(ERROR, "cache lookup for proc %u failed", func->funcid);
903
	procStruct = (Form_pg_proc) GETSTRUCT(procTuple);
904 905

	/*
906 907 908
	 * It must be a function with two arguments where the first is of the
	 * same type as the return value and the second is an int4. Also, just
	 * to be sure, check return type agrees with expr node.
909 910 911 912 913
	 */
	if (procStruct->pronargs != 2 ||
		procStruct->prorettype != procStruct->proargtypes[0] ||
		procStruct->proargtypes[1] != INT4OID ||
		procStruct->prorettype != ((Expr *) expr)->typeOid)
914 915
	{
		ReleaseSysCache(procTuple);
916
		return false;
917
	}
918 919

	/*
920 921
	 * Furthermore, the name of the function must be the same as the
	 * argument/result type's name.
922
	 */
923 924 925 926
	typeTuple = SearchSysCache(TYPEOID,
							   ObjectIdGetDatum(procStruct->prorettype),
							   0, 0, 0);
	if (!HeapTupleIsValid(typeTuple))
927 928
		elog(ERROR, "cache lookup for type %u failed",
			 procStruct->prorettype);
929
	typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
930 931 932
	if (strncmp(NameStr(procStruct->proname),
				NameStr(typeStruct->typname),
				NAMEDATALEN) != 0)
933 934 935
	{
		ReleaseSysCache(procTuple);
		ReleaseSysCache(typeTuple);
936
		return false;
937
	}
938 939 940 941 942 943

	/*
	 * OK, it is indeed a length-coercion function.
	 */
	if (coercedTypmod != NULL)
		*coercedTypmod = DatumGetInt32(second_arg->constvalue);
944 945 946

	ReleaseSysCache(procTuple);
	ReleaseSysCache(typeTuple);
947 948 949
	return true;
}

950 951 952 953
/*
 * Produce an appropriate Const node from a constant value produced
 * by the parser and an explicit type name to cast to.
 */
954
static Node *
955
parser_typecast_constant(Value *expr, TypeName *typename)
956 957
{
	Type		tp;
958
	Datum		datum;
959
	Const	   *con;
960 961
	char	   *const_string = NULL;
	bool		string_palloced = false;
962
	bool		isNull = false;
963

964 965
	tp = typenameType(TypeNameToInternalName(typename));

966 967 968
	switch (nodeTag(expr))
	{
		case T_Integer:
969
			const_string = DatumGetCString(DirectFunctionCall1(int4out,
970
										 Int32GetDatum(expr->val.ival)));
971
			string_palloced = true;
972 973
			break;
		case T_Float:
974
		case T_String:
975
		case T_BitString:
976
			const_string = expr->val.str;
977
			break;
978 979 980
		case T_Null:
			isNull = true;
			break;
981
		default:
982
			elog(ERROR, "Cannot cast this expression to type '%s'",
983
				 typeTypeName(tp));
984 985
	}

986 987 988
	if (isNull)
		datum = (Datum) NULL;
	else
989
		datum = stringTypeDatum(tp, const_string, typename->typmod);
990

991
	con = makeConst(typeTypeId(tp),
992
					typeLen(tp),
993 994
					datum,
					isNull,
Bruce Momjian's avatar
Bruce Momjian committed
995
					typeByVal(tp),
996 997 998 999 1000 1001
					false,		/* not a set */
					true /* is cast */ );

	if (string_palloced)
		pfree(const_string);

1002 1003
	ReleaseSysCache(tp);

1004
	return (Node *) con;
1005
}
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021

/*
 * Handle an explicit CAST applied to a non-constant expression.
 * (Actually, this works for constants too, but gram.y won't generate
 * a TypeCast node if the argument is just a constant.)
 *
 * The given expr has already been transformed, but we need to lookup
 * the type name and then apply any necessary coercion function(s).
 */
static Node *
parser_typecast_expression(ParseState *pstate,
						   Node *expr, TypeName *typename)
{
	Oid			inputType = exprType(expr);
	Oid			targetType;

1022
	targetType = typenameTypeId(TypeNameToInternalName(typename));
1023 1024 1025 1026 1027 1028

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

	if (inputType != targetType)
	{
1029
		expr = CoerceTargetExpr(pstate, expr, inputType,
Bruce Momjian's avatar
Bruce Momjian committed
1030 1031
								getBaseType(targetType),
								typename->typmod);
1032 1033
		if (expr == NULL)
			elog(ERROR, "Cannot cast type '%s' to '%s'",
1034 1035
				 format_type_be(inputType),
				 format_type_be(targetType));
1036
	}
1037

1038
	/*
1039 1040
	 * If the target is a fixed-length type, it may need a length coercion
	 * as well as a type coercion.
1041 1042
	 */
	expr = coerce_type_typmod(pstate, expr,
Bruce Momjian's avatar
Bruce Momjian committed
1043
							  getBaseType(targetType), typename->typmod);
1044 1045 1046

	return expr;
}
1047 1048 1049

/*
 * Given a TypeName node as returned by the grammar, generate the internal
1050
 * name of the corresponding type.	Note this does NOT check if the type
1051 1052 1053 1054 1055
 * exists or not.
 */
char *
TypeNameToInternalName(TypeName *typename)
{
1056
	Assert(typename->attrname == NULL);
1057 1058 1059 1060 1061 1062
	if (typename->arrayBounds != NIL)
	{
		/*
		 * By convention, the name of an array type is the name of its
		 * element type with "_" prepended.
		 */
1063
		char	   *arrayname = palloc(strlen(typename->name) + 2);
1064 1065 1066 1067 1068 1069 1070

		sprintf(arrayname, "_%s", typename->name);
		return arrayname;
	}
	else
		return typename->name;
}