command.c 51.9 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * command.c
4
 *	  random postgres portal and utility support code
5
 *
6
 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.133 2001/06/12 05:55:49 tgl Exp $
12 13
 *
 * NOTES
14 15 16 17
 *	  The PerformAddAttribute() code, like most of the relation
 *	  manipulating code in the commands/ directory, should go
 *	  someplace closer to the lib/catalog code.
 *
18 19
 *-------------------------------------------------------------------------
 */
Bruce Momjian's avatar
Bruce Momjian committed
20 21
#include "postgres.h"

22
#include "access/tuptoaster.h"
Bruce Momjian's avatar
Bruce Momjian committed
23 24
#include "catalog/catalog.h"
#include "catalog/catname.h"
25
#include "catalog/index.h"
Bruce Momjian's avatar
Bruce Momjian committed
26
#include "catalog/indexing.h"
27
#include "catalog/pg_attrdef.h"
28
#include "catalog/pg_opclass.h"
Bruce Momjian's avatar
Bruce Momjian committed
29
#include "catalog/pg_rewrite.h"
Bruce Momjian's avatar
Bruce Momjian committed
30
#include "commands/command.h"
31
#include "executor/spi.h"
32
#include "catalog/heap.h"
Bruce Momjian's avatar
Bruce Momjian committed
33
#include "miscadmin.h"
Bruce Momjian's avatar
Bruce Momjian committed
34 35
#include "optimizer/prep.h"
#include "utils/acl.h"
36
#include "utils/fmgroids.h"
37
#include "commands/trigger.h"
38 39 40 41

#include "parser/parse_expr.h"
#include "parser/parse_clause.h"
#include "parser/parse_relation.h"
42
#include "parser/parse_oper.h"
43 44 45 46 47 48 49
#include "nodes/makefuncs.h"
#include "optimizer/planmain.h"
#include "optimizer/clauses.h"
#include "rewrite/rewriteSupport.h"
#include "commands/view.h"
#include "utils/temprel.h"
#include "executor/spi_priv.h"
50
#include "catalog/pg_index.h"
51
#include "catalog/pg_shadow.h"
52
#include "utils/relcache.h"
53

54
#include "parser/parse.h"
Jan Wieck's avatar
TOAST  
Jan Wieck committed
55
#include "access/genam.h"
56

57

58
static void drop_default(Oid relid, int16 attnum);
59
static bool needs_toast_table(Relation rel);
60
static bool is_relation(char *name);
61 62


63
/* --------------------------------
64
 *		PortalCleanup
65 66 67 68 69
 * --------------------------------
 */
void
PortalCleanup(Portal portal)
{
70
	MemoryContext oldcontext;
71

72 73
	/*
	 * sanity checks
74 75 76 77
	 */
	AssertArg(PortalIsValid(portal));
	AssertArg(portal->cleanup == PortalCleanup);

78 79
	/*
	 * set proper portal-executor context before calling ExecMain.
80
	 */
81
	oldcontext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
82

83 84
	/*
	 * tell the executor to shutdown the query
85 86 87
	 */
	ExecutorEnd(PortalGetQueryDesc(portal), PortalGetState(portal));

88 89
	/*
	 * switch back to previous context
90
	 */
91
	MemoryContextSwitchTo(oldcontext);
92 93 94
}

/* --------------------------------
95
 *		PerformPortalFetch
96 97 98 99
 * --------------------------------
 */
void
PerformPortalFetch(char *name,
100 101 102 103
				   bool forward,
				   int count,
				   char *tag,
				   CommandDest dest)
104
{
105 106
	Portal		portal;
	QueryDesc  *queryDesc;
107
	EState	   *estate;
108
	MemoryContext oldcontext;
109
	bool		faked_desc = false;
110

111 112
	/*
	 * sanity checks
113 114 115
	 */
	if (name == NULL)
	{
116
		elog(NOTICE, "PerformPortalFetch: missing portal name");
117 118 119
		return;
	}

120 121
	/*
	 * get the portal from the portal name
122 123 124 125 126 127 128 129 130
	 */
	portal = GetPortalByName(name);
	if (!PortalIsValid(portal))
	{
		elog(NOTICE, "PerformPortalFetch: portal \"%s\" not found",
			 name);
		return;
	}

131 132
	/*
	 * switch into the portal context
133
	 */
134
	oldcontext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
135

136 137
	/*
	 * tell the destination to prepare to receive some tuples.
138
	 *
139 140
	 * If we've been asked for a MOVE, make a temporary QueryDesc with the
	 * appropriate dummy destination.
141
	 */
142
	queryDesc = PortalGetQueryDesc(portal);
143
	estate = PortalGetState(portal);
144

145
	if (dest != queryDesc->dest)			/* MOVE */
146
	{
147 148 149
		QueryDesc  *qdesc = (QueryDesc *) palloc(sizeof(QueryDesc));

		memcpy(qdesc, queryDesc, sizeof(QueryDesc));
150 151
		qdesc->dest = dest;
		queryDesc = qdesc;
152
		faked_desc = true;
153
	}
154

155
	BeginCommand(name,
156
				 queryDesc->operation,
157
				 PortalGetTupleDesc(portal),
158 159 160 161 162 163 164
				 false,			/* portal fetches don't end up in
								 * relations */
				 false,			/* this is a portal fetch, not a "retrieve
								 * portal" */
				 tag,
				 dest);

165 166 167 168 169 170 171 172
	/*
	 * Determine which direction to go in, and check to see if we're
	 * already at the end of the available tuples in that direction.  If
	 * so, do nothing.	(This check exists because not all plan node types
	 * are robust about being called again if they've already returned
	 * NULL once.)	If it's OK to do the fetch, call the executor.  Then,
	 * update the atStart/atEnd state depending on the number of tuples
	 * that were retrieved.
173
	 */
174 175
	if (forward)
	{
176
		if (!portal->atEnd)
177 178
		{
			ExecutorRun(queryDesc, estate, EXEC_FOR, (long) count);
179 180 181 182 183 184
			/*
			 *	I use CMD_UPDATE, because no CMD_MOVE or the like
			 *	exists, and I would like to provide the same
			 *	kind of info as CMD_UPDATE
			 */
			UpdateCommandInfo(CMD_UPDATE, 0, estate->es_processed);
185
			if (estate->es_processed > 0)
186
				portal->atStart = false;		/* OK to back up now */
187
			if (count <= 0 || (int) estate->es_processed < count)
188
				portal->atEnd = true;	/* we retrieved 'em all */
189 190 191 192
		}
	}
	else
	{
193
		if (!portal->atStart)
194 195
		{
			ExecutorRun(queryDesc, estate, EXEC_BACK, (long) count);
196 197 198 199 200 201
			/*
			 *	I use CMD_UPDATE, because no CMD_MOVE or the like
			 *	exists, and I would like to provide the same
			 *	kind of info as CMD_UPDATE
			 */
			UpdateCommandInfo(CMD_UPDATE, 0, estate->es_processed);
202
			if (estate->es_processed > 0)
203
				portal->atEnd = false;	/* OK to go forward now */
204 205 206 207
			if (count <= 0 || (int) estate->es_processed < count)
				portal->atStart = true; /* we retrieved 'em all */
		}
	}
208

209 210
	/*
	 * Clean up and switch back to old context.
211
	 */
212
	if (faked_desc)			/* MOVE */
213 214
		pfree(queryDesc);

215 216
	MemoryContextSwitchTo(oldcontext);

217 218 219
	/*
	 * Note: the "end-of-command" tag is returned by higher-level utility
	 * code
220
	 */
221 222 223
}

/* --------------------------------
224
 *		PerformPortalClose
225 226 227 228 229
 * --------------------------------
 */
void
PerformPortalClose(char *name, CommandDest dest)
{
230
	Portal		portal;
231

232 233
	/*
	 * sanity checks
234 235 236
	 */
	if (name == NULL)
	{
237
		elog(NOTICE, "PerformPortalClose: missing portal name");
238 239 240
		return;
	}

241 242
	/*
	 * get the portal from the portal name
243 244 245 246 247 248 249 250 251
	 */
	portal = GetPortalByName(name);
	if (!PortalIsValid(portal))
	{
		elog(NOTICE, "PerformPortalClose: portal \"%s\" not found",
			 name);
		return;
	}

252 253
	/*
	 * Note: PortalCleanup is called as a side-effect
254
	 */
255
	PortalDrop(&portal);
256 257 258
}

