tablecmds.c 95.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * tablecmds.c
4
 *	  Commands for creating and altering table structures and settings
5
 *
6
 * Portions Copyright (c) 1996-2002, 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/tablecmds.c,v 1.20 2002/07/12 18:43:16 tgl Exp $
12
 *
13 14
 *-------------------------------------------------------------------------
 */
Bruce Momjian's avatar
Bruce Momjian committed
15 16
#include "postgres.h"

17
#include "access/genam.h"
18
#include "access/tuptoaster.h"
Bruce Momjian's avatar
Bruce Momjian committed
19 20
#include "catalog/catalog.h"
#include "catalog/catname.h"
21
#include "catalog/dependency.h"
22
#include "catalog/heap.h"
23
#include "catalog/index.h"
Bruce Momjian's avatar
Bruce Momjian committed
24
#include "catalog/indexing.h"
25
#include "catalog/namespace.h"
26
#include "catalog/pg_attrdef.h"
27
#include "catalog/pg_constraint.h"
28
#include "catalog/pg_inherits.h"
29
#include "catalog/pg_namespace.h"
30
#include "catalog/pg_opclass.h"
31
#include "catalog/pg_trigger.h"
32
#include "catalog/pg_type.h"
33
#include "commands/tablecmds.h"
34 35
#include "commands/trigger.h"
#include "executor/executor.h"
Bruce Momjian's avatar
Bruce Momjian committed
36
#include "miscadmin.h"
37
#include "nodes/makefuncs.h"
38 39
#include "optimizer/clauses.h"
#include "optimizer/planmain.h"
Bruce Momjian's avatar
Bruce Momjian committed
40
#include "optimizer/prep.h"
41
#include "parser/gramparse.h"
42
#include "parser/parse_coerce.h"
43
#include "parser/parse_expr.h"
44
#include "parser/parse_relation.h"
45
#include "parser/parse_type.h"
46 47 48 49 50
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
51
#include "utils/relcache.h"
52

53

54 55 56 57 58 59
static List *MergeAttributes(List *schema, List *supers, bool istemp,
				List **supOids, List **supconstr, bool *supHasOids);
static bool change_varattnos_of_a_node(Node *node, const AttrNumber *newattno);
static void StoreCatalogInheritance(Oid relationId, List *supers);
static int	findAttrByName(const char *attributeName, List *schema);
static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
60 61 62
static void drop_default(Oid relid, int16 attnum);
static void CheckTupleType(Form_pg_class tuple_class);
static bool needs_toast_table(Relation rel);
63 64 65 66 67 68 69
static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
										 Relation rel, Relation pkrel);
static Oid	createForeignKeyConstraint(Relation rel, Relation pkrel,
									   FkConstraint *fkconstraint);
static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
									 Oid constrOid);
static char *fkMatchTypeToString(char match_type);
70

71
/* Used by attribute and relation renaming routines: */
72

73 74 75
#define RI_TRIGGER_PK	1		/* is a trigger on the PK relation */
#define RI_TRIGGER_FK	2		/* is a trigger on the FK relation */
#define RI_TRIGGER_NONE 0		/* is not an RI trigger function */
76

77 78 79 80 81 82
static int	ri_trigger_type(Oid tgfoid);
static void update_ri_trigger_args(Oid relid,
					   const char *oldname,
					   const char *newname,
					   bool fk_scan,
					   bool update_relname);
83

84

85 86 87
/* ----------------------------------------------------------------
 *		DefineRelation
 *				Creates a new relation.
88
 *
89 90
 * If successful, returns the OID of the new relation.
 * ----------------------------------------------------------------
91
 */
92 93
Oid
DefineRelation(CreateStmt *stmt, char relkind)
94
{
95 96 97 98 99 100 101 102 103 104 105 106
	char		relname[NAMEDATALEN];
	Oid			namespaceId;
	List	   *schema = stmt->tableElts;
	int			numberOfAttributes;
	Oid			relationId;
	Relation	rel;
	TupleDesc	descriptor;
	List	   *inheritOids;
	List	   *old_constraints;
	bool		parentHasOids;
	List	   *rawDefaults;
	List	   *listptr;
107
	int			i;
108
	AttrNumber	attnum;
109

110
	/*
111 112
	 * Truncate relname to appropriate length (probably a waste of time,
	 * as parser should have done this already).
113
	 */
114
	StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
115

116 117
	/*
	 * Look up the namespace in which we are supposed to create the
118 119 120
	 * relation.  Check we have permission to create there.
	 * Skip check if bootstrapping, since permissions machinery may not
	 * be working yet; also, always allow if it's a temp table.
121 122
	 */
	namespaceId = RangeVarGetCreationNamespace(stmt->relation);
123

124 125 126 127 128 129 130 131 132 133
	if (!IsBootstrapProcessingMode() && !isTempNamespace(namespaceId))
	{
		AclResult	aclresult;

		aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
										  ACL_CREATE);
		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, get_namespace_name(namespaceId));
	}

134
	/*
135 136
	 * Look up inheritance ancestors and generate relation schema,
	 * including inherited attributes.
137
	 */
138 139 140
	schema = MergeAttributes(schema, stmt->inhRelations,
							 stmt->relation->istemp,
							 &inheritOids, &old_constraints, &parentHasOids);
141

142 143 144
	numberOfAttributes = length(schema);
	if (numberOfAttributes <= 0)
		elog(ERROR, "DefineRelation: please inherit from a relation or define an attribute");
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159
	/*
	 * Create a relation descriptor from the relation schema and create
	 * the relation.  Note that in this stage only inherited (pre-cooked)
	 * defaults and constraints will be included into the new relation.
	 * (BuildDescForRelation takes care of the inherited defaults, but we
	 * have to copy inherited constraints here.)
	 */
	descriptor = BuildDescForRelation(schema);

	if (old_constraints != NIL)
	{
		ConstrCheck *check = (ConstrCheck *) palloc(length(old_constraints) *
													sizeof(ConstrCheck));
		int			ncheck = 0;
160
		int			constr_name_ctr = 0;
161 162

		foreach(listptr, old_constraints)
163
		{
164
			Constraint *cdef = (Constraint *) lfirst(listptr);
165

166
			if (cdef->contype != CONSTR_CHECK)
167
				continue;
168

169 170 171 172 173 174 175 176 177 178 179 180
			if (cdef->name != NULL)
			{
				for (i = 0; i < ncheck; i++)
				{
					if (strcmp(check[i].ccname, cdef->name) == 0)
						elog(ERROR, "Duplicate CHECK constraint name: '%s'",
							 cdef->name);
				}
				check[ncheck].ccname = cdef->name;
			}
			else
			{
181 182 183 184 185 186 187
				/*
				 * Generate a constraint name.  NB: this should match the
				 * form of names that GenerateConstraintName() may produce
				 * for names added later.  We are assured that there is
				 * no name conflict, because MergeAttributes() did not pass
				 * back any names of this form.
				 */
188
				check[ncheck].ccname = (char *) palloc(NAMEDATALEN);
189 190
				snprintf(check[ncheck].ccname, NAMEDATALEN, "$%d",
						 ++constr_name_ctr);
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
			}
			Assert(cdef->raw_expr == NULL && cdef->cooked_expr != NULL);
			check[ncheck].ccbin = pstrdup(cdef->cooked_expr);
			ncheck++;
		}
		if (ncheck > 0)
		{
			if (descriptor->constr == NULL)
			{
				descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
				descriptor->constr->defval = NULL;
				descriptor->constr->num_defval = 0;
				descriptor->constr->has_not_null = false;
			}
			descriptor->constr->num_check = ncheck;
			descriptor->constr->check = check;
207
		}
208 209
	}

210 211 212 213
	relationId = heap_create_with_catalog(relname,
										  namespaceId,
										  descriptor,
										  relkind,
214
										  false,
215 216 217 218 219
										  stmt->hasoids || parentHasOids,
										  allowSystemTableMods);

	StoreCatalogInheritance(relationId, inheritOids);

220
	/*
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	 * We must bump the command counter to make the newly-created relation
	 * tuple visible for opening.
	 */
	CommandCounterIncrement();

	/*
	 * Open the new relation and acquire exclusive lock on it.	This isn't
	 * really necessary for locking out other backends (since they can't
	 * see the new rel anyway until we commit), but it keeps the lock
	 * manager from complaining about deadlock risks.
	 */
	rel = heap_open(relationId, AccessExclusiveLock);

	/*
	 * Now add any newly specified column default values and CHECK
	 * constraints to the new relation.  These are passed to us in the
	 * form of raw parsetrees; we need to transform them to executable
	 * expression trees before they can be added. The most convenient way
	 * to do that is to apply the parser's transformExpr routine, but
	 * transformExpr doesn't work unless we have a pre-existing relation.
	 * So, the transformation has to be postponed to this final step of
	 * CREATE TABLE.
243
	 *
244
	 * First, scan schema to find new column defaults.
245
	 */
246 247
	rawDefaults = NIL;
	attnum = 0;
248

249 250 251 252
	foreach(listptr, schema)
	{
		ColumnDef  *colDef = lfirst(listptr);
		RawColumnDefault *rawEnt;
253

254
		attnum++;
255

256 257 258
		if (colDef->raw_default == NULL)
			continue;
		Assert(colDef->cooked_default == NULL);
259

260 261 262 263 264
		rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
		rawEnt->attnum = attnum;
		rawEnt->raw_default = colDef->raw_default;
		rawDefaults = lappend(rawDefaults, rawEnt);
	}
265

266
	/*
267
	 * Parse and add the defaults/constraints, if any.
268
	 */
269 270
	if (rawDefaults || stmt->constraints)
		AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
271

272
	/*
273 274
	 * Clean up.  We keep lock on new relation (although it shouldn't be
	 * visible to anyone else anyway, until commit).
275
	 */
276
	heap_close(rel, NoLock);
277

278 279
	return relationId;
}
280

281 282 283 284 285
/*
 * RemoveRelation
 *		Deletes a relation.
 */
void
286
RemoveRelation(const RangeVar *relation, DropBehavior behavior)
287 288
{
	Oid			relOid;
289
	ObjectAddress object;
290 291

	relOid = RangeVarGetRelid(relation, false);
292 293 294 295 296 297

	object.classId = RelOid_pg_class;
	object.objectId = relOid;
	object.objectSubId = 0;

	performDeletion(&object, behavior);
298 299
}

300
/*
301 302 303 304 305 306 307 308
 * TruncateRelation
 *				  Removes all the rows from a relation
 *
 * Exceptions:
 *				  BadArg if name is invalid
 *
 * Note:
 *				  Rows are removed, indices are truncated and reconstructed.
309 310
 */
void
311
TruncateRelation(const RangeVar *relation)
312 313
{
	Relation	rel;
314
	Oid			relid;
315

316 317 318
	/* Grab exclusive lock in preparation for truncate */
	rel = heap_openrv(relation, AccessExclusiveLock);
	relid = RelationGetRelid(rel);
319

320 321
	if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
		elog(ERROR, "TRUNCATE cannot be used on sequences. '%s' is a sequence",
322 323
			 RelationGetRelationName(rel));

324 325
	if (rel->rd_rel->relkind == RELKIND_VIEW)
		elog(ERROR, "TRUNCATE cannot be used on views. '%s' is a view",
326 327
			 RelationGetRelationName(rel));

328 329
	if (!allowSystemTableMods && IsSystemRelation(rel))
		elog(ERROR, "TRUNCATE cannot be used on system tables. '%s' is a system table",
330 331
			 RelationGetRelationName(rel));

332
	if (!pg_class_ownercheck(relid, GetUserId()))
333
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
334

335 336
	/* Keep the lock until transaction commit */
	heap_close(rel, NoLock);
337

338 339
	heap_truncate(relid);
}
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
/*----------
 * MergeAttributes
 *		Returns new schema given initial schema and superclasses.
 *
 * Input arguments:
 * 'schema' is the column/attribute definition for the table. (It's a list
 *		of ColumnDef's.) It is destructively changed.
 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
 * 'istemp' is TRUE if we are creating a temp relation.
 *
 * Output arguments:
 * 'supOids' receives an integer list of the OIDs of the parent relations.
 * 'supconstr' receives a list of constraints belonging to the parents,
 *		updated as necessary to be valid for the child.
 * 'supHasOids' is set TRUE if any parent has OIDs, else it is set FALSE.
 *
 * Return value:
 * Completed schema list.
 *
 * Notes:
 *	  The order in which the attributes are inherited is very important.
 *	  Intuitively, the inherited attributes should come first. If a table
 *	  inherits from multiple parents, the order of those attributes are
 *	  according to the order of the parents specified in CREATE TABLE.
 *
 *	  Here's an example:
 *
 *		create table person (name text, age int4, location point);
 *		create table emp (salary int4, manager text) inherits(person);
 *		create table student (gpa float8) inherits (person);
 *		create table stud_emp (percent int4) inherits (emp, student);
 *
 *	  The order of the attributes of stud_emp is:
 *
 *							person {1:name, 2:age, 3:location}
 *							/	 \
 *			   {6:gpa}	student   emp {4:salary, 5:manager}
 *							\	 /
 *						   stud_emp {7:percent}
 *
 *	   If the same attribute name appears multiple times, then it appears
 *	   in the result table in the proper location for its first appearance.
 *
 *	   Constraints (including NOT NULL constraints) for the child table
 *	   are the union of all relevant constraints, from both the child schema
 *	   and parent tables.
 *
 *	   The default value for a child column is defined as:
 *		(1) If the child schema specifies a default, that value is used.
 *		(2) If neither the child nor any parent specifies a default, then
 *			the column will not have a default.
 *		(3) If conflicting defaults are inherited from different parents
 *			(and not overridden by the child), an error is raised.
 *		(4) Otherwise the inherited default is used.
 *		Rule (3) is new in Postgres 7.1; in earlier releases you got a
 *		rather arbitrary choice of which parent default to use.
 *----------
398
 */
