heap.c 42.3 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * heap.c--
4
 *	  code to create and destroy POSTGRES heap relations
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/catalog/heap.c,v 1.42 1998/01/05 03:30:27 momjian Exp $
11 12
 *
 * INTERFACE ROUTINES
13
 *		heap_create()			- Create an uncataloged heap relation
14 15
 *		heap_create_with_catalog() - Create a cataloged relation
 *		heap_destroy_with_catalog()			- Removes named relation from catalogs
16 17
 *
 * NOTES
18
 *	  this code taken from access/heap/create.c, which contains
19
 *	  the old heap_create_with_catalogr, amcreate, and amdestroy.
20 21
 *	  those routines will soon call these routines using the function
 *	  manager,
22 23 24
 *	  just like the poorly named "NewXXX" routines do.	The
 *	  "New" routines are all going to die soon, once and for all!
 *		-cim 1/13/91
25 26 27
 *
 *-------------------------------------------------------------------------
 */
28 29
#include <postgres.h>

M
Marc G. Fournier 已提交
30
#include <miscadmin.h>
31
#include <fmgr.h>
M
Marc G. Fournier 已提交
32
#include <access/heapam.h>
33 34 35
#include <catalog/catalog.h>
#include <catalog/catname.h>
#include <catalog/heap.h>
36
#include <catalog/index.h>
37
#include <catalog/indexing.h>
38 39
#include <catalog/pg_attrdef.h>
#include <catalog/pg_index.h>
40
#include <catalog/pg_inherits.h>
41
#include <catalog/pg_ipl.h>
42
#include <catalog/pg_proc.h>
43
#include <catalog/pg_relcheck.h>
44
#include <catalog/pg_type.h>
45
#include <commands/trigger.h>
46 47
#include <nodes/plannodes.h>
#include <optimizer/tlist.h>
48 49 50
#include <parser/parse_expr.h>
#include <parser/parse_node.h>
#include <parser/parse_type.h>
51
#include <rewrite/rewriteRemove.h>
52 53 54
#include <storage/bufmgr.h>
#include <storage/lmgr.h>
#include <storage/smgr.h>
55
#include <tcop/tcopprot.h>
56 57 58
#include <utils/builtins.h>
#include <utils/mcxt.h>
#include <utils/relcache.h>
59
#include <utils/tqual.h>
M
Marc G. Fournier 已提交
60
#ifndef HAVE_MEMMOVE
61
#include <regex/utils.h>
M
Marc G. Fournier 已提交
62
#else
63
#include <string.h>
M
Marc G. Fournier 已提交
64
#endif
65

B
Bruce Momjian 已提交
66 67
static void AddPgRelationTuple(Relation pg_class_desc,
	   Relation new_rel_desc, Oid new_rel_oid, unsigned natts);
68 69 70 71 72 73 74 75 76 77 78
static void AddToTempRelList(Relation r);
static void DeletePgAttributeTuples(Relation rdesc);
static void DeletePgRelationTuple(Relation rdesc);
static void DeletePgTypeTuple(Relation rdesc);
static int	RelationAlreadyExists(Relation pg_class_desc, char relname[]);
static void RelationRemoveIndexes(Relation relation);
static void RelationRemoveInheritance(Relation relation);
static void RemoveFromTempRelList(Relation r);
static void addNewRelationType(char *typeName, Oid new_rel_oid);
static void StoreConstraints(Relation rel);
static void RemoveConstraints(Relation rel);
79 80


81
/* ----------------------------------------------------------------
82
 *				XXX UGLY HARD CODED BADNESS FOLLOWS XXX
83
 *
84 85
 *		these should all be moved to someplace in the lib/catalog
 *		module, if not obliterated first.
86 87 88 89 90 91
 * ----------------------------------------------------------------
 */


/*
 * Note:
92 93 94 95
 *		Should the executor special case these attributes in the future?
 *		Advantage:	consume 1/2 the space in the ATTRIBUTE relation.
 *		Disadvantage:  having rules to compute values in these tuples may
 *				be more difficult if not impossible.
96 97
 */

98 99 100
static FormData_pg_attribute a1 = {
	0xffffffff, {"ctid"}, 27l, 0l, sizeof(ItemPointerData),
	SelfItemPointerAttributeNumber, 0, -1, '\0', '\0', 'i', '\0', '\0'
101 102
};

103 104 105
static FormData_pg_attribute a2 = {
	0xffffffff, {"oid"}, 26l, 0l, sizeof(Oid),
	ObjectIdAttributeNumber, 0, -1, '\001', '\0', 'i', '\0', '\0'
106 107
};

108 109 110
static FormData_pg_attribute a3 = {
	0xffffffff, {"xmin"}, 28l, 0l, sizeof(TransactionId),
	MinTransactionIdAttributeNumber, 0, -1, '\0', '\0', 'i', '\0', '\0'
111 112
};

113 114
static FormData_pg_attribute a4 = {
	0xffffffff, {"cmin"}, 29l, 0l, sizeof(CommandId),
V
Vadim B. Mikheev 已提交
115
	MinCommandIdAttributeNumber, 0, -1, '\001', '\0', 'i', '\0', '\0'
116 117
};

118 119 120
static FormData_pg_attribute a5 = {
	0xffffffff, {"xmax"}, 28l, 0l, sizeof(TransactionId),
	MaxTransactionIdAttributeNumber, 0, -1, '\0', '\0', 'i', '\0', '\0'
121 122
};

123 124
static FormData_pg_attribute a6 = {
	0xffffffff, {"cmax"}, 29l, 0l, sizeof(CommandId),
V
Vadim B. Mikheev 已提交
125
	MaxCommandIdAttributeNumber, 0, -1, '\001', '\0', 'i', '\0', '\0'
126 127
};

128
static AttributeTupleForm HeapAtt[] =
V
Vadim B. Mikheev 已提交
129
{&a1, &a2, &a3, &a4, &a5, &a6};
130 131

/* ----------------------------------------------------------------
132
 *				XXX END OF UGLY HARD CODED BADNESS XXX
133 134 135 136 137 138 139
 * ----------------------------------------------------------------
 */

/* the tempRelList holds
   the list of temporary uncatalogued relations that are created.
   these relations should be destroyed at the end of transactions
*/
140 141
typedef struct tempRelList
{
142 143 144
	Relation   *rels;			/* array of relation descriptors */
	int			num;			/* number of temporary relations */
	int			size;			/* size of space allocated for the rels
145
								 * array */
146
} TempRelList;
147

148
#define TEMP_REL_LIST_SIZE	32
149

150
static TempRelList *tempRels = NULL;
151 152 153


/* ----------------------------------------------------------------
154
 *		heap_create		- Create an uncataloged heap relation
155
 *
156 157 158
 *		Fields relpages, reltuples, reltuples, relkeys, relhistory,
 *		relisindexed, and relkind of rdesc->rd_rel are initialized
 *		to all zeros, as are rd_last and rd_hook.  Rd_refcnt is set to 1.
159
 *
160 161 162 163
 *		Remove the system relation specific code to elsewhere eventually.
 *
 *		Eventually, must place information about this temporary relation
 *		into the transaction context block.
164 165
 *
 *
166 167
 * if heap_create is called with "" as the name, then heap_create will create
 * a temporary name	"temp_$RELOID" for the relation
168 169 170
 * ----------------------------------------------------------------
 */
