analyze.c 67.9 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * analyze.c--
4
 *	  transform the parse tree into a query tree
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.45 1997/10/12 07:09:20 vadim Exp $
11 12 13 14 15 16 17 18
 *
 *-------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "postgres.h"
#include "nodes/nodes.h"
19
#include "nodes/params.h"
20 21 22
#include "nodes/primnodes.h"
#include "nodes/parsenodes.h"
#include "nodes/relation.h"
23
#include "parse.h"				/* for AND, OR, etc. */
24
#include "catalog/pg_type.h"	/* for INT4OID, etc. */
25
#include "catalog/pg_proc.h"
26
#include "utils/elog.h"
27
#include "utils/builtins.h"		/* namecmp(), textout() */
28 29 30
#include "utils/lsyscache.h"
#include "utils/palloc.h"
#include "utils/mcxt.h"
31
#include "utils/syscache.h"
V
Vadim B. Mikheev 已提交
32
#include "utils/acl.h"
33 34 35 36
#include "parser/parse_query.h"
#include "parser/parse_state.h"
#include "nodes/makefuncs.h"	/* for makeResdom(), etc. */
#include "nodes/nodeFuncs.h"
V
Vadim B. Mikheev 已提交
37
#include "commands/sequence.h"
38 39 40 41

#include "optimizer/clauses.h"
#include "access/heapam.h"

V
Vadim B. Mikheev 已提交
42 43
#include "miscadmin.h"

44
#include "port-protos.h"		/* strdup() */
45

46
/* convert the parse tree into a query tree */
47 48 49 50 51 52 53 54 55 56 57
static Query *transformStmt(ParseState *pstate, Node *stmt);

static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
static Query *transformInsertStmt(ParseState *pstate, AppendStmt *stmt);
static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
static Query *transformExtendStmt(ParseState *pstate, ExtendStmt *stmt);
static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt);
static Query *transformSelectStmt(ParseState *pstate, RetrieveStmt *stmt);
static Query *transformUpdateStmt(ParseState *pstate, ReplaceStmt *stmt);
static Query *transformCursorStmt(ParseState *pstate, CursorStmt *stmt);
static Node *handleNestedDots(ParseState *pstate, Attr *attr, int *curr_resno);
58 59

#define EXPR_COLUMN_FIRST	 1
60
#define EXPR_RELATION_FIRST  2
61 62 63 64 65 66 67 68
static Node *transformExpr(ParseState *pstate, Node *expr, int precedence);
static Node *transformIdent(ParseState *pstate, Node *expr, int precedence);

static void makeRangeTable(ParseState *pstate, char *relname, List *frmList);
static List *expandAllTables(ParseState *pstate);
static char *figureColname(Node *expr, Node *resval);
static List *makeTargetNames(ParseState *pstate, List *cols);
static List *transformTargetList(ParseState *pstate, List *targetlist);
69
static TargetEntry *
70 71 72
make_targetlist_expr(ParseState *pstate,
					 char *colname, Node *expr,
					 List *arrayRef);
73
static bool inWhereClause = false;
74
static Node *transformWhereClause(ParseState *pstate, Node *a_expr);
75
static List *
76 77
transformGroupClause(ParseState *pstate, List *grouplist,
					 List *targetlist);
78
static List *
79 80
transformSortClause(ParseState *pstate,
					List *orderlist, List *targetlist,
81 82
					char *uniqueFlag);

83
static void parseFromClause(ParseState *pstate, List *frmList);
84
static Node *
85 86
ParseFunc(ParseState *pstate, char *funcname,
		  List *fargs, int *curr_resno);
87 88
static List *setup_tlist(char *attname, Oid relid);
static List *setup_base_tlist(Oid typeid);
89
static void
90 91 92 93 94
make_arguments(int nargs, List *fargs, Oid *input_typeids,
			   Oid *function_typeids);
static void AddAggToParseState(ParseState *pstate, Aggreg *aggreg);
static void finalizeAggregates(ParseState *pstate, Query *qry);
static void parseCheckAggregates(ParseState *pstate, Query *qry);
95
static ParseState *makeParseState(void);
96 97 98 99 100 101

/*****************************************************************************
 *
 *****************************************************************************/

/*
102 103 104
 * makeParseState() --
 *	  allocate and initialize a new ParseState.
 *	the CALLERS is responsible for freeing the ParseState* returned
105 106 107
 *
 */

108
static ParseState *
109 110
makeParseState(void)
{
111
	ParseState *pstate;
112 113 114 115 116 117 118 119 120 121 122 123 124 125

	pstate = malloc(sizeof(ParseState));
	pstate->p_last_resno = 1;
	pstate->p_rtable = NIL;
	pstate->p_numAgg = 0;
	pstate->p_aggs = NIL;
	pstate->p_is_insert = false;
	pstate->p_insert_columns = NIL;
	pstate->p_is_update = false;
	pstate->p_is_rule = false;
	pstate->p_target_relation = NULL;
	pstate->p_target_rangetblentry = NULL;

	return (pstate);
126
}
B
Bruce Momjian 已提交
127

128 129
/*
 * parse_analyze -
130
 *	  analyze a list of parse trees and transform them if necessary.
131 132 133 134 135 136
 *
 * Returns a list of transformed parse trees. Optimizable statements are
 * all transformed to Query while the rest stays the same.
 *
 * CALLER is responsible for freeing the QueryTreeList* returned
 */
137
QueryTreeList *
138
parse_analyze(List *pl)
139
{
140 141 142
	QueryTreeList *result;
	ParseState *pstate;
	int			i = 0;
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

	result = malloc(sizeof(QueryTreeList));
	result->len = length(pl);
	result->qtrees = (Query **) malloc(result->len * sizeof(Query *));

	inWhereClause = false;		/* to avoid nextval(sequence) in WHERE */

	while (pl != NIL)
	{
		pstate = makeParseState();
		result->qtrees[i++] = transformStmt(pstate, lfirst(pl));
		pl = lnext(pl);
		if (pstate->p_target_relation != NULL)
			heap_close(pstate->p_target_relation);
		free(pstate);
	}

	return result;
161 162 163 164
}

/*
 * transformStmt -
165 166
 *	  transform a Parse tree. If it is an optimizable statement, turn it
 *	  into a Query tree.
167
 */
168
static Query *
169
transformStmt(ParseState *pstate, Node *parseTree)
170
{
171
	Query	   *result = NULL;
172 173 174

	switch (nodeTag(parseTree))
	{
175 176 177 178 179 180 181
			/*------------------------
			 *	Non-optimizable statements
			 *------------------------
			 */
		case T_IndexStmt:
			result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
			break;
182

183 184 185
		case T_ExtendStmt:
			result = transformExtendStmt(pstate, (ExtendStmt *) parseTree);
			break;
186

187 188 189
		case T_RuleStmt:
			result = transformRuleStmt(pstate, (RuleStmt *) parseTree);
			break;
190

191 192 193
		case T_ViewStmt:
			{
				ViewStmt   *n = (ViewStmt *) parseTree;
194

195 196 197 198 199 200
				n->query = (Query *) transformStmt(pstate, (Node *) n->query);
				result = makeNode(Query);
				result->commandType = CMD_UTILITY;
				result->utilityStmt = (Node *) n;
			}
			break;
201

202 203 204
		case T_VacuumStmt:
			{
				MemoryContext oldcontext;
205

206 207 208 209 210 211 212 213 214 215 216 217
				/*
				 * make sure that this Query is allocated in TopMemory
				 * context because vacuum spans transactions and we don't
				 * want to lose the vacuum Query due to end-of-transaction
				 * free'ing
				 */
				oldcontext = MemoryContextSwitchTo(TopMemoryContext);
				result = makeNode(Query);
				result->commandType = CMD_UTILITY;
				result->utilityStmt = (Node *) parseTree;
				MemoryContextSwitchTo(oldcontext);
				break;
218

219 220 221 222
			}
		case T_ExplainStmt:
			{
				ExplainStmt *n = (ExplainStmt *) parseTree;
223

224 225 226 227 228 229
				result = makeNode(Query);
				result->commandType = CMD_UTILITY;
				n->query = transformStmt(pstate, (Node *) n->query);
				result->utilityStmt = (Node *) parseTree;
			}
			break;
230

231 232 233 234 235 236 237
			/*------------------------
			 *	Optimizable statements
			 *------------------------
			 */
		case T_AppendStmt:
			result = transformInsertStmt(pstate, (AppendStmt *) parseTree);
			break;
238

239 240 241
		case T_DeleteStmt:
			result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
			break;
242

243 244 245
		case T_ReplaceStmt:
			result = transformUpdateStmt(pstate, (ReplaceStmt *) parseTree);
			break;
246

247 248 249
		case T_CursorStmt:
			result = transformCursorStmt(pstate, (CursorStmt *) parseTree);
			break;
250

251 252 253
		case T_RetrieveStmt:
			result = transformSelectStmt(pstate, (RetrieveStmt *) parseTree);
			break;
254

255
		default:
256

257 258 259 260 261 262 263 264
			/*
			 * other statments don't require any transformation-- just
			 * return the original parsetree
			 */
			result = makeNode(Query);
			result->commandType = CMD_UTILITY;
			result->utilityStmt = (Node *) parseTree;
			break;
265 266
	}
	return result;
267 268 269 270
}

/*
 * transformDeleteStmt -
271
 *	  transforms a Delete Statement
272
 */
273
static Query *
274
transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
275
{
276
	Query	   *qry = makeNode(Query);
277

278
	qry->commandType = CMD_DELETE;
279

280 281
	/* set up a range table */
	makeRangeTable(pstate, stmt->relname, NULL);
282

283
	qry->uniqueFlag = NULL;
284

285 286
	/* fix where clause */
	qry->qual = transformWhereClause(pstate, stmt->whereClause);
287

288 289 290 291 292 293
	qry->rtable = pstate->p_rtable;
	qry->resultRelation = refnameRangeTablePosn(pstate->p_rtable, stmt->relname);

	/* make sure we don't have aggregates in the where clause */
	if (pstate->p_numAgg > 0)
		parseCheckAggregates(pstate, qry);
294

295
	return (Query *) qry;
296 297 298 299
}

/*
 * transformInsertStmt -
300
 *	  transform an Insert Statement
301
 */