/* ----------------
259
 *		AlterTableAddColumn
260
 *		(formerly known as PerformAddAttribute)
261
 *
262
 *		adds an additional attribute to a relation
263
 *
264 265 266 267 268
 *		Adds attribute field(s) to a relation.	Each new attribute
 *		is given attnums in sequential order and is added to the
 *		ATTRIBUTE relation.  If the AMI fails, defunct tuples will
 *		remain in the ATTRIBUTE relation for later vacuuming.
 *		Later, there may be some reserved attribute names???
269
 *
270
 *		(If needed, can instead use elog to handle exceptions.)
271
 *
272 273 274 275 276
 *		Note:
 *				Initial idea of ordering the tuple attributes so that all
 *		the variable length domains occured last was scratched.  Doing
 *		so would not speed access too much (in general) and would create
 *		many complications in formtuple, amgetattr, and addattribute.
277
 *
278 279 280 281 282 283 284 285 286
 *		scan attribute catalog for name conflict (within rel)
 *		scan type catalog for absence of data type (if not arg)
 *		create attnum magically???
 *		create attribute tuple
 *		insert attribute in attribute catalog
 *		modify reldesc
 *		create new relation tuple
 *		insert new relation in relation catalog
 *		delete original relation from relation catalog
287 288 289
 * ----------------
 */
void
290
AlterTableAddColumn(const char *relationName,
291
					bool inherits,
292
					ColumnDef *colDef)
293
{
294
	Relation	rel,
295
				attrdesc;
296
	Oid			myrelid;
297
	HeapTuple	reltup;
298
	HeapTuple	newreltup;
299
	HeapTuple	attributeTuple;
300
	Form_pg_attribute attribute;
301
	FormData_pg_attribute attributeD;
302 303 304 305 306 307
	int			i;
	int			minattnum,
				maxatts;
	Relation	idescs[Num_pg_attr_indices];
	Relation	ridescs[Num_pg_class_indices];
	bool		hasindex;
308 309 310 311 312 313 314

	/*
	 * permissions checking.  this would normally be done in utility.c,
	 * but this particular routine is recursive.
	 *
	 * normally, only the owner of a class can change its schema.
	 */
315
	if (!allowSystemTableMods && IsSystemRelationName(relationName))
316
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
317
			 relationName);
318
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
319
		elog(ERROR, "ALTER TABLE: permission denied");
320

321
	/*
322 323
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
324
	 */
325
	rel = heap_openr(relationName, AccessExclusiveLock);
326 327 328 329 330

	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 relationName);

331 332 333
	myrelid = RelationGetRelid(rel);
	heap_close(rel, NoLock);	/* close rel but keep lock! */

334 335 336 337
	/*
	 * we can't add a not null attribute
	 */
	if (colDef->is_not_null)
338
		elog(ERROR, "Can't add a NOT NULL attribute to an existing relation");
339

340
	if (colDef->raw_default || colDef->cooked_default)
341
		elog(ERROR, "Adding columns with defaults is not implemented.");
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356

	/*
	 * if the first element in the 'schema' list is a "*" then we are
	 * supposed to add this attribute to all classes that inherit from
	 * 'relationName' (as well as to 'relationName').
	 *
	 * any permissions or problems with duplicate attributes will cause the
	 * whole transaction to abort, which is what we want -- all or
	 * nothing.
	 */
	if (colDef != NULL)
	{
		if (inherits)
		{
357 358
			List	   *child,
					   *children;
359 360

			/* this routine is actually in the planner */
361
			children = find_all_inheritors(myrelid);
362 363 364 365 366 367 368 369

			/*
			 * find_all_inheritors does the recursive search of the
			 * inheritance hierarchy, so all we have to do is process all
			 * of the relids in the list that it returns.
			 */
			foreach(child, children)
			{
370
				Oid			childrelid = lfirsti(child);
371
				char	   *childrelname;
372

373 374
				if (childrelid == myrelid)
					continue;
375
				rel = heap_open(childrelid, AccessExclusiveLock);
376
				childrelname = pstrdup(RelationGetRelationName(rel));
377
				heap_close(rel, AccessExclusiveLock);
378 379 380 381

				AlterTableAddColumn(childrelname, false, colDef);

				pfree(childrelname);
382
			}
383
		}
384 385
	}

386
	rel = heap_openr(RelationRelationName, RowExclusiveLock);
387

388 389 390
	reltup = SearchSysCache(RELNAME,
							PointerGetDatum(relationName),
							0, 0, 0);
391 392

	if (!HeapTupleIsValid(reltup))
393
		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
394 395 396 397 398
			 relationName);

	minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
	maxatts = minattnum + 1;
	if (maxatts > MaxHeapAttributeNumber)
399
		elog(ERROR, "ALTER TABLE: relations limited to %d columns",
400 401
			 MaxHeapAttributeNumber);

402
	attrdesc = heap_openr(AttributeRelationName, RowExclusiveLock);
403

404
	/*
405
	 * Open all (if any) pg_attribute indices
406
	 */
407
	hasindex = RelationGetForm(attrdesc)->relhasindex;
408 409 410
	if (hasindex)
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);

411
	attributeD.attrelid = reltup->t_data->t_oid;
412 413

	attributeTuple = heap_addheader(Natts_pg_attribute,
414 415
									ATTRIBUTE_TUPLE_SIZE,
									(void *) &attributeD);
416

417
	attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
418 419 420 421

	i = 1 + minattnum;

	{
422
		HeapTuple	typeTuple;
423
		Form_pg_type tform;
424
		char	   *typename;
425
		int			attndims;
426

427 428 429 430
		if (SearchSysCacheExists(ATTNAME,
								 ObjectIdGetDatum(reltup->t_data->t_oid),
								 PointerGetDatum(colDef->colname),
								 0, 0))
431
			elog(ERROR, "ALTER TABLE: column name \"%s\" already exists in table \"%s\"",
432
				 colDef->colname, relationName);
433 434 435 436 437

		/*
		 * check to see if it is an array attribute.
		 */

438
		typename = colDef->typename->name;
439 440 441

		if (colDef->typename->arrayBounds)
		{
442
			attndims = length(colDef->typename->arrayBounds);
443
			typename = makeArrayTypeName(colDef->typename->name);
444 445
		}
		else
446
			attndims = 0;
447

448 449 450
		typeTuple = SearchSysCache(TYPENAME,
								   PointerGetDatum(typename),
								   0, 0, 0);
451
		if (!HeapTupleIsValid(typeTuple))
452
			elog(ERROR, "ALTER TABLE: type \"%s\" does not exist", typename);
453 454
		tform = (Form_pg_type) GETSTRUCT(typeTuple);

455
		namestrcpy(&(attribute->attname), colDef->colname);
456
		attribute->atttypid = typeTuple->t_data->t_oid;
457
		attribute->attlen = tform->typlen;
458
		attribute->attstattarget = DEFAULT_ATTSTATTARGET;
Bruce Momjian's avatar
Bruce Momjian committed
459
		attribute->attcacheoff = -1;
460
		attribute->atttypmod = colDef->typename->typmod;
461
		attribute->attnum = i;
462
		attribute->attbyval = tform->typbyval;
463
		attribute->attndims = attndims;
464
		attribute->attisset = (bool) (tform->typtype == 'c');
Jan Wieck's avatar
TOAST  
Jan Wieck committed
465
		attribute->attstorage = tform->typstorage;
466
		attribute->attalign = tform->typalign;
467
		attribute->attnotnull = false;
468 469
		attribute->atthasdef = (colDef->raw_default != NULL ||
								colDef->cooked_default != NULL);
470

471 472
		ReleaseSysCache(typeTuple);

473 474 475 476 477 478
		heap_insert(attrdesc, attributeTuple);
		if (hasindex)
			CatalogIndexInsert(idescs,
							   Num_pg_attr_indices,
							   attrdesc,
							   attributeTuple);
479
	}
480

481
	if (hasindex)
482
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
483

484
	heap_close(attrdesc, NoLock);
485

486 487 488 489 490 491
	/*
	 * Update number of attributes in pg_class tuple
	 */
	newreltup = heap_copytuple(reltup);

	((Form_pg_class) GETSTRUCT(newreltup))->relnatts = maxatts;
492
	simple_heap_update(rel, &newreltup->t_self, newreltup);
493 494 495

	/* keep catalog indices current */
	CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, ridescs);
496
	CatalogIndexInsert(ridescs, Num_pg_class_indices, rel, newreltup);
497 498
	CatalogCloseIndices(Num_pg_class_indices, ridescs);

499 500
	heap_freetuple(newreltup);
	ReleaseSysCache(reltup);
501 502

	heap_close(rel, NoLock);