Relation
171
heap_create(char *name,
172
			TupleDesc tupDesc)
173
{
174
	register unsigned i;
175 176 177 178 179 180 181 182
	Oid			relid;
	Relation	rdesc;
	int			len;
	bool		nailme = false;
	char	   *relname = name;
	char		tempname[40];
	int			isTemp = 0;
	int			natts = tupDesc->natts;
183 184 185 186

/*	  AttributeTupleForm *att = tupDesc->attrs; */

	extern GlobalMemory CacheCxt;
187
	MemoryContext oldcxt;
188 189 190 191 192 193 194 195

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	AssertArg(natts > 0);

	if (IsSystemRelationName(relname) && IsNormalProcessingMode())
196
	{
197
		elog(ABORT,
198
		 "Illegal class name: %s -- pg_ is reserved for system catalogs",
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
			 relname);
	}

	/* ----------------
	 *	switch to the cache context so that we don't lose
	 *	allocations at the end of this transaction, I guess.
	 *	-cim 6/14/90
	 * ----------------
	 */
	if (!CacheCxt)
		CacheCxt = CreateGlobalMemory("Cache");

	oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);

	/* ----------------
	 *	real ugly stuff to assign the proper relid in the relation
	 *	descriptor follows.
	 * ----------------
	 */
	if (!strcmp(RelationRelationName, relname))
	{
		relid = RelOid_pg_class;
		nailme = true;
222
	}
223
	else if (!strcmp(AttributeRelationName, relname))
224
	{
225 226
		relid = RelOid_pg_attribute;
		nailme = true;
227
	}
228
	else if (!strcmp(ProcedureRelationName, relname))
229
	{
230 231
		relid = RelOid_pg_proc;
		nailme = true;
232
	}
233
	else if (!strcmp(TypeRelationName, relname))
234
	{
235 236
		relid = RelOid_pg_type;
		nailme = true;
237
	}
238
	else
239
	{
240 241 242 243 244 245 246 247
		relid = newoid();

		if (name[0] == '\0')
		{
			sprintf(tempname, "temp_%d", relid);
			relname = tempname;
			isTemp = 1;
		}
248
	}
249 250 251 252 253 254 255 256 257 258

	/* ----------------
	 *	allocate a new relation descriptor.
	 *
	 *	XXX the length computation may be incorrect, handle elsewhere
	 * ----------------
	 */
	len = sizeof(RelationData);

	rdesc = (Relation) palloc(len);
B
Bruce Momjian 已提交
259
	MemSet((char *) rdesc, 0, len);
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

	/* ----------
	   create a new tuple descriptor from the one passed in
	*/
	rdesc->rd_att = CreateTupleDescCopyConstr(tupDesc);

	/* ----------------
	 *	initialize the fields of our new relation descriptor
	 * ----------------
	 */

	/* ----------------
	 *	nail the reldesc if this is a bootstrap create reln and
	 *	we may need it in the cache later on in the bootstrap
	 *	process so we don't ever want it kicked out.  e.g. pg_attribute!!!
	 * ----------------
	 */
	if (nailme)
		rdesc->rd_isnailed = true;

	RelationSetReferenceCount(rdesc, 1);

	rdesc->rd_rel = (Form_pg_class) palloc(sizeof *rdesc->rd_rel);

B
Bruce Momjian 已提交
284
	MemSet((char *) rdesc->rd_rel, 0,
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
		   sizeof *rdesc->rd_rel);
	namestrcpy(&(rdesc->rd_rel->relname), relname);
	rdesc->rd_rel->relkind = RELKIND_UNCATALOGED;
	rdesc->rd_rel->relnatts = natts;
	if (tupDesc->constr)
		rdesc->rd_rel->relchecks = tupDesc->constr->num_check;

	for (i = 0; i < natts; i++)
	{
		rdesc->rd_att->attrs[i]->attrelid = relid;
	}

	rdesc->rd_id = relid;

	if (nailme)
	{
		/* for system relations, set the reltype field here */
		rdesc->rd_rel->reltype = relid;
	}

	/* ----------------
	 *	remember if this is a temp relation
	 * ----------------
	 */

	rdesc->rd_istemp = isTemp;

	/* ----------------
	 *	have the storage manager create the relation.
	 * ----------------
	 */

	rdesc->rd_tmpunlinked = TRUE;		/* change once table is created */
B
Bruce Momjian 已提交
318
	rdesc->rd_fd = (File) smgrcreate(DEFAULT_SMGR, rdesc);
319 320 321 322 323 324 325 326 327 328 329 330 331 332
	rdesc->rd_tmpunlinked = FALSE;

	RelationRegisterRelation(rdesc);

	MemoryContextSwitchTo(oldcxt);

	/*
	 * add all temporary relations to the tempRels list so they can be
	 * properly disposed of at the end of transaction
	 */
	if (isTemp)
		AddToTempRelList(rdesc);

	return (rdesc);
333 334 335 336
}


/* ----------------------------------------------------------------
337
 *		heap_create_with_catalog		- Create a cataloged relation
338
 *
339
 *		this is done in 6 steps:
340
 *
341 342
 *		1) CheckAttributeNames() is used to make certain the tuple
 *		   descriptor contains a valid set of attribute names
343
 *
344 345 346
 *		2) pg_class is opened and RelationAlreadyExists()
 *		   preforms a scan to ensure that no relation with the
 *		   same name already exists.
347
 *
348
 *		3) heap_create_with_catalogr() is called to create the new relation
349
 *		   on disk.
350
 *
351 352
 *		4) TypeDefine() is called to define a new type corresponding
 *		   to the new relation.
353
 *
354 355
 *		5) AddNewAttributeTuples() is called to register the
 *		   new relation's schema in pg_attribute.
356
 *
357 358
 *		6) AddPgRelationTuple() is called to register the
 *		   relation itself in the catalogs.
359
 *
360 361 362 363
 *		7) StoreConstraints is called ()		- vadim 08/22/97
 *
 *		8) the relations are closed and the new relation's oid
 *		   is returned.
364 365
 *
 * old comments:
366 367 368 369 370 371 372 373 374 375 376 377 378 379
 *		A new relation is inserted into the RELATION relation
 *		with the specified attribute(s) (newly inserted into
 *		the ATTRIBUTE relation).  How does concurrency control
 *		work?  Is it automatic now?  Expects the caller to have
 *		attname, atttypid, atttyparg, attproc, and attlen domains filled.
 *		Create fills the attnum domains sequentually from zero,
 *		fills the attdisbursion domains with zeros, and fills the
 *		attrelid fields with the relid.
 *
 *		scan relation catalog for name conflict
 *		scan type catalog for typids (if not arg)
 *		create and insert attribute(s) into attribute catalog
 *		create new relation
 *		insert new relation into attribute catalog
380
 *
381
 *		Should coordinate with heap_create_with_catalogr().	Either
382
 *		it should not be called or there should be a way to prevent
383 384 385 386
 *		the relation from being removed at the end of the
 *		transaction if it is successful ('u'/'r' may be enough).
 *		Also, if the transaction does not commit, then the
 *		relation should be removed.
387
 *
388 389
 *		XXX amcreate ignores "off" when inserting (for now).
 *		XXX amcreate (like the other utilities) needs to understand indexes.
390 391 392 393 394
 *
 * ----------------------------------------------------------------
 */