399 400 401
static List *
MergeAttributes(List *schema, List *supers, bool istemp,
				List **supOids, List **supconstr, bool *supHasOids)
402
{
403 404 405 406 407 408 409 410 411
	List	   *entry;
	List	   *inhSchema = NIL;
	List	   *parentOids = NIL;
	List	   *constraints = NIL;
	bool		parentHasOids = false;
	bool		have_bogus_defaults = false;
	char	   *bogus_marker = "Bogus!";		/* marks conflicting
												 * defaults */
	int			child_attno;
412 413

	/*
414 415 416 417 418
	 * Check for duplicate names in the explicit list of attributes.
	 *
	 * Although we might consider merging such entries in the same way that
	 * we handle name conflicts for inherited attributes, it seems to make
	 * more sense to assume such conflicts are errors.
419
	 */
420
	foreach(entry, schema)
421
	{
422 423
		ColumnDef  *coldef = lfirst(entry);
		List	   *rest;
424

425
		foreach(rest, lnext(entry))
426
		{
427
			ColumnDef  *restdef = lfirst(rest);
428

429 430 431
			if (strcmp(coldef->colname, restdef->colname) == 0)
				elog(ERROR, "CREATE TABLE: attribute \"%s\" duplicated",
					 coldef->colname);
432 433 434 435
		}
	}

	/*
436 437 438
	 * Scan the parents left-to-right, and merge their attributes to form
	 * a list of inherited attributes (inhSchema).	Also check to see if
	 * we need to inherit an OID column.
439
	 */
440 441 442 443 444 445 446 447 448
	child_attno = 0;
	foreach(entry, supers)
	{
		RangeVar   *parent = (RangeVar *) lfirst(entry);
		Relation	relation;
		TupleDesc	tupleDesc;
		TupleConstr *constr;
		AttrNumber *newattno;
		AttrNumber	parent_attno;
449

450
		relation = heap_openrv(parent, AccessShareLock);
451

452 453 454 455 456 457 458
		if (relation->rd_rel->relkind != RELKIND_RELATION)
			elog(ERROR, "CREATE TABLE: inherited relation \"%s\" is not a table",
				 parent->relname);
		/* Permanent rels cannot inherit from temporary ones */
		if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
			elog(ERROR, "CREATE TABLE: cannot inherit from temp relation \"%s\"",
				 parent->relname);
459

460 461 462 463 464
		/*
		 * We should have an UNDER permission flag for this, but for now,
		 * demand that creator of a child table own the parent.
		 */
		if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
465 466
			aclcheck_error(ACLCHECK_NOT_OWNER,
						   RelationGetRelationName(relation));
467

468 469 470 471 472 473
		/*
		 * Reject duplications in the list of parents.
		 */
		if (intMember(RelationGetRelid(relation), parentOids))
			elog(ERROR, "CREATE TABLE: inherited relation \"%s\" duplicated",
				 parent->relname);
474

475 476
		parentOids = lappendi(parentOids, RelationGetRelid(relation));
		setRelhassubclassInRelation(RelationGetRelid(relation), true);
477

478
		parentHasOids |= relation->rd_rel->relhasoids;
479

480 481
		tupleDesc = RelationGetDescr(relation);
		constr = tupleDesc->constr;
482

483 484 485 486 487 488
		/*
		 * newattno[] will contain the child-table attribute numbers for
		 * the attributes of this parent table.  (They are not the same
		 * for parents after the first one.)
		 */
		newattno = (AttrNumber *) palloc(tupleDesc->natts * sizeof(AttrNumber));
489

490 491 492 493 494 495 496 497
		for (parent_attno = 1; parent_attno <= tupleDesc->natts;
			 parent_attno++)
		{
			Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
			char	   *attributeName = NameStr(attribute->attname);
			int			exist_attno;
			ColumnDef  *def;
			TypeName   *typename;
498

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
			/*
			 * Does it conflict with some previously inherited column?
			 */
			exist_attno = findAttrByName(attributeName, inhSchema);
			if (exist_attno > 0)
			{
				/*
				 * Yes, try to merge the two column definitions. They must
				 * have the same type and typmod.
				 */
				elog(NOTICE, "CREATE TABLE: merging multiple inherited definitions of attribute \"%s\"",
					 attributeName);
				def = (ColumnDef *) nth(exist_attno - 1, inhSchema);
				if (typenameTypeId(def->typename) != attribute->atttypid ||
					def->typename->typmod != attribute->atttypmod)
					elog(ERROR, "CREATE TABLE: inherited attribute \"%s\" type conflict (%s and %s)",
						 attributeName,
						 TypeNameToString(def->typename),
517
						 format_type_be(attribute->atttypid));
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
				/* Merge of NOT NULL constraints = OR 'em together */
				def->is_not_null |= attribute->attnotnull;
				/* Default and other constraints are handled below */
				newattno[parent_attno - 1] = exist_attno;
			}
			else
			{
				/*
				 * No, create a new inherited column
				 */
				def = makeNode(ColumnDef);
				def->colname = pstrdup(attributeName);
				typename = makeNode(TypeName);
				typename->typeid = attribute->atttypid;
				typename->typmod = attribute->atttypmod;
				def->typename = typename;
				def->is_not_null = attribute->attnotnull;
				def->raw_default = NULL;
				def->cooked_default = NULL;
				def->constraints = NIL;
				inhSchema = lappend(inhSchema, def);
				newattno[parent_attno - 1] = ++child_attno;
			}
541

542 543 544 545 546 547 548 549
			/*
			 * Copy default if any
			 */
			if (attribute->atthasdef)
			{
				char	   *this_default = NULL;
				AttrDefault *attrdef;
				int			i;
550

551 552 553 554 555 556 557 558 559 560 561 562
				/* Find default in constraint structure */
				Assert(constr != NULL);
				attrdef = constr->defval;
				for (i = 0; i < constr->num_defval; i++)
				{
					if (attrdef[i].adnum == parent_attno)
					{
						this_default = attrdef[i].adbin;
						break;
					}
				}
				Assert(this_default != NULL);
563

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
				/*
				 * If default expr could contain any vars, we'd need to
				 * fix 'em, but it can't; so default is ready to apply to
				 * child.
				 *
				 * If we already had a default from some prior parent, check
				 * to see if they are the same.  If so, no problem; if
				 * not, mark the column as having a bogus default. Below,
				 * we will complain if the bogus default isn't overridden
				 * by the child schema.
				 */
				Assert(def->raw_default == NULL);
				if (def->cooked_default == NULL)
					def->cooked_default = pstrdup(this_default);
				else if (strcmp(def->cooked_default, this_default) != 0)
				{
					def->cooked_default = bogus_marker;
					have_bogus_defaults = true;
				}
			}
		}
585

586 587 588 589 590 591 592 593
		/*
		 * Now copy the constraints of this parent, adjusting attnos using
		 * the completed newattno[] map
		 */
		if (constr && constr->num_check > 0)
		{
			ConstrCheck *check = constr->check;
			int			i;
594

595 596 597 598
			for (i = 0; i < constr->num_check; i++)
			{
				Constraint *cdef = makeNode(Constraint);
				Node	   *expr;
599

600
				cdef->contype = CONSTR_CHECK;
601 602 603 604 605 606 607
				/*
				 * Do not inherit generated constraint names, since they
				 * might conflict across multiple inheritance parents.
				 * (But conflicts between user-assigned names will cause
				 * an error.)
				 */
				if (ConstraintNameIsGenerated(check[i].ccname))
608 609 610 611 612 613 614 615 616 617 618
					cdef->name = NULL;
				else
					cdef->name = pstrdup(check[i].ccname);
				cdef->raw_expr = NULL;
				/* adjust varattnos of ccbin here */
				expr = stringToNode(check[i].ccbin);
				change_varattnos_of_a_node(expr, newattno);
				cdef->cooked_expr = nodeToString(expr);
				constraints = lappend(constraints, cdef);
			}
		}
619

620
		pfree(newattno);
621

622 623 624 625 626 627 628
		/*
		 * Close the parent rel, but keep our AccessShareLock on it until
		 * xact commit.  That will prevent someone else from deleting or
		 * ALTERing the parent before the child is committed.
		 */
		heap_close(relation, NoLock);
	}
629

630
	/*
631 632 633
	 * If we had no inherited attributes, the result schema is just the
	 * explicitly declared columns.  Otherwise, we need to merge the
	 * declared columns into the inherited schema list.
634
	 */
635 636 637 638 639 640 641
	if (inhSchema != NIL)
	{
		foreach(entry, schema)
		{
			ColumnDef  *newdef = lfirst(entry);
			char	   *attributeName = newdef->colname;
			int			exist_attno;
642

643 644 645 646 647 648 649
			/*
			 * Does it conflict with some previously inherited column?
			 */
			exist_attno = findAttrByName(attributeName, inhSchema);
			if (exist_attno > 0)
			{
				ColumnDef  *def;
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
				/*
				 * Yes, try to merge the two column definitions. They must
				 * have the same type and typmod.
				 */
				elog(NOTICE, "CREATE TABLE: merging attribute \"%s\" with inherited definition",
					 attributeName);
				def = (ColumnDef *) nth(exist_attno - 1, inhSchema);
				if (typenameTypeId(def->typename) != typenameTypeId(newdef->typename) ||
					def->typename->typmod != newdef->typename->typmod)
					elog(ERROR, "CREATE TABLE: attribute \"%s\" type conflict (%s and %s)",
						 attributeName,
						 TypeNameToString(def->typename),
						 TypeNameToString(newdef->typename));
				/* Merge of NOT NULL constraints = OR 'em together */
				def->is_not_null |= newdef->is_not_null;
				/* If new def has a default, override previous default */
				if (newdef->raw_default != NULL)
				{
					def->raw_default = newdef->raw_default;
					def->cooked_default = newdef->cooked_default;
				}
			}
			else
			{
				/*
				 * No, attach new column to result schema
				 */
				inhSchema = lappend(inhSchema, newdef);
			}
		}

		schema = inhSchema;
	}
684

685
	/*
686 687
	 * If we found any conflicting parent default values, check to make
	 * sure they were overridden by the child.
688
	 */
689
	if (have_bogus_defaults)
690
	{
691
		foreach(entry, schema)
692
		{
693
			ColumnDef  *def = lfirst(entry);
694

695 696 697 698
			if (def->cooked_default == bogus_marker)
				elog(ERROR, "CREATE TABLE: attribute \"%s\" inherits conflicting default values"
					 "\n\tTo resolve the conflict, specify a default explicitly",
					 def->colname);
699 700 701
		}
	}

702 703 704 705 706
	*supOids = parentOids;
	*supconstr = constraints;
	*supHasOids = parentHasOids;
	return schema;
}
707

708 709 710
/*
 * complementary static functions for MergeAttributes().
 *
711
 * Varattnos of pg_constraint.conbin must be rewritten when subclasses inherit
712 713 714 715 716 717 718 719 720 721 722
 * constraints from parent classes, since the inherited attributes could
 * be given different column numbers in multiple-inheritance cases.
 *
 * Note that the passed node tree is modified in place!
 */
static bool
change_varattnos_walker(Node *node, const AttrNumber *newattno)
{
	if (node == NULL)
		return false;
	if (IsA(node, Var))
723
	{
724
		Var		   *var = (Var *) node;
725

726 727
		if (var->varlevelsup == 0 && var->varno == 1 &&
			var->varattno > 0)
728
		{
729 730 731 732 733 734 735
			/*
			 * ??? the following may be a problem when the node is
			 * multiply referenced though stringToNode() doesn't create
			 * such a node currently.
			 */
			Assert(newattno[var->varattno - 1] > 0);
			var->varattno = newattno[var->varattno - 1];
736
		}
737
		return false;
738
	}
739 740
	return expression_tree_walker(node, change_varattnos_walker,
								  (void *) newattno);
741 742
}

743 744
static bool
change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
745
{
746
	return change_varattnos_walker(node, newattno);
747 748
}

749
/*
750 751 752 753 754
 * StoreCatalogInheritance
 *		Updates the system catalogs with proper inheritance information.
 *
 * supers is an integer list of the OIDs of the new relation's direct
 * ancestors.  NB: it is destructively changed to include indirect ancestors.
755
 */