302
static Query *
303
transformInsertStmt(ParseState *pstate, AppendStmt *stmt)
304
{
305
	Query	   *qry = makeNode(Query);	/* make a new query tree */
306
	List	   *icolumns;
307

308 309
	qry->commandType = CMD_INSERT;
	pstate->p_is_insert = true;
310

311 312
	/* set up a range table */
	makeRangeTable(pstate, stmt->relname, stmt->fromClause);
313

314
	qry->uniqueFlag = NULL;
315

316
	/* fix the target list */
317 318
	icolumns = pstate->p_insert_columns = makeTargetNames(pstate, stmt->cols);
	
319
	qry->targetList = transformTargetList(pstate, stmt->targetList);
320 321 322 323 324 325 326 327 328 329 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 382 383 384
	
	/* DEFAULT handling */
	if (length(qry->targetList) < pstate->p_target_relation->rd_att->natts &&
		pstate->p_target_relation->rd_att->constr &&
		pstate->p_target_relation->rd_att->constr->num_defval > 0)
	{
		AttributeTupleForm	   *att = pstate->p_target_relation->rd_att->attrs;
		AttrDefault			   *defval = pstate->p_target_relation->rd_att->constr->defval;
		int						ndef = pstate->p_target_relation->rd_att->constr->num_defval;
		
		/* 
		 * if stmt->cols == NIL then makeTargetNames returns list of all 
		 * attrs: have to shorter icolumns list...
		 */
		if (stmt->cols == NIL)
		{
			List   *extrl;
			int		i = length(qry->targetList);
			
			foreach (extrl, icolumns)
			{
				if (--i <= 0)
					break;
			}
			freeList (lnext(extrl));
			lnext(extrl) = NIL;
		}
		
		while (ndef-- > 0)
		{
			List		   *tl;
			Ident		   *id;
			TargetEntry	   *te;
			
			foreach (tl, icolumns)
			{
				id = (Ident *) lfirst(tl);
				if (!namestrcmp(&(att[defval[ndef].adnum - 1]->attname), id->name))
					break;
			}
			if (tl != NIL)		/* something given for this attr */
				continue;
			/* 
			 * Nothing given for this attr with DEFAULT expr, so
			 * add new TargetEntry to qry->targetList. 
			 * Note, that we set resno to defval[ndef].adnum:
			 * it's what transformTargetList()->make_targetlist_expr()
			 * does for INSERT ... SELECT. But for INSERT ... VALUES
			 * pstate->p_last_resno is used. It doesn't matter for 
			 * "normal" using (planner creates proper target list
			 * in preptlist.c), but may break RULEs in some way.
			 * It seems better to create proper target list here...
			 */
			te = makeNode(TargetEntry);
			te->resdom = makeResdom(defval[ndef].adnum,
									att[defval[ndef].adnum - 1]->atttypid,
									att[defval[ndef].adnum - 1]->attlen,
									pstrdup(nameout(&(att[defval[ndef].adnum - 1]->attname))),
									0, 0, 0);
			te->fjoin = NULL;
			te->expr = (Node *) stringToNode(defval[ndef].adbin);
			qry->targetList = lappend (qry->targetList, te);
		}
	}
	
385 386
	/* fix where clause */
	qry->qual = transformWhereClause(pstate, stmt->whereClause);
387

388 389 390
	/* now the range table will not change */
	qry->rtable = pstate->p_rtable;
	qry->resultRelation = refnameRangeTablePosn(pstate->p_rtable, stmt->relname);
391

392 393
	if (pstate->p_numAgg > 0)
		finalizeAggregates(pstate, qry);
394

395
	return (Query *) qry;
396 397 398 399
}

/*
 * transformIndexStmt -
400
 *	  transforms the qualification of the index statement
401
 */
402
static Query *
403
transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
404
{
405
	Query	   *q;
406

407 408
	q = makeNode(Query);
	q->commandType = CMD_UTILITY;
409

410 411 412
	/* take care of the where clause */
	stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
	stmt->rangetable = pstate->p_rtable;
413

414 415 416
	q->utilityStmt = (Node *) stmt;

	return q;
417 418 419 420
}

/*
 * transformExtendStmt -
421
 *	  transform the qualifications of the Extend Index Statement
422 423
 *
 */
424
static Query *
425
transformExtendStmt(ParseState *pstate, ExtendStmt *stmt)
426
{
427
	Query	   *q;
428

429 430
	q = makeNode(Query);
	q->commandType = CMD_UTILITY;
431

432 433 434
	/* take care of the where clause */
	stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
	stmt->rangetable = pstate->p_rtable;
435

436 437
	q->utilityStmt = (Node *) stmt;
	return q;
438 439 440 441
}

/*
 * transformRuleStmt -
442 443
 *	  transform a Create Rule Statement. The actions is a list of parse
 *	  trees which is transformed into a list of query trees.
444
 */
445
static Query *
446
transformRuleStmt(ParseState *pstate, RuleStmt *stmt)
447
{
448 449
	Query	   *q;
	List	   *actions;
450 451 452 453 454 455

	q = makeNode(Query);
	q->commandType = CMD_UTILITY;

	actions = stmt->actions;

456
	/*
457
	 * transform each statment, like parse_analyze()
458
	 */
459 460
	while (actions != NIL)
	{
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
		/*
		 * NOTE: 'CURRENT' must always have a varno equal to 1 and 'NEW'
		 * equal to 2.
		 */
		addRangeTableEntry(pstate, stmt->object->relname, "*CURRENT*",
						   FALSE, FALSE, NULL);
		addRangeTableEntry(pstate, stmt->object->relname, "*NEW*",
						   FALSE, FALSE, NULL);

		pstate->p_last_resno = 1;
		pstate->p_is_rule = true;		/* for expand all */
		pstate->p_numAgg = 0;
		pstate->p_aggs = NULL;

		lfirst(actions) = transformStmt(pstate, lfirst(actions));
		actions = lnext(actions);
	}
479

480 481
	/* take care of the where clause */
	stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
482

483 484
	q->utilityStmt = (Node *) stmt;
	return q;
485 486 487 488 489
}


/*
 * transformSelectStmt -
490
 *	  transforms a Select Statement
491 492
 *
 */
493
static Query *
494
transformSelectStmt(ParseState *pstate, RetrieveStmt *stmt)
495
{
496
	Query	   *qry = makeNode(Query);
497 498

	qry->commandType = CMD_SELECT;
499

500 501
	/* set up a range table */
	makeRangeTable(pstate, NULL, stmt->fromClause);
502

503
	qry->uniqueFlag = stmt->unique;
504

505 506
	qry->into = stmt->into;
	qry->isPortal = FALSE;
507

508 509
	/* fix the target list */
	qry->targetList = transformTargetList(pstate, stmt->targetList);
510

511 512
	/* fix where clause */
	qry->qual = transformWhereClause(pstate, stmt->whereClause);
513

514 515 516
	/* check subselect clause */
	if (stmt->selectClause)
		elog(NOTICE, "UNION not yet supported; using first SELECT only", NULL);
517

518 519 520
	/* check subselect clause */
	if (stmt->havingClause)
		elog(NOTICE, "HAVING not yet supported; ignore clause", NULL);
521

522 523 524 525 526
	/* fix order clause */
	qry->sortClause = transformSortClause(pstate,
										  stmt->sortClause,
										  qry->targetList,
										  qry->uniqueFlag);
527

528 529 530 531 532
	/* fix group by clause */
	qry->groupClause = transformGroupClause(pstate,
											stmt->groupClause,
											qry->targetList);
	qry->rtable = pstate->p_rtable;
533

534 535
	if (pstate->p_numAgg > 0)
		finalizeAggregates(pstate, qry);
536

537
	return (Query *) qry;
538 539 540 541
}

/*
 * transformUpdateStmt -
542
 *	  transforms an update statement
543 544
 *
 */
545
static Query *
546
transformUpdateStmt(ParseState *pstate, ReplaceStmt *stmt)
547
{
548
	Query	   *qry = makeNode(Query);
549 550 551

	qry->commandType = CMD_UPDATE;
	pstate->p_is_update = true;
552

553 554 555 556 557
	/*
	 * the FROM clause is non-standard SQL syntax. We used to be able to
	 * do this with REPLACE in POSTQUEL so we keep the feature.
	 */
	makeRangeTable(pstate, stmt->relname, stmt->fromClause);
558

559 560
	/* fix the target list */
	qry->targetList = transformTargetList(pstate, stmt->targetList);
561

562 563
	/* fix where clause */
	qry->qual = transformWhereClause(pstate, stmt->whereClause);
564

565 566
	qry->rtable = pstate->p_rtable;
	qry->resultRelation = refnameRangeTablePosn(pstate->p_rtable, stmt->relname);
567

568 569 570
	/* make sure we don't have aggregates in the where clause */
	if (pstate->p_numAgg > 0)
		parseCheckAggregates(pstate, qry);
571

572
	return (Query *) qry;
573 574 575 576
}

/*
 * transformCursorStmt -
577
 *	  transform a Create Cursor Statement
578 579
 *
 */
580
static Query *
581
transformCursorStmt(ParseState *pstate, CursorStmt *stmt)
582
{
583
	Query	   *qry = makeNode(Query);
584

585 586 587 588 589 590
	/*
	 * in the old days, a cursor statement is a 'retrieve into portal'; If
	 * you change the following, make sure you also go through the code in
	 * various places that tests the kind of operation.
	 */
	qry->commandType = CMD_SELECT;
591

592 593
	/* set up a range table */
	makeRangeTable(pstate, NULL, stmt->fromClause);
594

595
	qry->uniqueFlag = stmt->unique;
596

597 598 599
	qry->into = stmt->portalname;
	qry->isPortal = TRUE;
	qry->isBinary = stmt->binary;		/* internal portal */
600

601 602
	/* fix the target list */
	qry->targetList = transformTargetList(pstate, stmt->targetList);
603

604 605
	/* fix where clause */
	qry->qual = transformWhereClause(pstate, stmt->whereClause);
606

607 608 609 610 611 612 613 614 615
	/* fix order clause */
	qry->sortClause = transformSortClause(pstate,
										  stmt->sortClause,
										  qry->targetList,
										  qry->uniqueFlag);
	/* fix group by clause */
	qry->groupClause = transformGroupClause(pstate,
											stmt->groupClause,
											qry->targetList);
M
Fixes:  
Marc G. Fournier 已提交
616

617
	qry->rtable = pstate->p_rtable;
618

619 620
	if (pstate->p_numAgg > 0)
		finalizeAggregates(pstate, qry);
621

622
	return (Query *) qry;
623 624 625 626 627 628 629 630 631 632
}

/*****************************************************************************
 *
 * Transform Exprs, Aggs, etc.
 *
 *****************************************************************************/

/*
 * transformExpr -
633 634 635 636
 *	  analyze and transform expressions. Type checking and type casting is
 *	  done here. The optimizer and the executor cannot handle the original
 *	  (raw) expressions collected by the parse tree. Hence the transformation
 *	  here.
637
 */