/* --------------------------------
395
 *		CheckAttributeNames
396
 *
397 398
 *		this is used to make certain the tuple descriptor contains a
 *		valid set of attribute names.  a problem simply generates
399
 *		elog(ABORT) which aborts the current transaction.
400 401 402 403 404
 * --------------------------------
 */
static void
CheckAttributeNames(TupleDesc tupdesc)
{
405 406 407
	unsigned	i;
	unsigned	j;
	int			natts = tupdesc->natts;
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

	/* ----------------
	 *	first check for collision with system attribute names
	 * ----------------
	 *
	 *	 also, warn user if attribute to be created has
	 *	 an unknown typid  (usually as a result of a 'retrieve into'
	 *	  - jolly
	 */
	for (i = 0; i < natts; i += 1)
	{
		for (j = 0; j < sizeof HeapAtt / sizeof HeapAtt[0]; j += 1)
		{
			if (nameeq(&(HeapAtt[j]->attname),
					   &(tupdesc->attrs[i]->attname)))
			{
424
				elog(ABORT,
425 426 427 428 429 430 431 432 433 434
					 "create: system attribute named \"%s\"",
					 HeapAtt[j]->attname.data);
			}
		}
		if (tupdesc->attrs[i]->atttypid == UNKNOWNOID)
		{
			elog(NOTICE,
				 "create: attribute named \"%s\" has an unknown type",
				 tupdesc->attrs[i]->attname.data);
		}
435
	}
436 437 438 439 440 441 442 443 444 445 446 447

	/* ----------------
	 *	next check for repeated attribute names
	 * ----------------
	 */
	for (i = 1; i < natts; i += 1)
	{
		for (j = 0; j < i; j += 1)
		{
			if (nameeq(&(tupdesc->attrs[j]->attname),
					   &(tupdesc->attrs[i]->attname)))
			{
448
				elog(ABORT,
449 450 451 452
					 "create: repeated attribute \"%s\"",
					 tupdesc->attrs[j]->attname.data);
			}
		}
453 454 455 456
	}
}

/* --------------------------------
457
 *		RelationAlreadyExists
458
 *
459 460 461
 *		this preforms a scan of pg_class to ensure that
 *		no relation with the same name already exists.	The caller
 *		has to open pg_class and pass an open descriptor.
462 463
 * --------------------------------
 */
464
static int
465 466
RelationAlreadyExists(Relation pg_class_desc, char relname[])
{
467 468 469
	ScanKeyData key;
	HeapScanDesc pg_class_scan;
	HeapTuple	tup;
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

	/*
	 * If this is not bootstrap (initdb) time, use the catalog index on
	 * pg_class.
	 */

	if (!IsBootstrapProcessingMode())
	{
		tup = ClassNameIndexScan(pg_class_desc, relname);
		if (HeapTupleIsValid(tup))
		{
			pfree(tup);
			return ((int) true);
		}
		else
			return ((int) false);
	}

	/* ----------------
	 *	At bootstrap time, we have to do this the hard way.  Form the
	 *	scan key.
	 * ----------------
	 */
	ScanKeyEntryInitialize(&key,
						   0,
						   (AttrNumber) Anum_pg_class_relname,
						   (RegProcedure) NameEqualRegProcedure,
						   (Datum) relname);

	/* ----------------
	 *	begin the scan
	 * ----------------
	 */
	pg_class_scan = heap_beginscan(pg_class_desc,
								   0,
505
								   false,
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
								   1,
								   &key);

	/* ----------------
	 *	get a tuple.  if the tuple is NULL then it means we
	 *	didn't find an existing relation.
	 * ----------------
	 */
	tup = heap_getnext(pg_class_scan, 0, (Buffer *) NULL);

	/* ----------------
	 *	end the scan and return existance of relation.
	 * ----------------
	 */
	heap_endscan(pg_class_scan);

	return
		(PointerIsValid(tup) == true);
524 525 526
}

/* --------------------------------
527
 *		AddNewAttributeTuples
528
 *
529 530
 *		this registers the new relation's schema by adding
 *		tuples to pg_attribute.
531 532 533 534
 * --------------------------------
 */
static void
AddNewAttributeTuples(Oid new_rel_oid,
535
					  TupleDesc tupdesc)
536
{
537
	AttributeTupleForm *dpp;
538 539 540 541 542 543
	unsigned	i;
	HeapTuple	tup;
	Relation	rdesc;
	bool		hasindex;
	Relation	idescs[Num_pg_attr_indices];
	int			natts = tupdesc->natts;
544 545 546 547 548 549 550 551 552 553 554 555 556 557

	/* ----------------
	 *	open pg_attribute
	 * ----------------
	 */
	rdesc = heap_openr(AttributeRelationName);

	/* -----------------
	 * Check if we have any indices defined on pg_attribute.
	 * -----------------
	 */
	Assert(rdesc);
	Assert(rdesc->rd_rel);
	hasindex = RelationGetRelationTupleForm(rdesc)->relhasindex;
558
	if (hasindex)
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);

	/* ----------------
	 *	initialize tuple descriptor.  Note we use setheapoverride()
	 *	so that we can see the effects of our TypeDefine() done
	 *	previously.
	 * ----------------
	 */
	setheapoverride(true);
	fillatt(tupdesc);
	setheapoverride(false);

	/* ----------------
	 *	first we add the user attributes..
	 * ----------------
	 */
	dpp = tupdesc->attrs;
	for (i = 0; i < natts; i++)
	{
		(*dpp)->attrelid = new_rel_oid;
		(*dpp)->attdisbursion = 0;

		tup = heap_addheader(Natts_pg_attribute,
							 ATTRIBUTE_TUPLE_SIZE,
							 (char *) *dpp);

		heap_insert(rdesc, tup);
		if (hasindex)
			CatalogIndexInsert(idescs, Num_pg_attr_indices, rdesc, tup);

		pfree(tup);
		dpp++;
	}

	/* ----------------
	 *	next we add the system attributes..
	 * ----------------
	 */
	dpp = HeapAtt;
	for (i = 0; i < -1 - FirstLowInvalidHeapAttributeNumber; i++)
	{
		(*dpp)->attrelid = new_rel_oid;
		/* (*dpp)->attdisbursion = 0;	   unneeded */

		tup = heap_addheader(Natts_pg_attribute,
							 ATTRIBUTE_TUPLE_SIZE,
							 (char *) *dpp);

		heap_insert(rdesc, tup);

		if (hasindex)
			CatalogIndexInsert(idescs, Num_pg_attr_indices, rdesc, tup);

		pfree(tup);
		dpp++;
	}

	heap_close(rdesc);

	/*
	 * close pg_attribute indices
	 */
621
	if (hasindex)
622
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
623 624 625
}

/* --------------------------------
626
 *		AddPgRelationTuple
627
 *
628 629
 *		this registers the new relation in the catalogs by
 *		adding a tuple to pg_class.
630 631
 * --------------------------------
 */
632
static void
633
AddPgRelationTuple(Relation pg_class_desc,
634 635 636
				   Relation new_rel_desc,
				   Oid new_rel_oid,
				   unsigned natts)