756 757
static void
StoreCatalogInheritance(Oid relationId, List *supers)
758
{
759 760 761 762
	Relation	relation;
	TupleDesc	desc;
	int16		seqNumber;
	List	   *entry;
763
	HeapTuple	tuple;
764

765
	/*
766
	 * sanity checks
767
	 */
768
	AssertArg(OidIsValid(relationId));
769

770 771
	if (supers == NIL)
		return;
Bruce Momjian's avatar
Bruce Momjian committed
772

773
	/*
774 775
	 * Store INHERITS information in pg_inherits using direct ancestors only.
	 * Also enter dependencies on the direct ancestors.
776
	 */
777 778
	relation = heap_openr(InheritsRelationName, RowExclusiveLock);
	desc = RelationGetDescr(relation);
Bruce Momjian's avatar
Bruce Momjian committed
779

780 781
	seqNumber = 1;
	foreach(entry, supers)
782
	{
783 784 785
		Oid			entryOid = lfirsti(entry);
		Datum		datum[Natts_pg_inherits];
		char		nullarr[Natts_pg_inherits];
786 787
		ObjectAddress childobject,
					parentobject;
Bruce Momjian's avatar
Bruce Momjian committed
788

789 790 791
		datum[0] = ObjectIdGetDatum(relationId);		/* inhrel */
		datum[1] = ObjectIdGetDatum(entryOid);	/* inhparent */
		datum[2] = Int16GetDatum(seqNumber);	/* inhseqno */
792

793 794 795
		nullarr[0] = ' ';
		nullarr[1] = ' ';
		nullarr[2] = ' ';
796

797
		tuple = heap_formtuple(desc, datum, nullarr);
798

799
		simple_heap_insert(relation, tuple);
800

801
		if (RelationGetForm(relation)->relhasindex)
802
		{
803
			Relation	idescs[Num_pg_inherits_indices];
804

805 806 807
			CatalogOpenIndices(Num_pg_inherits_indices, Name_pg_inherits_indices, idescs);
			CatalogIndexInsert(idescs, Num_pg_inherits_indices, relation, tuple);
			CatalogCloseIndices(Num_pg_inherits_indices, idescs);
808 809
		}

810
		heap_freetuple(tuple);
811

812 813 814 815 816 817 818 819 820 821 822 823
		/*
		 * Store a dependency too
		 */
		parentobject.classId = RelOid_pg_class;
		parentobject.objectId = entryOid;
		parentobject.objectSubId = 0;
		childobject.classId = RelOid_pg_class;
		childobject.objectId = relationId;
		childobject.objectSubId = 0;

		recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);

824 825
		seqNumber += 1;
	}
826

827
	heap_close(relation, RowExclusiveLock);
828

829 830 831 832 833 834 835 836 837 838 839 840 841 842
	/* ----------------
	 * Expand supers list to include indirect ancestors as well.
	 *
	 * Algorithm:
	 *	0. begin with list of direct superclasses.
	 *	1. append after each relationId, its superclasses, recursively.
	 *	2. remove all but last of duplicates.
	 * ----------------
	 */

	/*
	 * 1. append after each relationId, its superclasses, recursively.
	 */
	foreach(entry, supers)
843
	{
844 845 846 847 848
		HeapTuple	tuple;
		Oid			id;
		int16		number;
		List	   *next;
		List	   *current;
849

850 851 852
		id = (Oid) lfirsti(entry);
		current = entry;
		next = lnext(entry);
853

854 855 856 857 858 859 860 861
		for (number = 1;; number += 1)
		{
			tuple = SearchSysCache(INHRELID,
								   ObjectIdGetDatum(id),
								   Int16GetDatum(number),
								   0, 0);
			if (!HeapTupleIsValid(tuple))
				break;
862

863 864 865 866 867 868 869 870 871
			lnext(current) = lconsi(((Form_pg_inherits)
									 GETSTRUCT(tuple))->inhparent,
									NIL);

			ReleaseSysCache(tuple);

			current = lnext(current);
		}
		lnext(current) = next;
872 873
	}

874 875 876 877 878 879 880 881
	/*
	 * 2. remove all but last of duplicates.
	 */
	foreach(entry, supers)
	{
		Oid			thisone;
		bool		found;
		List	   *rest;
882

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
again:
		thisone = lfirsti(entry);
		found = false;
		foreach(rest, lnext(entry))
		{
			if (thisone == lfirsti(rest))
			{
				found = true;
				break;
			}
		}
		if (found)
		{
			/*
			 * found a later duplicate, so remove this entry.
			 */
			lfirsti(entry) = lfirsti(lnext(entry));
			lnext(entry) = lnext(lnext(entry));
901

902 903 904 905
			goto again;
		}
	}
}
906 907

/*
908 909 910 911
 * Look for an existing schema entry with the given name.
 *
 * Returns the index (starting with 1) if attribute already exists in schema,
 * 0 if it doesn't.
912
 */
913 914
static int
findAttrByName(const char *attributeName, List *schema)
915
{
916 917 918 919 920 921 922 923 924 925 926 927
	List	   *s;
	int			i = 0;

	foreach(s, schema)
	{
		ColumnDef  *def = lfirst(s);

		++i;
		if (strcmp(attributeName, def->colname) == 0)
			return i;
	}
	return 0;
928
}
929

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
/*
 * Update a relation's pg_class.relhassubclass entry to the given value
 */
static void
setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
{
	Relation	relationRelation;
	HeapTuple	tuple;
	Relation	idescs[Num_pg_class_indices];

	/*
	 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
	 */
	relationRelation = heap_openr(RelationRelationName, RowExclusiveLock);
	tuple = SearchSysCacheCopy(RELOID,
							   ObjectIdGetDatum(relationId),
							   0, 0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "setRelhassubclassInRelation: cache lookup failed for relation %u", relationId);

	((Form_pg_class) GETSTRUCT(tuple))->relhassubclass = relhassubclass;
	simple_heap_update(relationRelation, &tuple->t_self, tuple);

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

	heap_freetuple(tuple);
	heap_close(relationRelation, RowExclusiveLock);
}
961 962


963
/*
964 965 966 967 968 969 970 971 972 973 974 975
 *		renameatt		- changes the name of a attribute in a relation
 *
 *		Attname attribute is changed in attribute catalog.
 *		No record of the previous attname is kept (correct?).
 *
 *		get proper relrelation from relation catalog (if not arg)
 *		scan attribute catalog
 *				for name conflict (within rel)
 *				for original attribute (if not arg)
 *		modify attname in attribute tuple
 *		insert modified attribute in attribute catalog
 *		delete original attribute from attribute catalog
976
 */
977
void
978 979 980 981
renameatt(Oid relid,
		  const char *oldattname,
		  const char *newattname,
		  bool recurse)
982
{
983 984 985 986 987
	Relation	targetrelation;
	Relation	attrelation;
	HeapTuple	atttup;
	List	   *indexoidlist;
	List	   *indexoidscan;
988

989 990 991 992
	/*
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
	 */
993
	targetrelation = heap_open(relid, AccessExclusiveLock);
994

995 996 997 998 999 1000 1001 1002 1003 1004 1005
	/*
	 * 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 
		&& IsSystemRelation(targetrelation))
		elog(ERROR, "renameatt: class \"%s\" is a system catalog",
			 RelationGetRelationName(targetrelation));
	if (!pg_class_ownercheck(relid, GetUserId()))
1006 1007
		aclcheck_error(ACLCHECK_NOT_OWNER,
					   RelationGetRelationName(targetrelation));
1008

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
	/*
	 * if the 'recurse' flag is set then we are supposed to rename this
	 * attribute in all classes that inherit from 'relname' (as well as in
	 * 'relname').
	 *
	 * any permissions or problems with duplicate attributes will cause the
	 * whole transaction to abort, which is what we want -- all or
	 * nothing.
	 */
	if (recurse)
1019
	{
1020 1021 1022 1023
		List	   *child,
				   *children;

		/* this routine is actually in the planner */
1024
		children = find_all_inheritors(relid);
1025 1026 1027

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

1035
			if (childrelid == relid)
1036
				continue;
1037 1038
			/* note we need not recurse again! */
			renameatt(childrelid, oldattname, newattname, false);
1039 1040 1041
		}
	}

1042
	attrelation = heap_openr(AttributeRelationName, RowExclusiveLock);
1043

1044 1045 1046 1047 1048 1049
	atttup = SearchSysCacheCopy(ATTNAME,
								ObjectIdGetDatum(relid),
								PointerGetDatum(oldattname),
								0, 0);
	if (!HeapTupleIsValid(atttup))
		elog(ERROR, "renameatt: attribute \"%s\" does not exist", oldattname);
1050

1051 1052
	if (((Form_pg_attribute) GETSTRUCT(atttup))->attnum < 0)
		elog(ERROR, "renameatt: system attribute \"%s\" not renamed", oldattname);
1053

1054 1055 1056 1057 1058 1059
	/* should not already exist */
	if (SearchSysCacheExists(ATTNAME,
							 ObjectIdGetDatum(relid),
							 PointerGetDatum(newattname),
							 0, 0))
		elog(ERROR, "renameatt: attribute \"%s\" exists", newattname);
1060

1061 1062
	namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
			   newattname);
1063

1064
	simple_heap_update(attrelation, &atttup->t_self, atttup);
1065

1066 1067 1068
	/* keep system catalog indices current */
	{
		Relation	irelations[Num_pg_attr_indices];
1069

1070 1071 1072 1073
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
		CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, atttup);
		CatalogCloseIndices(Num_pg_attr_indices, irelations);
	}
1074

1075
	heap_freetuple(atttup);
1076

1077 1078 1079 1080 1081
	/*
	 * Update column names of indexes that refer to the column being
	 * renamed.
	 */
	indexoidlist = RelationGetIndexList(targetrelation);
1082

1083 1084 1085 1086
	foreach(indexoidscan, indexoidlist)
	{
		Oid			indexoid = lfirsti(indexoidscan);
		HeapTuple	indextup;
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
		/*
		 * First check to see if index is a functional index. If so, its
		 * column name is a function name and shouldn't be renamed here.
		 */
		indextup = SearchSysCache(INDEXRELID,
								  ObjectIdGetDatum(indexoid),
								  0, 0, 0);
		if (!HeapTupleIsValid(indextup))
			elog(ERROR, "renameatt: can't find index id %u", indexoid);
		if (OidIsValid(((Form_pg_index) GETSTRUCT(indextup))->indproc))
		{
			ReleaseSysCache(indextup);
			continue;
		}
		ReleaseSysCache(indextup);
1103

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
		/*
		 * Okay, look to see if any column name of the index matches the
		 * old attribute name.
		 */
		atttup = SearchSysCacheCopy(ATTNAME,
									ObjectIdGetDatum(indexoid),
									PointerGetDatum(oldattname),
									0, 0);
		if (!HeapTupleIsValid(atttup))
			continue;			/* Nope, so ignore it */
1114

1115 1116 1117 1118 1119
		/*
		 * Update the (copied) attribute tuple.
		 */
		namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
				   newattname);
1120

1121
		simple_heap_update(attrelation, &atttup->t_self, atttup);
1122

1123 1124 1125
		/* keep system catalog indices current */
		{
			Relation	irelations[Num_pg_attr_indices];
1126

1127 1128 1129 1130 1131 1132
			CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
			CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, atttup);
			CatalogCloseIndices(Num_pg_attr_indices, irelations);
		}
		heap_freetuple(atttup);
	}
1133

1134
	freeList(indexoidlist);
1135

1136
	heap_close(attrelation, RowExclusiveLock);
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	/*
	 * Update att name in any RI triggers associated with the relation.
	 */
	if (targetrelation->rd_rel->reltriggers > 0)
	{
		/* update tgargs column reference where att is primary key */
		update_ri_trigger_args(RelationGetRelid(targetrelation),
							   oldattname, newattname,
							   false, false);
		/* update tgargs column reference where att is foreign key */
		update_ri_trigger_args(RelationGetRelid(targetrelation),
							   oldattname, newattname,
							   true, false);
1151 1152
	}

1153
	heap_close(targetrelation, NoLock); /* close rel but keep lock! */
1154 1155
}

1156
/*
1157 1158 1159 1160 1161 1162 1163
 *		renamerel		- change the name of a relation
 *
 *		XXX - When renaming sequences, we don't bother to modify the
 *			  sequence name that is stored within the sequence itself
 *			  (this would cause problems with MVCC). In the future,
 *			  the sequence name should probably be removed from the
 *			  sequence, AFAIK there's no need for it to be there.
1164 1165
 */
void
1166
renamerel(Oid relid, const char *newrelname)
1167
{
1168 1169 1170 1171 1172 1173 1174 1175
	Relation	targetrelation;
	Relation	relrelation;	/* for RELATION relation */
	HeapTuple	reltup;
	Oid			namespaceId;
	char	   *oldrelname;
	char		relkind;
	bool		relhastriggers;
	Relation	irelations[Num_pg_class_indices];
1176

1177
	/*
1178 1179
	 * Grab an exclusive lock on the target table or index, which we will
	 * NOT release until end of transaction.
1180
	 */
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
	targetrelation = relation_open(relid, AccessExclusiveLock);

	oldrelname = pstrdup(RelationGetRelationName(targetrelation));
	namespaceId = RelationGetNamespace(targetrelation);

	/* Validity checks */
	if (!allowSystemTableMods &&
		IsSystemRelation(targetrelation))
		elog(ERROR, "renamerel: system relation \"%s\" may not be renamed",
			 oldrelname);

	relkind = targetrelation->rd_rel->relkind;
	relhastriggers = (targetrelation->rd_rel->reltriggers > 0);
1194 1195

	/*
1196 1197
	 * Find relation's pg_class tuple, and make sure newrelname isn't in
	 * use.
1198
	 */
1199
	relrelation = heap_openr(RelationRelationName, RowExclusiveLock);
1200

1201 1202 1203 1204 1205 1206
	reltup = SearchSysCacheCopy(RELOID,
								PointerGetDatum(relid),
								0, 0, 0);
	if (!HeapTupleIsValid(reltup))
		elog(ERROR, "renamerel: relation \"%s\" does not exist",
			 oldrelname);
1207

1208 1209
	if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
		elog(ERROR, "renamerel: relation \"%s\" exists", newrelname);
1210

1211
	/*
1212 1213
	 * Update pg_class tuple with new relname.	(Scribbling on reltup is
	 * OK because it's a copy...)
1214
	 */
1215
	namestrcpy(&(((Form_pg_class) GETSTRUCT(reltup))->relname), newrelname);
1216

1217 1218 1219 1220 1221 1222 1223 1224 1225
	simple_heap_update(relrelation, &reltup->t_self, reltup);

	/* keep the system catalog indices current */
	CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, irelations);
	CatalogIndexInsert(irelations, Num_pg_class_indices, relrelation, reltup);
	CatalogCloseIndices(Num_pg_class_indices, irelations);

	heap_close(relrelation, NoLock);
	heap_freetuple(reltup);