503 504

	/*
505 506
	 * Automatically create the secondary relation for TOAST if it
	 * formerly had no such but now has toastable attributes.
507 508 509
	 */
	CommandCounterIncrement();
	AlterTableCreateToastTable(relationName, true);
510 511 512 513 514 515 516
}


/*
 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
 */
void
517 518 519
AlterTableAlterColumnDefault(const char *relationName,
							 bool inh, const char *colName,
							 Node *newDefault)
520
{
521 522 523 524
	Relation	rel;
	HeapTuple	tuple;
	int16		attnum;
	Oid			myrelid;
525 526 527 528 529

	if (!allowSystemTableMods && IsSystemRelationName(relationName))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 relationName);
#ifndef NO_SECURITY
530
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
531 532 533
		elog(ERROR, "ALTER TABLE: permission denied");
#endif

534
	rel = heap_openr(relationName, AccessExclusiveLock);
535 536 537
	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 relationName);
538 539
	myrelid = RelationGetRelid(rel);
	heap_close(rel, NoLock);
540

541 542 543
	/*
	 * Propagate to children if desired
	 */
544
	if (inh)
545 546 547 548 549 550 551 552 553 554 555 556 557
	{
		List	   *child,
				   *children;

		/* this routine is actually in the planner */
		children = find_all_inheritors(myrelid);

		/*
		 * find_all_inheritors does the recursive search of the
		 * inheritance hierarchy, so all we have to do is process all of
		 * the relids in the list that it returns.
		 */
		foreach(child, children)
558
		{
559 560 561 562 563
			Oid			childrelid = lfirsti(child);

			if (childrelid == myrelid)
				continue;
			rel = heap_open(childrelid, AccessExclusiveLock);
564 565
			AlterTableAlterColumnDefault(RelationGetRelationName(rel),
										 false, colName, newDefault);
566 567 568 569 570 571 572
			heap_close(rel, AccessExclusiveLock);
		}
	}

	/* -= now do the thing on this relation =- */

	/* reopen the business */
573
	rel = heap_openr(relationName, AccessExclusiveLock);
574 575 576 577

	/*
	 * get the number of the attribute
	 */
578 579 580 581
	tuple = SearchSysCache(ATTNAME,
						   ObjectIdGetDatum(myrelid),
						   PointerGetDatum(colName),
						   0, 0);
582 583 584 585 586
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 relationName, colName);

	attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
587
	ReleaseSysCache(tuple);
588

589
	if (newDefault)
590
	{
591
		/* SET DEFAULT */
592 593 594 595 596
		List	   *rawDefaults = NIL;
		RawColumnDefault *rawEnt;

		/* Get rid of the old one first */
		drop_default(myrelid, attnum);
597 598 599

		rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
		rawEnt->attnum = attnum;
600
		rawEnt->raw_default = newDefault;
601 602
		rawDefaults = lappend(rawDefaults, rawEnt);

603 604 605 606 607 608 609 610
		/*
		 * This function is intended for CREATE TABLE, so it processes a
		 * _list_ of defaults, but we just do one.
		 */
		AddRelationRawConstraints(rel, rawDefaults, NIL);
	}
	else
	{
611
		/* DROP DEFAULT */
612 613 614 615
		Relation	attr_rel;
		ScanKeyData scankeys[3];
		HeapScanDesc scan;

616
		attr_rel = heap_openr(AttributeRelationName, RowExclusiveLock);
617 618
		ScanKeyEntryInitialize(&scankeys[0], 0x0,
							   Anum_pg_attribute_attrelid, F_OIDEQ,
619
							   ObjectIdGetDatum(myrelid));
620 621
		ScanKeyEntryInitialize(&scankeys[1], 0x0,
							   Anum_pg_attribute_attnum, F_INT2EQ,
622
							   Int16GetDatum(attnum));
623 624
		ScanKeyEntryInitialize(&scankeys[2], 0x0,
							   Anum_pg_attribute_atthasdef, F_BOOLEQ,
625
							   BoolGetDatum(true));
626 627 628 629 630 631 632 633 634 635 636 637

		scan = heap_beginscan(attr_rel, false, SnapshotNow, 3, scankeys);
		AssertState(scan != NULL);

		if (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
		{
			HeapTuple	newtuple;
			Relation	irelations[Num_pg_attr_indices];

			/* update to false */
			newtuple = heap_copytuple(tuple);
			((Form_pg_attribute) GETSTRUCT(newtuple))->atthasdef = FALSE;
638
			simple_heap_update(attr_rel, &tuple->t_self, newtuple);
639 640 641 642 643 644 645 646 647 648 649 650 651

			/* keep the system catalog indices current */
			CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
			CatalogIndexInsert(irelations, Num_pg_attr_indices, attr_rel, newtuple);
			CatalogCloseIndices(Num_pg_attr_indices, irelations);

			/* get rid of actual default definition */
			drop_default(myrelid, attnum);
		}

		heap_endscan(scan);
		heap_close(attr_rel, NoLock);
	}
652 653 654 655 656 657 658 659

	heap_close(rel, NoLock);
}


static void
drop_default(Oid relid, int16 attnum)
{
660 661 662 663
	ScanKeyData scankeys[2];
	HeapScanDesc scan;
	Relation	attrdef_rel;
	HeapTuple	tuple;
664

665
	attrdef_rel = heap_openr(AttrDefaultRelationName, RowExclusiveLock);
666 667
	ScanKeyEntryInitialize(&scankeys[0], 0x0,
						   Anum_pg_attrdef_adrelid, F_OIDEQ,
668
						   ObjectIdGetDatum(relid));
669 670
	ScanKeyEntryInitialize(&scankeys[1], 0x0,
						   Anum_pg_attrdef_adnum, F_INT2EQ,
671
						   Int16GetDatum(attnum));
672

673
	scan = heap_beginscan(attrdef_rel, false, SnapshotNow, 2, scankeys);
674

675
	if (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
676
		simple_heap_delete(attrdef_rel, &tuple->t_self);
677

678
	heap_endscan(scan);
679

680
	heap_close(attrdef_rel, NoLock);
681 682 683
}


684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
/*
 * ALTER TABLE ALTER COLUMN SET STATISTICS
 */
void
AlterTableAlterColumnStatistics(const char *relationName,
								bool inh, const char *colName,
								Node *statsTarget)
{
	Relation	rel;
	Oid			myrelid;
	int			newtarget;
	Relation	attrelation;
	HeapTuple	tuple;

#ifndef NO_SECURITY
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
		elog(ERROR, "ALTER TABLE: permission denied");
#endif

	rel = heap_openr(relationName, AccessExclusiveLock);
	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 relationName);
	myrelid = RelationGetRelid(rel);
	heap_close(rel, NoLock);	/* close rel, but keep lock! */

	/*
	 * Propagate to children if desired
	 */
	if (inh)
	{
		List	   *child,
				   *children;

		/* this routine is actually in the planner */
		children = find_all_inheritors(myrelid);

		/*
		 * find_all_inheritors does the recursive search of the
		 * inheritance hierarchy, so all we have to do is process all of
		 * the relids in the list that it returns.
		 */
		foreach(child, children)
		{
			Oid			childrelid = lfirsti(child);

			if (childrelid == myrelid)
				continue;
			rel = heap_open(childrelid, AccessExclusiveLock);
			AlterTableAlterColumnStatistics(RelationGetRelationName(rel),
											false, colName, statsTarget);
			heap_close(rel, AccessExclusiveLock);
		}
	}

	/* -= now do the thing on this relation =- */

	Assert(IsA(statsTarget, Integer));
	newtarget = intVal(statsTarget);

	/* Limit target to sane range (should we raise an error instead?) */
	if (newtarget < 0)
		newtarget = 0;
	else if (newtarget > 1000)
		newtarget = 1000;

	attrelation = heap_openr(AttributeRelationName, RowExclusiveLock);

	tuple = SearchSysCacheCopy(ATTNAME,
							   ObjectIdGetDatum(myrelid),
							   PointerGetDatum(colName),
							   0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 relationName, colName);

	if (((Form_pg_attribute) GETSTRUCT(tuple))->attnum < 0)
		elog(ERROR, "ALTER TABLE: cannot change system attribute \"%s\"",
			 colName);

	((Form_pg_attribute) GETSTRUCT(tuple))->attstattarget = newtarget;

	simple_heap_update(attrelation, &tuple->t_self, tuple);

	/* keep system catalog indices current */
	{
		Relation	irelations[Num_pg_attr_indices];

		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
		CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, tuple);
		CatalogCloseIndices(Num_pg_attr_indices, irelations);
	}

	heap_freetuple(tuple);
778
	heap_close(attrelation, NoLock);
779 780 781
}