637
{
638 639 640 641 642 643
	Form_pg_class new_rel_reltup;
	HeapTuple	tup;
	Relation	idescs[Num_pg_class_indices];
	bool		isBootstrap;
	extern bool ItsSequenceCreation;	/* It's hack, I know... - vadim
										 * 03/28/97		*/
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702

	/* ----------------
	 *	first we munge some of the information in our
	 *	uncataloged relation's relation descriptor.
	 * ----------------
	 */
	new_rel_reltup = new_rel_desc->rd_rel;

	/* CHECK should get new_rel_oid first via an insert then use XXX */
	/* new_rel_reltup->reltuples = 1; *//* XXX */

	new_rel_reltup->relowner = GetUserId();
	if (ItsSequenceCreation)
		new_rel_reltup->relkind = RELKIND_SEQUENCE;
	else
		new_rel_reltup->relkind = RELKIND_RELATION;
	new_rel_reltup->relnatts = natts;

	/* ----------------
	 *	now form a tuple to add to pg_class
	 *	XXX Natts_pg_class_fixed is a hack - see pg_class.h
	 * ----------------
	 */
	tup = heap_addheader(Natts_pg_class_fixed,
						 CLASS_TUPLE_SIZE,
						 (char *) new_rel_reltup);
	tup->t_oid = new_rel_oid;

	/* ----------------
	 *	finally insert the new tuple and free it.
	 *
	 *	Note: I have no idea why we do a
	 *			SetProcessingMode(BootstrapProcessing);
	 *		  here -cim 6/14/90
	 * ----------------
	 */
	isBootstrap = IsBootstrapProcessingMode() ? true : false;

	SetProcessingMode(BootstrapProcessing);

	heap_insert(pg_class_desc, tup);

	if (!isBootstrap)
	{

		/*
		 * First, open the catalog indices and insert index tuples for the
		 * new relation.
		 */

		CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_class_indices, pg_class_desc, tup);
		CatalogCloseIndices(Num_pg_class_indices, idescs);

		/* now restore processing mode */
		SetProcessingMode(NormalProcessing);
	}

	pfree(tup);
703 704 705 706
}


/* --------------------------------
707
 *		addNewRelationType -
708
 *
709
 *		define a complex type corresponding to the new relation
710 711
 * --------------------------------
 */
712
static void
713 714
addNewRelationType(char *typeName, Oid new_rel_oid)
{
715
	Oid			new_type_oid;
716 717 718 719 720 721 722 723 724 725 726 727 728

	/*
	 * The sizes are set to oid size because it makes implementing sets
	 * MUCH easier, and no one (we hope) uses these fields to figure out
	 * how much space to allocate for the type. An oid is the type used
	 * for a set definition.  When a user requests a set, what they
	 * actually get is the oid of a tuple in the pg_proc catalog, so the
	 * size of the "set" is the size of an oid. Similarly, byval being
	 * true makes sets much easier, and it isn't used by anything else.
	 * Note the assumption that OIDs are the same size as int4s.
	 */
	new_type_oid = TypeCreate(typeName, /* type name */
							  new_rel_oid,		/* relation oid */
729 730
							  typeLen(typeidType(OIDOID)),	/* internal size */
							  typeLen(typeidType(OIDOID)),	/* external size */
731 732 733
							  'c',		/* type-type (catalog) */
							  ',',		/* default array delimiter */
							  "int4in", /* input procedure */
734 735
							  "int4out",/* output procedure */
							  "int4in",	/* receive procedure */
736
							  "int4out",/* send procedure */
737 738 739 740
							  NULL,		/* array element type - irrelevent */
							  "-",		/* default type value */
							  (bool) 1, /* passed by value */
							  'i');		/* default alignment */
741 742 743
}

/* --------------------------------
744
 *		heap_create_with_catalog
745
 *
746
 *		creates a new cataloged relation.  see comments above.
747 748 749
 * --------------------------------
 */
Oid
750
heap_create_with_catalog(char relname[],
751
						TupleDesc tupdesc)
752
{
753 754 755
	Relation	pg_class_desc;
	Relation	new_rel_desc;
	Oid			new_rel_oid;
756

757
	int			natts = tupdesc->natts;
758 759 760 761 762 763 764

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	AssertState(IsNormalProcessingMode() || IsBootstrapProcessingMode());
	if (natts == 0 || natts > MaxHeapAttributeNumber)
765
		elog(ABORT, "amcreate: from 1 to %d attributes must be specified",
766 767 768 769 770 771 772 773 774 775 776 777 778 779
			 MaxHeapAttributeNumber);

	CheckAttributeNames(tupdesc);

	/* ----------------
	 *	open pg_class and see that the relation doesn't
	 *	already exist.
	 * ----------------
	 */
	pg_class_desc = heap_openr(RelationRelationName);

	if (RelationAlreadyExists(pg_class_desc, relname))
	{
		heap_close(pg_class_desc);
780
		elog(ABORT, "amcreate: %s relation already exists", relname);
781 782 783 784 785 786 787
	}

	/* ----------------
	 *	ok, relation does not already exist so now we
	 *	create an uncataloged relation and pull its relation oid
	 *	from the newly formed relation descriptor.
	 *
788
	 *	Note: The call to heap_create() does all the "real" work
789 790 791
	 *	of creating the disk file for the relation.
	 * ----------------
	 */
792
	new_rel_desc = heap_create(relname, tupdesc);
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	new_rel_oid = new_rel_desc->rd_att->attrs[0]->attrelid;

	/* ----------------
	 *	since defining a relation also defines a complex type,
	 *	we add a new system type corresponding to the new relation.
	 * ----------------
	 */
	addNewRelationType(relname, new_rel_oid);

	/* ----------------
	 *	now add tuples to pg_attribute for the attributes in
	 *	our new relation.
	 * ----------------
	 */
	AddNewAttributeTuples(new_rel_oid, tupdesc);

	/* ----------------
	 *	now update the information in pg_class.
	 * ----------------
	 */
	AddPgRelationTuple(pg_class_desc,
					   new_rel_desc,
					   new_rel_oid,
					   natts);

	StoreConstraints(new_rel_desc);

	/* ----------------
	 *	ok, the relation has been cataloged, so close our relations
	 *	and return the oid of the newly created relation.
	 *
	 *	SOMEDAY: fill the STATISTIC relation properly.
	 * ----------------
	 */
	heap_close(new_rel_desc);
828
	heap_close(pg_class_desc);
829 830

	return new_rel_oid;
831 832 833 834
}


/* ----------------------------------------------------------------
835
 *		heap_destroy_with_catalog	- removes all record of named relation from catalogs
836
 *
837 838 839 840 841 842 843 844
 *		1)	open relation, check for existence, etc.
 *		2)	remove inheritance information
 *		3)	remove indexes
 *		4)	remove pg_class tuple
 *		5)	remove pg_attribute tuples
 *		6)	remove pg_type tuples
 *		7)	RemoveConstraints ()
 *		8)	unlink relation
845 846
 *
 * old comments
847 848 849
 *		Except for vital relations, removes relation from
 *		relation catalog, and related attributes from
 *		attribute catalog (needed?).  (Anything else?)
850
 *
851 852 853 854 855 856
 *		get proper relation from relation catalog (if not arg)
 *		check if relation is vital (strcmp()/reltype?)
 *		scan attribute catalog deleting attributes of reldesc
 *				(necessary?)
 *		delete relation from relation catalog
 *		(How are the tuples of the relation discarded?)
857
 *
858 859 860 861
 *		XXX Must fix to work with indexes.
 *		There may be a better order for doing things.
 *		Problems with destroying a deleted database--cannot create
 *		a struct reldesc without having an open file descriptor.
862 863 864 865
 * ----------------------------------------------------------------
 */