1226 1227

	/*
1228
	 * Also rename the associated type, if any.
1229
	 */
1230 1231
	if (relkind != RELKIND_INDEX)
		TypeRename(oldrelname, namespaceId, newrelname);
1232

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
	/*
	 * Update rel name in any RI triggers associated with the relation.
	 */
	if (relhastriggers)
	{
		/* update tgargs where relname is primary key */
		update_ri_trigger_args(relid,
							   oldrelname,
							   newrelname,
							   false, true);
		/* update tgargs where relname is foreign key */
		update_ri_trigger_args(relid,
							   oldrelname,
							   newrelname,
							   true, true);
	}
1249 1250

	/*
1251
	 * Close rel, but keep exclusive lock!
1252
	 */
1253 1254
	relation_close(targetrelation, NoLock);
}
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
/*
 * Given a trigger function OID, determine whether it is an RI trigger,
 * and if so whether it is attached to PK or FK relation.
 *
 * XXX this probably doesn't belong here; should be exported by
 * ri_triggers.c
 */
static int
ri_trigger_type(Oid tgfoid)
{
	switch (tgfoid)
	{
		case F_RI_FKEY_CASCADE_DEL:
		case F_RI_FKEY_CASCADE_UPD:
		case F_RI_FKEY_RESTRICT_DEL:
		case F_RI_FKEY_RESTRICT_UPD:
		case F_RI_FKEY_SETNULL_DEL:
		case F_RI_FKEY_SETNULL_UPD:
		case F_RI_FKEY_SETDEFAULT_DEL:
		case F_RI_FKEY_SETDEFAULT_UPD:
		case F_RI_FKEY_NOACTION_DEL:
		case F_RI_FKEY_NOACTION_UPD:
			return RI_TRIGGER_PK;

		case F_RI_FKEY_CHECK_INS:
		case F_RI_FKEY_CHECK_UPD:
			return RI_TRIGGER_FK;
	}

	return RI_TRIGGER_NONE;
1287 1288
}

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
/*
 * Scan pg_trigger for RI triggers that are on the specified relation
 * (if fk_scan is false) or have it as the tgconstrrel (if fk_scan
 * is true).  Update RI trigger args fields matching oldname to contain
 * newname instead.  If update_relname is true, examine the relname
 * fields; otherwise examine the attname fields.
 */
static void
update_ri_trigger_args(Oid relid,
					   const char *oldname,
					   const char *newname,
					   bool fk_scan,
					   bool update_relname)
{
	Relation	tgrel;
	ScanKeyData skey[1];
1305 1306
	SysScanDesc	trigscan;
	HeapTuple	tuple;
1307 1308 1309 1310 1311 1312
	Datum		values[Natts_pg_trigger];
	char		nulls[Natts_pg_trigger];
	char		replaces[Natts_pg_trigger];

	tgrel = heap_openr(TriggerRelationName, RowExclusiveLock);
	if (fk_scan)
1313 1314 1315 1316 1317 1318 1319 1320 1321
	{
		ScanKeyEntryInitialize(&skey[0], 0x0,
							   Anum_pg_trigger_tgconstrrelid,
							   F_OIDEQ,
							   ObjectIdGetDatum(relid));
		trigscan = systable_beginscan(tgrel, TriggerConstrRelidIndex,
									  true, SnapshotNow,
									  1, skey);
	}
1322
	else
1323 1324 1325 1326 1327 1328 1329 1330 1331
	{
		ScanKeyEntryInitialize(&skey[0], 0x0,
							   Anum_pg_trigger_tgrelid,
							   F_OIDEQ,
							   ObjectIdGetDatum(relid));
		trigscan = systable_beginscan(tgrel, TriggerRelidNameIndex,
									  true, SnapshotNow,
									  1, skey);
	}
1332

1333
	while ((tuple = systable_getnext(trigscan)) != NULL)
1334
	{
1335
		Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple);
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
		bytea	   *val;
		bytea	   *newtgargs;
		bool		isnull;
		int			tg_type;
		bool		examine_pk;
		bool		changed;
		int			tgnargs;
		int			i;
		int			newlen;
		const char *arga[RI_MAX_ARGUMENTS];
		const char *argp;

		tg_type = ri_trigger_type(pg_trigger->tgfoid);
		if (tg_type == RI_TRIGGER_NONE)
		{
			/* Not an RI trigger, forget it */
			continue;
		}

		/*
		 * It is an RI trigger, so parse the tgargs bytea.
		 *
		 * NB: we assume the field will never be compressed or moved out of
		 * line; so does trigger.c ...
		 */
		tgnargs = pg_trigger->tgnargs;
		val = (bytea *) fastgetattr(tuple,
									Anum_pg_trigger_tgargs,
									tgrel->rd_att, &isnull);
		if (isnull || tgnargs < RI_FIRST_ATTNAME_ARGNO ||
			tgnargs > RI_MAX_ARGUMENTS)
		{
			/* This probably shouldn't happen, but ignore busted triggers */
			continue;
		}
		argp = (const char *) VARDATA(val);
		for (i = 0; i < tgnargs; i++)
		{
			arga[i] = argp;
			argp += strlen(argp) + 1;
		}
1377

1378 1379 1380 1381 1382 1383 1384 1385
		/*
		 * Figure out which item(s) to look at.  If the trigger is
		 * primary-key type and attached to my rel, I should look at the
		 * PK fields; if it is foreign-key type and attached to my rel, I
		 * should look at the FK fields.  But the opposite rule holds when
		 * examining triggers found by tgconstrrel search.
		 */
		examine_pk = (tg_type == RI_TRIGGER_PK) == (!fk_scan);
1386

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		changed = false;
		if (update_relname)
		{
			/* Change the relname if needed */
			i = examine_pk ? RI_PK_RELNAME_ARGNO : RI_FK_RELNAME_ARGNO;
			if (strcmp(arga[i], oldname) == 0)
			{
				arga[i] = newname;
				changed = true;
			}
		}
		else
		{
			/* Change attname(s) if needed */
			i = examine_pk ? RI_FIRST_ATTNAME_ARGNO + RI_KEYPAIR_PK_IDX :
				RI_FIRST_ATTNAME_ARGNO + RI_KEYPAIR_FK_IDX;
			for (; i < tgnargs; i += 2)
			{
				if (strcmp(arga[i], oldname) == 0)
				{
					arga[i] = newname;
					changed = true;
				}
			}
		}
1412

1413 1414 1415 1416 1417
		if (!changed)
		{
			/* Don't need to update this tuple */
			continue;
		}
1418

1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
		/*
		 * Construct modified tgargs bytea.
		 */
		newlen = VARHDRSZ;
		for (i = 0; i < tgnargs; i++)
			newlen += strlen(arga[i]) + 1;
		newtgargs = (bytea *) palloc(newlen);
		VARATT_SIZEP(newtgargs) = newlen;
		newlen = VARHDRSZ;
		for (i = 0; i < tgnargs; i++)
		{
			strcpy(((char *) newtgargs) + newlen, arga[i]);
			newlen += strlen(arga[i]) + 1;
		}
1433

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
		/*
		 * Build modified tuple.
		 */
		for (i = 0; i < Natts_pg_trigger; i++)
		{
			values[i] = (Datum) 0;
			replaces[i] = ' ';
			nulls[i] = ' ';
		}
		values[Anum_pg_trigger_tgargs - 1] = PointerGetDatum(newtgargs);
		replaces[Anum_pg_trigger_tgargs - 1] = 'r';
1445

1446
		tuple = heap_modifytuple(tuple, tgrel, values, nulls, replaces);
1447

1448 1449 1450 1451
		/*
		 * Update pg_trigger and its indexes
		 */
		simple_heap_update(tgrel, &tuple->t_self, tuple);
1452 1453

		{
1454 1455 1456 1457 1458
			Relation	irelations[Num_pg_attr_indices];

			CatalogOpenIndices(Num_pg_trigger_indices, Name_pg_trigger_indices, irelations);
			CatalogIndexInsert(irelations, Num_pg_trigger_indices, tgrel, tuple);
			CatalogCloseIndices(Num_pg_trigger_indices, irelations);
1459 1460
		}

1461 1462 1463
		/* free up our scratch memory */
		pfree(newtgargs);
		heap_freetuple(tuple);
1464
	}
1465

1466
	systable_endscan(trigscan);
1467

1468
	heap_close(tgrel, RowExclusiveLock);
1469

1470 1471 1472 1473 1474 1475
	/*
	 * Increment cmd counter to make updates visible; this is needed in
	 * case the same tuple has to be updated again by next pass (can
	 * happen in case of a self-referential FK relationship).
	 */
	CommandCounterIncrement();
1476
}
1477

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508

/* ----------------
 *		AlterTableAddColumn
 *		(formerly known as PerformAddAttribute)
 *
 *		adds an additional attribute to a relation
 *
 *		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???
 *
 *		(If needed, can instead use elog to handle exceptions.)
 *
 *		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, heap_getattr, and addattribute.
 *
 *		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
 * ----------------
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1509 1510
 */
void
1511 1512 1513
AlterTableAddColumn(Oid myrelid,
					bool inherits,
					ColumnDef *colDef)
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1514
{
1515 1516 1517
	Relation	rel,
				pgclass,
				attrdesc;
1518
	HeapTuple	reltup;
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
	HeapTuple	newreltup;
	HeapTuple	attributeTuple;
	Form_pg_attribute attribute;
	FormData_pg_attribute attributeD;
	int			i;
	int			minattnum,
				maxatts;
	HeapTuple	typeTuple;
	Form_pg_type tform;
	int			attndims;
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1529

1530
	/*
1531 1532 1533
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
	 */
1534
	rel = heap_open(myrelid, AccessExclusiveLock);
1535 1536 1537

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

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
	/*
	 * 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
		&& IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 RelationGetRelationName(rel));
	if (!pg_class_ownercheck(myrelid, GetUserId()))
1551
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
1552 1553

	/*
1554 1555 1556 1557 1558
	 * Recurse to add the column to child classes, if requested.
	 *
	 * any permissions or problems with duplicate attributes will cause the
	 * whole transaction to abort, which is what we want -- all or
	 * nothing.
1559
	 */
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
	if (inherits)
	{
		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;

			AlterTableAddColumn(childrelid, false, colDef);
		}
	}

	/*
	 * OK, get on with it...
	 *
	 * Implementation restrictions: because we don't touch the table rows,
	 * the new column values will initially appear to be NULLs.  (This
	 * happens because the heap tuple access routines always check for
	 * attnum > # of attributes in tuple, and return NULL if so.)
	 * Therefore we can't support a DEFAULT value in SQL92-compliant
	 * fashion, and we also can't allow a NOT NULL constraint.
	 *
	 * We do allow CHECK constraints, even though these theoretically could
	 * fail for NULL rows (eg, CHECK (newcol IS NOT NULL)).
	 */
	if (colDef->raw_default || colDef->cooked_default)
		elog(ERROR, "Adding columns with defaults is not implemented."
			 "\n\tAdd the column, then use ALTER TABLE SET DEFAULT.");

	if (colDef->is_not_null)
		elog(ERROR, "Adding NOT NULL columns is not implemented."
			 "\n\tAdd the column, then use ALTER TABLE ... SET NOT NULL.");

	pgclass = heap_openr(RelationRelationName, RowExclusiveLock);
1606

1607
	reltup = SearchSysCache(RELOID,
1608
							ObjectIdGetDatum(myrelid),
1609
							0, 0, 0);
1610 1611
	if (!HeapTupleIsValid(reltup))
		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
1612
			 RelationGetRelationName(rel));
1613

1614 1615 1616 1617 1618 1619
	if (SearchSysCacheExists(ATTNAME,
							 ObjectIdGetDatum(myrelid),
							 PointerGetDatum(colDef->colname),
							 0, 0))
		elog(ERROR, "ALTER TABLE: column name \"%s\" already exists in table \"%s\"",
			 colDef->colname, RelationGetRelationName(rel));
1620

1621 1622 1623 1624 1625 1626
	minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
	maxatts = minattnum + 1;
	if (maxatts > MaxHeapAttributeNumber)
		elog(ERROR, "ALTER TABLE: relations limited to %d columns",
			 MaxHeapAttributeNumber);
	i = minattnum + 1;
1627

1628
	attrdesc = heap_openr(AttributeRelationName, RowExclusiveLock);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1629

1630 1631 1632 1633
	if (colDef->typename->arrayBounds)
		attndims = length(colDef->typename->arrayBounds);
	else
		attndims = 0;
1634