782 783 784
#ifdef	_DROP_COLUMN_HACK__
/*
 *	ALTER TABLE DROP COLUMN trial implementation
785
 *
786 787 788 789 790 791 792 793 794
 */

/*
 *	system table scan(index scan/sequential scan)
 */
typedef struct SysScanDescData
{
	Relation	heap_rel;
	Relation	irel;
795 796 797
	HeapScanDesc scan;
	IndexScanDesc iscan;
	HeapTupleData tuple;
798
	Buffer		buffer;
799 800
}			SysScanDescData, *SysScanDesc;

801 802 803
static void *
systable_beginscan(Relation rel, const char *indexRelname, int nkeys, ScanKey entry)
{
804 805
	bool		hasindex = (rel->rd_rel->relhasindex && !IsIgnoringSystemIndexes());
	SysScanDesc sysscan;
806 807 808 809 810 811 812 813 814

	sysscan = (SysScanDesc) palloc(sizeof(SysScanDescData));
	sysscan->heap_rel = rel;
	sysscan->irel = (Relation) NULL;
	sysscan->tuple.t_datamcxt = NULL;
	sysscan->tuple.t_data = NULL;
	sysscan->buffer = InvalidBuffer;
	if (hasindex)
	{
815
		sysscan->irel = index_openr((char *) indexRelname);
816 817 818 819 820 821
		sysscan->iscan = index_beginscan(sysscan->irel, false, nkeys, entry);
	}
	else
		sysscan->scan = heap_beginscan(rel, false, SnapshotNow, nkeys, entry);
	return (void *) sysscan;
}
822

823 824 825
static void
systable_endscan(void *scan)
{
826
	SysScanDesc sysscan = (SysScanDesc) scan;
827 828 829 830 831 832 833 834 835 836 837 838

	if (sysscan->irel)
	{
		if (BufferIsValid(sysscan->buffer))
			ReleaseBuffer(sysscan->buffer);
		index_endscan(sysscan->iscan);
		index_close(sysscan->irel);
	}
	else
		heap_endscan(sysscan->scan);
	pfree(scan);
}
839

840 841 842
static HeapTuple
systable_getnext(void *scan)
{
843
	SysScanDesc sysscan = (SysScanDesc) scan;
844
	HeapTuple	htup = (HeapTuple) NULL;
845
	RetrieveIndexResult indexRes;
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

	if (sysscan->irel)
	{
		if (BufferIsValid(sysscan->buffer))
		{
			ReleaseBuffer(sysscan->buffer);
			sysscan->buffer = InvalidBuffer;
		}
		while (indexRes = index_getnext(sysscan->iscan, ForwardScanDirection), indexRes != NULL)
		{
			sysscan->tuple.t_self = indexRes->heap_iptr;
			heap_fetch(sysscan->heap_rel, SnapshotNow, &sysscan->tuple, &(sysscan->buffer));
			pfree(indexRes);
			if (sysscan->tuple.t_data != NULL)
			{
				htup = &sysscan->tuple;
				break;
			}
		}
	}
	else
		htup = heap_getnext(sysscan->scan, 0);
	return htup;
}

/*
 *	find a specified attribute in a node entry
 */
static bool
875
find_attribute_walker(Node *node, int *attnump)
876 877 878 879 880
{
	if (node == NULL)
		return false;
	if (IsA(node, Var))
	{
881 882
		Var		   *var = (Var *) node;

883
		if (var->varlevelsup == 0 && var->varno == 1 &&
884
			var->varattno == *attnump)
885 886
			return true;
	}
887 888
	return expression_tree_walker(node, find_attribute_walker,
								  (void *) attnump);
889
}
890

891 892 893
static bool
find_attribute_in_node(Node *node, int attnum)
{
894
	return find_attribute_walker(node, &attnum);
895
}
896

897 898 899 900 901 902
/*
 *	Remove/check references for the column
 */
static bool
RemoveColumnReferences(Oid reloid, int attnum, bool checkonly, HeapTuple reltup)
{
903 904 905 906 907 908 909 910 911 912
	Relation	indexRelation,
				rcrel;
	ScanKeyData entry;
	HeapScanDesc scan;
	void	   *sysscan;
	HeapTuple	htup,
				indexTuple;
	Form_pg_index index;
	Form_pg_class pgcform = (Form_pg_class) NULL;
	int			i;
913 914
	bool		checkok = true;

915

916
	if (!checkonly)
917 918
		pgcform = (Form_pg_class) GETSTRUCT(reltup);

919
	/*
920
	 * Remove/check constraints here
921 922
	 */
	ScanKeyEntryInitialize(&entry, (bits16) 0x0, Anum_pg_relcheck_rcrelid,
923
					   (RegProcedure) F_OIDEQ, ObjectIdGetDatum(reloid));
924
	rcrel = heap_openr(RelCheckRelationName, RowExclusiveLock);
925
	sysscan = systable_beginscan(rcrel, RelCheckIndex, 1, &entry);
926 927 928

	while (HeapTupleIsValid(htup = systable_getnext(sysscan)))
	{
929
		Form_pg_relcheck relcheck;
930 931
		char	   *ccbin;
		Node	   *node;
932 933

		relcheck = (Form_pg_relcheck) GETSTRUCT(htup);
934
		ccbin = DatumGetCString(DirectFunctionCall1(textout,
935
									 PointerGetDatum(&relcheck->rcbin)));
936 937 938 939 940 941 942 943 944 945 946
		node = stringToNode(ccbin);
		pfree(ccbin);
		if (find_attribute_in_node(node, attnum))
		{
			if (checkonly)
			{
				checkok = false;
				elog(ERROR, "target column is used in a constraint");
			}
			else
			{
947
				simple_heap_delete(rcrel, &htup->t_self);
948 949 950 951 952 953 954 955
				pgcform->relchecks--;
			}
		}
	}
	systable_endscan(sysscan);
	heap_close(rcrel, NoLock);

	/*
956
	 * What to do with triggers/rules/views/procedues ?
957 958 959
	 */

	/*
960
	 * Remove/check indexes
961 962 963
	 */
	indexRelation = heap_openr(IndexRelationName, RowExclusiveLock);
	ScanKeyEntryInitialize(&entry, 0, Anum_pg_index_indrelid, F_OIDEQ,
964
						   ObjectIdGetDatum(reloid));
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
	scan = heap_beginscan(indexRelation, false, SnapshotNow, 1, &entry);
	while (HeapTupleIsValid(indexTuple = heap_getnext(scan, 0)))
	{
		index = (Form_pg_index) GETSTRUCT(indexTuple);
		for (i = 0; i < INDEX_MAX_KEYS; i++)
		{
			if (index->indkey[i] == InvalidAttrNumber)
				break;
			else if (index->indkey[i] == attnum)
			{
				if (checkonly)
				{
					checkok = false;
					elog(ERROR, "target column is used in an index");
				}
				else
				{
982
					htup = SearchSysCache(RELOID,
983
									 ObjectIdGetDatum(index->indexrelid),
984
										  0, 0, 0);
985
					RemoveIndex(NameStr(((Form_pg_class) GETSTRUCT(htup))->relname));
986
					ReleaseSysCache(htup);
987 988 989 990 991 992 993 994 995 996
				}
				break;
			}
		}
	}
	heap_endscan(scan);
	heap_close(indexRelation, NoLock);

	return checkok;
}
997 998

#endif	 /* _DROP_COLUMN_HACK__ */
999 1000 1001 1002 1003 1004

/*
 * ALTER TABLE DROP COLUMN
 */
void
AlterTableDropColumn(const char *relationName,
1005 1006
					 bool inh, const char *colName,
					 int behavior)
1007
{
1008
#ifdef	_DROP_COLUMN_HACK__
1009
	Relation	rel,
1010
				attrdesc;
1011 1012
	Oid			myrelid,
				attoid;
1013
	HeapTuple	reltup;
1014
	HeapTupleData classtuple;
1015 1016 1017 1018
	Buffer		buffer;
	Form_pg_attribute attribute;
	HeapTuple	tup;
	Relation	idescs[Num_pg_attr_indices];
1019
	int			attnum;
1020 1021 1022
	bool		hasindex;
	char		dropColname[32];

1023
	if (inh)
1024
		elog(ERROR, "ALTER TABLE / DROP COLUMN with inherit option is not supported yet");
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	/*
	 * permissions checking.  this would normally be done in utility.c,
	 * but this particular routine is recursive.
	 *
	 * normally, only the owner of a class can change its schema.
	 */
	if (!allowSystemTableMods && IsSystemRelationName(relationName))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 relationName);