/* --------------------------------
866
 *		RelationRemoveInheritance
867
 *
868 869 870 871
 *		Note: for now, we cause an exception if relation is a
 *		superclass.  Someday, we may want to allow this and merge
 *		the type info into subclass procedures....	this seems like
 *		lots of work.
872 873
 * --------------------------------
 */
874
static void
875 876
RelationRemoveInheritance(Relation relation)
{
877 878 879 880
	Relation	catalogRelation;
	HeapTuple	tuple;
	HeapScanDesc scan;
	ScanKeyData entry;
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898

	/* ----------------
	 *	open pg_inherits
	 * ----------------
	 */
	catalogRelation = heap_openr(InheritsRelationName);

	/* ----------------
	 *	form a scan key for the subclasses of this class
	 *	and begin scanning
	 * ----------------
	 */
	ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_inherits_inhparent,
						   ObjectIdEqualRegProcedure,
					  ObjectIdGetDatum(RelationGetRelationId(relation)));

	scan = heap_beginscan(catalogRelation,
						  false,
899
						  false,
900 901 902 903 904 905 906 907 908 909 910 911 912
						  1,
						  &entry);

	/* ----------------
	 *	if any subclasses exist, then we disallow the deletion.
	 * ----------------
	 */
	tuple = heap_getnext(scan, 0, (Buffer *) NULL);
	if (HeapTupleIsValid(tuple))
	{
		heap_endscan(scan);
		heap_close(catalogRelation);

913
		elog(ABORT, "relation <%d> inherits \"%s\"",
914 915 916 917 918 919 920 921 922 923 924 925 926
			 ((InheritsTupleForm) GETSTRUCT(tuple))->inhrel,
			 RelationGetRelationName(relation));
	}

	/* ----------------
	 *	If we get here, it means the relation has no subclasses
	 *	so we can trash it.  First we remove dead INHERITS tuples.
	 * ----------------
	 */
	entry.sk_attno = Anum_pg_inherits_inhrel;

	scan = heap_beginscan(catalogRelation,
						  false,
927
						  false,
928 929 930 931 932 933 934 935 936 937 938 939 940
						  1,
						  &entry);

	for (;;)
	{
		tuple = heap_getnext(scan, 0, (Buffer *) NULL);
		if (!HeapTupleIsValid(tuple))
		{
			break;
		}
		heap_delete(catalogRelation, &tuple->t_ctid);
	}

941 942
	heap_endscan(scan);
	heap_close(catalogRelation);
943 944 945 946 947 948 949 950 951 952 953 954

	/* ----------------
	 *	now remove dead IPL tuples
	 * ----------------
	 */
	catalogRelation =
		heap_openr(InheritancePrecidenceListRelationName);

	entry.sk_attno = Anum_pg_ipl_iplrel;

	scan = heap_beginscan(catalogRelation,
						  false,
955
						  false,
956 957 958 959 960 961 962 963 964 965 966
						  1,
						  &entry);

	for (;;)
	{
		tuple = heap_getnext(scan, 0, (Buffer *) NULL);
		if (!HeapTupleIsValid(tuple))
		{
			break;
		}
		heap_delete(catalogRelation, &tuple->t_ctid);
967
	}
968 969 970

	heap_endscan(scan);
	heap_close(catalogRelation);
971 972 973
}

/* --------------------------------
974 975
 *		RelationRemoveIndexes
 *
976 977
 * --------------------------------
 */
978
static void
979 980
RelationRemoveIndexes(Relation relation)
{
981 982 983 984
	Relation	indexRelation;
	HeapTuple	tuple;
	HeapScanDesc scan;
	ScanKeyData entry;
985 986 987 988 989 990 991 992 993

	indexRelation = heap_openr(IndexRelationName);

	ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_index_indrelid,
						   ObjectIdEqualRegProcedure,
					  ObjectIdGetDatum(RelationGetRelationId(relation)));

	scan = heap_beginscan(indexRelation,
						  false,
994
						  false,
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
						  1,
						  &entry);

	for (;;)
	{
		tuple = heap_getnext(scan, 0, (Buffer *) NULL);
		if (!HeapTupleIsValid(tuple))
		{
			break;
		}

		index_destroy(((IndexTupleForm) GETSTRUCT(tuple))->indexrelid);
1007
	}
1008 1009 1010

	heap_endscan(scan);
	heap_close(indexRelation);
1011 1012 1013
}

/* --------------------------------
1014
 *		DeletePgRelationTuple
1015 1016 1017
 *
 * --------------------------------
 */
1018
static void
1019 1020
DeletePgRelationTuple(Relation rdesc)
{
1021 1022 1023 1024
	Relation	pg_class_desc;
	HeapScanDesc pg_class_scan;
	ScanKeyData key;
	HeapTuple	tup;
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

	/* ----------------
	 *	open pg_class
	 * ----------------
	 */
	pg_class_desc = heap_openr(RelationRelationName);

	/* ----------------
	 *	create a scan key to locate the relation oid of the
	 *	relation to delete
	 * ----------------
	 */
	ScanKeyEntryInitialize(&key, 0, ObjectIdAttributeNumber,
						   F_INT4EQ, rdesc->rd_att->attrs[0]->attrelid);

	pg_class_scan = heap_beginscan(pg_class_desc,
								   0,
1042
								   false,
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
								   1,
								   &key);

	/* ----------------
	 *	use heap_getnext() to fetch the pg_class tuple.  If this
	 *	tuple is not valid then something's wrong.
	 * ----------------
	 */
	tup = heap_getnext(pg_class_scan, 0, (Buffer *) NULL);

	if (!PointerIsValid(tup))
	{
		heap_endscan(pg_class_scan);
		heap_close(pg_class_desc);
1057
		elog(ABORT, "DeletePgRelationTuple: %s relation nonexistent",
1058 1059 1060 1061 1062 1063 1064
			 &rdesc->rd_rel->relname);
	}

	/* ----------------
	 *	delete the relation tuple from pg_class, and finish up.
	 * ----------------
	 */
1065
	heap_endscan(pg_class_scan);
1066 1067
	heap_delete(pg_class_desc, &tup->t_ctid);

1068 1069 1070 1071
	heap_close(pg_class_desc);
}

/* --------------------------------
1072
 *		DeletePgAttributeTuples
1073 1074 1075
 *
 * --------------------------------
 */