638
static Node *
639
transformExpr(ParseState *pstate, Node *expr, int precedence)
640
{
641
	Node	   *result = NULL;
642

643 644 645 646 647
	if (expr == NULL)
		return NULL;

	switch (nodeTag(expr))
	{
648
		case T_Attr:
649
			{
650 651
				Attr	   *att = (Attr *) expr;
				Node	   *temp;
652

653 654 655
				/* what if att.attrs == "*"?? */
				temp = handleNestedDots(pstate, att, &pstate->p_last_resno);
				if (att->indirection != NIL)
656
				{
657
					List	   *idx = att->indirection;
658

659
					while (idx != NIL)
660
					{
661 662 663 664 665 666
						A_Indices  *ai = (A_Indices *) lfirst(idx);
						Node	   *lexpr = NULL,
								   *uexpr;

						uexpr = transformExpr(pstate, ai->uidx, precedence);	/* must exists */
						if (exprType(uexpr) != INT4OID)
667
							elog(WARN, "array index expressions must be int4's");
668 669 670 671 672 673
						if (ai->lidx != NULL)
						{
							lexpr = transformExpr(pstate, ai->lidx, precedence);
							if (exprType(lexpr) != INT4OID)
								elog(WARN, "array index expressions must be int4's");
						}
674
#if 0
675 676 677
						pfree(ai->uidx);
						if (ai->lidx != NULL)
							pfree(ai->lidx);
678
#endif
679 680
						ai->lidx = lexpr;
						ai->uidx = uexpr;
681

682 683 684 685 686 687 688 689 690 691 692 693
						/*
						 * note we reuse the list of indices, make sure we
						 * don't free them! Otherwise, make a new list
						 * here
						 */
						idx = lnext(idx);
					}
					result = (Node *) make_array_ref(temp, att->indirection);
				}
				else
				{
					result = temp;
694
				}
695
				break;
696
			}
697
		case T_A_Const:
698
			{
699 700
				A_Const    *con = (A_Const *) expr;
				Value	   *val = &con->val;
701

702 703 704 705 706 707 708 709 710
				if (con->typename != NULL)
				{
					result = parser_typecast(val, con->typename, -1);
				}
				else
				{
					result = (Node *) make_const(val);
				}
				break;
711
			}
712
		case T_ParamNo:
713
			{
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
				ParamNo    *pno = (ParamNo *) expr;
				Oid			toid;
				int			paramno;
				Param	   *param;

				paramno = pno->number;
				toid = param_type(paramno);
				if (!OidIsValid(toid))
				{
					elog(WARN, "Parameter '$%d' is out of range",
						 paramno);
				}
				param = makeNode(Param);
				param->paramkind = PARAM_NUM;
				param->paramid = (AttrNumber) paramno;
				param->paramname = "<unnamed>";
				param->paramtype = (Oid) toid;
				param->param_tlist = (List *) NULL;

				result = (Node *) param;
				break;
735
			}
736
		case T_A_Expr:
737
			{
738
				A_Expr	   *a = (A_Expr *) expr;
739

740
				switch (a->oper)
741
				{
742 743 744 745
					case OP:
						{
							Node	   *lexpr = transformExpr(pstate, a->lexpr, precedence);
							Node	   *rexpr = transformExpr(pstate, a->rexpr, precedence);
746

747 748 749 750 751 752
							result = (Node *) make_op(a->opname, lexpr, rexpr);
						}
						break;
					case ISNULL:
						{
							Node	   *lexpr = transformExpr(pstate, a->lexpr, precedence);
753

754 755 756 757 758 759 760 761
							result = ParseFunc(pstate,
										  "nullvalue", lcons(lexpr, NIL),
											   &pstate->p_last_resno);
						}
						break;
					case NOTNULL:
						{
							Node	   *lexpr = transformExpr(pstate, a->lexpr, precedence);
762

763
							result = ParseFunc(pstate,
764
									   "nonnullvalue", lcons(lexpr, NIL),
765 766 767 768 769 770 771 772
											   &pstate->p_last_resno);
						}
						break;
					case AND:
						{
							Expr	   *expr = makeNode(Expr);
							Node	   *lexpr = transformExpr(pstate, a->lexpr, precedence);
							Node	   *rexpr = transformExpr(pstate, a->rexpr, precedence);
773

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
							if (exprType(lexpr) != BOOLOID)
								elog(WARN,
									 "left-hand side of AND is type '%s', not bool",
									 tname(get_id_type(exprType(lexpr))));
							if (exprType(rexpr) != BOOLOID)
								elog(WARN,
									 "right-hand side of AND is type '%s', not bool",
									 tname(get_id_type(exprType(rexpr))));
							expr->typeOid = BOOLOID;
							expr->opType = AND_EXPR;
							expr->args = makeList(lexpr, rexpr, -1);
							result = (Node *) expr;
						}
						break;
					case OR:
						{
							Expr	   *expr = makeNode(Expr);
							Node	   *lexpr = transformExpr(pstate, a->lexpr, precedence);
							Node	   *rexpr = transformExpr(pstate, a->rexpr, precedence);
793

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
							if (exprType(lexpr) != BOOLOID)
								elog(WARN,
									 "left-hand side of OR is type '%s', not bool",
									 tname(get_id_type(exprType(lexpr))));
							if (exprType(rexpr) != BOOLOID)
								elog(WARN,
									 "right-hand side of OR is type '%s', not bool",
									 tname(get_id_type(exprType(rexpr))));
							expr->typeOid = BOOLOID;
							expr->opType = OR_EXPR;
							expr->args = makeList(lexpr, rexpr, -1);
							result = (Node *) expr;
						}
						break;
					case NOT:
						{
							Expr	   *expr = makeNode(Expr);
							Node	   *rexpr = transformExpr(pstate, a->rexpr, precedence);
812

813 814 815 816 817 818 819 820 821 822
							if (exprType(rexpr) != BOOLOID)
								elog(WARN,
								"argument to NOT is type '%s', not bool",
									 tname(get_id_type(exprType(rexpr))));
							expr->typeOid = BOOLOID;
							expr->opType = NOT_EXPR;
							expr->args = makeList(rexpr, -1);
							result = (Node *) expr;
						}
						break;
823 824 825
				}
				break;
			}
826 827
		case T_Ident:
			{
828

829 830 831 832 833 834 835 836 837 838 839
				/*
				 * look for a column name or a relation name (the default
				 * behavior)
				 */
				result = transformIdent(pstate, expr, precedence);
				break;
			}
		case T_FuncCall:
			{
				FuncCall   *fn = (FuncCall *) expr;
				List	   *args;
840

841 842 843 844
				/* transform the list of arguments */
				foreach(args, fn->args)
					lfirst(args) = transformExpr(pstate, (Node *) lfirst(args), precedence);
				result = ParseFunc(pstate,
845
						  fn->funcname, fn->args, &pstate->p_last_resno);
846 847 848 849 850 851
				break;
			}
		default:
			/* should not reach here */
			elog(WARN, "transformExpr: does not know how to transform %d\n",
				 nodeTag(expr));
852
			break;
853
	}
854 855

	return result;
856 857
}

858
static Node *
859
transformIdent(ParseState *pstate, Node *expr, int precedence)
860
{
861 862 863 864 865
	Ident	   *ident = (Ident *) expr;
	RangeTblEntry *rte;
	Node	   *column_result,
			   *relation_result,
			   *result;
866 867 868 869 870

	column_result = relation_result = result = 0;
	/* try to find the ident as a column */
	if ((rte = colnameRangeTableEntry(pstate, ident->name)) != NULL)
	{
871
		Attr	   *att = makeNode(Attr);
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893

		att->relname = rte->refname;
		att->attrs = lcons(makeString(ident->name), NIL);
		column_result =
			(Node *) handleNestedDots(pstate, att, &pstate->p_last_resno);
	}

	/* try to find the ident as a relation */
	if (refnameRangeTableEntry(pstate->p_rtable, ident->name) != NULL)
	{
		ident->isRel = TRUE;
		relation_result = (Node *) ident;
	}

	/* choose the right result based on the precedence */
	if (precedence == EXPR_COLUMN_FIRST)
	{
		if (column_result)
			result = column_result;
		else
			result = relation_result;
	}
894
	else
895 896 897 898 899 900 901 902 903
	{
		if (relation_result)
			result = relation_result;
		else
			result = column_result;
	}

	if (result == NULL)
		elog(WARN, "attribute \"%s\" not found", ident->name);
904

905
	return result;
906 907
}

908 909 910 911 912 913 914 915
/*****************************************************************************
 *
 * From Clause
 *
 *****************************************************************************/

/*
 * parseFromClause -
916 917 918 919 920
 *	  turns the table references specified in the from-clause into a
 *	  range table. The range table may grow as we transform the expressions
 *	  in the target list. (Note that this happens because in POSTQUEL, we
 *	  allow references to relations not specified in the from-clause. We
 *	  also allow that in our POST-SQL)
921 922 923
 *
 */
static void
924
parseFromClause(ParseState *pstate, List *frmList)
925
{
926
	List	   *fl;
927

928 929
	foreach(fl, frmList)
	{
930 931 932 933 934
		RangeVar   *r = lfirst(fl);
		RelExpr    *baserel = r->relExpr;
		char	   *relname = baserel->relname;
		char	   *refname = r->name;
		RangeTblEntry *rte;
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952

		if (refname == NULL)
			refname = relname;

		/*
		 * marks this entry to indicate it comes from the FROM clause. In
		 * SQL, the target list can only refer to range variables
		 * specified in the from clause but we follow the more powerful
		 * POSTQUEL semantics and automatically generate the range
		 * variable if not specified. However there are times we need to
		 * know whether the entries are legitimate.
		 *
		 * eg. select * from foo f where f.x = 1; will generate wrong answer
		 * if we expand * to foo.x.
		 */
		rte = addRangeTableEntry(pstate, relname, refname, baserel->inh, TRUE,
								 baserel->timeRange);
	}
953 954 955 956
}

/*
 * makeRangeTable -
957 958
 *	  make a range table with the specified relation (optional) and the
 *	  from-clause.
959 960
 */
static void
961
makeRangeTable(ParseState *pstate, char *relname, List *frmList)
962
{
963
	RangeTblEntry *rte;
964

965
	parseFromClause(pstate, frmList);
966

967 968 969 970 971 972 973 974 975 976 977 978
	if (relname == NULL)
		return;

	if (refnameRangeTablePosn(pstate->p_rtable, relname) < 1)
		rte = addRangeTableEntry(pstate, relname, relname, FALSE, FALSE, NULL);
	else
		rte = refnameRangeTableEntry(pstate->p_rtable, relname);

	pstate->p_target_rangetblentry = rte;
	Assert(pstate->p_target_relation == NULL);
	pstate->p_target_relation = heap_open(rte->relid);
	Assert(pstate->p_target_relation != NULL);
B
Bruce Momjian 已提交
979
	/* will close relation later */
980 981 982
}

/*
983 984
 *	exprType -
 *	  returns the Oid of the type of the expression. (Used for typechecking.)
985 986
 */
Oid
987
exprType(Node *expr)
988
{
989
	Oid			type = (Oid) 0;
990 991 992

	switch (nodeTag(expr))
	{
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
		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;
		case T_Aggreg:
			type = ((Aggreg *) expr)->aggtype;
			break;
		case T_Param:
			type = ((Param *) expr)->paramtype;
			break;
		case T_Ident:
			/* is this right? */
			type = UNKNOWNOID;
			break;
		default:
			elog(WARN, "exprType: don't know how to get type for %d node",
				 nodeTag(expr));
			break;
1025 1026
	}
	return type;
1027 1028 1029 1030
}

/*
 * expandAllTables -
1031 1032
 *	  turns '*' (in the target list) into a list of attributes (of all
 *	  relations in the range table)
1033
 */