#ifndef NO_SECURITY
1036
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
1037 1038 1039 1040
		elog(ERROR, "ALTER TABLE: permission denied");
#endif

	/*
1041 1042
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
1043 1044
	 */
	rel = heap_openr(relationName, AccessExclusiveLock);
1045 1046 1047 1048 1049

	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 relationName);

1050 1051 1052 1053
	myrelid = RelationGetRelid(rel);
	heap_close(rel, NoLock);	/* close rel but keep lock! */

	/*
1054
	 * What to do when rel has inheritors ?
1055 1056 1057 1058 1059
	 */
	if (length(find_all_inheritors(myrelid)) > 1)
		elog(ERROR, "ALTER TABLE: cannot drop a column on table that is inherited from");

	/*
1060
	 * lock the pg_class tuple for update
1061
	 */
1062 1063 1064 1065
	rel = heap_openr(RelationRelationName, RowExclusiveLock);
	reltup = SearchSysCache(RELNAME,
							PointerGetDatum(relationName),
							0, 0, 0);
1066 1067 1068 1069
	if (!HeapTupleIsValid(reltup))
		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
			 relationName);
	classtuple.t_self = reltup->t_self;
1070 1071
	ReleaseSysCache(reltup);

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
	switch (heap_mark4update(rel, &classtuple, &buffer))
	{
		case HeapTupleSelfUpdated:
		case HeapTupleMayBeUpdated:
			break;
		default:
			elog(ERROR, "couldn't lock pg_class tuple");
	}
	reltup = heap_copytuple(&classtuple);
	ReleaseBuffer(buffer);

	attrdesc = heap_openr(AttributeRelationName, RowExclusiveLock);

	/*
1086
	 * Get the target pg_attribute tuple and make a modifiable copy
1087
	 */
1088 1089 1090 1091
	tup = SearchSysCacheCopy(ATTNAME,
							 ObjectIdGetDatum(reltup->t_data->t_oid),
							 PointerGetDatum(colName),
							 0, 0);
1092 1093
	if (!HeapTupleIsValid(tup))
		elog(ERROR, "ALTER TABLE: column name \"%s\" doesn't exist in table \"%s\"",
1094
			 colName, relationName);
1095 1096 1097

	attribute = (Form_pg_attribute) GETSTRUCT(tup);
	attnum = attribute->attnum;
1098 1099 1100
	if (attnum <= 0)
		elog(ERROR, "ALTER TABLE: column name \"%s\" was already dropped",
			 colName);
1101
	attoid = tup->t_data->t_oid;
1102

1103
	/*
1104
	 * Check constraints/indices etc here
1105 1106 1107 1108 1109 1110 1111 1112
	 */
	if (behavior != CASCADE)
	{
		if (!RemoveColumnReferences(myrelid, attnum, true, NULL))
			elog(ERROR, "the column is referenced");
	}

	/*
1113
	 * change the target pg_attribute tuple
1114 1115 1116 1117 1118
	 */
	sprintf(dropColname, "*already Dropped*%d", attnum);
	namestrcpy(&(attribute->attname), dropColname);
	ATTRIBUTE_DROP_COLUMN(attribute);

1119
	simple_heap_update(attrdesc, &tup->t_self, tup);
1120 1121 1122 1123 1124
	hasindex = (!IsIgnoringSystemIndexes() && RelationGetForm(attrdesc)->relhasindex);
	if (hasindex)
	{
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_attr_indices,
1125
						   attrdesc, tup);
1126 1127 1128 1129 1130 1131 1132
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
	}
	heap_close(attrdesc, NoLock);
	heap_freetuple(tup);

	/* delete comments */
	DeleteComments(attoid);
1133

1134 1135
	/* delete attrdef */
	drop_default(myrelid, attnum);
1136

1137
	/*
1138
	 * Remove objects which reference this column
1139 1140 1141 1142 1143 1144 1145
	 */
	if (behavior == CASCADE)
	{
		Relation	ridescs[Num_pg_class_indices];

		RemoveColumnReferences(myrelid, attnum, false, reltup);
		/* update pg_class tuple */
1146
		simple_heap_update(rel, &reltup->t_self, reltup);
1147 1148 1149 1150 1151 1152 1153 1154
		CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, ridescs);
		CatalogIndexInsert(ridescs, Num_pg_class_indices, rel, reltup);
		CatalogCloseIndices(Num_pg_class_indices, ridescs);
	}

	heap_freetuple(reltup);
	heap_close(rel, NoLock);
#else
1155 1156
				elog(ERROR, "ALTER TABLE / DROP COLUMN is not implemented");
#endif	 /* _DROP_COLUMN_HACK__ */
1157
}
1158

1159 1160


1161 1162 1163
/*
 * ALTER TABLE ADD CONSTRAINT
 */
1164
void
1165
AlterTableAddConstraint(char *relationName,
1166
						bool inh, Node *newConstraint)