1076
static void
1077 1078
DeletePgAttributeTuples(Relation rdesc)
{
1079 1080 1081 1082
	Relation	pg_attribute_desc;
	HeapScanDesc pg_attribute_scan;
	ScanKeyData key;
	HeapTuple	tup;
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

	/* ----------------
	 *	open pg_attribute
	 * ----------------
	 */
	pg_attribute_desc = heap_openr(AttributeRelationName);

	/* ----------------
	 *	create a scan key to locate the attribute tuples to delete
	 *	and begin the scan.
	 * ----------------
	 */
	ScanKeyEntryInitialize(&key, 0, Anum_pg_attribute_attrelid,
						   F_INT4EQ, rdesc->rd_att->attrs[0]->attrelid);

	/* -----------------
	 * Get a write lock _before_ getting the read lock in the scan
	 * ----------------
	 */
	RelationSetLockForWrite(pg_attribute_desc);

	pg_attribute_scan = heap_beginscan(pg_attribute_desc,
									   0,
1106
									   false,
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
									   1,
									   &key);

	/* ----------------
	 *	use heap_getnext() / amdelete() until all attribute tuples
	 *	have been deleted.
	 * ----------------
	 */
	while (tup = heap_getnext(pg_attribute_scan, 0, (Buffer *) NULL),
		   PointerIsValid(tup))
	{

		heap_delete(pg_attribute_desc, &tup->t_ctid);
	}

	/* ----------------
	 *	finish up.
	 * ----------------
	 */
	heap_endscan(pg_attribute_scan);

	/* ----------------
	 * Release the write lock
	 * ----------------
	 */
	RelationUnsetLockForWrite(pg_attribute_desc);
	heap_close(pg_attribute_desc);
1134 1135 1136 1137
}


/* --------------------------------
1138
 *		DeletePgTypeTuple
1139
 *
1140 1141 1142 1143
 *		If the user attempts to destroy a relation and there
 *		exists attributes in other relations of type
 *		"relation we are deleting", then we have to do something
 *		special.  presently we disallow the destroy.
1144 1145
 * --------------------------------
 */
1146
static void
1147 1148
DeletePgTypeTuple(Relation rdesc)
{
1149 1150 1151 1152 1153 1154 1155 1156 1157
	Relation	pg_type_desc;
	HeapScanDesc pg_type_scan;
	Relation	pg_attribute_desc;
	HeapScanDesc pg_attribute_scan;
	ScanKeyData key;
	ScanKeyData attkey;
	HeapTuple	tup;
	HeapTuple	atttup;
	Oid			typoid;
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174

	/* ----------------
	 *	open pg_type
	 * ----------------
	 */
	pg_type_desc = heap_openr(TypeRelationName);

	/* ----------------
	 *	create a scan key to locate the type tuple corresponding
	 *	to this relation.
	 * ----------------
	 */
	ScanKeyEntryInitialize(&key, 0, Anum_pg_type_typrelid, F_INT4EQ,
						   rdesc->rd_att->attrs[0]->attrelid);

	pg_type_scan = heap_beginscan(pg_type_desc,
								  0,
1175
								  false,
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
								  1,
								  &key);

	/* ----------------
	 *	use heap_getnext() to fetch the pg_type tuple.	If this
	 *	tuple is not valid then something's wrong.
	 * ----------------
	 */
	tup = heap_getnext(pg_type_scan, 0, (Buffer *) NULL);

	if (!PointerIsValid(tup))
	{
		heap_endscan(pg_type_scan);
		heap_close(pg_type_desc);
1190
		elog(ABORT, "DeletePgTypeTuple: %s type nonexistent",
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
			 &rdesc->rd_rel->relname);
	}

	/* ----------------
	 *	now scan pg_attribute.	if any other relations have
	 *	attributes of the type of the relation we are deleteing
	 *	then we have to disallow the deletion.	should talk to
	 *	stonebraker about this.  -cim 6/19/90
	 * ----------------
	 */
	typoid = tup->t_oid;

	pg_attribute_desc = heap_openr(AttributeRelationName);

	ScanKeyEntryInitialize(&attkey,
						   0, Anum_pg_attribute_atttypid, F_INT4EQ,
						   typoid);

	pg_attribute_scan = heap_beginscan(pg_attribute_desc,
									   0,
1211
									   false,
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
									   1,
									   &attkey);

	/* ----------------
	 *	try and get a pg_attribute tuple.  if we succeed it means
	 *	we cant delete the relation because something depends on
	 *	the schema.
	 * ----------------
	 */
	atttup = heap_getnext(pg_attribute_scan, 0, (Buffer *) NULL);

	if (PointerIsValid(atttup))
	{
1225
		Oid			relid = ((AttributeTupleForm) GETSTRUCT(atttup))->attrelid;
1226 1227 1228 1229 1230 1231

		heap_endscan(pg_type_scan);
		heap_close(pg_type_desc);
		heap_endscan(pg_attribute_scan);
		heap_close(pg_attribute_desc);

1232
		elog(ABORT, "DeletePgTypeTuple: att of type %s exists in relation %d",
1233 1234
			 &rdesc->rd_rel->relname, relid);
	}
M
Marc G. Fournier 已提交
1235 1236
	heap_endscan(pg_attribute_scan);
	heap_close(pg_attribute_desc);
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247

	/* ----------------
	 *	Ok, it's safe so we delete the relation tuple
	 *	from pg_type and finish up.  But first end the scan so that
	 *	we release the read lock on pg_type.  -mer 13 Aug 1991
	 * ----------------
	 */
	heap_endscan(pg_type_scan);
	heap_delete(pg_type_desc, &tup->t_ctid);

	heap_close(pg_type_desc);
M
Marc G. Fournier 已提交
1248 1249 1250
}

/* --------------------------------
1251
 *		heap_destroy_with_catalog
M
Marc G. Fournier 已提交
1252 1253 1254 1255
 *
 * --------------------------------
 */
void
1256
heap_destroy_with_catalog(char *relname)
M
Marc G. Fournier 已提交
1257
{
1258 1259
	Relation	rdesc;
	Oid			rid;
1260 1261 1262 1263 1264 1265 1266 1267

	/* ----------------
	 *	first open the relation.  if the relation does exist,
	 *	heap_openr() returns NULL.
	 * ----------------
	 */
	rdesc = heap_openr(relname);
	if (rdesc == NULL)
1268
		elog(ABORT, "Relation %s Does Not Exist!", relname);
1269 1270 1271 1272 1273 1274 1275 1276 1277

	RelationSetLockForWrite(rdesc);
	rid = rdesc->rd_id;

	/* ----------------
	 *	prevent deletion of system relations
	 * ----------------
	 */
	if (IsSystemRelationName(RelationGetRelationName(rdesc)->data))
1278
		elog(ABORT, "amdestroy: cannot destroy %s relation",
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
			 &rdesc->rd_rel->relname);

	/* ----------------
	 *	remove inheritance information
	 * ----------------
	 */
	RelationRemoveInheritance(rdesc);

	/* ----------------
	 *	remove indexes if necessary
	 * ----------------
	 */
	if (rdesc->rd_rel->relhasindex)
	{
		RelationRemoveIndexes(rdesc);
	}

	/* ----------------
	 *	remove rules if necessary
	 * ----------------
	 */
	if (rdesc->rd_rules != NULL)
	{
		RelationRemoveRules(rid);
	}

	/* triggers */
	if (rdesc->rd_rel->reltriggers > 0)
		RelationRemoveTriggers(rdesc);

	/* ----------------
	 *	delete attribute tuples
	 * ----------------
	 */
	DeletePgAttributeTuples(rdesc);

	/* ----------------
	 *	delete type tuple.	here we want to see the effects
	 *	of the deletions we just did, so we use setheapoverride().
	 * ----------------
	 */
	setheapoverride(true);
	DeletePgTypeTuple(rdesc);
	setheapoverride(false);

	/* ----------------
	 *	delete relation tuple
	 * ----------------
	 */
	DeletePgRelationTuple(rdesc);

	/*
	 * release dirty buffers of this relation
	 */
	ReleaseRelationBuffers(rdesc);

	/* ----------------
	 *	flush the relation from the relcache
	 * ----------------
	 * Does nothing!!! Flushing moved below.	- vadim 06/04/97
	RelationIdInvalidateRelationCacheByRelationId(rdesc->rd_id);
	 */

	RemoveConstraints(rdesc);

	/* ----------------
	 *	unlink the relation and finish up.
	 * ----------------
	 */
	if (!(rdesc->rd_istemp) || !(rdesc->rd_tmpunlinked))
	{
B
Bruce Momjian 已提交
1350
		smgrunlink(DEFAULT_SMGR, rdesc);
1351 1352 1353 1354 1355 1356 1357 1358 1359
	}
	rdesc->rd_tmpunlinked = TRUE;

	RelationUnsetLockForWrite(rdesc);

	heap_close(rdesc);

	/* ok - flush the relation from the relcache */
	RelationForgetRelation(rid);
M
Marc G. Fournier 已提交
1360 1361 1362
}