1635 1636
	typeTuple = typenameType(colDef->typename);
	tform = (Form_pg_type) GETSTRUCT(typeTuple);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1637

1638 1639 1640
	attributeTuple = heap_addheader(Natts_pg_attribute,
									ATTRIBUTE_TUPLE_SIZE,
									(void *) &attributeD);
1641

1642
	attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
1643

1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
	attribute->attrelid = myrelid;
	namestrcpy(&(attribute->attname), colDef->colname);
	attribute->atttypid = typeTuple->t_data->t_oid;
	attribute->attstattarget = DEFAULT_ATTSTATTARGET;
	attribute->attlen = tform->typlen;
	attribute->attcacheoff = -1;
	attribute->atttypmod = colDef->typename->typmod;
	attribute->attnum = i;
	attribute->attbyval = tform->typbyval;
	attribute->attndims = attndims;
	attribute->attisset = (bool) (tform->typtype == 'c');
	attribute->attstorage = tform->typstorage;
	attribute->attalign = tform->typalign;
	attribute->attnotnull = colDef->is_not_null;
	attribute->atthasdef = (colDef->raw_default != NULL ||
							colDef->cooked_default != NULL);
1660

1661
	ReleaseSysCache(typeTuple);
1662

1663
	simple_heap_insert(attrdesc, attributeTuple);
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

	/* Update indexes on pg_attribute */
	if (RelationGetForm(attrdesc)->relhasindex)
	{
		Relation	idescs[Num_pg_attr_indices];

		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_attr_indices, attrdesc, attributeTuple);
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
	}

	heap_close(attrdesc, RowExclusiveLock);
1676

1677
	/*
1678
	 * Update number of attributes in pg_class tuple
1679
	 */
1680
	newreltup = heap_copytuple(reltup);
1681

1682 1683
	((Form_pg_class) GETSTRUCT(newreltup))->relnatts = maxatts;
	simple_heap_update(pgclass, &newreltup->t_self, newreltup);
1684

1685 1686 1687 1688
	/* keep catalog indices current */
	if (RelationGetForm(pgclass)->relhasindex)
	{
		Relation	ridescs[Num_pg_class_indices];
1689

1690 1691 1692 1693
		CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, ridescs);
		CatalogIndexInsert(ridescs, Num_pg_class_indices, pgclass, newreltup);
		CatalogCloseIndices(Num_pg_class_indices, ridescs);
	}
1694

1695 1696
	heap_freetuple(newreltup);
	ReleaseSysCache(reltup);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1697

1698 1699 1700
	heap_close(pgclass, NoLock);

	heap_close(rel, NoLock);	/* close rel but keep lock! */
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1701

1702
	/*
1703
	 * Make our catalog updates visible for subsequent steps.
1704
	 */
1705
	CommandCounterIncrement();
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1706

1707
	/*
1708 1709 1710 1711
	 * Add any CHECK constraints attached to the new column.
	 *
	 * To do this we must re-open the rel so that its new attr list gets
	 * loaded into the relcache.
1712
	 */
1713 1714 1715 1716 1717 1718
	if (colDef->constraints != NIL)
	{
		rel = heap_open(myrelid, AccessExclusiveLock);
		AddRelationRawConstraints(rel, NIL, colDef->constraints);
		heap_close(rel, NoLock);
	}
1719

1720 1721 1722 1723 1724
	/*
	 * Automatically create the secondary relation for TOAST if it
	 * formerly had no such but now has toastable attributes.
	 */
	AlterTableCreateToastTable(myrelid, true);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
1725 1726
}

1727
/*
1728
 * ALTER TABLE ALTER COLUMN DROP NOT NULL
1729
 */
1730 1731 1732
void
AlterTableAlterColumnDropNotNull(Oid myrelid,
								 bool inh, const char *colName)
1733
{
1734 1735 1736 1737 1738 1739
	Relation	rel;
	HeapTuple	tuple;
	AttrNumber	attnum;
	Relation	attr_rel;
	List	   	*indexoidlist;
	List	   	*indexoidscan;
1740

1741
	rel = heap_open(myrelid, AccessExclusiveLock);
1742

1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 RelationGetRelationName(rel));

	if (!allowSystemTableMods
		&& IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 RelationGetRelationName(rel));

	if (!pg_class_ownercheck(myrelid, GetUserId()))
1753
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
1754 1755 1756 1757 1758

	/*
	 * Propagate to children if desired
	 */
	if (inh)
1759
	{
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
		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)
1772
		{
1773
			Oid			childrelid = lfirsti(child);
1774

1775 1776 1777 1778
			if (childrelid == myrelid)
				continue;
			AlterTableAlterColumnDropNotNull(childrelid,
											 false, colName);
1779 1780
		}
	}
1781

1782
	/* -= now do the thing on this relation =- */
1783 1784

	/*
1785
	 * get the number of the attribute
1786
	 */
1787 1788 1789 1790 1791 1792 1793
	tuple = SearchSysCache(ATTNAME,
						   ObjectIdGetDatum(myrelid),
						   PointerGetDatum(colName),
						   0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 RelationGetRelationName(rel), colName);
1794

1795 1796
	attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
	ReleaseSysCache(tuple);
1797

1798 1799 1800 1801
	/* Prevent them from altering a system attribute */
	if (attnum < 0)
		elog(ERROR, "ALTER TABLE: Cannot alter system attribute \"%s\"",
			 colName);
1802 1803

	/*
1804
	 * Check that the attribute is not in a primary key
1805
	 */
1806

1807 1808
	/* Loop over all indices on the relation */
	indexoidlist = RelationGetIndexList(rel);
1809

1810
	foreach(indexoidscan, indexoidlist)
1811
	{
1812 1813 1814 1815
		Oid		indexoid = lfirsti(indexoidscan);
		HeapTuple	indexTuple;
		Form_pg_index 	indexStruct;
		int		i;
1816

1817 1818 1819 1820 1821 1822 1823
		indexTuple = SearchSysCache(INDEXRELID,
									ObjectIdGetDatum(indexoid),
									0, 0, 0);
		if (!HeapTupleIsValid(indexTuple))
			elog(ERROR, "ALTER TABLE: Index %u not found",
				 indexoid);
		indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
1824

1825 1826
		/* If the index is not a primary key, skip the check */
		if (indexStruct->indisprimary)
1827
		{
1828 1829 1830 1831 1832 1833
			/*
			 * Loop over each attribute in the primary key and
			 * see if it matches the to-be-altered attribute
			 */
			for (i = 0; i < INDEX_MAX_KEYS &&
					 indexStruct->indkey[i] != InvalidAttrNumber; i++)
1834
			{
1835 1836
				if (indexStruct->indkey[i] == attnum)
					elog(ERROR, "ALTER TABLE: Attribute \"%s\" is in a primary key", colName);
1837 1838 1839
			}
		}

1840 1841
		ReleaseSysCache(indexTuple);
	}
1842

1843
	freeList(indexoidlist);
1844 1845

	/*
1846
	 * Okay, actually perform the catalog change
1847
	 */
1848
	attr_rel = heap_openr(AttributeRelationName, RowExclusiveLock);
1849

1850 1851 1852 1853 1854 1855 1856
	tuple = SearchSysCacheCopy(ATTNAME,
							   ObjectIdGetDatum(myrelid),
							   PointerGetDatum(colName),
							   0, 0);
	if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 RelationGetRelationName(rel), colName);
1857

1858
	((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
1859

1860
	simple_heap_update(attr_rel, &tuple->t_self, tuple);
Bruce Momjian's avatar
Bruce Momjian committed
1861

1862 1863 1864 1865
	/* keep the system catalog indices current */
	if (RelationGetForm(attr_rel)->relhasindex)
	{
		Relation	idescs[Num_pg_attr_indices];
Bruce Momjian's avatar
Bruce Momjian committed
1866

1867 1868 1869
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_attr_indices, attr_rel, tuple);
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
1870
	}
1871

1872
	heap_close(attr_rel, RowExclusiveLock);
1873 1874 1875

	heap_close(rel, NoLock);
}
1876 1877

/*
1878
 * ALTER TABLE ALTER COLUMN SET NOT NULL
1879
 */
1880
void
1881 1882
AlterTableAlterColumnSetNotNull(Oid myrelid,
								bool inh, const char *colName)