1167
{
1168
	if (newConstraint == NULL)
1169 1170
		elog(ERROR, "ALTER TABLE / ADD CONSTRAINT passed invalid constraint.");

1171
#ifndef NO_SECURITY
1172
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
1173 1174 1175
		elog(ERROR, "ALTER TABLE: permission denied");
#endif

1176
	/* Disallow ADD CONSTRAINT on views, indexes, sequences, etc */
1177
	if (!is_relation(relationName))
1178 1179
		elog(ERROR, "ALTER TABLE ADD CONSTRAINT: %s is not a table",
			 relationName);
1180

1181
	switch (nodeTag(newConstraint))
1182 1183
	{
		case T_Constraint:
1184
			{
1185 1186 1187
				Constraint *constr = (Constraint *) newConstraint;

				switch (constr->contype)
1188
				{
1189
					case CONSTR_CHECK:
1190
						{
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
							ParseState *pstate;
							bool		successful = true;
							HeapScanDesc scan;
							ExprContext *econtext;
							TupleTableSlot *slot;
							HeapTuple	tuple;
							RangeTblEntry *rte;
							List	   *qual;
							List	   *constlist;
							Relation	rel;
							Node	   *expr;
							char	   *name;
1203
							Oid	myrelid;
1204 1205 1206 1207 1208 1209 1210 1211 1212

							if (constr->name)
								name = constr->name;
							else
								name = "<unnamed>";

							constlist = makeList1(constr);

							rel = heap_openr(relationName, AccessExclusiveLock);
1213
							myrelid = RelationGetRelid(rel);
1214 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 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

							/* make sure it is not a view */
							if (rel->rd_rel->relkind == RELKIND_VIEW)
								elog(ERROR, "ALTER TABLE: cannot add constraint to a view");

							/*
							 * Scan all of the rows, looking for a false
							 * match
							 */
							scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL);
							AssertState(scan != NULL);

							/*
							 * We need to make a parse state and range
							 * table to allow us to transformExpr and
							 * fix_opids to get a version of the
							 * expression we can pass to ExecQual
							 */
							pstate = make_parsestate(NULL);
							rte = addRangeTableEntry(pstate, relationName, NULL,
													 false, true);
							addRTEtoQuery(pstate, rte, true, true);

							/* Convert the A_EXPR in raw_expr into an EXPR */
							expr = transformExpr(pstate, constr->raw_expr,
												 EXPR_COLUMN_FIRST);

							/*
							 * Make sure it yields a boolean result.
							 */
							if (exprType(expr) != BOOLOID)
								elog(ERROR, "CHECK '%s' does not yield boolean result",
									 name);

							/*
							 * Make sure no outside relations are referred
							 * to.
							 */
							if (length(pstate->p_rtable) != 1)
								elog(ERROR, "Only relation '%s' can be referenced in CHECK",
									 relationName);

							/*
							 * Might as well try to reduce any constant
							 * expressions.
							 */
							expr = eval_const_expressions(expr);

							/* And fix the opids */
							fix_opids(expr);

							qual = makeList1(expr);

							/* Make tuple slot to hold tuples */
							slot = MakeTupleTableSlot();
							ExecSetSlotDescriptor(slot, RelationGetDescr(rel), false);
							/* Make an expression context for ExecQual */
							econtext = MakeExprContext(slot, CurrentMemoryContext);

							/*
							 * Scan through the rows now, checking the
							 * expression at each row.
							 */
							while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
							{
								ExecStoreTuple(tuple, slot, InvalidBuffer, false);
								if (!ExecQual(qual, econtext, true))
								{
									successful = false;
									break;
								}
								ResetExprContext(econtext);
							}
1287

1288 1289
							FreeExprContext(econtext);
							pfree(slot);
1290

1291
							heap_endscan(scan);
1292

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
							if (!successful)
								elog(ERROR, "AlterTableAddConstraint: rejected due to CHECK constraint %s", name);

							/*
							 * Call AddRelationRawConstraints to do the
							 * real adding -- It duplicates some of the
							 * above, but does not check the validity of
							 * the constraint against tuples already in
							 * the table.
							 */
							AddRelationRawConstraints(rel, NIL, constlist);
							heap_close(rel, NoLock);
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

							if (inh) {
								List	   *child,
									   *children;

								/* this routine is actually in the planner */
								children = find_all_inheritors(myrelid);

								/*
								 * find_all_inheritors does the recursive search of the
								 * inheritance hierarchy, so all we have to do is process all
								 * of the relids in the list that it returns.
								 */
								foreach(child, children)
								{
									Oid			childrelid = lfirsti(child);
									char	   *childrelname;
	
									if (childrelid == myrelid)
										continue;
									rel = heap_open(childrelid, AccessExclusiveLock);
									childrelname = pstrdup(RelationGetRelationName(rel));
									heap_close(rel, AccessExclusiveLock);

									AlterTableAddConstraint(childrelname, false, newConstraint);
	
									pfree(childrelname);
								}
							}
1334 1335
							pfree(constlist);

1336 1337 1338 1339 1340
							break;
						}
					case CONSTR_PRIMARY:
						{

1341 1342 1343 1344
							break;
						}
					default:
						elog(ERROR, "ALTER TABLE / ADD CONSTRAINT is not implemented for that constraint type.");
1345
				}
1346
				break;
1347
			}
1348
		case T_FkConstraint:
1349
			{
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
				FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
				Relation	rel,
							pkrel;
				HeapScanDesc scan;
				HeapTuple	tuple;
				Trigger		trig;
				List	   *list;
				int			count;
				List	   *indexoidlist,
						   *indexoidscan;
				Form_pg_attribute *rel_attrs = NULL;
				int			i;
				bool		found = false;

1364 1365 1366 1367 1368 1369 1370
				Oid     fktypoid[INDEX_MAX_KEYS];
				Oid     pktypoid[INDEX_MAX_KEYS];
				int     attloc;
 
				for (i=0; i<INDEX_MAX_KEYS; i++) 
					fktypoid[i]=pktypoid[i]=0;

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
				if (is_temp_rel_name(fkconstraint->pktable_name) &&
					!is_temp_rel_name(relationName))
					elog(ERROR, "ALTER TABLE / ADD CONSTRAINT: Unable to reference temporary table from permanent table constraint.");

				/*
				 * Grab an exclusive lock on the pk table, so that someone
				 * doesn't delete rows out from under us.
				 */

				pkrel = heap_openr(fkconstraint->pktable_name, AccessExclusiveLock);
				if (pkrel->rd_rel->relkind != RELKIND_RELATION)
					elog(ERROR, "referenced table \"%s\" not a relation",
						 fkconstraint->pktable_name);

				/*
				 * Grab an exclusive lock on the fk table, and then scan
				 * through each tuple, calling the RI_FKey_Match_Ins
				 * (insert trigger) as if that tuple had just been
				 * inserted.  If any of those fail, it should elog(ERROR)
				 * and that's that.
				 */
				rel = heap_openr(relationName, AccessExclusiveLock);
				if (rel->rd_rel->relkind != RELKIND_RELATION)
					elog(ERROR, "referencing table \"%s\" not a relation",
						 relationName);

				/*
				 * First we check for limited correctness of the
				 * constraint
				 */

				rel_attrs = pkrel->rd_att->attrs;
				indexoidlist = RelationGetIndexList(pkrel);

				foreach(indexoidscan, indexoidlist)
1406
				{
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
					Oid			indexoid = lfirsti(indexoidscan);
					HeapTuple	indexTuple;
					Form_pg_index indexStruct;

					indexTuple = SearchSysCache(INDEXRELID,
											  ObjectIdGetDatum(indexoid),
												0, 0, 0);
					if (!HeapTupleIsValid(indexTuple))
						elog(ERROR, "transformFkeyGetPrimaryKey: index %u not found",
							 indexoid);
					indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);

					if (indexStruct->indisunique)
					{
						List	   *attrl;

						/*
						 * Make sure this index has the same number of
						 * keys -- It obviously won't match otherwise.
						 */
						for (i = 0; i < INDEX_MAX_KEYS && indexStruct->indkey[i] != 0; i++);
						if (i != length(fkconstraint->pk_attrs))
Tom Lane's avatar
Tom Lane committed
1429
							found = false;
1430 1431
						else
						{
1432
							attloc=0;
1433 1434
							/* go through the fkconstraint->pk_attrs list */
							foreach(attrl, fkconstraint->pk_attrs)
1435
							{
1436 1437 1438 1439
								Ident	   *attr = lfirst(attrl);

								found = false;
								for (i = 0; i < INDEX_MAX_KEYS && indexStruct->indkey[i] != 0; i++)
1440
								{
1441 1442 1443
									int			pkattno = indexStruct->indkey[i];

									if (pkattno > 0)
Tom Lane's avatar
Tom Lane committed
1444
									{
1445 1446 1447 1448
										char	   *name = NameStr(rel_attrs[pkattno - 1]->attname);

										if (strcmp(name, attr->name) == 0)
										{
1449 1450 1451 1452 1453
											/* We get the type of this attribute here and
											 * store it so we can use it later for making
											 * sure the types are comparable.
											 */
											pktypoid[attloc++]=rel_attrs[pkattno-1]->atttypid;
1454 1455 1456
											found = true;
											break;
										}
Tom Lane's avatar
Tom Lane committed
1457
									}
1458
								}
1459 1460
								if (!found)
									break;
1461 1462 1463
							}
						}
					}
1464 1465 1466
					ReleaseSysCache(indexTuple);
					if (found)
						break;
1467
				}
1468

1469 1470 1471
				if (!found)
					elog(ERROR, "UNIQUE constraint matching given keys for referenced table \"%s\" not found",
						 fkconstraint->pktable_name);
1472

1473 1474
				freeList(indexoidlist);
				heap_close(pkrel, NoLock);
1475

1476 1477 1478 1479 1480
				rel_attrs = rel->rd_att->attrs;
				if (fkconstraint->fk_attrs != NIL)
				{
					List	   *fkattrs;
					Ident	   *fkattr;
1481 1482

					found = false;
1483
					attloc = 0;
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
					foreach(fkattrs, fkconstraint->fk_attrs)
					{
						int			count;

						found = false;
						fkattr = lfirst(fkattrs);
						for (count = 0; count < rel->rd_att->natts; count++)
						{
							char	   *name = NameStr(rel->rd_att->attrs[count]->attname);

							if (strcmp(name, fkattr->name) == 0)
							{
1496 1497 1498 1499 1500
								/*
								 * Here once again we get the types, this
								 * time for the fk table's attributes
								 */
								fktypoid[attloc++]=rel->rd_att->attrs[count]->atttypid;
1501 1502 1503
								found = true;
								break;
							}
1504
						}
1505 1506
						if (!found)
							break;
1507 1508
					}
					if (!found)
1509
						elog(ERROR, "columns referenced in foreign key constraint not found.");
1510 1511
				}

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
				for (i=0; i < INDEX_MAX_KEYS && fktypoid[i] !=0; i++) {
					/*
					 * fktypoid[i] is the foreign key table's i'th element's type oid
					 * pktypoid[i] is the primary key table's i'th element's type oid
					 * We let oper() do our work for us, including elog(ERROR) if the
					 * types can't compare with =
					 */
					Operator o=oper("=", fktypoid[i], pktypoid[i], false);
					ReleaseSysCache(o);
				}

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
				trig.tgoid = 0;
				if (fkconstraint->constr_name)
					trig.tgname = fkconstraint->constr_name;
				else
					trig.tgname = "<unknown>";
				trig.tgfoid = 0;
				trig.tgtype = 0;
				trig.tgenabled = TRUE;
				trig.tgisconstraint = TRUE;
				trig.tginitdeferred = FALSE;
				trig.tgdeferrable = FALSE;

				trig.tgargs = (char **) palloc(
					 sizeof(char *) * (4 + length(fkconstraint->fk_attrs)
									   + length(fkconstraint->pk_attrs)));

				if (fkconstraint->constr_name)
					trig.tgargs[0] = fkconstraint->constr_name;
				else
					trig.tgargs[0] = "<unknown>";
				trig.tgargs[1] = (char *) relationName;
				trig.tgargs[2] = fkconstraint->pktable_name;
				trig.tgargs[3] = fkconstraint->match_type;
				count = 4;
				foreach(list, fkconstraint->fk_attrs)
1548
				{
1549 1550
					Ident	   *fk_at = lfirst(list);

1551
					trig.tgargs[count] = fk_at->name;
1552
					count += 2;
1553
				}
1554 1555
				count = 5;
				foreach(list, fkconstraint->pk_attrs)
1556
				{
1557 1558
					Ident	   *pk_at = lfirst(list);

1559
					trig.tgargs[count] = pk_at->name;
1560
					count += 2;
1561
				}
1562
				trig.tgnargs = count - 1;
1563

1564 1565
				scan = heap_beginscan(rel, false, SnapshotNow, 0, NULL);
				AssertState(scan != NULL);
1566

1567 1568 1569 1570 1571 1572
				while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
				{
					/* Make a call to the check function */
					/* No parameters are passed, but we do set a context */
					FunctionCallInfoData fcinfo;
					TriggerData trigdata;
1573

1574 1575
					MemSet(&fcinfo, 0, sizeof(fcinfo));
					/* We assume RI_FKey_check_ins won't look at flinfo... */
1576

1577 1578 1579 1580 1581 1582
					trigdata.type = T_TriggerData;
					trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
					trigdata.tg_relation = rel;
					trigdata.tg_trigtuple = tuple;
					trigdata.tg_newtuple = NULL;
					trigdata.tg_trigger = &trig;
1583

1584
					fcinfo.context = (Node *) &trigdata;
1585

1586 1587 1588 1589 1590
					RI_FKey_check_ins(&fcinfo);
				}
				heap_endscan(scan);
				heap_close(rel, NoLock);		/* close rel but keep
												 * lock! */
1591

1592 1593 1594
				pfree(trig.tgargs);
				break;
			}