1034
static List *
1035
expandAllTables(ParseState *pstate)
1036
{
1037 1038 1039 1040
	List	   *target = NIL;
	List	   *legit_rtable = NIL;
	List	   *rt,
			   *rtable;
1041

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
	rtable = pstate->p_rtable;
	if (pstate->p_is_rule)
	{

		/*
		 * skip first two entries, "*new*" and "*current*"
		 */
		rtable = lnext(lnext(pstate->p_rtable));
	}

	/* this should not happen */
	if (rtable == NULL)
		elog(WARN, "cannot expand: null p_rtable");
1055 1056

	/*
1057 1058
	 * go through the range table and make a list of range table entries
	 * which we will expand.
1059
	 */
1060 1061
	foreach(rt, rtable)
	{
1062
		RangeTblEntry *rte = lfirst(rt);
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

		/*
		 * we only expand those specify in the from clause. (This will
		 * also prevent us from using the wrong table in inserts: eg.
		 * tenk2 in "insert into tenk2 select * from tenk1;")
		 */
		if (!rte->inFromCl)
			continue;
		legit_rtable = lappend(legit_rtable, rte);
	}

	foreach(rt, legit_rtable)
	{
1076 1077
		RangeTblEntry *rte = lfirst(rt);
		List	   *temp = target;
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

		if (temp == NIL)
			target = expandAll(pstate, rte->relname, rte->refname,
							   &pstate->p_last_resno);
		else
		{
			while (temp != NIL && lnext(temp) != NIL)
				temp = lnext(temp);
			lnext(temp) = expandAll(pstate, rte->relname, rte->refname,
									&pstate->p_last_resno);
		}
1089
	}
1090
	return target;
1091 1092 1093 1094 1095
}


/*
 * figureColname -
1096 1097
 *	  if the name of the resulting column is not specified in the target
 *	  list, we have to guess.
1098 1099
 *
 */
1100
static char *
1101
figureColname(Node *expr, Node *resval)
1102
{
1103 1104
	switch (nodeTag(expr))
	{
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
			case T_Aggreg:
			return (char *)		/* XXX */
			((Aggreg *) expr)->aggname;
		case T_Expr:
			if (((Expr *) expr)->opType == FUNC_EXPR)
			{
				if (nodeTag(resval) == T_FuncCall)
					return ((FuncCall *) resval)->funcname;
			}
			break;
		default:
			break;
1117
	}
1118 1119

	return "?column?";
1120 1121 1122 1123 1124 1125 1126 1127 1128
}

/*****************************************************************************
 *
 * Target list
 *
 *****************************************************************************/

/*
B
Bruce Momjian 已提交
1129
 * makeTargetNames -
1130 1131 1132
 *	  generate a list of column names if not supplied or
 *	  test supplied column names to make sure they are in target table
 *	  (used exclusively for inserts)
1133
 */
1134
static List *
1135
makeTargetNames(ParseState *pstate, List *cols)
1136
{
1137
	List	   *tl = NULL;
1138 1139 1140 1141 1142

	/* Generate ResTarget if not supplied */

	if (cols == NIL)
	{
1143 1144
		int			numcol;
		int			i;
1145 1146 1147 1148 1149
		AttributeTupleForm *attr = pstate->p_target_relation->rd_att->attrs;

		numcol = pstate->p_target_relation->rd_rel->relnatts;
		for (i = 0; i < numcol; i++)
		{
1150
			Ident	   *id = makeNode(Ident);
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

			id->name = palloc(NAMEDATALEN);
			strNcpy(id->name, attr[i]->attname.data, NAMEDATALEN - 1);
			id->indirection = NIL;
			id->isRel = false;
			if (tl == NIL)
				cols = tl = lcons(id, NIL);
			else
			{
				lnext(tl) = lcons(id, NIL);
				tl = lnext(tl);
			}
		}
1164
	}
1165
	else
1166
	{
1167
		foreach(tl, cols)
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
		{
			List	   *nxt;
			char	   *name = ((Ident *) lfirst(tl))->name;
		
			/* elog on failure */
			varattno(pstate->p_target_relation, name);
			foreach(nxt, lnext(tl))
				if (!strcmp(name, ((Ident *) lfirst(nxt))->name))
					elog (WARN, "Attribute %s should be specified only once", name);
		}
	}
	
1180
	return cols;
1181 1182 1183 1184
}

/*
 * transformTargetList -
1185
 *	  turns a list of ResTarget's into a list of TargetEntry's
1186
 */
1187
static List *
1188
transformTargetList(ParseState *pstate, List *targetlist)
1189
{
1190 1191
	List	   *p_target = NIL;
	List	   *tail_p_target = NIL;
1192 1193 1194

	while (targetlist != NIL)
	{
1195 1196
		ResTarget  *res = (ResTarget *) lfirst(targetlist);
		TargetEntry *tent = makeNode(TargetEntry);
1197 1198 1199

		switch (nodeTag(res->val))
		{
1200 1201 1202 1203 1204 1205 1206
			case T_Ident:
				{
					Node	   *expr;
					Oid			type_id;
					int			type_len;
					char	   *identname;
					char	   *resname;
1207

1208 1209
					identname = ((Ident *) res->val)->name;
					handleTargetColname(pstate, &res->name, NULL, identname);
1210

1211 1212 1213 1214
					/*
					 * here we want to look for column names only, not
					 * relation
					 */
1215

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
					/*
					 * names (even though they can be stored in Ident
					 * nodes,
					 */
					/* too)														*/
					expr = transformIdent(pstate, (Node *) res->val, EXPR_COLUMN_FIRST);
					type_id = exprType(expr);
					type_len = tlen(get_id_type(type_id));
					resname = (res->name) ? res->name : identname;
					tent->resdom = makeResdom((AttrNumber) pstate->p_last_resno++,
											  (Oid) type_id,
											  (Size) type_len,
											  resname,
											  (Index) 0,
											  (Oid) 0,
											  0);

					tent->expr = expr;
					break;
				}
			case T_ParamNo:
			case T_FuncCall:
			case T_A_Const:
			case T_A_Expr:
1240
				{
1241 1242 1243 1244 1245 1246 1247 1248 1249
					Node	   *expr = transformExpr(pstate, (Node *) res->val, EXPR_COLUMN_FIRST);

					handleTargetColname(pstate, &res->name, NULL, NULL);
					/* note indirection has not been transformed */
					if (pstate->p_is_insert && res->indirection != NIL)
					{
						/* this is an array assignment */
						char	   *val;
						char	   *str,
1250
								   *save_str;
1251 1252
						List	   *elt;
						int			i = 0,
1253
									ndims;
1254
						int			lindx[MAXDIM],
1255
									uindx[MAXDIM];
1256 1257 1258
						int			resdomno;
						Relation	rd;
						Value	   *constval;
1259

1260 1261 1262
						if (exprType(expr) != UNKNOWNOID ||
							!IsA(expr, Const))
							elog(WARN, "yyparse: string constant expected");
1263

1264
						val = (char *) textout((struct varlena *)
1265
										   ((Const *) expr)->constvalue);
1266 1267
						str = save_str = (char *) palloc(strlen(val) + MAXDIM * 25 + 2);
						foreach(elt, res->indirection)
1268
						{
1269 1270 1271 1272
							A_Indices  *aind = (A_Indices *) lfirst(elt);

							aind->uidx = transformExpr(pstate, aind->uidx, EXPR_COLUMN_FIRST);
							if (!IsA(aind->uidx, Const))
1273 1274
								elog(WARN,
									 "Array Index for Append should be a constant");
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
							uindx[i] = ((Const *) aind->uidx)->constvalue;
							if (aind->lidx != NULL)
							{
								aind->lidx = transformExpr(pstate, aind->lidx, EXPR_COLUMN_FIRST);
								if (!IsA(aind->lidx, Const))
									elog(WARN,
										 "Array Index for Append should be a constant");
								lindx[i] = ((Const *) aind->lidx)->constvalue;
							}
							else
							{
								lindx[i] = 1;
							}
							if (lindx[i] > uindx[i])
								elog(WARN, "yyparse: lower index cannot be greater than upper index");
							sprintf(str, "[%d:%d]", lindx[i], uindx[i]);
							str += strlen(str);
							i++;
1293
						}
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
						sprintf(str, "=%s", val);
						rd = pstate->p_target_relation;
						Assert(rd != NULL);
						resdomno = varattno(rd, res->name);
						ndims = att_attnelems(rd, resdomno);
						if (i != ndims)
							elog(WARN, "yyparse: array dimensions do not match");
						constval = makeNode(Value);
						constval->type = T_String;
						constval->val.str = save_str;
						tent = make_targetlist_expr(pstate, res->name,
1305
										   (Node *) make_const(constval),
1306 1307
													NULL);
						pfree(save_str);
1308
					}
1309
					else
1310
					{
1311
						char	   *colname = res->name;
1312

1313 1314
						/* this is not an array assignment */
						if (colname == NULL)
1315 1316
						{

1317 1318 1319 1320 1321 1322
							/*
							 * if you're wondering why this is here, look
							 * at the yacc grammar for why a name can be
							 * missing. -ay
							 */
							colname = figureColname(expr, res->val);
1323
						}
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
						if (res->indirection)
						{
							List	   *ilist = res->indirection;

							while (ilist != NIL)
							{
								A_Indices  *ind = lfirst(ilist);

								ind->lidx = transformExpr(pstate, ind->lidx, EXPR_COLUMN_FIRST);
								ind->uidx = transformExpr(pstate, ind->uidx, EXPR_COLUMN_FIRST);
								ilist = lnext(ilist);
							}
						}
						res->name = colname;
						tent = make_targetlist_expr(pstate, res->name, expr,
													res->indirection);
1340
					}
1341
					break;
1342
				}
1343
			case T_Attr:
1344
				{
1345 1346 1347 1348 1349 1350 1351 1352
					Oid			type_id;
					int			type_len;
					Attr	   *att = (Attr *) res->val;
					Node	   *result;
					char	   *attrname;
					char	   *resname;
					Resdom	   *resnode;
					List	   *attrs = att->attrs;
1353 1354

					/*
1355 1356
					 * Target item is a single '*', expand all tables (eg.
					 * SELECT * FROM emp)
1357
					 */
1358 1359 1360 1361 1362 1363
					if (att->relname != NULL && !strcmp(att->relname, "*"))
					{
						if (tail_p_target == NIL)
							p_target = tail_p_target = expandAllTables(pstate);
						else
							lnext(tail_p_target) = expandAllTables(pstate);
1364

1365 1366 1367
						while (lnext(tail_p_target) != NIL)
							/* make sure we point to the last target entry */
							tail_p_target = lnext(tail_p_target);
1368

1369 1370 1371 1372 1373 1374
						/*
						 * skip rest of while loop
						 */
						targetlist = lnext(targetlist);
						continue;
					}
1375 1376

					/*
1377 1378
					 * Target item is relation.*, expand the table (eg.
					 * SELECT emp.*, dname FROM emp, dept)
1379
					 */
1380 1381 1382
					attrname = strVal(lfirst(att->attrs));
					if (att->attrs != NIL && !strcmp(attrname, "*"))
					{
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
						/*
						 * tail_p_target is the target list we're building
						 * in the while loop. Make sure we fix it after
						 * appending more nodes.
						 */
						if (tail_p_target == NIL)
							p_target = tail_p_target = expandAll(pstate, att->relname,
									att->relname, &pstate->p_last_resno);
						else
							lnext(tail_p_target) =
								expandAll(pstate, att->relname, att->relname,
										  &pstate->p_last_resno);
						while (lnext(tail_p_target) != NIL)
							/* make sure we point to the last target entry */
							tail_p_target = lnext(tail_p_target);

						/*
						 * skip the rest of the while loop
						 */
						targetlist = lnext(targetlist);
						continue;
					}
1406 1407


1408 1409 1410 1411 1412 1413 1414
					/*
					 * Target item is fully specified: ie.
					 * relation.attribute
					 */
					result = handleNestedDots(pstate, att, &pstate->p_last_resno);
					handleTargetColname(pstate, &res->name, att->relname, attrname);
					if (att->indirection != NIL)
1415
					{
1416
						List	   *ilist = att->indirection;
1417

1418 1419 1420 1421 1422 1423 1424 1425 1426
						while (ilist != NIL)
						{
							A_Indices  *ind = lfirst(ilist);

							ind->lidx = transformExpr(pstate, ind->lidx, EXPR_COLUMN_FIRST);
							ind->uidx = transformExpr(pstate, ind->uidx, EXPR_COLUMN_FIRST);
							ilist = lnext(ilist);
						}
						result = (Node *) make_array_ref(result, att->indirection);
1427
					}
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
					type_id = exprType(result);
					type_len = tlen(get_id_type(type_id));
					/* move to last entry */
					while (lnext(attrs) != NIL)
						attrs = lnext(attrs);
					resname = (res->name) ? res->name : strVal(lfirst(attrs));
					resnode = makeResdom((AttrNumber) pstate->p_last_resno++,
										 (Oid) type_id,
										 (Size) type_len,
										 resname,
										 (Index) 0,
										 (Oid) 0,
										 0);
					tent->resdom = resnode;
					tent->expr = result;
					break;
1444
				}
1445 1446 1447 1448
			default:
				/* internal error */
				elog(WARN,
					 "internal error: do not know how to transform targetlist");
1449
				break;
1450 1451
		}

1452 1453 1454 1455
		if (p_target == NIL)
		{
			p_target = tail_p_target = lcons(tent, NIL);
		}
1456
		else
1457 1458 1459
		{
			lnext(tail_p_target) = lcons(tent, NIL);
			tail_p_target = lnext(tail_p_target);
1460
		}
1461
		targetlist = lnext(targetlist);
1462
	}
B
Bruce Momjian 已提交
1463

1464
	return p_target;
1465 1466 1467 1468 1469
}