1883
{
1884
	Relation	rel;
1885 1886 1887 1888 1889
	HeapTuple	tuple;
	AttrNumber	attnum;
	Relation	attr_rel;
	HeapScanDesc 	scan;
	TupleDesc	tupdesc;
1890

1891
	rel = heap_open(myrelid, AccessExclusiveLock);
1892

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

1897 1898 1899
	if (!allowSystemTableMods
		&& IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
1900
			 RelationGetRelationName(rel));
1901

1902
	if (!pg_class_ownercheck(myrelid, GetUserId()))
1903
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
1904 1905

	/*
1906
	 * Propagate to children if desired
1907
	 */
1908
	if (inh)
1909
	{
1910 1911
		List	   *child,
				   *children;
1912

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

1916 1917 1918 1919 1920 1921
		/*
		 * 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)
1922
		{
1923
			Oid			childrelid = lfirsti(child);
1924

1925 1926 1927 1928 1929
			if (childrelid == myrelid)
				continue;
			AlterTableAlterColumnSetNotNull(childrelid,
											false, colName);
		}
1930 1931
	}

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

1934
	/*
1935
	 * get the number of the attribute
1936
	 */
1937 1938 1939 1940 1941 1942 1943
	tuple = SearchSysCache(ATTNAME,
						   ObjectIdGetDatum(myrelid),
						   PointerGetDatum(colName),
						   0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 RelationGetRelationName(rel), colName);
1944

1945 1946
	attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
	ReleaseSysCache(tuple);
1947

1948 1949 1950 1951
	/* Prevent them from altering a system attribute */
	if (attnum < 0)
		elog(ERROR, "ALTER TABLE: Cannot alter system attribute \"%s\"",
			 colName);
1952

1953
	/*
1954 1955
	 * Perform a scan to ensure that there are no NULL
	 * values already in the relation
1956
	 */
1957
	tupdesc = RelationGetDescr(rel);
1958

1959
	scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1960

1961
	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1962 1963 1964
	{
		Datum 		d;
		bool		isnull;
1965

1966
		d = heap_getattr(tuple, attnum, tupdesc, &isnull);
1967

1968 1969 1970 1971
		if (isnull)
			elog(ERROR, "ALTER TABLE: Attribute \"%s\" contains NULL values",
				 colName);
	}
1972

1973
	heap_endscan(scan);
1974

1975 1976 1977 1978
	/*
	 * Okay, actually perform the catalog change
	 */
	attr_rel = heap_openr(AttributeRelationName, RowExclusiveLock);
1979

1980 1981 1982 1983 1984 1985 1986
	tuple = SearchSysCacheCopy(ATTNAME,
							   ObjectIdGetDatum(myrelid),
							   PointerGetDatum(colName),
							   0, 0);
	if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 RelationGetRelationName(rel), colName);
1987

1988
	((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
1989

1990
	simple_heap_update(attr_rel, &tuple->t_self, tuple);
1991

1992 1993 1994 1995
	/* keep the system catalog indices current */
	if (RelationGetForm(attr_rel)->relhasindex)
	{
		Relation	idescs[Num_pg_attr_indices];
1996

1997 1998 1999 2000
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_attr_indices, attr_rel, tuple);
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
	}
2001

2002
	heap_close(attr_rel, RowExclusiveLock);
2003

2004 2005
	heap_close(rel, NoLock);
}
2006 2007


2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
/*
 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
 */
void
AlterTableAlterColumnDefault(Oid myrelid,
							 bool inh, const char *colName,
							 Node *newDefault)
{
	Relation	rel;
	HeapTuple	tuple;
	AttrNumber	attnum;
2019

2020
	rel = heap_open(myrelid, AccessExclusiveLock);
2021

2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
	/*
	 * We allow defaults on views so that INSERT into a view can have
	 * default-ish behavior.  This works because the rewriter substitutes
	 * default values into INSERTs before it expands rules.
	 */
	if (rel->rd_rel->relkind != RELKIND_RELATION &&
		rel->rd_rel->relkind != RELKIND_VIEW)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table or view",
			 RelationGetRelationName(rel));

	if (!allowSystemTableMods
		&& IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 RelationGetRelationName(rel));
2036

2037
	if (!pg_class_ownercheck(myrelid, GetUserId()))
2038
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
2039 2040

	/*
2041
	 * Propagate to children if desired
2042
	 */
2043
	if (inh)
2044
	{
2045 2046
		List	   *child,
				   *children;
2047

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

2051 2052 2053 2054 2055 2056 2057 2058
		/*
		 * 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);
2059

2060 2061 2062 2063 2064
			if (childrelid == myrelid)
				continue;
			AlterTableAlterColumnDefault(childrelid,
										 false, colName, newDefault);
		}
2065 2066
	}

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

2069
	/*
2070
	 * get the number of the attribute
2071
	 */
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
	tuple = SearchSysCache(ATTNAME,
						   ObjectIdGetDatum(myrelid),
						   PointerGetDatum(colName),
						   0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
			 RelationGetRelationName(rel), colName);

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

	if (newDefault)
2084
	{
2085 2086
		/* SET DEFAULT */
		RawColumnDefault *rawEnt;
2087

2088 2089
		/* Get rid of the old one first */
		drop_default(myrelid, attnum);
2090

2091 2092 2093
		rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
		rawEnt->attnum = attnum;
		rawEnt->raw_default = newDefault;
2094

2095 2096 2097 2098 2099 2100 2101
		/*
		 * This function is intended for CREATE TABLE, so it processes a
		 * _list_ of defaults, but we just do one.
		 */
		AddRelationRawConstraints(rel, makeList1(rawEnt), NIL);
	}
	else
2102
	{
2103 2104
		/* DROP DEFAULT */
		Relation	attr_rel;
2105

2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
		/* Fix the pg_attribute row */
		attr_rel = heap_openr(AttributeRelationName, RowExclusiveLock);

		tuple = SearchSysCacheCopy(ATTNAME,
								   ObjectIdGetDatum(myrelid),
								   PointerGetDatum(colName),
								   0, 0);
		if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
			elog(ERROR, "ALTER TABLE: relation \"%s\" has no column \"%s\"",
				 RelationGetRelationName(rel), colName);

		((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = FALSE;

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

		/* keep the system catalog indices current */
		if (RelationGetForm(attr_rel)->relhasindex)
2123
		{
2124 2125 2126 2127 2128
			Relation	idescs[Num_pg_attr_indices];

			CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
			CatalogIndexInsert(idescs, Num_pg_attr_indices, attr_rel, tuple);
			CatalogCloseIndices(Num_pg_attr_indices, idescs);
2129
		}
2130 2131 2132 2133 2134

		heap_close(attr_rel, RowExclusiveLock);

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

2137
	heap_close(rel, NoLock);
2138 2139
}

2140

2141
static void
2142
drop_default(Oid relid, int16 attnum)
2143
{
2144 2145 2146
	ScanKeyData scankeys[2];
	HeapScanDesc scan;
	Relation	attrdef_rel;
2147 2148
	HeapTuple	tuple;

2149 2150 2151 2152 2153 2154 2155
	attrdef_rel = heap_openr(AttrDefaultRelationName, RowExclusiveLock);
	ScanKeyEntryInitialize(&scankeys[0], 0x0,
						   Anum_pg_attrdef_adrelid, F_OIDEQ,
						   ObjectIdGetDatum(relid));
	ScanKeyEntryInitialize(&scankeys[1], 0x0,
						   Anum_pg_attrdef_adnum, F_INT2EQ,
						   Int16GetDatum(attnum));
2156

2157
	scan = heap_beginscan(attrdef_rel, SnapshotNow, 2, scankeys);
2158

2159
	if ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2160
		simple_heap_delete(attrdef_rel, &tuple->t_self);
2161

2162
	heap_endscan(scan);
2163

2164 2165
	heap_close(attrdef_rel, NoLock);
}
2166 2167


2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
/*
 * ALTER TABLE ALTER COLUMN SET STATISTICS / STORAGE
 */
void
AlterTableAlterColumnFlags(Oid myrelid,
						   bool inh, const char *colName,
						   Node *flagValue, const char *flagType)
{
	Relation	rel;
	int			newtarget = 1;
	char        newstorage = 'p';
	Relation	attrelation;
	HeapTuple	tuple;
	Form_pg_attribute attrtuple;

	rel = heap_open(myrelid, AccessExclusiveLock);
2184

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

2189 2190 2191 2192 2193 2194
	/*
	 * we allow statistics case for system tables
	 */
	if (*flagType != 'S' && !allowSystemTableMods && IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 RelationGetRelationName(rel));
2195

2196
	if (!pg_class_ownercheck(myrelid, GetUserId()))
2197
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
2198

2199 2200 2201 2202 2203 2204 2205 2206
	/*
	 * Check the supplied parameters before anything else
	 */
	if (*flagType == 'S')
	{
		/* STATISTICS */
		Assert(IsA(flagValue, Integer));
		newtarget = intVal(flagValue);
2207

2208 2209 2210 2211 2212 2213 2214
		/*
		 * Limit target to sane range (should we raise an error instead?)
		 */
		if (newtarget < 0)
			newtarget = 0;
		else if (newtarget > 1000)
			newtarget = 1000;
2215
	}
2216 2217 2218 2219
	else if (*flagType == 'M')
	{
		/* STORAGE */
		char        *storagemode;
2220

2221 2222
		Assert(IsA(flagValue, String));
		storagemode = strVal(flagValue);
2223

2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
		if (strcasecmp(storagemode, "plain") == 0)
			newstorage = 'p';
		else if (strcasecmp(storagemode, "external") == 0)
			newstorage = 'e';
		else if (strcasecmp(storagemode, "extended") == 0)
			newstorage = 'x';
		else if (strcasecmp(storagemode, "main") == 0)
			newstorage = 'm';
		else
			elog(ERROR, "ALTER TABLE: \"%s\" storage not recognized",
				 storagemode);
	}
	else
	{
		elog(ERROR, "ALTER TABLE: Invalid column flag: %c",
			 (int) *flagType);
	}
2241 2242

	/*
2243
	 * Propagate to children if desired
2244
	 */
2245
	if (inh)
2246
	{
2247 2248
		List	   *child,
				   *children;
2249

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

2253 2254 2255 2256 2257 2258
		/*
		 * 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)
2259
		{
2260
			Oid			childrelid = lfirsti(child);
2261

2262 2263 2264 2265
			if (childrelid == myrelid)
				continue;
			AlterTableAlterColumnFlags(childrelid,
									   false, colName, flagValue, flagType);
2266 2267 2268
		}
	}

2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
	/* -= now do the thing on this relation =- */

	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\"",
			 RelationGetRelationName(rel), colName);
	attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);

	if (attrtuple->attnum < 0)
		elog(ERROR, "ALTER TABLE: cannot change system attribute \"%s\"",
			 colName);
2285
	/*
2286
	 * Now change the appropriate field
2287
	 */
2288 2289 2290
	if (*flagType == 'S')
		attrtuple->attstattarget = newtarget;
	else if (*flagType == 'M')
2291
	{
2292 2293 2294 2295 2296 2297 2298 2299 2300
		/*
		 * safety check: do not allow toasted storage modes unless column
		 * datatype is TOAST-aware.
		 */
		if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
			attrtuple->attstorage = newstorage;
		else
			elog(ERROR, "ALTER TABLE: Column datatype %s can only have storage \"plain\"",
				 format_type_be(attrtuple->atttypid));
2301 2302
	}

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

2305
	/* keep system catalog indices current */
2306
	{
2307
		Relation	irelations[Num_pg_attr_indices];
2308

2309 2310 2311
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, irelations);
		CatalogIndexInsert(irelations, Num_pg_attr_indices, attrelation, tuple);
		CatalogCloseIndices(Num_pg_attr_indices, irelations);
2312
	}
2313 2314 2315 2316

	heap_freetuple(tuple);
	heap_close(attrelation, NoLock);
	heap_close(rel, NoLock);	/* close rel, but keep lock! */
2317 2318
}

2319

2320
/*
2321
 * ALTER TABLE DROP COLUMN
2322
 */
2323 2324 2325
void
AlterTableDropColumn(Oid myrelid,
					 bool inh, const char *colName,
2326
					 DropBehavior behavior)
2327
{
2328
	elog(ERROR, "ALTER TABLE / DROP COLUMN is not implemented");
2329 2330 2331 2332
}


/*
2333
 * ALTER TABLE ADD CONSTRAINT
2334 2335
 */
void
2336 2337 2338 2339 2340
AlterTableAddConstraint(Oid myrelid,
						bool inh, List *newConstraints)
{
	Relation	rel;
	List	   *listptr;
2341
	int			counter = 0;
2342 2343 2344 2345 2346

	/*
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
	 */
2347
	rel = heap_open(myrelid, AccessExclusiveLock);
2348

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

2353 2354 2355 2356 2357 2358
	if (!allowSystemTableMods
		&& IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 RelationGetRelationName(rel));

	if (!pg_class_ownercheck(myrelid, GetUserId()))
2359
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
2360 2361

	if (inh)
2362 2363 2364 2365 2366
	{
		List	   *child,
				   *children;

		/* this routine is actually in the planner */
2367
		children = find_all_inheritors(myrelid);
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377

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

2378
			if (childrelid == myrelid)
2379
				continue;
2380
			AlterTableAddConstraint(childrelid, false, newConstraints);
2381 2382 2383
		}
	}

2384 2385
	foreach(listptr, newConstraints)
	{
2386 2387 2388 2389 2390 2391
		/*
		 * copy is because we may destructively alter the node below
		 * by inserting a generated name; this name is not necessarily
		 * correct for children or parents.
		 */
		Node	   *newConstraint = copyObject(lfirst(listptr));
2392

2393 2394 2395 2396 2397
		switch (nodeTag(newConstraint))
		{
			case T_Constraint:
				{
					Constraint *constr = (Constraint *) newConstraint;
2398

2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
					/*
					 * Currently, we only expect to see CONSTR_CHECK nodes
					 * arriving here (see the preprocessing done in
					 * parser/analyze.c).  Use a switch anyway to make it
					 * easier to add more code later.
					 */
					switch (constr->contype)
					{
						case CONSTR_CHECK:
							{
								ParseState *pstate;
								bool		successful = true;
								HeapScanDesc scan;
								ExprContext *econtext;
								TupleTableSlot *slot;
								HeapTuple	tuple;
								RangeTblEntry *rte;
								List	   *qual;
								Node	   *expr;
2418

2419 2420 2421
								/*
								 * Assign or validate constraint name
								 */
2422
								if (constr->name)
2423 2424 2425 2426 2427 2428 2429 2430
								{
									if (ConstraintNameIsUsed(RelationGetRelid(rel),
															 RelationGetNamespace(rel),
															 constr->name))
										elog(ERROR, "constraint \"%s\" already exists for relation \"%s\"",
											 constr->name,
											 RelationGetRelationName(rel));
								}
2431
								else
2432 2433 2434
									constr->name = GenerateConstraintName(RelationGetRelid(rel),
																		  RelationGetNamespace(rel),
																		  &counter);
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458

								/*
								 * 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 = addRangeTableEntryForRelation(pstate,
																	myrelid,
											makeAlias(RelationGetRelationName(rel), NIL),
																	false,
																	true);
								addRTEtoQuery(pstate, rte, true, true);

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

								/*
								 * Make sure it yields a boolean result.
								 */
2459
								expr = coerce_to_boolean(expr, "CHECK");
2460 2461 2462 2463 2464 2465 2466 2467 2468

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

2469 2470 2471 2472 2473 2474 2475 2476
								/*
								 * No subplans or aggregates, either...
								 */
								if (contain_subplans(expr))
									elog(ERROR, "cannot use subselect in CHECK constraint expression");
								if (contain_agg_clause(expr))
									elog(ERROR, "cannot use aggregate function in CHECK constraint expression");

2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
								/*
								 * 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.
								 */
2498
								scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
2499

2500
								while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
								{
									ExecStoreTuple(tuple, slot, InvalidBuffer, false);
									if (!ExecQual(qual, econtext, true))
									{
										successful = false;
										break;
									}
									ResetExprContext(econtext);
								}

								heap_endscan(scan);

								FreeExprContext(econtext);
								pfree(slot);

								if (!successful)
2517 2518
									elog(ERROR, "AlterTableAddConstraint: rejected due to CHECK constraint %s",
										 constr->name);
2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540

								/*
								 * 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,
													  makeList1(constr));

								break;
							}
						default:
							elog(ERROR, "ALTER TABLE / ADD CONSTRAINT is not implemented for that constraint type.");
					}
					break;
				}
			case T_FkConstraint:
				{
					FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
					Relation	pkrel;
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
					Oid			constrOid;

					/*
					 * Assign or validate constraint name
					 */
					if (fkconstraint->constr_name)
					{
						if (ConstraintNameIsUsed(RelationGetRelid(rel),
												 RelationGetNamespace(rel),
												 fkconstraint->constr_name))
							elog(ERROR, "constraint \"%s\" already exists for relation \"%s\"",
								 fkconstraint->constr_name,
								 RelationGetRelationName(rel));
					}
					else
						fkconstraint->constr_name = GenerateConstraintName(RelationGetRelid(rel),
																		   RelationGetNamespace(rel),
																		   &counter);
2559 2560 2561 2562

					/*
					 * Grab an exclusive lock on the pk table, so that
					 * someone doesn't delete rows out from under us.
2563 2564 2565 2566
					 * (Although a lesser lock would do for that purpose,
					 * we'll need exclusive lock anyway to add triggers
					 * to the pk table; trying to start with a lesser lock
					 * will just create a risk of deadlock.)
2567 2568 2569 2570 2571 2572 2573 2574
					 */
					pkrel = heap_openrv(fkconstraint->pktable,
										AccessExclusiveLock);

					/*
					 * Validity checks
					 */
					if (pkrel->rd_rel->relkind != RELKIND_RELATION)
2575 2576 2577 2578 2579 2580 2581 2582 2583
						elog(ERROR, "referenced relation \"%s\" is not a table",
							 RelationGetRelationName(pkrel));

					if (!allowSystemTableMods
						&& IsSystemRelation(pkrel))
						elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
							 RelationGetRelationName(pkrel));

					/* XXX shouldn't there be a permission check too? */
2584 2585 2586

					if (isTempNamespace(RelationGetNamespace(pkrel)) &&
						!isTempNamespace(RelationGetNamespace(rel)))
2587
						elog(ERROR, "ALTER TABLE / ADD CONSTRAINT: Unable to reference temporary table from permanent table constraint");
2588 2589

					/*
2590 2591
					 * Check that the constraint is satisfied by existing
					 * rows (we can skip this during table creation).
2592 2593 2594 2595 2596 2597
					 *
					 * NOTE: we assume parser has already checked for
					 * existence of an appropriate unique index on the
					 * referenced relation, and that the column datatypes
					 * are comparable.
					 */
2598 2599
					if (!fkconstraint->skip_validation)
						validateForeignKeyConstraint(fkconstraint, rel, pkrel);
2600

2601 2602 2603 2604 2605
					/*
					 * Record the FK constraint in pg_constraint.
					 */
					constrOid = createForeignKeyConstraint(rel, pkrel,
														   fkconstraint);
2606

2607 2608 2609 2610
					/*
					 * Create the triggers that will enforce the constraint.
					 */
					createForeignKeyTriggers(rel, fkconstraint, constrOid);
2611

2612 2613 2614 2615
					/*
					 * Close pk table, but keep lock until we've committed.
					 */
					heap_close(pkrel, NoLock);
2616

2617 2618 2619 2620 2621 2622
					break;
				}
			default:
				elog(ERROR, "ALTER TABLE / ADD CONSTRAINT unable to determine type of constraint passed");
		}
	}
2623

2624 2625 2626
	/* Close rel, but keep lock till commit */
	heap_close(rel, NoLock);
}
2627

2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
/*
 * Scan the existing rows in a table to verify they meet a proposed FK
 * constraint.
 *
 * Caller must have opened and locked both relations.
 */
static void
validateForeignKeyConstraint(FkConstraint *fkconstraint,
							 Relation rel,
							 Relation pkrel)
{
	HeapScanDesc scan;
	HeapTuple	tuple;
	Trigger		trig;
	List	   *list;
	int			count;

	/*
	 * Scan through each tuple, calling RI_FKey_check_ins
	 * (insert trigger) as if that tuple had just been
	 * inserted.  If any of those fail, it should
	 * elog(ERROR) and that's that.
	 */
	MemSet(&trig, 0, sizeof(trig));
	trig.tgoid = InvalidOid;
	trig.tgname = fkconstraint->constr_name;
	trig.tgenabled = TRUE;
	trig.tgisconstraint = TRUE;
	trig.tgconstrrelid = RelationGetRelid(pkrel);
	trig.tgdeferrable = FALSE;
	trig.tginitdeferred = FALSE;

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

	trig.tgargs[0] = trig.tgname;
	trig.tgargs[1] = RelationGetRelationName(rel);
	trig.tgargs[2] = RelationGetRelationName(pkrel);
	trig.tgargs[3] = fkMatchTypeToString(fkconstraint->fk_matchtype);
	count = 4;
	foreach(list, fkconstraint->fk_attrs)
	{
		Ident	   *fk_at = lfirst(list);
2672

2673 2674 2675 2676 2677 2678 2679
		trig.tgargs[count] = fk_at->name;
		count += 2;
	}
	count = 5;
	foreach(list, fkconstraint->pk_attrs)
	{
		Ident	   *pk_at = lfirst(list);
2680

2681 2682 2683 2684
		trig.tgargs[count] = pk_at->name;
		count += 2;
	}
	trig.tgnargs = count - 1;
2685

2686
	scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
2687

2688 2689 2690 2691
	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
	{
		FunctionCallInfoData fcinfo;
		TriggerData trigdata;
2692

2693 2694 2695 2696 2697 2698
		/*
		 * Make a call to the trigger function
		 *
		 * No parameters are passed, but we do set a context
		 */
		MemSet(&fcinfo, 0, sizeof(fcinfo));
2699

2700 2701 2702 2703 2704 2705 2706 2707 2708
		/*
		 * We assume RI_FKey_check_ins won't look at flinfo...
		 */
		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;
2709

2710 2711 2712
		fcinfo.context = (Node *) &trigdata;

		RI_FKey_check_ins(&fcinfo);
2713 2714
	}

2715 2716 2717
	heap_endscan(scan);

	pfree(trig.tgargs);
2718 2719
}

2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
/*
 * Record an FK constraint in pg_constraint.
 */
static Oid
createForeignKeyConstraint(Relation rel, Relation pkrel,
						   FkConstraint *fkconstraint)
{
	int16	   *fkattr;
	int16	   *pkattr;
	int			fkcount;
	int			pkcount;
	List	   *l;
	int			i;

	/* Convert foreign-key attr names to attr number array */
	fkcount = length(fkconstraint->fk_attrs);
	fkattr = (int16 *) palloc(fkcount * sizeof(int16));
	i = 0;
	foreach(l, fkconstraint->fk_attrs)
	{
		Ident *id = (Ident *) lfirst(l);

		fkattr[i++] = get_attnum(RelationGetRelid(rel), id->name);
	}

	/* The same for the referenced primary key attrs */
	pkcount = length(fkconstraint->pk_attrs);
	pkattr = (int16 *) palloc(pkcount * sizeof(int16));
	i = 0;
	foreach(l, fkconstraint->pk_attrs)
	{
		Ident *id = (Ident *) lfirst(l);

		pkattr[i++] = get_attnum(RelationGetRelid(pkrel), id->name);
	}

	/* Now we can make the pg_constraint entry */
	return CreateConstraintEntry(fkconstraint->constr_name,
								 RelationGetNamespace(rel),
								 CONSTRAINT_FOREIGN,
								 fkconstraint->deferrable,
								 fkconstraint->initdeferred,
								 RelationGetRelid(rel),
								 fkattr,
								 fkcount,
								 InvalidOid, /* not a domain constraint */
								 RelationGetRelid(pkrel),
								 pkattr,
								 pkcount,
								 fkconstraint->fk_upd_action,
								 fkconstraint->fk_del_action,
								 fkconstraint->fk_matchtype,
								 NULL,
								 NULL);
}

/*
 * Create the triggers that implement an FK constraint.
 */
static void
createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
						 Oid constrOid)
{
	RangeVar   *myRel;
	CreateTrigStmt *fk_trigger;
	List	   *fk_attr;
	List	   *pk_attr;
	Ident	   *id;
	ObjectAddress trigobj,
				constrobj;

	/*
	 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
	 */
	myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
						 RelationGetRelationName(rel));

	/*
	 * Preset objectAddress fields
	 */
	constrobj.classId = get_system_catalog_relid(ConstraintRelationName);
	constrobj.objectId = constrOid;
	constrobj.objectSubId = 0;
	trigobj.classId = get_system_catalog_relid(TriggerRelationName);
	trigobj.objectSubId = 0;

	/* Make changes-so-far visible */
	CommandCounterIncrement();

	/*
	 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the
	 * CHECK action.
	 */
	fk_trigger = makeNode(CreateTrigStmt);
	fk_trigger->trigname = fkconstraint->constr_name;
	fk_trigger->relation = myRel;
	fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
	fk_trigger->before = false;
	fk_trigger->row = true;
	fk_trigger->actions[0] = 'i';
	fk_trigger->actions[1] = 'u';
	fk_trigger->actions[2] = '\0';
	fk_trigger->lang = NULL;
	fk_trigger->text = NULL;

	fk_trigger->attr = NIL;
	fk_trigger->when = NULL;
	fk_trigger->isconstraint = true;
	fk_trigger->deferrable = fkconstraint->deferrable;
	fk_trigger->initdeferred = fkconstraint->initdeferred;
	fk_trigger->constrrel = fkconstraint->pktable;

	fk_trigger->args = NIL;
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkconstraint->constr_name));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(myRel->relname));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkconstraint->pktable->relname));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
	fk_attr = fkconstraint->fk_attrs;
	pk_attr = fkconstraint->pk_attrs;
	if (length(fk_attr) != length(pk_attr))
		elog(ERROR, "number of key attributes in referenced table must be equal to foreign key"
			 "\n\tIllegal FOREIGN KEY definition references \"%s\"",
			 fkconstraint->pktable->relname);

	while (fk_attr != NIL)
	{
		id = (Ident *) lfirst(fk_attr);
		fk_trigger->args = lappend(fk_trigger->args, makeString(id->name));

		id = (Ident *) lfirst(pk_attr);
		fk_trigger->args = lappend(fk_trigger->args, makeString(id->name));

		fk_attr = lnext(fk_attr);
		pk_attr = lnext(pk_attr);
	}

	trigobj.objectId = CreateTrigger(fk_trigger, true);

	/* Register dependency from trigger to constraint */
	recordDependencyOn(&trigobj, &constrobj, DEPENDENCY_INTERNAL);

	/* Make changes-so-far visible */
	CommandCounterIncrement();

	/*
	 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the
	 * ON DELETE action on the referenced table.
	 */
	fk_trigger = makeNode(CreateTrigStmt);
	fk_trigger->trigname = fkconstraint->constr_name;
	fk_trigger->relation = fkconstraint->pktable;
	fk_trigger->before = false;
	fk_trigger->row = true;
	fk_trigger->actions[0] = 'd';
	fk_trigger->actions[1] = '\0';
	fk_trigger->lang = NULL;
	fk_trigger->text = NULL;

	fk_trigger->attr = NIL;
	fk_trigger->when = NULL;
	fk_trigger->isconstraint = true;
	fk_trigger->deferrable = fkconstraint->deferrable;
	fk_trigger->initdeferred = fkconstraint->initdeferred;
	fk_trigger->constrrel = myRel;
	switch (fkconstraint->fk_del_action)
	{
		case FKCONSTR_ACTION_NOACTION:
			fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
			break;
		case FKCONSTR_ACTION_RESTRICT:
			fk_trigger->deferrable = false;
			fk_trigger->initdeferred = false;
			fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
			break;
		case FKCONSTR_ACTION_CASCADE:
			fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
			break;
		case FKCONSTR_ACTION_SETNULL:
			fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
			break;
		case FKCONSTR_ACTION_SETDEFAULT:
			fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
			break;
		default:
			elog(ERROR, "Unrecognized ON DELETE action for FOREIGN KEY constraint");
			break;
	}

	fk_trigger->args = NIL;
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkconstraint->constr_name));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(myRel->relname));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkconstraint->pktable->relname));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
	fk_attr = fkconstraint->fk_attrs;
	pk_attr = fkconstraint->pk_attrs;
	while (fk_attr != NIL)
	{
		id = (Ident *) lfirst(fk_attr);
		fk_trigger->args = lappend(fk_trigger->args, makeString(id->name));

		id = (Ident *) lfirst(pk_attr);
		fk_trigger->args = lappend(fk_trigger->args, makeString(id->name));

		fk_attr = lnext(fk_attr);
		pk_attr = lnext(pk_attr);
	}

	trigobj.objectId = CreateTrigger(fk_trigger, true);

	/* Register dependency from trigger to constraint */
	recordDependencyOn(&trigobj, &constrobj, DEPENDENCY_INTERNAL);

	/* Make changes-so-far visible */
	CommandCounterIncrement();

	/*
	 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the
	 * ON UPDATE action on the referenced table.
	 */
	fk_trigger = makeNode(CreateTrigStmt);
	fk_trigger->trigname = fkconstraint->constr_name;
	fk_trigger->relation = fkconstraint->pktable;
	fk_trigger->before = false;
	fk_trigger->row = true;
	fk_trigger->actions[0] = 'u';
	fk_trigger->actions[1] = '\0';
	fk_trigger->lang = NULL;
	fk_trigger->text = NULL;

	fk_trigger->attr = NIL;
	fk_trigger->when = NULL;
	fk_trigger->isconstraint = true;
	fk_trigger->deferrable = fkconstraint->deferrable;
	fk_trigger->initdeferred = fkconstraint->initdeferred;
	fk_trigger->constrrel = myRel;
	switch (fkconstraint->fk_upd_action)
	{
		case FKCONSTR_ACTION_NOACTION:
			fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
			break;
		case FKCONSTR_ACTION_RESTRICT:
			fk_trigger->deferrable = false;
			fk_trigger->initdeferred = false;
			fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
			break;
		case FKCONSTR_ACTION_CASCADE:
			fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
			break;
		case FKCONSTR_ACTION_SETNULL:
			fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
			break;
		case FKCONSTR_ACTION_SETDEFAULT:
			fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
			break;
		default:
			elog(ERROR, "Unrecognized ON UPDATE action for FOREIGN KEY constraint");
			break;
	}

	fk_trigger->args = NIL;
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkconstraint->constr_name));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(myRel->relname));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkconstraint->pktable->relname));
	fk_trigger->args = lappend(fk_trigger->args,
							   makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
	fk_attr = fkconstraint->fk_attrs;
	pk_attr = fkconstraint->pk_attrs;
	while (fk_attr != NIL)
	{
		id = (Ident *) lfirst(fk_attr);
		fk_trigger->args = lappend(fk_trigger->args, makeString(id->name));

		id = (Ident *) lfirst(pk_attr);
		fk_trigger->args = lappend(fk_trigger->args, makeString(id->name));

		fk_attr = lnext(fk_attr);
		pk_attr = lnext(pk_attr);
	}

	trigobj.objectId = CreateTrigger(fk_trigger, true);

	/* Register dependency from trigger to constraint */
	recordDependencyOn(&trigobj, &constrobj, DEPENDENCY_INTERNAL);
}