/*
1363
 * heap_destroy
1364
 *	  destroy and close temporary relations
M
Marc G. Fournier 已提交
1365 1366 1367
 *
 */

1368
void
1369
heap_destroy(Relation rdesc)
M
Marc G. Fournier 已提交
1370
{
1371 1372
	ReleaseRelationBuffers(rdesc);
	if (!(rdesc->rd_istemp) || !(rdesc->rd_tmpunlinked))
B
Bruce Momjian 已提交
1373
		smgrunlink(DEFAULT_SMGR, rdesc);
1374 1375 1376
	rdesc->rd_tmpunlinked = TRUE;
	heap_close(rdesc);
	RemoveFromTempRelList(rdesc);
M
Marc G. Fournier 已提交
1377 1378 1379 1380
}


/**************************************************************
1381
  functions to deal with the list of temporary relations
M
Marc G. Fournier 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
**************************************************************/

/* --------------
   InitTempRellist():

   initialize temporary relations list
   the tempRelList is a list of temporary relations that
   are created in the course of the transactions
   they need to be destroyed properly at the end of the transactions

   MODIFIES the global variable tempRels

 >> NOTE <<

   malloc is used instead of palloc because we KNOW when we are
1397
   going to free these things.	Keeps us away from the memory context
M
Marc G. Fournier 已提交
1398 1399 1400 1401
   hairyness

*/
void
1402
InitTempRelList(void)
M
Marc G. Fournier 已提交
1403
{
1404 1405 1406 1407 1408
	if (tempRels)
	{
		free(tempRels->rels);
		free(tempRels);
	}
M
Marc G. Fournier 已提交
1409

1410 1411 1412
	tempRels = (TempRelList *) malloc(sizeof(TempRelList));
	tempRels->size = TEMP_REL_LIST_SIZE;
	tempRels->rels = (Relation *) malloc(sizeof(Relation) * tempRels->size);
B
Bruce Momjian 已提交
1413
	MemSet(tempRels->rels, 0, sizeof(Relation) * tempRels->size);
1414
	tempRels->num = 0;
M
Marc G. Fournier 已提交
1415 1416 1417 1418 1419 1420
}

/*
   removes a relation from the TempRelList

   MODIFIES the global variable tempRels
1421 1422
	  we don't really remove it, just mark it as NULL
	  and DestroyTempRels will look for NULLs
M
Marc G. Fournier 已提交
1423
*/
1424
static void
M
Marc G. Fournier 已提交
1425 1426
RemoveFromTempRelList(Relation r)
{
1427
	int			i;
M
Marc G. Fournier 已提交
1428

1429 1430
	if (!tempRels)
		return;
M
Marc G. Fournier 已提交
1431

1432 1433 1434 1435 1436 1437 1438
	for (i = 0; i < tempRels->num; i++)
	{
		if (tempRels->rels[i] == r)
		{
			tempRels->rels[i] = NULL;
			break;
		}
M
Marc G. Fournier 已提交
1439 1440 1441 1442 1443 1444 1445 1446
	}
}

/*
   add a temporary relation to the TempRelList

   MODIFIES the global variable tempRels
*/
1447
static void
M
Marc G. Fournier 已提交
1448 1449
AddToTempRelList(Relation r)
{
1450 1451
	if (!tempRels)
		return;
M
Marc G. Fournier 已提交
1452

1453 1454 1455 1456 1457 1458 1459 1460
	if (tempRels->num == tempRels->size)
	{
		tempRels->size += TEMP_REL_LIST_SIZE;
		tempRels->rels = realloc(tempRels->rels,
								 sizeof(Relation) * tempRels->size);
	}
	tempRels->rels[tempRels->num] = r;
	tempRels->num++;
M
Marc G. Fournier 已提交
1461 1462 1463 1464 1465 1466
}

/*
   go through the tempRels list and destroy each of the relations
*/
void
1467
DestroyTempRels(void)
M
Marc G. Fournier 已提交
1468
{
1469 1470
	int			i;
	Relation	rdesc;
M
Marc G. Fournier 已提交
1471

1472 1473
	if (!tempRels)
		return;
M
Marc G. Fournier 已提交
1474

1475 1476 1477 1478 1479
	for (i = 0; i < tempRels->num; i++)
	{
		rdesc = tempRels->rels[i];
		/* rdesc may be NULL if it has been removed from the list already */
		if (rdesc)
1480
			heap_destroy(rdesc);
1481 1482 1483 1484
	}
	free(tempRels->rels);
	free(tempRels);
	tempRels = NULL;
M
Marc G. Fournier 已提交
1485 1486
}

1487

1488
static void
B
Bruce Momjian 已提交
1489
StoreAttrDefault(Relation rel, AttrDefault *attrdef)
1490
{
1491 1492
	char		str[MAX_PARSE_BUFFER];
	char		cast[2 * NAMEDATALEN] = {0};
1493
	AttributeTupleForm atp = rel->rd_att->attrs[attrdef->adnum - 1];
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
	QueryTreeList *queryTree_list;
	Query	   *query;
	List	   *planTree_list;
	TargetEntry *te;
	Resdom	   *resdom;
	Node	   *expr;
	char	   *adbin;
	MemoryContext oldcxt;
	Relation	adrel;
	Relation	idescs[Num_pg_attrdef_indices];
	HeapTuple	tuple;
	Datum		values[4];
	char		nulls[4] = {' ', ' ', ' ', ' '};
1507 1508
	extern GlobalMemory CacheCxt;

1509
start:;
1510 1511 1512
	sprintf(str, "select %s%s from %.*s", attrdef->adsrc, cast,
			NAMEDATALEN, rel->rd_rel->relname.data);
	setheapoverride(true);
1513
	planTree_list = (List *) pg_parse_and_plan(str, NULL, 0, &queryTree_list, None);
1514 1515 1516 1517 1518
	setheapoverride(false);
	query = (Query *) (queryTree_list->qtrees[0]);

	if (length(query->rtable) > 1 ||
		flatten_tlist(query->targetList) != NIL)
1519
		elog(ABORT, "DEFAULT: cannot use attribute(s)");
1520 1521 1522 1523 1524 1525 1526 1527 1528
	te = (TargetEntry *) lfirst(query->targetList);
	resdom = te->resdom;
	expr = te->expr;

	if (IsA(expr, Const))
	{
		if (((Const *) expr)->consttype != atp->atttypid)
		{
			if (*cast != 0)
1529
				elog(ABORT, "DEFAULT: const type mismatched");
B
Bruce Momjian 已提交
1530
			sprintf(cast, ":: %s", typeidTypeName(atp->atttypid));
1531 1532 1533 1534
			goto start;
		}
	}
	else if (exprType(expr) != atp->atttypid)
1535
		elog(ABORT, "DEFAULT: type mismatched");
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558

	adbin = nodeToString(expr);
	oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);
	attrdef->adbin = (char *) palloc(strlen(adbin) + 1);
	strcpy(attrdef->adbin, adbin);
	(void) MemoryContextSwitchTo(oldcxt);
	pfree(adbin);

	values[Anum_pg_attrdef_adrelid - 1] = rel->rd_id;
	values[Anum_pg_attrdef_adnum - 1] = attrdef->adnum;
	values[Anum_pg_attrdef_adbin - 1] = PointerGetDatum(textin(attrdef->adbin));
	values[Anum_pg_attrdef_adsrc - 1] = PointerGetDatum(textin(attrdef->adsrc));
	adrel = heap_openr(AttrDefaultRelationName);
	tuple = heap_formtuple(adrel->rd_att, values, nulls);
	CatalogOpenIndices(Num_pg_attrdef_indices, Name_pg_attrdef_indices, idescs);
	heap_insert(adrel, tuple);
	CatalogIndexInsert(idescs, Num_pg_attrdef_indices, adrel, tuple);
	CatalogCloseIndices(Num_pg_attrdef_indices, idescs);
	heap_close(adrel);

	pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
	pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
	pfree(tuple);