/*
 * make_targetlist_expr -
1470
 *	  make a TargetEntry from an expression
1471 1472 1473 1474
 *
 * arrayRef is a list of transformed A_Indices
 */
static TargetEntry *
1475
make_targetlist_expr(ParseState *pstate,
1476
					 char *colname,
1477 1478
					 Node *expr,
					 List *arrayRef)
1479
{
1480 1481 1482 1483 1484 1485 1486 1487 1488
	Oid			type_id,
				attrtype;
	int			type_len,
				attrlen;
	int			resdomno;
	Relation	rd;
	bool		attrisset;
	TargetEntry *tent;
	Resdom	   *resnode;
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524

	if (expr == NULL)
		elog(WARN, "make_targetlist_expr: invalid use of NULL expression");

	type_id = exprType(expr);
	if (type_id == InvalidOid)
	{
		type_len = 0;
	}
	else
		type_len = tlen(get_id_type(type_id));

	/* I have no idea what the following does! */
	/* It appears to process target columns that will be receiving results */
	if (pstate->p_is_insert || pstate->p_is_update)
	{

		/*
		 * append or replace query -- append, replace work only on one
		 * relation, so multiple occurence of same resdomno is bogus
		 */
		rd = pstate->p_target_relation;
		Assert(rd != NULL);
		resdomno = varattno(rd, colname);
		attrisset = varisset(rd, colname);
		attrtype = att_typeid(rd, resdomno);
		if ((arrayRef != NIL) && (lfirst(arrayRef) == NIL))
			attrtype = GetArrayElementType(attrtype);
		if (attrtype == BPCHAROID || attrtype == VARCHAROID)
		{
			attrlen = rd->rd_att->attrs[resdomno - 1]->attlen;
		}
		else
		{
			attrlen = tlen(get_id_type(attrtype));
		}
1525
#if 0
1526 1527
		if (Input_is_string && Typecast_ok)
		{
1528
			Datum		val;
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

			if (type_id == typeid(type("unknown")))
			{
				val = (Datum) textout((struct varlena *)
									  ((Const) lnext(expr))->constvalue);
			}
			else
			{
				val = ((Const) lnext(expr))->constvalue;
			}
			if (attrisset)
			{
				lnext(expr) = makeConst(attrtype,
										attrlen,
										val,
										false,
										true,
										true,	/* is set */
										false);
			}
			else
			{
				lnext(expr) =
					makeConst(attrtype,
							  attrlen,
							  (Datum) fmgr(typeid_get_retinfunc(attrtype),
										 val, get_typelem(attrtype), -1),
							  false,
							  true /* Maybe correct-- 80% chance */ ,
							  false,	/* is not a set */
							  false);
			}
		}
		else if ((Typecast_ok) && (attrtype != type_id))
		{
			lnext(expr) =
				parser_typecast2(expr, get_id_type(attrtype));
		}
		else if (attrtype != type_id)
		{
			if ((attrtype == INT2OID) && (type_id == INT4OID))
				lfirst(expr) = lispInteger(INT2OID);	/* handle CASHOID too */
			else if ((attrtype == FLOAT4OID) && (type_id == FLOAT8OID))
				lfirst(expr) = lispInteger(FLOAT4OID);
			else
				elog(WARN, "unequal type in tlist : %s \n", colname);
		}

		Input_is_string = false;
		Input_is_integer = false;
		Typecast_ok = true;
1580
#endif
B
Bruce Momjian 已提交
1581

1582 1583 1584 1585 1586 1587 1588 1589
		if (attrtype != type_id)
		{
			if (IsA(expr, Const))
			{
				/* try to cast the constant */
				if (arrayRef && !(((A_Indices *) lfirst(arrayRef))->lidx))
				{
					/* updating a single item */
1590
					Oid			typelem = get_typelem(attrtype);
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614

					expr = (Node *) parser_typecast2(expr,
													 type_id,
													 get_id_type(typelem),
													 attrlen);
				}
				else
					expr = (Node *) parser_typecast2(expr,
													 type_id,
												   get_id_type(attrtype),
													 attrlen);
			}
			else
			{
				/* currently, we can't handle casting of expressions */
				elog(WARN, "parser: attribute '%s' is of type '%s' but expression is of type '%s'",
					 colname,
					 get_id_typname(attrtype),
					 get_id_typname(type_id));
			}
		}

		if (arrayRef != NIL)
		{
1615 1616 1617 1618 1619
			Expr	   *target_expr;
			Attr	   *att = makeNode(Attr);
			List	   *ar = arrayRef;
			List	   *upperIndexpr = NIL;
			List	   *lowerIndexpr = NIL;
1620 1621 1622 1623 1624 1625 1626

			att->relname = pstrdup(RelationGetRelationName(rd)->data);
			att->attrs = lcons(makeString(colname), NIL);
			target_expr = (Expr *) handleNestedDots(pstate, att,
												  &pstate->p_last_resno);
			while (ar != NIL)
			{
1627
				A_Indices  *ind = lfirst(ar);
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669

				if (lowerIndexpr || (!upperIndexpr && ind->lidx))
				{

					/*
					 * XXX assume all lowerIndexpr is non-null in this
					 * case
					 */
					lowerIndexpr = lappend(lowerIndexpr, ind->lidx);
				}
				upperIndexpr = lappend(upperIndexpr, ind->uidx);
				ar = lnext(ar);
			}

			expr = (Node *) make_array_set(target_expr,
										   upperIndexpr,
										   lowerIndexpr,
										   (Expr *) expr);
			attrtype = att_typeid(rd, resdomno);
			attrlen = tlen(get_id_type(attrtype));
		}
	}
	else
	{
		resdomno = pstate->p_last_resno++;
		attrtype = type_id;
		attrlen = type_len;
	}
	tent = makeNode(TargetEntry);

	resnode = makeResdom((AttrNumber) resdomno,
						 (Oid) attrtype,
						 (Size) attrlen,
						 colname,
						 (Index) 0,
						 (Oid) 0,
						 0);

	tent->resdom = resnode;
	tent->expr = expr;

	return tent;
1670
}
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680


/*****************************************************************************
 *
 * Where Clause
 *
 *****************************************************************************/

/*
 * transformWhereClause -
1681
 *	  transforms the qualification and make sure it is of type Boolean
1682 1683
 *
 */
1684
static Node *
1685
transformWhereClause(ParseState *pstate, Node *a_expr)
1686
{
1687
	Node	   *qual;
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

	if (a_expr == NULL)
		return (Node *) NULL;	/* no qualifiers */

	inWhereClause = true;
	qual = transformExpr(pstate, a_expr, EXPR_COLUMN_FIRST);
	inWhereClause = false;
	if (exprType(qual) != BOOLOID)
	{
		elog(WARN,
			 "where clause must return type bool, not %s",
			 tname(get_id_type(exprType(qual))));
	}
	return qual;
1702 1703 1704 1705 1706 1707 1708 1709 1710
}

/*****************************************************************************
 *
 * Sort Clause
 *
 *****************************************************************************/

/*
1711 1712 1713
 *	find_targetlist_entry -
 *	  returns the Resdom in the target list matching the specified varname
 *	  and range
1714 1715
 *
 */
1716
static TargetEntry *
1717
find_targetlist_entry(ParseState *pstate, SortGroupBy *sortgroupby, List *tlist)
1718
{
1719 1720 1721 1722
	List	   *i;
	int			real_rtable_pos = 0,
				target_pos = 0;
	TargetEntry *target_result = NULL;
1723 1724 1725 1726 1727 1728 1729

	if (sortgroupby->range)
		real_rtable_pos = refnameRangeTablePosn(pstate->p_rtable,
												sortgroupby->range);

	foreach(i, tlist)
	{
1730 1731 1732 1733 1734
		TargetEntry *target = (TargetEntry *) lfirst(i);
		Resdom	   *resnode = target->resdom;
		Var		   *var = (Var *) target->expr;
		char	   *resname = resnode->resname;
		int			test_rtable_pos = var->varno;
M
Fixes:  
Marc G. Fournier 已提交
1735

1736
#ifdef PARSEDEBUG
1737 1738
		printf("find_targetlist_entry- target name is %s, position %d, resno %d\n",
			   (sortgroupby->name ? sortgroupby->name : "(null)"), target_pos + 1, sortgroupby->resno);
1739 1740
#endif

1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
		if (!sortgroupby->name)
		{
			if (sortgroupby->resno == ++target_pos)
			{
				target_result = target;
				break;
			}
		}
		else
		{
			if (!strcmp(resname, sortgroupby->name))
			{
				if (sortgroupby->range)
				{
					if (real_rtable_pos == test_rtable_pos)
					{
						if (target_result != NULL)
							elog(WARN, "Order/Group By %s is ambiguous", sortgroupby->name);
						else
							target_result = target;
					}
				}
				else
				{
					if (target_result != NULL)
						elog(WARN, "Order/Group By %s is ambiguous", sortgroupby->name);
					else
						target_result = target;
				}
			}
		}
M
Fixes:  
Marc G. Fournier 已提交
1772
	}
1773
	return target_result;
1774 1775
}