/*
 * fkMatchTypeToString -
 *	  convert FKCONSTR_MATCH_xxx code to string to use in trigger args
 */
static char *
fkMatchTypeToString(char match_type)
{
	switch (match_type) 
	{
		case FKCONSTR_MATCH_FULL:
			return pstrdup("FULL");
		case FKCONSTR_MATCH_PARTIAL:
			return pstrdup("PARTIAL");
		case FKCONSTR_MATCH_UNSPECIFIED:
			return pstrdup("UNSPECIFIED");
		default:
			elog(ERROR, "fkMatchTypeToString: Unknown MATCH TYPE '%c'",
				 match_type);
	}
	return NULL;				/* can't get here */
}
3037

3038
/*
3039
 * ALTER TABLE DROP CONSTRAINT
3040 3041
 */
void
3042 3043
AlterTableDropConstraint(Oid myrelid,
						 bool inh, const char *constrName,
3044
						 DropBehavior behavior)
3045
{
3046
	Relation	rel;
3047
	int			deleted = 0;
3048 3049

	/*
3050 3051
	 * Acquire an exclusive lock on the target relation for the duration
	 * of the operation.
3052
	 */
3053
	rel = heap_open(myrelid, AccessExclusiveLock);
3054

3055 3056 3057 3058
	/* Disallow DROP CONSTRAINT on views, indexes, sequences, etc */
	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 RelationGetRelationName(rel));