1595 1596 1597
		default:
			elog(ERROR, "ALTER TABLE / ADD CONSTRAINT unable to determine type of constraint passed");
	}
1598 1599 1600 1601
}



1602 1603
/*
 * ALTER TABLE DROP CONSTRAINT
1604 1605 1606
 * Note: It is legal to remove a constraint with name "" as it is possible
 * to add a constraint with name "".
 * Christopher Kings-Lynne
1607 1608 1609
 */
void
AlterTableDropConstraint(const char *relationName,
1610 1611
						 bool inh, const char *constrName,
						 int behavior)
1612
{
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 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
	Relation		rel;
	int			deleted;

#ifndef NO_SECURITY
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
		elog(ERROR, "ALTER TABLE: permission denied");
#endif

	/* We don't support CASCADE yet  - in fact, RESTRICT
	 * doesn't work to the spec either! */
	if (behavior == CASCADE)
		elog(ERROR, "ALTER TABLE / DROP CONSTRAINT does not support the CASCADE keyword");

	/*
	 * Acquire an exclusive lock on the target relation for
	 * the duration of the operation.
	 */

	rel = heap_openr(relationName, AccessExclusiveLock);

	/* Disallow DROP CONSTRAINT on views, indexes, sequences, etc */
	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE / DROP CONSTRAINT: %s is not a table",
			 relationName);

	/*
	 * Since all we have is the name of the constraint, we have to look through
	 * all catalogs that could possibly contain a constraint for this relation.
	 * We also keep a count of the number of constraints removed.
	 */

	deleted = 0;

	/*
	 * First, we remove all CHECK constraints with the given name
	 */

	deleted += RemoveCheckConstraint(rel, constrName, inh);

	/*
	 * Now we remove NULL, UNIQUE, PRIMARY KEY and FOREIGN KEY constraints.
	 *
	 * Unimplemented.
	 */

	/* Close the target relation */
	heap_close(rel, NoLock);

	/* If zero constraints deleted, complain */
	if (deleted == 0)
		elog(ERROR, "ALTER TABLE / DROP CONSTRAINT: %s does not exist",
			 constrName);
	/* Otherwise if more than one constraint deleted, notify */
	else if (deleted > 1)
		elog(NOTICE, "Multiple constraints dropped");

1669 1670 1671
}


1672 1673 1674 1675 1676 1677
/*
 * ALTER TABLE OWNER
 */
void
AlterTableOwner(const char *relationName, const char *newOwnerName)
{
1678 1679
	Relation	class_rel;
	HeapTuple	tuple;
1680
	int32		newOwnerSysid;
1681 1682 1683 1684 1685
	Relation	idescs[Num_pg_class_indices];

	/*
	 * first check that we are a superuser
	 */
1686
	if (!superuser())
1687 1688 1689 1690 1691
		elog(ERROR, "ALTER TABLE: permission denied");

	/*
	 * look up the new owner in pg_shadow and get the sysid
	 */
1692 1693 1694
	tuple = SearchSysCache(SHADOWNAME,
						   PointerGetDatum(newOwnerName),
						   0, 0, 0);
1695 1696 1697
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: user \"%s\" not found", newOwnerName);
	newOwnerSysid = ((Form_pg_shadow) GETSTRUCT(tuple))->usesysid;
1698
	ReleaseSysCache(tuple);
1699 1700

	/*
1701
	 * find the table's entry in pg_class and make a modifiable copy
1702 1703 1704
	 */
	class_rel = heap_openr(RelationRelationName, RowExclusiveLock);

1705 1706 1707
	tuple = SearchSysCacheCopy(RELNAME,
							   PointerGetDatum(relationName),
							   0, 0, 0);
1708 1709 1710 1711
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
			 relationName);

1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
	switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
	{
		case RELKIND_RELATION:
		case RELKIND_INDEX:
		case RELKIND_VIEW:
		case RELKIND_SEQUENCE:
			/* ok to change owner */
			break;
		default:
			elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table, index, view, or sequence",
				 relationName);
	}
1724 1725 1726 1727 1728 1729

	/*
	 * modify the table's entry and write to the heap
	 */
	((Form_pg_class) GETSTRUCT(tuple))->relowner = newOwnerSysid;

1730
	simple_heap_update(class_rel, &tuple->t_self, tuple);
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740

	/* Keep the catalog indices up to date */
	CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, idescs);
	CatalogIndexInsert(idescs, Num_pg_class_indices, class_rel, tuple);
	CatalogCloseIndices(Num_pg_class_indices, idescs);

	/*
	 * unlock everything and return
	 */
	heap_freetuple(tuple);
1741
	heap_close(class_rel, NoLock);
1742 1743
}

1744

Jan Wieck's avatar
TOAST  
Jan Wieck committed
1745 1746 1747 1748
/*
 * ALTER TABLE CREATE TOAST TABLE
 */
void
1749
AlterTableCreateToastTable(const char *relationName, bool silent)
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1750
{
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
	Relation	rel;
	Oid			myrelid;
	HeapTuple	reltup;
	HeapTupleData classtuple;
	TupleDesc	tupdesc;
	Relation	class_rel;
	Buffer		buffer;
	Relation	ridescs[Num_pg_class_indices];
	Oid			toast_relid;
	Oid			toast_idxid;
	char		toast_relname[NAMEDATALEN + 1];
	char		toast_idxname[NAMEDATALEN + 1];
	Relation	toast_idxrel;
	IndexInfo  *indexInfo;
	Oid			classObjectId[1];
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1766 1767

	/*
1768
	 * permissions checking.  XXX exactly what is appropriate here?
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1769 1770
	 */
#ifndef NO_SECURITY
1771
	if (!pg_ownercheck(GetUserId(), relationName, RELNAME))
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1772 1773 1774
		elog(ERROR, "ALTER TABLE: permission denied");
#endif

1775
	/*
1776 1777 1778 1779
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
	 */
	rel = heap_openr(relationName, AccessExclusiveLock);
1780 1781 1782 1783 1784

	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 relationName);

1785 1786 1787 1788
	myrelid = RelationGetRelid(rel);

	/*
	 * lock the pg_class tuple for update (is that really needed?)
1789
	 */
1790 1791
	class_rel = heap_openr(RelationRelationName, RowExclusiveLock);

1792 1793 1794
	reltup = SearchSysCache(RELNAME,
							PointerGetDatum(relationName),
							0, 0, 0);
1795 1796 1797 1798
	if (!HeapTupleIsValid(reltup))
		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
			 relationName);
	classtuple.t_self = reltup->t_self;
1799 1800
	ReleaseSysCache(reltup);

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
	switch (heap_mark4update(class_rel, &classtuple, &buffer))
	{
		case HeapTupleSelfUpdated:
		case HeapTupleMayBeUpdated:
			break;
		default:
			elog(ERROR, "couldn't lock pg_class tuple");
	}
	reltup = heap_copytuple(&classtuple);
	ReleaseBuffer(buffer);