1776
static Oid
1777 1778
any_ordering_op(int restype)
{
1779 1780
	Operator	order_op;
	Oid			order_opid;
1781 1782 1783 1784 1785

	order_op = oper("<", restype, restype, false);
	order_opid = oprid(order_op);

	return order_opid;
1786 1787 1788 1789
}

/*
 * transformGroupClause -
1790
 *	  transform a Group By clause
1791 1792
 *
 */
1793
static List *
1794
transformGroupClause(ParseState *pstate, List *grouplist, List *targetlist)
1795
{
1796 1797
	List	   *glist = NIL,
			   *gl = NIL;
1798 1799 1800

	while (grouplist != NIL)
	{
1801 1802 1803
		GroupClause *grpcl = makeNode(GroupClause);
		TargetEntry *restarget;
		Resdom	   *resdom;
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822

		restarget = find_targetlist_entry(pstate, lfirst(grouplist), targetlist);

		if (restarget == NULL)
			elog(WARN, "The field being grouped by must appear in the target list");

		grpcl->entry = restarget;
		resdom = restarget->resdom;
		grpcl->grpOpoid = oprid(oper("<",
									 resdom->restype,
									 resdom->restype, false));
		if (glist == NIL)
			gl = glist = lcons(grpcl, NIL);
		else
		{
			lnext(gl) = lcons(grpcl, NIL);
			gl = lnext(gl);
		}
		grouplist = lnext(grouplist);
1823 1824
	}

1825
	return glist;
1826 1827 1828 1829
}

/*
 * transformSortClause -
1830
 *	  transform an Order By clause
1831 1832
 *
 */
1833
static List *
1834 1835
transformSortClause(ParseState *pstate,
					List *orderlist, List *targetlist,
1836
					char *uniqueFlag)
1837
{
1838 1839 1840
	List	   *sortlist = NIL;
	List	   *s = NIL,
			   *i;
1841 1842 1843

	while (orderlist != NIL)
	{
1844 1845 1846 1847
		SortGroupBy *sortby = lfirst(orderlist);
		SortClause *sortcl = makeNode(SortClause);
		TargetEntry *restarget;
		Resdom	   *resdom;
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866

		restarget = find_targetlist_entry(pstate, sortby, targetlist);
		if (restarget == NULL)
			elog(WARN, "The field being ordered by must appear in the target list");

		sortcl->resdom = resdom = restarget->resdom;
		sortcl->opoid = oprid(oper(sortby->useOp,
								   resdom->restype,
								   resdom->restype, false));
		if (sortlist == NIL)
		{
			s = sortlist = lcons(sortcl, NIL);
		}
		else
		{
			lnext(s) = lcons(sortcl, NIL);
			s = lnext(s);
		}
		orderlist = lnext(orderlist);
1867
	}
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879

	if (uniqueFlag)
	{
		if (uniqueFlag[0] == '*')
		{

			/*
			 * concatenate all elements from target list that are not
			 * already in the sortby list
			 */
			foreach(i, targetlist)
			{
1880
				TargetEntry *tlelt = (TargetEntry *) lfirst(i);
1881 1882 1883 1884

				s = sortlist;
				while (s != NIL)
				{
1885
					SortClause *sortcl = lfirst(s);
1886 1887 1888 1889 1890 1891 1892 1893

					if (sortcl->resdom == tlelt->resdom)
						break;
					s = lnext(s);
				}
				if (s == NIL)
				{
					/* not a member of the sortclauses yet */
1894
					SortClause *sortcl = makeNode(SortClause);
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904

					sortcl->resdom = tlelt->resdom;
					sortcl->opoid = any_ordering_op(tlelt->resdom->restype);

					sortlist = lappend(sortlist, sortcl);
				}
			}
		}
		else
		{
1905 1906
			TargetEntry *tlelt = NULL;
			char	   *uniqueAttrName = uniqueFlag;
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921

			/* only create sort clause with the specified unique attribute */
			foreach(i, targetlist)
			{
				tlelt = (TargetEntry *) lfirst(i);
				if (strcmp(tlelt->resdom->resname, uniqueAttrName) == 0)
					break;
			}
			if (i == NIL)
			{
				elog(WARN, "The field specified in the UNIQUE ON clause is not in the targetlist");
			}
			s = sortlist;
			foreach(s, sortlist)
			{
1922
				SortClause *sortcl = lfirst(s);
1923 1924 1925 1926 1927 1928 1929

				if (sortcl->resdom == tlelt->resdom)
					break;
			}
			if (s == NIL)
			{
				/* not a member of the sortclauses yet */
1930
				SortClause *sortcl = makeNode(SortClause);
1931 1932 1933 1934 1935 1936 1937 1938

				sortcl->resdom = tlelt->resdom;
				sortcl->opoid = any_ordering_op(tlelt->resdom->restype);

				sortlist = lappend(sortlist, sortcl);
			}
		}

1939 1940
	}

1941
	return sortlist;
1942 1943 1944 1945 1946 1947 1948
}

/*
 ** HandleNestedDots --
 **    Given a nested dot expression (i.e. (relation func ... attr), build up
 ** a tree with of Iter and Func nodes.
 */
1949
static Node *
1950
handleNestedDots(ParseState *pstate, Attr *attr, int *curr_resno)
1951
{
1952 1953
	List	   *mutator_iter;
	Node	   *retval = NULL;
1954 1955 1956

	if (attr->paramNo != NULL)
	{
1957
		Param	   *param = (Param *) transformExpr(pstate, (Node *) attr->paramNo, EXPR_RELATION_FIRST);
1958 1959 1960 1961 1962 1963 1964 1965

		retval =
			ParseFunc(pstate, strVal(lfirst(attr->attrs)),
					  lcons(param, NIL),
					  curr_resno);
	}
	else
	{
1966
		Ident	   *ident = makeNode(Ident);
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983

		ident->name = attr->relname;
		ident->isRel = TRUE;
		retval =
			ParseFunc(pstate, strVal(lfirst(attr->attrs)),
					  lcons(ident, NIL),
					  curr_resno);
	}

	foreach(mutator_iter, lnext(attr->attrs))
	{
		retval = ParseFunc(pstate, strVal(lfirst(mutator_iter)),
						   lcons(retval, NIL),
						   curr_resno);
	}

	return (retval);
1984 1985 1986 1987
}

/*
 ** make_arguments --
1988
 **   Given the number and types of arguments to a function, and the
1989 1990 1991 1992
 **   actual arguments and argument types, do the necessary typecasting.
 */
static void
make_arguments(int nargs,
1993 1994 1995
			   List *fargs,
			   Oid *input_typeids,
			   Oid *function_typeids)
1996
{
1997 1998 1999 2000 2001 2002 2003 2004 2005

	/*
	 * there are two ways an input typeid can differ from a function
	 * typeid : either the input type inherits the function type, so no
	 * typecasting is necessary, or the input type can be typecast into
	 * the function type. right now, we only typecast unknowns, and that
	 * is all we check for.
	 */

2006 2007
	List	   *current_fargs;
	int			i;
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021

	for (i = 0, current_fargs = fargs;
		 i < nargs;
		 i++, current_fargs = lnext(current_fargs))
	{

		if (input_typeids[i] == UNKNOWNOID && function_typeids[i] != InvalidOid)
		{
			lfirst(current_fargs) =
				parser_typecast2(lfirst(current_fargs),
								 input_typeids[i],
								 get_id_type(function_typeids[i]),
								 -1);
		}
2022 2023 2024 2025 2026
	}
}

/*
 ** setup_tlist --
2027 2028 2029 2030
 **		Build a tlist that says which attribute to project to.
 **		This routine is called by ParseFunc() to set up a target list
 **		on a tuple parameter or return value.  Due to a bug in 4.0,
 **		it's not possible to refer to system attributes in this case.
2031
 */
2032
static List *
2033 2034
setup_tlist(char *attname, Oid relid)
{
2035 2036 2037 2038 2039
	TargetEntry *tle;
	Resdom	   *resnode;
	Var		   *varnode;
	Oid			typeid;
	int			attno;
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058

	attno = get_attnum(relid, attname);
	if (attno < 0)
		elog(WARN, "cannot reference attribute %s of tuple params/return values for functions", attname);

	typeid = find_atttype(relid, attname);
	resnode = makeResdom(1,
						 typeid,
						 tlen(get_id_type(typeid)),
						 get_attname(relid, attno),
						 0,
						 (Oid) 0,
						 0);
	varnode = makeVar(-1, attno, typeid, -1, attno);

	tle = makeNode(TargetEntry);
	tle->resdom = resnode;
	tle->expr = (Node *) varnode;
	return (lcons(tle, NIL));
2059 2060 2061 2062
}

/*
 ** setup_base_tlist --
2063 2064
 **		Build a tlist that extracts a base type from the tuple
 **		returned by the executor.
2065
 */
2066
static List *
2067 2068
setup_base_tlist(Oid typeid)
{
2069 2070 2071
	TargetEntry *tle;
	Resdom	   *resnode;
	Var		   *varnode;
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085

	resnode = makeResdom(1,
						 typeid,
						 tlen(get_id_type(typeid)),
						 "<noname>",
						 0,
						 (Oid) 0,
						 0);
	varnode = makeVar(-1, 1, typeid, -1, 1);
	tle = makeNode(TargetEntry);
	tle->resdom = resnode;
	tle->expr = (Node *) varnode;

	return (lcons(tle, NIL));
2086 2087 2088 2089
}

/*
 * ParseComplexProjection -
2090 2091
 *	  handles function calls with a single argument that is of complex type.
 *	  This routine returns NULL if it can't handle the projection (eg. sets).
2092
 */
2093
static Node *
2094
ParseComplexProjection(ParseState *pstate,
2095
					   char *funcname,
2096 2097
					   Node *first_arg,
					   bool *attisset)