3059

3060 3061 3062 3063 3064 3065
	if (!allowSystemTableMods
		&& IsSystemRelation(rel))
		elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
			 RelationGetRelationName(rel));

	if (!pg_class_ownercheck(myrelid, GetUserId()))
3066
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
3067 3068

	/*
3069
	 * Process child tables if requested.
3070
	 */
3071 3072 3073 3074
	if (inh)
	{
		List	   *child,
				   *children;
3075

3076 3077
		/* This routine is actually in the planner */
		children = find_all_inheritors(myrelid);
3078

3079 3080 3081 3082 3083 3084 3085 3086 3087
		/*
		 * 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);
			Relation	inhrel;
3088

3089 3090 3091 3092 3093 3094 3095 3096
			if (childrelid == myrelid)
				continue;
			inhrel = heap_open(childrelid, AccessExclusiveLock);
			/* do NOT count child constraints in deleted. */
			RemoveRelConstraints(inhrel, constrName, behavior);
			heap_close(inhrel, NoLock);
		}
	}
3097 3098

	/*
3099
	 * Now do the thing on this relation.
3100
	 */
3101
	deleted += RemoveRelConstraints(rel, constrName, behavior);
3102

3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
	/* 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");
}

/*
 * ALTER TABLE OWNER
3117
 */
3118 3119
void
AlterTableOwner(Oid relationOid, int32 newOwnerSysId)
3120
{
3121 3122 3123 3124 3125
	Relation		target_rel;
	Relation		class_rel;
	HeapTuple		tuple;
	Relation		idescs[Num_pg_class_indices];
	Form_pg_class	tuple_class;
3126

3127
	/* Get exclusive lock till end of transaction on the target table */
3128 3129
	/* Use relation_open here so that we work on indexes... */
	target_rel = relation_open(relationOid, AccessExclusiveLock);
3130

3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
	/* Get its pg_class tuple, too */
	class_rel = heap_openr(RelationRelationName, RowExclusiveLock);

	tuple = SearchSysCacheCopy(RELOID,
							   ObjectIdGetDatum(relationOid),
							   0, 0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "ALTER TABLE: relation %u not found", relationOid);
	tuple_class = (Form_pg_class) GETSTRUCT(tuple);

	/* Can we change the ownership of this tuple? */
	CheckTupleType(tuple_class);
3143 3144

	/*
3145 3146
	 * Okay, this is a valid tuple: change its ownership and
	 * write to the heap.
3147
	 */
3148 3149
	tuple_class->relowner = newOwnerSysId;
	simple_heap_update(class_rel, &tuple->t_self, tuple);
3150

3151 3152 3153 3154
	/* 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);
3155 3156

	/*
3157 3158 3159
	 * If we are operating on a table, also change the ownership of any
	 * indexes that belong to the table, as well as the table's toast
	 * table (if it has one)
3160
	 */
3161 3162
	if (tuple_class->relkind == RELKIND_RELATION ||
		tuple_class->relkind == RELKIND_TOASTVALUE)
3163
	{
3164
		List *index_oid_list, *i;
3165

3166 3167
		/* Find all the indexes belonging to this relation */
		index_oid_list = RelationGetIndexList(target_rel);
3168

3169 3170 3171 3172 3173
		/* For each index, recursively change its ownership */
		foreach(i, index_oid_list)
		{
			AlterTableOwner(lfirsti(i), newOwnerSysId);
		}
3174

3175 3176
		freeList(index_oid_list);
	}
3177

3178 3179 3180 3181 3182 3183
	if (tuple_class->relkind == RELKIND_RELATION)
	{
		/* If it has a toast table, recurse to change its ownership */
		if (tuple_class->reltoastrelid != InvalidOid)
		{
			AlterTableOwner(tuple_class->reltoastrelid, newOwnerSysId);
3184 3185 3186
		}
	}

3187 3188
	heap_freetuple(tuple);
	heap_close(class_rel, RowExclusiveLock);
3189
	relation_close(target_rel, NoLock);
3190 3191
}

3192 3193
static void
CheckTupleType(Form_pg_class tuple_class)
3194
{
3195
	switch (tuple_class->relkind)
3196
	{
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
		case RELKIND_RELATION:
		case RELKIND_INDEX:
		case RELKIND_VIEW:
		case RELKIND_SEQUENCE:
		case RELKIND_TOASTVALUE:
			/* ok to change owner */
			break;
		default:
			elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table, TOAST table, index, view, or sequence",
				 NameStr(tuple_class->relname));
3207 3208 3209 3210
	}
}

/*
3211
 * ALTER TABLE CREATE TOAST TABLE
3212
 */
3213 3214
void
AlterTableCreateToastTable(Oid relOid, bool silent)
3215
{
3216 3217 3218 3219
	Relation	rel;
	HeapTuple	reltup;
	HeapTupleData classtuple;
	TupleDesc	tupdesc;
3220
	bool		shared_relation;
3221 3222 3223 3224 3225 3226 3227 3228 3229
	Relation	class_rel;
	Buffer		buffer;
	Relation	ridescs[Num_pg_class_indices];
	Oid			toast_relid;
	Oid			toast_idxid;
	char		toast_relname[NAMEDATALEN];
	char		toast_idxname[NAMEDATALEN];
	IndexInfo  *indexInfo;
	Oid			classObjectId[2];
3230 3231
	ObjectAddress baseobject,
				toastobject;
3232

3233 3234 3235 3236 3237
	/*
	 * Grab an exclusive lock on the target table, which we will NOT
	 * release until end of transaction.
	 */
	rel = heap_open(relOid, AccessExclusiveLock);
3238

3239
	/* Check permissions */
3240 3241 3242
	if (rel->rd_rel->relkind != RELKIND_RELATION)
		elog(ERROR, "ALTER TABLE: relation \"%s\" is not a table",
			 RelationGetRelationName(rel));
3243

3244
	if (!pg_class_ownercheck(relOid, GetUserId()))
3245
		aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
3246

3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
	/*
	 * Toast table is shared if and only if its parent is.
	 *
	 * We cannot allow toasting a shared relation after initdb (because
	 * there's no way to mark it toasted in other databases' pg_class).
	 * Unfortunately we can't distinguish initdb from a manually started
	 * standalone backend.  However, we can at least prevent this mistake
	 * under normal multi-user operation.
	 */
	shared_relation = rel->rd_rel->relisshared;
	if (shared_relation && IsUnderPostmaster)
		elog(ERROR, "Shared relations cannot be toasted after initdb");

3260 3261 3262 3263
	/*
	 * lock the pg_class tuple for update (is that really needed?)
	 */
	class_rel = heap_openr(RelationRelationName, RowExclusiveLock);
3264

3265 3266 3267 3268 3269 3270 3271 3272 3273
	reltup = SearchSysCache(RELOID,
							ObjectIdGetDatum(relOid),
							0, 0, 0);
	if (!HeapTupleIsValid(reltup))
		elog(ERROR, "ALTER TABLE: relation \"%s\" not found",
			 RelationGetRelationName(rel));
	classtuple.t_self = reltup->t_self;
	ReleaseSysCache(reltup);

3274 3275
	switch (heap_mark4update(class_rel, &classtuple, &buffer,
							 GetCurrentCommandId()))
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
	{
		case HeapTupleSelfUpdated:
		case HeapTupleMayBeUpdated:
			break;
		default:
			elog(ERROR, "couldn't lock pg_class tuple");
	}
	reltup = heap_copytuple(&classtuple);
	ReleaseBuffer(buffer);

	/*
	 * Is it already toasted?
	 */
	if (((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid != InvalidOid)
	{
		if (silent)
3292
		{
3293 3294 3295 3296
			heap_close(rel, NoLock);
			heap_close(class_rel, NoLock);
			heap_freetuple(reltup);
			return;
3297 3298
		}

3299 3300 3301
		elog(ERROR, "ALTER TABLE: relation \"%s\" already has a toast table",
			 RelationGetRelationName(rel));
	}
3302

3303 3304 3305 3306 3307 3308
	/*
	 * Check to see whether the table actually needs a TOAST table.
	 */
	if (!needs_toast_table(rel))
	{
		if (silent)
3309
		{
3310 3311 3312 3313
			heap_close(rel, NoLock);
			heap_close(class_rel, NoLock);
			heap_freetuple(reltup);
			return;
3314 3315
		}

3316 3317 3318
		elog(ERROR, "ALTER TABLE: relation \"%s\" does not need a toast table",
			 RelationGetRelationName(rel));
	}
3319

3320 3321 3322 3323 3324
	/*
	 * Create the toast table and its index
	 */
	sprintf(toast_relname, "pg_toast_%u", relOid);
	sprintf(toast_idxname, "pg_toast_%u_index", relOid);
3325

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
	/* 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",
					   BYTEAOID,
					   -1, 0, false);
3340

3341 3342 3343 3344 3345 3346 3347 3348
	/*
	 * 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.
	 */
	tupdesc->attrs[0]->attstorage = 'p';
	tupdesc->attrs[1]->attstorage = 'p';
	tupdesc->attrs[2]->attstorage = 'p';
3349

3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
	/*
	 * Note: the toast relation is placed in the regular pg_toast namespace
	 * 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.
	 */
	toast_relid = heap_create_with_catalog(toast_relname,
										   PG_TOAST_NAMESPACE,
										   tupdesc,
										   RELKIND_TOASTVALUE,
3360
										   shared_relation,
3361 3362
										   false,
										   true);
3363

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

3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
	/*
	 * Create unique index on chunk_id, chunk_seq.
	 *
	 * NOTE: the tuple toaster could actually function with a single-column
	 * index on chunk_id only.	However, it couldn't be unique then.  We
	 * want it to be unique as a check against the possibility of
	 * duplicate TOAST chunk OIDs.	Too, the index might be a little more
	 * efficient this way, since btree isn't all that happy with large
	 * numbers of equal keys.
	 */
3377

3378 3379 3380 3381 3382 3383 3384 3385
	indexInfo = makeNode(IndexInfo);
	indexInfo->ii_NumIndexAttrs = 2;
	indexInfo->ii_NumKeyAttrs = 2;
	indexInfo->ii_KeyAttrNumbers[0] = 1;
	indexInfo->ii_KeyAttrNumbers[1] = 2;
	indexInfo->ii_Predicate = NIL;
	indexInfo->ii_FuncOid = InvalidOid;
	indexInfo->ii_Unique = true;
3386

3387 3388
	classObjectId[0] = OID_BTREE_OPS_OID;
	classObjectId[1] = INT4_BTREE_OPS_OID;
3389

3390 3391
	toast_idxid = index_create(toast_relid, toast_idxname, indexInfo,
							   BTREE_AM_OID, classObjectId,
3392
							   true, false, true);
3393

3394 3395 3396 3397 3398 3399
	/*
	 * Update toast rel's pg_class entry to show that it has an index. The
	 * index OID is stored into the reltoastidxid field for easy access by
	 * the tuple toaster.
	 */
	setRelhasindex(toast_relid, true, true, toast_idxid);
3400 3401

	/*
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415
	 * Store the toast table's OID in the parent relation's tuple
	 */
	((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
	simple_heap_update(class_rel, &reltup->t_self, reltup);

	/*
	 * Keep catalog indices current
	 */
	CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, ridescs);
	CatalogIndexInsert(ridescs, Num_pg_class_indices, class_rel, reltup);
	CatalogCloseIndices(Num_pg_class_indices, ridescs);

	heap_freetuple(reltup);

3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
	/*
	 * Register dependency from the toast table to the master, so that
	 * the toast table will be deleted if the master is.
	 */
	baseobject.classId = RelOid_pg_class;
	baseobject.objectId = relOid;
	baseobject.objectSubId = 0;
	toastobject.classId = RelOid_pg_class;
	toastobject.objectId = toast_relid;
	toastobject.objectSubId = 0;

	recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);

3429 3430
	/*
	 * Close relations and make changes visible
3431
	 */
3432 3433 3434
	heap_close(class_rel, NoLock);
	heap_close(rel, NoLock);

3435
	CommandCounterIncrement();
3436
}
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487

/*
 * Check to see whether the table needs a TOAST table.	It does only if
 * (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;
	Form_pg_attribute *att;
	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
		{
			int32		maxlen = type_maximum_size(att[i]->atttypid,
												   att[i]->atttypmod);

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