1559 1560 1561

}

1562
static void
1563
StoreRelCheck(Relation rel, ConstrCheck *check)
1564
{
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
	char		str[MAX_PARSE_BUFFER];
	QueryTreeList *queryTree_list;
	Query	   *query;
	List	   *planTree_list;
	Plan	   *plan;
	List	   *qual;
	char	   *ccbin;
	MemoryContext oldcxt;
	Relation	rcrel;
	Relation	idescs[Num_pg_relcheck_indices];
	HeapTuple	tuple;
	Datum		values[4];
	char		nulls[4] = {' ', ' ', ' ', ' '};
1578 1579 1580 1581 1582
	extern GlobalMemory CacheCxt;

	sprintf(str, "select 1 from %.*s where %s",
			NAMEDATALEN, rel->rd_rel->relname.data, check->ccsrc);
	setheapoverride(true);
1583
	planTree_list = (List *) pg_parse_and_plan(str, NULL, 0, &queryTree_list, None);
1584 1585 1586 1587
	setheapoverride(false);
	query = (Query *) (queryTree_list->qtrees[0]);

	if (length(query->rtable) > 1)
1588
		elog(ABORT, "CHECK: only relation %.*s can be referenced",
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
			 NAMEDATALEN, rel->rd_rel->relname.data);

	plan = (Plan *) lfirst(planTree_list);
	qual = plan->qual;

	ccbin = nodeToString(qual);
	oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);
	check->ccbin = (char *) palloc(strlen(ccbin) + 1);
	strcpy(check->ccbin, ccbin);
	(void) MemoryContextSwitchTo(oldcxt);
	pfree(ccbin);

	values[Anum_pg_relcheck_rcrelid - 1] = rel->rd_id;
	values[Anum_pg_relcheck_rcname - 1] = PointerGetDatum(namein(check->ccname));
	values[Anum_pg_relcheck_rcbin - 1] = PointerGetDatum(textin(check->ccbin));
	values[Anum_pg_relcheck_rcsrc - 1] = PointerGetDatum(textin(check->ccsrc));
	rcrel = heap_openr(RelCheckRelationName);
	tuple = heap_formtuple(rcrel->rd_att, values, nulls);
	CatalogOpenIndices(Num_pg_relcheck_indices, Name_pg_relcheck_indices, idescs);
	heap_insert(rcrel, tuple);
	CatalogIndexInsert(idescs, Num_pg_relcheck_indices, rcrel, tuple);
	CatalogCloseIndices(Num_pg_relcheck_indices, idescs);
	heap_close(rcrel);

	pfree(DatumGetPointer(values[Anum_pg_relcheck_rcname - 1]));
	pfree(DatumGetPointer(values[Anum_pg_relcheck_rcbin - 1]));
	pfree(DatumGetPointer(values[Anum_pg_relcheck_rcsrc - 1]));
	pfree(tuple);

	return;
1619 1620
}

1621 1622
static void
StoreConstraints(Relation rel)
1623
{
1624 1625
	TupleConstr *constr = rel->rd_att->constr;
	int			i;
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642

	if (!constr)
		return;

	if (constr->num_defval > 0)
	{
		for (i = 0; i < constr->num_defval; i++)
			StoreAttrDefault(rel, &(constr->defval[i]));
	}

	if (constr->num_check > 0)
	{
		for (i = 0; i < constr->num_check; i++)
			StoreRelCheck(rel, &(constr->check[i]));
	}

	return;
1643 1644
}

1645 1646
static void
RemoveAttrDefault(Relation rel)
1647
{
1648 1649 1650 1651
	Relation	adrel;
	HeapScanDesc adscan;
	ScanKeyData key;
	HeapTuple	tup;
1652 1653 1654 1655 1656 1657 1658 1659

	adrel = heap_openr(AttrDefaultRelationName);

	ScanKeyEntryInitialize(&key, 0, Anum_pg_attrdef_adrelid,
						   ObjectIdEqualRegProcedure, rel->rd_id);

	RelationSetLockForWrite(adrel);

1660
	adscan = heap_beginscan(adrel, 0, false, 1, &key);
1661 1662 1663 1664 1665 1666 1667 1668

	while (tup = heap_getnext(adscan, 0, (Buffer *) NULL), PointerIsValid(tup))
		heap_delete(adrel, &tup->t_ctid);

	heap_endscan(adscan);

	RelationUnsetLockForWrite(adrel);
	heap_close(adrel);
1669 1670 1671

}

1672 1673
static void
RemoveRelCheck(Relation rel)
1674
{
1675 1676 1677 1678
	Relation	rcrel;
	HeapScanDesc rcscan;
	ScanKeyData key;
	HeapTuple	tup;
1679 1680 1681 1682 1683 1684 1685 1686

	rcrel = heap_openr(RelCheckRelationName);

	ScanKeyEntryInitialize(&key, 0, Anum_pg_relcheck_rcrelid,
						   ObjectIdEqualRegProcedure, rel->rd_id);

	RelationSetLockForWrite(rcrel);

1687
	rcscan = heap_beginscan(rcrel, 0, false, 1, &key);
1688 1689 1690 1691 1692 1693 1694 1695

	while (tup = heap_getnext(rcscan, 0, (Buffer *) NULL), PointerIsValid(tup))
		heap_delete(rcrel, &tup->t_ctid);

	heap_endscan(rcscan);

	RelationUnsetLockForWrite(rcrel);
	heap_close(rcrel);
1696 1697

}
1698

1699 1700
static void
RemoveConstraints(Relation rel)
1701
{
1702
	TupleConstr *constr = rel->rd_att->constr;
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

	if (!constr)
		return;

	if (constr->num_defval > 0)
		RemoveAttrDefault(rel);

	if (constr->num_check > 0)
		RemoveRelCheck(rel);

	return;
1714
}