2098
{
2099 2100 2101 2102 2103 2104
	Oid			argtype;
	Oid			argrelid;
	Name		relname;
	Relation	rd;
	Oid			relid;
	int			attnum;
2105 2106

	switch (nodeTag(first_arg))
2107
	{
2108
		case T_Iter:
2109
			{
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
				Func	   *func;
				Iter	   *iter;

				iter = (Iter *) first_arg;
				func = (Func *) ((Expr *) iter->iterexpr)->oper;
				argtype = funcid_get_rettype(func->funcid);
				argrelid = typeid_get_relid(argtype);
				if (argrelid &&
					((attnum = get_attnum(argrelid, funcname))
					 != InvalidAttrNumber))
				{
2121

2122 2123 2124 2125
					/*
					 * the argument is a function returning a tuple, so
					 * funcname may be a projection
					 */
2126

2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
					/* add a tlist to the func node and return the Iter */
					rd = heap_openr(tname(get_id_type(argtype)));
					if (RelationIsValid(rd))
					{
						relid = RelationGetRelationId(rd);
						relname = RelationGetRelationName(rd);
						heap_close(rd);
					}
					if (RelationIsValid(rd))
					{
						func->func_tlist =
							setup_tlist(funcname, argrelid);
						iter->itertype = att_typeid(rd, attnum);
						return ((Node *) iter);
					}
					else
					{
						elog(WARN,
							 "Function %s has bad returntype %d",
							 funcname, argtype);
					}
2148 2149 2150
				}
				else
				{
2151 2152
					/* drop through */
					;
2153
				}
2154
				break;
2155
			}
2156
		case T_Var:
2157
			{
2158 2159 2160 2161 2162 2163 2164

				/*
				 * The argument is a set, so this is either a projection
				 * or a function call on this set.
				 */
				*attisset = true;
				break;
2165
			}
2166 2167 2168 2169
		case T_Expr:
			{
				Expr	   *expr = (Expr *) first_arg;
				Func	   *funcnode;
2170

2171 2172
				if (expr->opType != FUNC_EXPR)
					break;
2173

2174 2175 2176
				funcnode = (Func *) expr->oper;
				argtype = funcid_get_rettype(funcnode->funcid);
				argrelid = typeid_get_relid(argtype);
2177

2178 2179 2180 2181 2182 2183 2184 2185
				/*
				 * the argument is a function returning a tuple, so
				 * funcname may be a projection
				 */
				if (argrelid &&
					(attnum = get_attnum(argrelid, funcname))
					!= InvalidAttrNumber)
				{
2186

2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
					/* add a tlist to the func node */
					rd = heap_openr(tname(get_id_type(argtype)));
					if (RelationIsValid(rd))
					{
						relid = RelationGetRelationId(rd);
						relname = RelationGetRelationName(rd);
						heap_close(rd);
					}
					if (RelationIsValid(rd))
					{
						Expr	   *newexpr;

						funcnode->func_tlist =
							setup_tlist(funcname, argrelid);
						funcnode->functype = att_typeid(rd, attnum);

						newexpr = makeNode(Expr);
						newexpr->typeOid = funcnode->functype;
						newexpr->opType = FUNC_EXPR;
						newexpr->oper = (Node *) funcnode;
						newexpr->args = lcons(first_arg, NIL);

						return ((Node *) newexpr);
					}

				}

				elog(WARN, "Function %s has bad returntype %d",
					 funcname, argtype);
				break;
			}
		case T_Param:
2219
			{
2220
				Param	   *param = (Param *) first_arg;
2221

2222 2223 2224 2225 2226
				/*
				 * If the Param is a complex type, this could be a
				 * projection
				 */
				rd = heap_openr(tname(get_id_type(param->paramtype)));
2227 2228 2229 2230 2231 2232
				if (RelationIsValid(rd))
				{
					relid = RelationGetRelationId(rd);
					relname = RelationGetRelationName(rd);
					heap_close(rd);
				}
2233 2234 2235
				if (RelationIsValid(rd) &&
					(attnum = get_attnum(relid, funcname))
					!= InvalidAttrNumber)
2236 2237
				{

2238 2239 2240
					param->paramtype = att_typeid(rd, attnum);
					param->param_tlist = setup_tlist(funcname, relid);
					return ((Node *) param);
2241
				}
2242
				break;
2243
			}
2244
		default:
2245
			break;
2246
	}
2247 2248 2249 2250

	return NULL;
}

2251
static Node *
2252
ParseFunc(ParseState *pstate, char *funcname, List *fargs, int *curr_resno)
2253
{
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
	Oid			rettype = (Oid) 0;
	Oid			argrelid = (Oid) 0;
	Oid			funcid = (Oid) 0;
	List	   *i = NIL;
	Node	   *first_arg = NULL;
	char	   *relname = NULL;
	char	   *refname = NULL;
	Relation	rd;
	Oid			relid;
	int			nargs;
	Func	   *funcnode;
	Oid			oid_array[8];
	Oid		   *true_oid_array;
	Node	   *retval;
	bool		retset;
	bool		exists;
	bool		attisset = false;
	Oid			toid = (Oid) 0;
	Expr	   *expr;
2273 2274

	if (fargs)
2275
	{
2276 2277 2278
		first_arg = lfirst(fargs);
		if (first_arg == NULL)
			elog(WARN, "function %s does not allow NULL input", funcname);
2279
	}
2280 2281 2282 2283 2284 2285 2286

	/*
	 * * check for projection methods: if function takes one argument, and *
	 * that argument is a relation, param, or PQ function returning a
	 * complex * type, then the function could be a projection.
	 */
	if (length(fargs) == 1)
2287 2288
	{

2289 2290
		if (nodeTag(first_arg) == T_Ident && ((Ident *) first_arg)->isRel)
		{
2291 2292
			RangeTblEntry *rte;
			Ident	   *ident = (Ident *) first_arg;
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311

			/*
			 * first arg is a relation. This could be a projection.
			 */
			refname = ident->name;

			rte = refnameRangeTableEntry(pstate->p_rtable, refname);
			if (rte == NULL)
				rte = addRangeTableEntry(pstate, refname, refname, FALSE, FALSE, NULL);

			relname = rte->relname;
			relid = rte->relid;

			/*
			 * If the attr isn't a set, just make a var for it.  If it is
			 * a set, treat it like a function and drop through.
			 */
			if (get_attnum(relid, funcname) != InvalidAttrNumber)
			{
2312
				Oid			dummyTypeId;
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372

				return
					((Node *) make_var(pstate,
									   refname,
									   funcname,
									   &dummyTypeId));
			}
			else
			{
				/* drop through - attr is a set */
				;
			}
		}
		else if (ISCOMPLEX(exprType(first_arg)))
		{

			/*
			 * Attempt to handle projection of a complex argument. If
			 * ParseComplexProjection can't handle the projection, we have
			 * to keep going.
			 */
			retval = ParseComplexProjection(pstate,
											funcname,
											first_arg,
											&attisset);
			if (attisset)
			{
				toid = exprType(first_arg);
				rd = heap_openr(tname(get_id_type(toid)));
				if (RelationIsValid(rd))
				{
					relname = RelationGetRelationName(rd)->data;
					heap_close(rd);
				}
				else
					elog(WARN,
						 "Type %s is not a relation type",
						 tname(get_id_type(toid)));
				argrelid = typeid_get_relid(toid);

				/*
				 * A projection contains either an attribute name or the
				 * "*".
				 */
				if ((get_attnum(argrelid, funcname) == InvalidAttrNumber)
					&& strcmp(funcname, "*"))
				{
					elog(WARN, "Functions on sets are not yet supported");
				}
			}

			if (retval)
				return retval;
		}
		else
		{

			/*
			 * Parsing aggregates.
			 */
2373
			Oid			basetype;
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387

			/*
			 * the aggregate count is a special case, ignore its base
			 * type.  Treat it as zero
			 */
			if (strcmp(funcname, "count") == 0)
				basetype = 0;
			else
				basetype = exprType(lfirst(fargs));
			if (SearchSysCacheTuple(AGGNAME,
									PointerGetDatum(funcname),
									ObjectIdGetDatum(basetype),
									0, 0))
			{
2388
				Aggreg	   *aggreg = ParseAgg(funcname, basetype, lfirst(fargs));
2389 2390 2391 2392 2393 2394

				AddAggToParseState(pstate, aggreg);
				return (Node *) aggreg;
			}
		}
	}
2395

2396 2397 2398 2399 2400 2401 2402

	/*
	 * * If we dropped through to here it's really a function (or a set,
	 * which * is implemented as a function.) * extract arg type info and
	 * transform relation name arguments into * varnodes of the
	 * appropriate form.
	 */
B
Bruce Momjian 已提交
2403
	MemSet(&oid_array[0], 0, 8 * sizeof(Oid));
2404 2405 2406 2407

	nargs = 0;
	foreach(i, fargs)
	{
2408 2409 2410
		int			vnum;
		RangeTblEntry *rte;
		Node	   *pair = lfirst(i);
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438

		if (nodeTag(pair) == T_Ident && ((Ident *) pair)->isRel)
		{

			/*
			 * a relation
			 */
			refname = ((Ident *) pair)->name;

			rte = refnameRangeTableEntry(pstate->p_rtable, refname);
			if (rte == NULL)
				rte = addRangeTableEntry(pstate, refname, refname,
										 FALSE, FALSE, NULL);
			relname = rte->relname;

			vnum = refnameRangeTablePosn(pstate->p_rtable, rte->refname);

			/*
			 * for func(relname), the param to the function is the tuple
			 * under consideration.  we build a special VarNode to reflect
			 * this -- it has varno set to the correct range table entry,
			 * but has varattno == 0 to signal that the whole tuple is the
			 * argument.
			 */
			toid = typeid(type(relname));
			/* replace it in the arg list */
			lfirst(fargs) =
				makeVar(vnum, 0, toid, vnum, 0);
2439
		}
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
		else if (!attisset)
		{						/* set functions don't have parameters */

			/*
			 * any functiona args which are typed "unknown", but aren't
			 * constants, we don't know what to do with, because we can't
			 * cast them	- jolly
			 */
			if (exprType(pair) == UNKNOWNOID &&
				!IsA(pair, Const))
			{
				elog(WARN, "ParseFunc: no function named %s that takes in an unknown type as argument #%d", funcname, nargs);
			}
			else
				toid = exprType(pair);
2455 2456
		}

2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
		oid_array[nargs++] = toid;
	}

	/*
	 * func_get_detail looks up the function in the catalogs, does
	 * disambiguation for polymorphic functions, handles inheritance, and
	 * returns the funcid and type and set or singleton status of the
	 * function's return value.  it also returns the true argument types
	 * to the function.  if func_get_detail returns true, the function
	 * exists.	otherwise, there was an error.
	 */
	if (attisset)
	{							/* we know all of these fields already */

		/*
		 * We create a funcnode with a placeholder function SetEval.
		 * SetEval() never actually gets executed.	When the function
		 * evaluation routines see it, they use the funcid projected out
		 * from the relation as the actual function to call. Example:
		 * retrieve (emp.mgr.name) The plan for this will scan the emp
		 * relation, projecting out the mgr attribute, which is a funcid.
		 * This function is then called (instead of SetEval) and "name" is
		 * projected from its result.
		 */
		funcid = SetEvalRegProcedure;
		rettype = toid;
		retset = true;
		true_oid_array = oid_array;
		exists = true;
2486
	}
2487
	else
2488
	{
2489 2490
		exists = func_get_detail(funcname, nargs, oid_array, &funcid,
								 &rettype, &retset, &true_oid_array);
2491 2492
	}

2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
	if (!exists)
		elog(WARN, "no such attribute or function %s", funcname);

	/* got it */
	funcnode = makeNode(Func);
	funcnode->funcid = funcid;
	funcnode->functype = rettype;
	funcnode->funcisindex = false;
	funcnode->funcsize = 0;
	funcnode->func_fcache = NULL;
	funcnode->func_tlist = NIL;
	funcnode->func_planlist = NIL;

	/* perform the necessary typecasting */
	make_arguments(nargs, fargs, oid_array, true_oid_array);

	/*
	 * for functions returning base types, we want to project out the
	 * return value.  set up a target list to do that.	the executor will
	 * ignore these for c functions, and do the right thing for postquel
	 * functions.
	 */

	if (typeid_get_relid(rettype) == InvalidOid)
		funcnode->func_tlist = setup_base_tlist(rettype);

	/*
	 * For sets, we want to make a targetlist to project out this
	 * attribute of the set tuples.
	 */
	if (attisset)
	{
		if (!strcmp(funcname, "*"))
		{
			funcnode->func_tlist =
				expandAll(pstate, relname, refname, curr_resno);
		}
		else
		{
			funcnode->func_tlist = setup_tlist(funcname, argrelid);
			rettype = find_atttype(argrelid, funcname);
2534 2535
		}
	}
2536 2537 2538 2539 2540 2541 2542

	/*
	 * Sequence handling.
	 */
	if (funcid == SeqNextValueRegProcedure ||
		funcid == SeqCurrValueRegProcedure)
	{
2543 2544
		Const	   *seq;
		char	   *seqrel;
2545
		text	   *seqname;
2546
		int32		aclcheck_result = -1;
2547
		extern text *lower (text *string);
2548 2549 2550 2551 2552

		Assert(length(fargs) == 1);
		seq = (Const *) lfirst(fargs);
		if (!IsA((Node *) seq, Const))
			elog(WARN, "%s: only constant sequence names are acceptable", funcname);
2553 2554 2555 2556
		seqname = lower ((text*)DatumGetPointer(seq->constvalue));
		pfree (DatumGetPointer(seq->constvalue));
		seq->constvalue = PointerGetDatum (seqname);
		seqrel = textout(seqname);
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567

		if ((aclcheck_result = pg_aclcheck(seqrel, GetPgUserName(),
			   ((funcid == SeqNextValueRegProcedure) ? ACL_WR : ACL_RD)))
			!= ACLCHECK_OK)
			elog(WARN, "%s.%s: %s",
			  seqrel, funcname, aclcheck_error_strings[aclcheck_result]);

		pfree(seqrel);

		if (funcid == SeqNextValueRegProcedure && inWhereClause)
			elog(WARN, "nextval of a sequence in WHERE disallowed");
2568
	}
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581

	expr = makeNode(Expr);
	expr->typeOid = rettype;
	expr->opType = FUNC_EXPR;
	expr->oper = (Node *) funcnode;
	expr->args = fargs;
	retval = (Node *) expr;

	/*
	 * if the function returns a set of values, then we need to iterate
	 * over all the returned values in the executor, so we stick an iter
	 * node here.  if it returns a singleton, then we don't need the iter
	 * node.
2582
	 */
2583 2584 2585

	if (retset)
	{
2586
		Iter	   *iter = makeNode(Iter);
2587 2588 2589 2590

		iter->itertype = rettype;
		iter->iterexpr = retval;
		retval = (Node *) iter;
2591
	}
2592 2593

	return (retval);
2594 2595 2596 2597 2598 2599 2600 2601
}