Jan Wieck's avatar
TOAST  
Jan Wieck committed
1812
	/*
1813
	 * Is it already toasted?
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1814
	 */
1815
	if (((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid != InvalidOid)
1816
	{
Bruce Momjian's avatar
Bruce Momjian committed
1817
		if (silent)
1818 1819 1820
		{
			heap_close(rel, NoLock);
			heap_close(class_rel, NoLock);
1821
			heap_freetuple(reltup);
1822 1823 1824
			return;
		}

1825 1826
		elog(ERROR, "ALTER TABLE: relation \"%s\" already has a toast table",
			 relationName);
Bruce Momjian's avatar
Bruce Momjian committed
1827
	}
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1828 1829

	/*
1830
	 * Check to see whether the table actually needs a TOAST table.
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1831
	 */
1832
	if (!needs_toast_table(rel))
1833
	{
Bruce Momjian's avatar
Bruce Momjian committed
1834
		if (silent)
1835 1836 1837 1838 1839 1840 1841
		{
			heap_close(rel, NoLock);
			heap_close(class_rel, NoLock);
			heap_freetuple(reltup);
			return;
		}

1842 1843 1844
		elog(ERROR, "ALTER TABLE: relation \"%s\" does not need a toast table",
			 relationName);
	}
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1845 1846

	/*
1847
	 * Create the toast table and its index
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1848
	 */
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
	sprintf(toast_relname, "pg_toast_%u", myrelid);
	sprintf(toast_idxname, "pg_toast_%u_idx", myrelid);

	/* this is pretty painful...  need a tuple descriptor */
	tupdesc = CreateTemplateTupleDesc(3);
	TupleDescInitEntry(tupdesc, (AttrNumber) 1,
					   "chunk_id",
					   OIDOID,
					   -1, 0, false);
	TupleDescInitEntry(tupdesc, (AttrNumber) 2,
					   "chunk_seq",
					   INT4OID,
					   -1, 0, false);
	TupleDescInitEntry(tupdesc, (AttrNumber) 3,
					   "chunk_data",
1864
					   BYTEAOID,
1865
					   -1, 0, false);
1866

1867
	/*
1868 1869 1870
	 * Ensure that the toast table doesn't itself get toasted, or we'll be
	 * toast :-(.  This is essential for chunk_data because type bytea is
	 * toastable; hit the other two just to be sure.
1871 1872 1873 1874
	 */
	tupdesc->attrs[0]->attstorage = 'p';
	tupdesc->attrs[1]->attstorage = 'p';
	tupdesc->attrs[2]->attstorage = 'p';
1875

1876 1877 1878 1879 1880 1881
	/*
	 * Note: the toast relation is considered a "normal" relation even if
	 * its master relation is a temp table.  There cannot be any naming
	 * collision, and the toast rel will be destroyed when its master is,
	 * so there's no need to handle the toast rel as temp.
	 */
1882 1883 1884
	toast_relid = heap_create_with_catalog(toast_relname, tupdesc,
										   RELKIND_TOASTVALUE,
										   false, true);
1885 1886 1887 1888 1889

	/* make the toast relation visible, else index creation will fail */
	CommandCounterIncrement();

	/* create index on chunk_id */
1890 1891 1892 1893 1894 1895 1896 1897 1898

	indexInfo = makeNode(IndexInfo);
	indexInfo->ii_NumIndexAttrs = 1;
	indexInfo->ii_NumKeyAttrs = 1;
	indexInfo->ii_KeyAttrNumbers[0] = 1;
	indexInfo->ii_Predicate = NULL;
	indexInfo->ii_FuncOid = InvalidOid;
	indexInfo->ii_Unique = false;

1899
	classObjectId[0] = OID_OPS_OID;
1900 1901 1902 1903

	index_create(toast_relname, toast_idxname, indexInfo,
				 BTREE_AM_OID, classObjectId,
				 false, false, true);
1904

1905 1906 1907
	/*
	 * Update toast rel's pg_class entry to show that it has an index.
	 */
1908 1909 1910 1911 1912 1913
	setRelhasindex(toast_relid, true);

	/*
	 * Make index visible
	 */
	CommandCounterIncrement();
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1914 1915

	/*
1916
	 * Get the OID of the newly created index
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1917
	 */
1918 1919 1920
	toast_idxrel = index_openr(toast_idxname);
	toast_idxid = RelationGetRelid(toast_idxrel);
	index_close(toast_idxrel);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1921 1922 1923 1924 1925 1926

	/*
	 * Store the toast table- and index-Oid's in the relation tuple
	 */
	((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
	((Form_pg_class) GETSTRUCT(reltup))->reltoastidxid = toast_idxid;
1927
	simple_heap_update(class_rel, &reltup->t_self, reltup);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1928

1929 1930 1931
	/*
	 * Keep catalog indices current
	 */
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1932
	CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, ridescs);
1933
	CatalogIndexInsert(ridescs, Num_pg_class_indices, class_rel, reltup);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1934 1935 1936 1937
	CatalogCloseIndices(Num_pg_class_indices, ridescs);

	heap_freetuple(reltup);

1938
	/*
1939
	 * Close relations and make changes visible
1940
	 */
1941
	heap_close(class_rel, NoLock);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1942
	heap_close(rel, NoLock);
1943 1944

	CommandCounterIncrement();
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1945 1946
}

1947
/*
1948
 * Check to see whether the table needs a TOAST table.	It does only if
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
 * (1) there are any toastable attributes, and (2) the maximum length
 * of a tuple could exceed TOAST_TUPLE_THRESHOLD.  (We don't want to
 * create a toast table for something like "f1 varchar(20)".)
 */
static bool
needs_toast_table(Relation rel)
{
	int32		data_length = 0;
	bool		maxlength_unknown = false;
	bool		has_toastable_attrs = false;
	TupleDesc	tupdesc;
1960
	Form_pg_attribute *att;
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
	int32		tuple_length;
	int			i;

	tupdesc = rel->rd_att;
	att = tupdesc->attrs;

	for (i = 0; i < tupdesc->natts; i++)
	{
		data_length = att_align(data_length, att[i]->attlen, att[i]->attalign);
		if (att[i]->attlen >= 0)
		{
			/* Fixed-length types are never toastable */
			data_length += att[i]->attlen;
		}
		else
		{
1977 1978
			int32		maxlen = type_maximum_size(att[i]->atttypid,
												   att[i]->atttypmod);
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996

			if (maxlen < 0)
				maxlength_unknown = true;
			else
				data_length += maxlen;
			if (att[i]->attstorage != 'p')
				has_toastable_attrs = true;
		}
	}
	if (!has_toastable_attrs)
		return false;			/* nothing to toast? */
	if (maxlength_unknown)
		return true;			/* any unlimited-length attrs? */
	tuple_length = MAXALIGN(offsetof(HeapTupleHeaderData, t_bits) +
							BITMAPLEN(tupdesc->natts)) +
		MAXALIGN(data_length);
	return (tuple_length > TOAST_TUPLE_THRESHOLD);
}
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1997 1998


1999 2000 2001 2002 2003
/*
 *
 * LOCK TABLE
 *
 */
2004
void
2005
LockTableCommand(LockStmt *lockstmt)
2006 2007 2008 2009
{
	Relation	rel;
	int			aclresult;

2010
	rel = heap_openr(lockstmt->relname, NoLock);
2011

2012
	if (rel->rd_rel->relkind != RELKIND_RELATION)
2013
		elog(ERROR, "LOCK TABLE: %s is not a table", lockstmt->relname);
2014

2015
	if (lockstmt->mode == AccessShareLock)
2016
		aclresult = pg_aclcheck(lockstmt->relname, GetUserId(), ACL_SELECT);
2017
	else
2018 2019
		aclresult = pg_aclcheck(lockstmt->relname, GetUserId(),
								ACL_UPDATE | ACL_DELETE);
2020 2021 2022 2023 2024 2025

	if (aclresult != ACLCHECK_OK)
		elog(ERROR, "LOCK TABLE: permission denied");

	LockRelation(rel, lockstmt->mode);

2026
	heap_close(rel, NoLock);	/* close rel, keep lock */
2027
}
2028

2029

2030
static bool
2031
is_relation(char *name)
2032
{
2033
	Relation	rel = heap_openr(name, NoLock);
Bruce Momjian's avatar
Bruce Momjian committed
2034

2035
	bool		retval = (rel->rd_rel->relkind == RELKIND_RELATION);
Bruce Momjian's avatar
Bruce Momjian committed
2036 2037 2038 2039 2040

	heap_close(rel, NoLock);

	return retval;
}