/*****************************************************************************
 *
 *****************************************************************************/

/*
 * AddAggToParseState -
2602
 *	  add the aggregate to the list of unique aggregates in pstate.
2603 2604 2605 2606
 *
 * SIDE EFFECT: aggno in target list entry will be modified
 */
static void
2607
AddAggToParseState(ParseState *pstate, Aggreg *aggreg)
2608
{
2609 2610
	List	   *ag;
	int			i;
2611 2612 2613 2614 2615 2616 2617 2618

	/*
	 * see if we have the aggregate already (we only need to record the
	 * aggregate once)
	 */
	i = 0;
	foreach(ag, pstate->p_aggs)
	{
2619
		Aggreg	   *a = lfirst(ag);
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629

		if (!strcmp(a->aggname, aggreg->aggname) &&
			equal(a->target, aggreg->target))
		{

			/* fill in the aggno and we're done */
			aggreg->aggno = i;
			return;
		}
		i++;
2630
	}
2631 2632 2633 2634 2635 2636

	/* not found, new aggregate */
	aggreg->aggno = i;
	pstate->p_numAgg++;
	pstate->p_aggs = lappend(pstate->p_aggs, aggreg);
	return;
2637 2638 2639 2640
}

/*
 * finalizeAggregates -
2641 2642
 *	  fill in qry_aggs from pstate. Also checks to make sure that aggregates
 *	  are used in the proper place.
2643 2644
 */
static void
2645
finalizeAggregates(ParseState *pstate, Query *qry)
2646
{
2647 2648
	List	   *l;
	int			i;
2649 2650 2651 2652 2653 2654 2655 2656 2657

	parseCheckAggregates(pstate, qry);

	qry->qry_numAgg = pstate->p_numAgg;
	qry->qry_aggs =
		(Aggreg **) palloc(sizeof(Aggreg *) * qry->qry_numAgg);
	i = 0;
	foreach(l, pstate->p_aggs)
		qry->qry_aggs[i++] = (Aggreg *) lfirst(l);
2658 2659
}

2660
/*
2661
 * contain_agg_clause--
2662 2663 2664
 *	  Recursively find aggreg nodes from a clause.
 *
 *	  Returns true if any aggregate found.
2665
 */
2666
static bool
2667
contain_agg_clause(Node *clause)
2668
{
2669 2670 2671
	if (clause == NULL)
		return FALSE;
	else if (IsA(clause, Aggreg))
2672
		return TRUE;
2673 2674 2675 2676 2677 2678
	else if (IsA(clause, Iter))
		return contain_agg_clause(((Iter *) clause)->iterexpr);
	else if (single_node(clause))
		return FALSE;
	else if (or_clause(clause))
	{
2679
		List	   *temp;
2680

2681 2682 2683 2684 2685 2686 2687
		foreach(temp, ((Expr *) clause)->args)
			if (contain_agg_clause(lfirst(temp)))
			return TRUE;
		return FALSE;
	}
	else if (is_funcclause(clause))
	{
2688
		List	   *temp;
2689

2690 2691 2692 2693 2694 2695 2696
		foreach(temp, ((Expr *) clause)->args)
			if (contain_agg_clause(lfirst(temp)))
			return TRUE;
		return FALSE;
	}
	else if (IsA(clause, ArrayRef))
	{
2697
		List	   *temp;
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715

		foreach(temp, ((ArrayRef *) clause)->refupperindexpr)
			if (contain_agg_clause(lfirst(temp)))
			return TRUE;
		foreach(temp, ((ArrayRef *) clause)->reflowerindexpr)
			if (contain_agg_clause(lfirst(temp)))
			return TRUE;
		if (contain_agg_clause(((ArrayRef *) clause)->refexpr))
			return TRUE;
		if (contain_agg_clause(((ArrayRef *) clause)->refassgnexpr))
			return TRUE;
		return FALSE;
	}
	else if (not_clause(clause))
		return contain_agg_clause((Node *) get_notclausearg((Expr *) clause));
	else if (is_opclause(clause))
		return (contain_agg_clause((Node *) get_leftop((Expr *) clause)) ||
			  contain_agg_clause((Node *) get_rightop((Expr *) clause)));
2716

2717
	return FALSE;
2718 2719
}

2720 2721
/*
 * exprIsAggOrGroupCol -
2722
 *	  returns true if the expression does not contain non-group columns.
2723
 */
2724
static bool
2725
exprIsAggOrGroupCol(Node *expr, List *groupClause)
2726
{
2727
	List	   *gl;
2728 2729

	if (expr == NULL || IsA(expr, Const) ||
2730
		IsA(expr, Param) ||IsA(expr, Aggreg))
2731 2732
		return TRUE;

2733 2734
	foreach(gl, groupClause)
	{
2735
		GroupClause *grpcl = lfirst(gl);
2736

2737 2738 2739 2740 2741 2742
		if (equal(expr, grpcl->entry->expr))
			return TRUE;
	}

	if (IsA(expr, Expr))
	{
2743
		List	   *temp;
2744 2745 2746 2747 2748 2749

		foreach(temp, ((Expr *) expr)->args)
			if (!exprIsAggOrGroupCol(lfirst(temp), groupClause))
			return FALSE;
		return TRUE;
	}
2750

2751
	return FALSE;
2752 2753
}

2754 2755
/*
 * tleIsAggOrGroupCol -
2756
 *	  returns true if the TargetEntry is Agg or GroupCol.
2757
 */
2758
static bool
2759
tleIsAggOrGroupCol(TargetEntry *tle, List *groupClause)
2760
{
2761 2762
	Node	   *expr = tle->expr;
	List	   *gl;
2763

2764
	if (expr == NULL || IsA(expr, Const) ||IsA(expr, Param))
2765 2766 2767 2768
		return TRUE;

	foreach(gl, groupClause)
	{
2769
		GroupClause *grpcl = lfirst(gl);
2770 2771 2772 2773 2774 2775 2776

		if (tle->resdom->resno == grpcl->entry->resdom->resno)
		{
			if (contain_agg_clause((Node *) expr))
				elog(WARN, "parser: aggregates not allowed in GROUP BY clause");
			return TRUE;
		}
2777 2778
	}

2779 2780
	if (IsA(expr, Aggreg))
		return TRUE;
2781

2782 2783
	if (IsA(expr, Expr))
	{
2784
		List	   *temp;
2785

2786 2787 2788 2789 2790
		foreach(temp, ((Expr *) expr)->args)
			if (!exprIsAggOrGroupCol(lfirst(temp), groupClause))
			return FALSE;
		return TRUE;
	}
2791

2792
	return FALSE;
2793 2794 2795 2796
}

/*
 * parseCheckAggregates -
2797 2798 2799
 *	  this should really be done earlier but the current grammar
 *	  cannot differentiate functions from aggregates. So we have do check
 *	  here when the target list and the qualifications are finalized.
2800 2801
 */
static void
2802
parseCheckAggregates(ParseState *pstate, Query *qry)
2803
{
2804
	List	   *tl;
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821

	Assert(pstate->p_numAgg > 0);

	/*
	 * aggregates never appear in WHERE clauses. (we have to check where
	 * clause first because if there is an aggregate, the check for
	 * non-group column in target list may fail.)
	 */
	if (contain_agg_clause(qry->qual))
		elog(WARN, "parser: aggregates not allowed in WHERE clause");

	/*
	 * the target list can only contain aggregates, group columns and
	 * functions thereof.
	 */
	foreach(tl, qry->targetList)
	{
2822
		TargetEntry *tle = lfirst(tl);
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832

		if (!tleIsAggOrGroupCol(tle, qry->groupClause))
			elog(WARN,
				 "parser: illegal use of aggregates or non-group column in target list");
	}

	/*
	 * the expression specified in the HAVING clause has the same
	 * restriction as those in the target list.
	 */
2833
/*
2834 2835 2836 2837 2838 2839 2840
 * Need to change here when we get HAVING works. Currently
 * qry->havingQual is NULL.		- vadim 04/05/97
	if (!exprIsAggOrGroupCol(qry->havingQual, qry->groupClause))
		elog(WARN,
			 "parser: illegal use of aggregates or non-group column in HAVING clause");
 */
	return;
2841
}