1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.343 2008/11/09 21:24:32 tgl Exp $
15 * heap_create() - Create an uncataloged heap relation
16 * heap_create_with_catalog() - Create a cataloged relation
17 * heap_drop_with_catalog() - Removes named relation from catalogs
20 * this code taken from access/heap/create.c, which contains
21 * the old heap_create_with_catalog, amcreate, and amdestroy.
22 * those routines will soon call these routines using the function
24 * just like the poorly named "NewXXX" routines do. The
25 * "New" routines are all going to die soon, once and for all!
28 *-------------------------------------------------------------------------
32 #include "access/genam.h"
33 #include "access/heapam.h"
34 #include "access/sysattr.h"
35 #include "access/transam.h"
36 #include "access/xact.h"
37 #include "catalog/catalog.h"
38 #include "catalog/dependency.h"
39 #include "catalog/heap.h"
40 #include "catalog/index.h"
41 #include "catalog/indexing.h"
42 #include "catalog/pg_attrdef.h"
43 #include "catalog/pg_constraint.h"
44 #include "catalog/pg_inherits.h"
45 #include "catalog/pg_namespace.h"
46 #include "catalog/pg_statistic.h"
47 #include "catalog/pg_tablespace.h"
48 #include "catalog/pg_type.h"
49 #include "catalog/pg_type_fn.h"
50 #include "commands/tablecmds.h"
51 #include "commands/typecmds.h"
52 #include "miscadmin.h"
53 #include "nodes/nodeFuncs.h"
54 #include "optimizer/var.h"
55 #include "parser/parse_coerce.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_relation.h"
58 #include "storage/bufmgr.h"
59 #include "storage/freespace.h"
60 #include "storage/smgr.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/inval.h"
64 #include "utils/lsyscache.h"
65 #include "utils/relcache.h"
66 #include "utils/snapmgr.h"
67 #include "utils/syscache.h"
68 #include "utils/tqual.h"
71 static void AddNewRelationTuple(Relation pg_class_desc,
72 Relation new_rel_desc,
73 Oid new_rel_oid, Oid new_type_oid,
77 static Oid AddNewRelationType(const char *typeName,
82 static void RelationRemoveInheritance(Oid relid);
83 static void StoreRelCheck(Relation rel, char *ccname, Node *expr,
84 bool is_local, int inhcount);
85 static void StoreConstraints(Relation rel, List *cooked_constraints);
86 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
87 bool allow_merge, bool is_local);
88 static void SetRelationNumChecks(Relation rel, int numchecks);
89 static Node *cookConstraint(ParseState *pstate,
92 static List *insert_ordered_unique_oid(List *list, Oid datum);
95 /* ----------------------------------------------------------------
96 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
98 * these should all be moved to someplace in the lib/catalog
99 * module, if not obliterated first.
100 * ----------------------------------------------------------------
106 * Should the system special case these attributes in the future?
107 * Advantage: consume much less space in the ATTRIBUTE relation.
108 * Disadvantage: special cases will be all over the place.
111 static FormData_pg_attribute a1 = {
112 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
113 SelfItemPointerAttributeNumber, 0, -1, -1,
114 false, 'p', 's', true, false, false, true, 0
117 static FormData_pg_attribute a2 = {
118 0, {"oid"}, OIDOID, 0, sizeof(Oid),
119 ObjectIdAttributeNumber, 0, -1, -1,
120 true, 'p', 'i', true, false, false, true, 0
123 static FormData_pg_attribute a3 = {
124 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
125 MinTransactionIdAttributeNumber, 0, -1, -1,
126 true, 'p', 'i', true, false, false, true, 0
129 static FormData_pg_attribute a4 = {
130 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
131 MinCommandIdAttributeNumber, 0, -1, -1,
132 true, 'p', 'i', true, false, false, true, 0
135 static FormData_pg_attribute a5 = {
136 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
137 MaxTransactionIdAttributeNumber, 0, -1, -1,
138 true, 'p', 'i', true, false, false, true, 0
141 static FormData_pg_attribute a6 = {
142 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
143 MaxCommandIdAttributeNumber, 0, -1, -1,
144 true, 'p', 'i', true, false, false, true, 0
148 * We decided to call this attribute "tableoid" rather than say
149 * "classoid" on the basis that in the future there may be more than one
150 * table of a particular class/type. In any case table is still the word
153 static FormData_pg_attribute a7 = {
154 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
155 TableOidAttributeNumber, 0, -1, -1,
156 true, 'p', 'i', true, false, false, true, 0
159 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
162 * This function returns a Form_pg_attribute pointer for a system attribute.
163 * Note that we elog if the presented attno is invalid, which would only
164 * happen if there's a problem upstream.
167 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
169 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
170 elog(ERROR, "invalid system attribute number %d", attno);
171 if (attno == ObjectIdAttributeNumber && !relhasoids)
172 elog(ERROR, "invalid system attribute number %d", attno);
173 return SysAtt[-attno - 1];
177 * If the given name is a system attribute name, return a Form_pg_attribute
178 * pointer for a prototype definition. If not, return NULL.
181 SystemAttributeByName(const char *attname, bool relhasoids)
185 for (j = 0; j < (int) lengthof(SysAtt); j++)
187 Form_pg_attribute att = SysAtt[j];
189 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
191 if (strcmp(NameStr(att->attname), attname) == 0)
200 /* ----------------------------------------------------------------
201 * XXX END OF UGLY HARD CODED BADNESS XXX
202 * ---------------------------------------------------------------- */
205 /* ----------------------------------------------------------------
206 * heap_create - Create an uncataloged heap relation
208 * Note API change: the caller must now always provide the OID
209 * to use for the relation.
211 * rel->rd_rel is initialized by RelationBuildLocalRelation,
212 * and is mostly zeroes at return.
213 * ----------------------------------------------------------------
216 heap_create(const char *relname,
222 bool shared_relation,
223 bool allow_system_table_mods)
228 /* The caller must have provided an OID for the relation. */
229 Assert(OidIsValid(relid));
234 if (!allow_system_table_mods &&
235 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
236 IsNormalProcessingMode())
238 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
239 errmsg("permission denied to create \"%s.%s\"",
240 get_namespace_name(relnamespace), relname),
241 errdetail("System catalog modifications are currently disallowed.")));
244 * Decide if we need storage or not, and handle a couple other special
245 * cases for particular relkinds.
250 case RELKIND_COMPOSITE_TYPE:
251 create_storage = false;
254 * Force reltablespace to zero if the relation has no physical
255 * storage. This is mainly just for cleanliness' sake.
257 reltablespace = InvalidOid;
259 case RELKIND_SEQUENCE:
260 create_storage = true;
263 * Force reltablespace to zero for sequences, since we don't
264 * support moving them around into different tablespaces.
266 reltablespace = InvalidOid;
269 create_storage = true;
274 * Never allow a pg_class entry to explicitly specify the database's
275 * default tablespace in reltablespace; force it to zero instead. This
276 * ensures that if the database is cloned with a different default
277 * tablespace, the pg_class entry will still match where CREATE DATABASE
278 * will put the physically copied relation.
280 * Yes, this is a bit of a hack.
282 if (reltablespace == MyDatabaseTableSpace)
283 reltablespace = InvalidOid;
286 * build the relcache entry.
288 rel = RelationBuildLocalRelation(relname,
296 * Have the storage manager create the relation's disk file, if needed.
298 * We create storage for the main fork here, and also for the FSM for a
299 * heap or toast relation. The caller is responsible for creating any
300 * additional forks if needed.
304 Assert(rel->rd_smgr == NULL);
305 RelationOpenSmgr(rel);
306 smgrcreate(rel->rd_smgr, MAIN_FORKNUM, rel->rd_istemp, false);
309 * For a real heap, create FSM fork as well. Indexams are
310 * responsible for creating any extra forks themselves.
312 if (relkind == RELKIND_RELATION || relkind == RELKIND_TOASTVALUE)
313 smgrcreate(rel->rd_smgr, FSM_FORKNUM, rel->rd_istemp, false);
319 /* ----------------------------------------------------------------
320 * heap_create_with_catalog - Create a cataloged relation
322 * this is done in multiple steps:
324 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
325 * descriptor contains a valid set of attribute names and types
327 * 2) pg_class is opened and get_relname_relid()
328 * performs a scan to ensure that no relation with the
329 * same name already exists.
331 * 3) heap_create() is called to create the new relation on disk.
333 * 4) TypeCreate() is called to define a new type corresponding
334 * to the new relation.
336 * 5) AddNewRelationTuple() is called to register the
337 * relation in pg_class.
339 * 6) AddNewAttributeTuples() is called to register the
340 * new relation's schema in pg_attribute.
342 * 7) StoreConstraints is called () - vadim 08/22/97
344 * 8) the relations are closed and the new relation's oid
347 * ----------------------------------------------------------------
350 /* --------------------------------
351 * CheckAttributeNamesTypes
353 * this is used to make certain the tuple descriptor contains a
354 * valid set of attribute names and datatypes. a problem simply
355 * generates ereport(ERROR) which aborts the current transaction.
356 * --------------------------------
359 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
363 int natts = tupdesc->natts;
365 /* Sanity check on column count */
366 if (natts < 0 || natts > MaxHeapAttributeNumber)
368 (errcode(ERRCODE_TOO_MANY_COLUMNS),
369 errmsg("tables can have at most %d columns",
370 MaxHeapAttributeNumber)));
373 * first check for collision with system attribute names
375 * Skip this for a view or type relation, since those don't have system
378 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
380 for (i = 0; i < natts; i++)
382 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
383 tupdesc->tdhasoid) != NULL)
385 (errcode(ERRCODE_DUPLICATE_COLUMN),
386 errmsg("column name \"%s\" conflicts with a system column name",
387 NameStr(tupdesc->attrs[i]->attname))));
392 * next check for repeated attribute names
394 for (i = 1; i < natts; i++)
396 for (j = 0; j < i; j++)
398 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
399 NameStr(tupdesc->attrs[i]->attname)) == 0)
401 (errcode(ERRCODE_DUPLICATE_COLUMN),
402 errmsg("column name \"%s\" specified more than once",
403 NameStr(tupdesc->attrs[j]->attname))));
408 * next check the attribute types
410 for (i = 0; i < natts; i++)
412 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
413 tupdesc->attrs[i]->atttypid);
417 /* --------------------------------
420 * Verify that the proposed datatype of an attribute is legal.
421 * This is needed because there are types (and pseudo-types)
422 * in the catalogs that we do not support as elements of real tuples.
423 * --------------------------------
426 CheckAttributeType(const char *attname, Oid atttypid)
428 char att_typtype = get_typtype(atttypid);
430 if (atttypid == UNKNOWNOID)
433 * Warn user, but don't fail, if column to be created has UNKNOWN type
434 * (usually as a result of a 'retrieve into' - jolly)
437 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
438 errmsg("column \"%s\" has type \"unknown\"", attname),
439 errdetail("Proceeding with relation creation anyway.")));
441 else if (att_typtype == TYPTYPE_PSEUDO)
444 * Refuse any attempt to create a pseudo-type column, except for a
445 * special hack for pg_statistic: allow ANYARRAY during initdb
447 if (atttypid != ANYARRAYOID || IsUnderPostmaster)
449 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
450 errmsg("column \"%s\" has pseudo-type %s",
451 attname, format_type_be(atttypid))));
453 else if (att_typtype == TYPTYPE_COMPOSITE)
456 * For a composite type, recurse into its attributes. You might think
457 * this isn't necessary, but since we allow system catalogs to break
458 * the rule, we have to guard against the case.
464 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
466 tupdesc = RelationGetDescr(relation);
468 for (i = 0; i < tupdesc->natts; i++)
470 Form_pg_attribute attr = tupdesc->attrs[i];
472 if (attr->attisdropped)
474 CheckAttributeType(NameStr(attr->attname), attr->atttypid);
477 relation_close(relation, AccessShareLock);
481 /* --------------------------------
482 * AddNewAttributeTuples
484 * this registers the new relation's schema by adding
485 * tuples to pg_attribute.
486 * --------------------------------
489 AddNewAttributeTuples(Oid new_rel_oid,
495 const Form_pg_attribute *dpp;
499 CatalogIndexState indstate;
500 int natts = tupdesc->natts;
501 ObjectAddress myself,
505 * open pg_attribute and its indexes.
507 rel = heap_open(AttributeRelationId, RowExclusiveLock);
509 indstate = CatalogOpenIndexes(rel);
512 * First we add the user attributes. This is also a convenient place to
513 * add dependencies on their datatypes.
515 dpp = tupdesc->attrs;
516 for (i = 0; i < natts; i++)
518 /* Fill in the correct relation OID */
519 (*dpp)->attrelid = new_rel_oid;
520 /* Make sure these are OK, too */
521 (*dpp)->attstattarget = -1;
522 (*dpp)->attcacheoff = -1;
524 tup = heap_addheader(Natts_pg_attribute,
526 ATTRIBUTE_TUPLE_SIZE,
529 simple_heap_insert(rel, tup);
531 CatalogIndexInsert(indstate, tup);
535 myself.classId = RelationRelationId;
536 myself.objectId = new_rel_oid;
537 myself.objectSubId = i + 1;
538 referenced.classId = TypeRelationId;
539 referenced.objectId = (*dpp)->atttypid;
540 referenced.objectSubId = 0;
541 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
547 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
548 * all for a view or type relation. We don't bother with making datatype
549 * dependencies here, since presumably all these types are pinned.
551 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
554 for (i = 0; i < (int) lengthof(SysAtt); i++, dpp++)
556 if (tupdesc->tdhasoid ||
557 (*dpp)->attnum != ObjectIdAttributeNumber)
559 Form_pg_attribute attStruct;
561 tup = heap_addheader(Natts_pg_attribute,
563 ATTRIBUTE_TUPLE_SIZE,
565 attStruct = (Form_pg_attribute) GETSTRUCT(tup);
567 /* Fill in the correct relation OID in the copied tuple */
568 attStruct->attrelid = new_rel_oid;
570 /* Fill in correct inheritance info for the OID column */
571 if (attStruct->attnum == ObjectIdAttributeNumber)
573 attStruct->attislocal = oidislocal;
574 attStruct->attinhcount = oidinhcount;
578 * Unneeded since they should be OK in the constant data
581 /* attStruct->attstattarget = 0; */
582 /* attStruct->attcacheoff = -1; */
584 simple_heap_insert(rel, tup);
586 CatalogIndexInsert(indstate, tup);
596 CatalogCloseIndexes(indstate);
598 heap_close(rel, RowExclusiveLock);
601 /* --------------------------------
604 * Construct and insert a new tuple in pg_class.
606 * Caller has already opened and locked pg_class.
607 * Tuple data is taken from new_rel_desc->rd_rel, except for the
608 * variable-width fields which are not present in a cached reldesc.
609 * We always initialize relacl to NULL (i.e., default permissions),
610 * and reloptions is set to the passed-in text array (if any).
611 * --------------------------------
614 InsertPgClassTuple(Relation pg_class_desc,
615 Relation new_rel_desc,
619 Form_pg_class rd_rel = new_rel_desc->rd_rel;
620 Datum values[Natts_pg_class];
621 bool nulls[Natts_pg_class];
624 /* This is a tad tedious, but way cleaner than what we used to do... */
625 memset(values, 0, sizeof(values));
626 memset(nulls, false, sizeof(nulls));
628 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
629 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
630 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
631 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
632 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
633 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
634 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
635 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
636 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
637 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
638 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
639 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
640 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
641 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
642 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
643 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
644 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
645 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
646 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
647 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
648 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
649 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
650 /* start out with empty permissions */
651 nulls[Anum_pg_class_relacl - 1] = true;
652 if (reloptions != (Datum) 0)
653 values[Anum_pg_class_reloptions - 1] = reloptions;
655 nulls[Anum_pg_class_reloptions - 1] = true;
657 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
660 * The new tuple must have the oid already chosen for the rel. Sure would
661 * be embarrassing to do this sort of thing in polite company.
663 HeapTupleSetOid(tup, new_rel_oid);
665 /* finally insert the new tuple, update the indexes, and clean up */
666 simple_heap_insert(pg_class_desc, tup);
668 CatalogUpdateIndexes(pg_class_desc, tup);
673 /* --------------------------------
674 * AddNewRelationTuple
676 * this registers the new relation in the catalogs by
677 * adding a tuple to pg_class.
678 * --------------------------------
681 AddNewRelationTuple(Relation pg_class_desc,
682 Relation new_rel_desc,
689 Form_pg_class new_rel_reltup;
692 * first we update some of the information in our uncataloged relation's
693 * relation descriptor.
695 new_rel_reltup = new_rel_desc->rd_rel;
699 case RELKIND_RELATION:
701 case RELKIND_TOASTVALUE:
702 /* The relation is real, but as yet empty */
703 new_rel_reltup->relpages = 0;
704 new_rel_reltup->reltuples = 0;
706 case RELKIND_SEQUENCE:
707 /* Sequences always have a known size */
708 new_rel_reltup->relpages = 1;
709 new_rel_reltup->reltuples = 1;
712 /* Views, etc, have no disk storage */
713 new_rel_reltup->relpages = 0;
714 new_rel_reltup->reltuples = 0;
718 /* Initialize relfrozenxid */
719 if (relkind == RELKIND_RELATION ||
720 relkind == RELKIND_TOASTVALUE)
723 * Initialize to the minimum XID that could put tuples in the table.
724 * We know that no xacts older than RecentXmin are still running, so
727 new_rel_reltup->relfrozenxid = RecentXmin;
732 * Other relation types will not contain XIDs, so set relfrozenxid to
733 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
734 * we force its xmin to be FrozenTransactionId always; see
735 * commands/sequence.c.)
737 new_rel_reltup->relfrozenxid = InvalidTransactionId;
740 new_rel_reltup->relowner = relowner;
741 new_rel_reltup->reltype = new_type_oid;
742 new_rel_reltup->relkind = relkind;
744 new_rel_desc->rd_att->tdtypeid = new_type_oid;
746 /* Now build and insert the tuple */
747 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid, reloptions);
751 /* --------------------------------
752 * AddNewRelationType -
754 * define a composite type corresponding to the new relation
755 * --------------------------------
758 AddNewRelationType(const char *typeName,
765 TypeCreate(InvalidOid, /* no predetermined OID */
766 typeName, /* type name */
767 typeNamespace, /* type namespace */
768 new_rel_oid, /* relation oid */
769 new_rel_kind, /* relation kind */
770 -1, /* internal size (varlena) */
771 TYPTYPE_COMPOSITE, /* type-type (composite) */
772 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
773 false, /* composite types are never preferred */
774 DEFAULT_TYPDELIM, /* default array delimiter */
775 F_RECORD_IN, /* input procedure */
776 F_RECORD_OUT, /* output procedure */
777 F_RECORD_RECV, /* receive procedure */
778 F_RECORD_SEND, /* send procedure */
779 InvalidOid, /* typmodin procedure - none */
780 InvalidOid, /* typmodout procedure - none */
781 InvalidOid, /* analyze procedure - default */
782 InvalidOid, /* array element type - irrelevant */
783 false, /* this is not an array type */
784 new_array_type, /* array type if any */
785 InvalidOid, /* domain base type - irrelevant */
786 NULL, /* default value - none */
787 NULL, /* default binary representation */
788 false, /* passed by reference */
789 'd', /* alignment - must be the largest! */
790 'x', /* fully TOASTable */
792 0, /* array dimensions for typBaseType */
793 false); /* Type NOT NULL */
796 /* --------------------------------
797 * heap_create_with_catalog
799 * creates a new cataloged relation. see comments above.
800 * --------------------------------
803 heap_create_with_catalog(const char *relname,
809 List *cooked_constraints,
811 bool shared_relation,
814 OnCommitAction oncommit,
816 bool allow_system_table_mods)
818 Relation pg_class_desc;
819 Relation new_rel_desc;
822 Oid new_array_oid = InvalidOid;
824 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
829 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
831 CheckAttributeNamesTypes(tupdesc, relkind);
833 if (get_relname_relid(relname, relnamespace))
835 (errcode(ERRCODE_DUPLICATE_TABLE),
836 errmsg("relation \"%s\" already exists", relname)));
839 * Since we are going to create a rowtype as well, also check for
840 * collision with an existing type name. If there is one and it's an
841 * autogenerated array, we can rename it out of the way; otherwise we can
842 * at least give a good error message.
844 old_type_oid = GetSysCacheOid(TYPENAMENSP,
845 CStringGetDatum(relname),
846 ObjectIdGetDatum(relnamespace),
848 if (OidIsValid(old_type_oid))
850 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
852 (errcode(ERRCODE_DUPLICATE_OBJECT),
853 errmsg("type \"%s\" already exists", relname),
854 errhint("A relation has an associated type of the same name, "
855 "so you must use a name that doesn't conflict "
856 "with any existing type.")));
860 * Validate shared/non-shared tablespace (must check this before doing
861 * GetNewRelFileNode, to prevent Assert therein)
865 if (reltablespace != GLOBALTABLESPACE_OID)
866 /* elog since this is not a user-facing error */
868 "shared relations must be placed in pg_global tablespace");
872 if (reltablespace == GLOBALTABLESPACE_OID)
874 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
875 errmsg("only shared relations can be placed in pg_global tablespace")));
879 * Allocate an OID for the relation, unless we were told what to use.
881 * The OID will be the relfilenode as well, so make sure it doesn't
882 * collide with either pg_class OIDs or existing physical files.
884 if (!OidIsValid(relid))
885 relid = GetNewRelFileNode(reltablespace, shared_relation,
889 * Create the relcache entry (mostly dummy at this point) and the physical
890 * disk file. (If we fail further down, it's the smgr's responsibility to
891 * remove the disk file again.)
893 new_rel_desc = heap_create(relname,
900 allow_system_table_mods);
902 Assert(relid == RelationGetRelid(new_rel_desc));
905 * Decide whether to create an array type over the relation's rowtype. We
906 * do not create any array types for system catalogs (ie, those made
907 * during initdb). We create array types for regular relations, views,
908 * and composite types ... but not, eg, for toast tables or sequences.
910 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
911 relkind == RELKIND_VIEW ||
912 relkind == RELKIND_COMPOSITE_TYPE))
914 /* OK, so pre-assign a type OID for the array type */
915 Relation pg_type = heap_open(TypeRelationId, AccessShareLock);
917 new_array_oid = GetNewOid(pg_type);
918 heap_close(pg_type, AccessShareLock);
922 * Since defining a relation also defines a complex type, we add a new
923 * system type corresponding to the new relation.
925 * NOTE: we could get a unique-index failure here, in case someone else is
926 * creating the same type name in parallel but hadn't committed yet when
927 * we checked for a duplicate name above.
929 new_type_oid = AddNewRelationType(relname,
936 * Now make the array type if wanted.
938 if (OidIsValid(new_array_oid))
942 relarrayname = makeArrayTypeName(relname, relnamespace);
944 TypeCreate(new_array_oid, /* force the type's OID to this */
945 relarrayname, /* Array type name */
946 relnamespace, /* Same namespace as parent */
947 InvalidOid, /* Not composite, no relationOid */
948 0, /* relkind, also N/A here */
949 -1, /* Internal size (varlena) */
950 TYPTYPE_BASE, /* Not composite - typelem is */
951 TYPCATEGORY_ARRAY, /* type-category (array) */
952 false, /* array types are never preferred */
953 DEFAULT_TYPDELIM, /* default array delimiter */
954 F_ARRAY_IN, /* array input proc */
955 F_ARRAY_OUT, /* array output proc */
956 F_ARRAY_RECV, /* array recv (bin) proc */
957 F_ARRAY_SEND, /* array send (bin) proc */
958 InvalidOid, /* typmodin procedure - none */
959 InvalidOid, /* typmodout procedure - none */
960 InvalidOid, /* analyze procedure - default */
961 new_type_oid, /* array element type - the rowtype */
962 true, /* yes, this is an array type */
963 InvalidOid, /* this has no array type */
964 InvalidOid, /* domain base type - irrelevant */
965 NULL, /* default value - none */
966 NULL, /* default binary representation */
967 false, /* passed by reference */
968 'd', /* alignment - must be the largest! */
969 'x', /* fully TOASTable */
971 0, /* array dimensions for typBaseType */
972 false); /* Type NOT NULL */
978 * now create an entry in pg_class for the relation.
980 * NOTE: we could get a unique-index failure here, in case someone else is
981 * creating the same relation name in parallel but hadn't committed yet
982 * when we checked for a duplicate name above.
984 AddNewRelationTuple(pg_class_desc,
993 * now add tuples to pg_attribute for the attributes in our new relation.
995 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
996 oidislocal, oidinhcount);
999 * Make a dependency link to force the relation to be deleted if its
1000 * namespace is. Also make a dependency link to its owner.
1002 * For composite types, these dependencies are tracked for the pg_type
1003 * entry, so we needn't record them here. Likewise, TOAST tables don't
1004 * need a namespace dependency (they live in a pinned namespace) nor an
1005 * owner dependency (they depend indirectly through the parent table).
1006 * Also, skip this in bootstrap mode, since we don't make dependencies
1007 * while bootstrapping.
1009 if (relkind != RELKIND_COMPOSITE_TYPE &&
1010 relkind != RELKIND_TOASTVALUE &&
1011 !IsBootstrapProcessingMode())
1013 ObjectAddress myself,
1016 myself.classId = RelationRelationId;
1017 myself.objectId = relid;
1018 myself.objectSubId = 0;
1019 referenced.classId = NamespaceRelationId;
1020 referenced.objectId = relnamespace;
1021 referenced.objectSubId = 0;
1022 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1024 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1028 * Store any supplied constraints and defaults.
1030 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1031 * entry, so the relation must be valid and self-consistent at this point.
1032 * In particular, there are not yet constraints and defaults anywhere.
1034 StoreConstraints(new_rel_desc, cooked_constraints);
1037 * If there's a special on-commit action, remember it
1039 if (oncommit != ONCOMMIT_NOOP)
1040 register_on_commit_action(relid, oncommit);
1043 * ok, the relation has been cataloged, so close our relations and return
1044 * the OID of the newly created relation.
1046 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1047 heap_close(pg_class_desc, RowExclusiveLock);
1054 * RelationRemoveInheritance
1056 * Formerly, this routine checked for child relations and aborted the
1057 * deletion if any were found. Now we rely on the dependency mechanism
1058 * to check for or delete child relations. By the time we get here,
1059 * there are no children and we need only remove any pg_inherits rows
1060 * linking this relation to its parent(s).
1063 RelationRemoveInheritance(Oid relid)
1065 Relation catalogRelation;
1070 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1073 Anum_pg_inherits_inhrelid,
1074 BTEqualStrategyNumber, F_OIDEQ,
1075 ObjectIdGetDatum(relid));
1077 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1078 SnapshotNow, 1, &key);
1080 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1081 simple_heap_delete(catalogRelation, &tuple->t_self);
1083 systable_endscan(scan);
1084 heap_close(catalogRelation, RowExclusiveLock);
1088 * DeleteRelationTuple
1090 * Remove pg_class row for the given relid.
1092 * Note: this is shared by relation deletion and index deletion. It's
1093 * not intended for use anyplace else.
1096 DeleteRelationTuple(Oid relid)
1098 Relation pg_class_desc;
1101 /* Grab an appropriate lock on the pg_class relation */
1102 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1104 tup = SearchSysCache(RELOID,
1105 ObjectIdGetDatum(relid),
1107 if (!HeapTupleIsValid(tup))
1108 elog(ERROR, "cache lookup failed for relation %u", relid);
1110 /* delete the relation tuple from pg_class, and finish up */
1111 simple_heap_delete(pg_class_desc, &tup->t_self);
1113 ReleaseSysCache(tup);
1115 heap_close(pg_class_desc, RowExclusiveLock);
1119 * DeleteAttributeTuples
1121 * Remove pg_attribute rows for the given relid.
1123 * Note: this is shared by relation deletion and index deletion. It's
1124 * not intended for use anyplace else.
1127 DeleteAttributeTuples(Oid relid)
1134 /* Grab an appropriate lock on the pg_attribute relation */
1135 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1137 /* Use the index to scan only attributes of the target relation */
1138 ScanKeyInit(&key[0],
1139 Anum_pg_attribute_attrelid,
1140 BTEqualStrategyNumber, F_OIDEQ,
1141 ObjectIdGetDatum(relid));
1143 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1144 SnapshotNow, 1, key);
1146 /* Delete all the matching tuples */
1147 while ((atttup = systable_getnext(scan)) != NULL)
1148 simple_heap_delete(attrel, &atttup->t_self);
1150 /* Clean up after the scan */
1151 systable_endscan(scan);
1152 heap_close(attrel, RowExclusiveLock);
1156 * RemoveAttributeById
1158 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1159 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1160 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1161 * is handled by dependency.c.)
1164 RemoveAttributeById(Oid relid, AttrNumber attnum)
1169 Form_pg_attribute attStruct;
1170 char newattname[NAMEDATALEN];
1173 * Grab an exclusive lock on the target table, which we will NOT release
1174 * until end of transaction. (In the simple case where we are directly
1175 * dropping this column, AlterTableDropColumn already did this ... but
1176 * when cascading from a drop of some other object, we may not have any
1179 rel = relation_open(relid, AccessExclusiveLock);
1181 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1183 tuple = SearchSysCacheCopy(ATTNUM,
1184 ObjectIdGetDatum(relid),
1185 Int16GetDatum(attnum),
1187 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1188 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1190 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1194 /* System attribute (probably OID) ... just delete the row */
1196 simple_heap_delete(attr_rel, &tuple->t_self);
1200 /* Dropping user attributes is lots harder */
1202 /* Mark the attribute as dropped */
1203 attStruct->attisdropped = true;
1206 * Set the type OID to invalid. A dropped attribute's type link
1207 * cannot be relied on (once the attribute is dropped, the type might
1208 * be too). Fortunately we do not need the type row --- the only
1209 * really essential information is the type's typlen and typalign,
1210 * which are preserved in the attribute's attlen and attalign. We set
1211 * atttypid to zero here as a means of catching code that incorrectly
1212 * expects it to be valid.
1214 attStruct->atttypid = InvalidOid;
1216 /* Remove any NOT NULL constraint the column may have */
1217 attStruct->attnotnull = false;
1219 /* We don't want to keep stats for it anymore */
1220 attStruct->attstattarget = 0;
1223 * Change the column name to something that isn't likely to conflict
1225 snprintf(newattname, sizeof(newattname),
1226 "........pg.dropped.%d........", attnum);
1227 namestrcpy(&(attStruct->attname), newattname);
1229 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1231 /* keep the system catalog indexes current */
1232 CatalogUpdateIndexes(attr_rel, tuple);
1236 * Because updating the pg_attribute row will trigger a relcache flush for
1237 * the target relation, we need not do anything else to notify other
1238 * backends of the change.
1241 heap_close(attr_rel, RowExclusiveLock);
1244 RemoveStatistics(relid, attnum);
1246 relation_close(rel, NoLock);
1252 * If the specified relation/attribute has a default, remove it.
1253 * (If no default, raise error if complain is true, else return quietly.)
1256 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1257 DropBehavior behavior, bool complain)
1259 Relation attrdef_rel;
1260 ScanKeyData scankeys[2];
1265 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1267 ScanKeyInit(&scankeys[0],
1268 Anum_pg_attrdef_adrelid,
1269 BTEqualStrategyNumber, F_OIDEQ,
1270 ObjectIdGetDatum(relid));
1271 ScanKeyInit(&scankeys[1],
1272 Anum_pg_attrdef_adnum,
1273 BTEqualStrategyNumber, F_INT2EQ,
1274 Int16GetDatum(attnum));
1276 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1277 SnapshotNow, 2, scankeys);
1279 /* There should be at most one matching tuple, but we loop anyway */
1280 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1282 ObjectAddress object;
1284 object.classId = AttrDefaultRelationId;
1285 object.objectId = HeapTupleGetOid(tuple);
1286 object.objectSubId = 0;
1288 performDeletion(&object, behavior);
1293 systable_endscan(scan);
1294 heap_close(attrdef_rel, RowExclusiveLock);
1296 if (complain && !found)
1297 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1302 * RemoveAttrDefaultById
1304 * Remove a pg_attrdef entry specified by OID. This is the guts of
1305 * attribute-default removal. Note it should be called via performDeletion,
1309 RemoveAttrDefaultById(Oid attrdefId)
1311 Relation attrdef_rel;
1314 ScanKeyData scankeys[1];
1318 AttrNumber myattnum;
1320 /* Grab an appropriate lock on the pg_attrdef relation */
1321 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1323 /* Find the pg_attrdef tuple */
1324 ScanKeyInit(&scankeys[0],
1325 ObjectIdAttributeNumber,
1326 BTEqualStrategyNumber, F_OIDEQ,
1327 ObjectIdGetDatum(attrdefId));
1329 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1330 SnapshotNow, 1, scankeys);
1332 tuple = systable_getnext(scan);
1333 if (!HeapTupleIsValid(tuple))
1334 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1336 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1337 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1339 /* Get an exclusive lock on the relation owning the attribute */
1340 myrel = relation_open(myrelid, AccessExclusiveLock);
1342 /* Now we can delete the pg_attrdef row */
1343 simple_heap_delete(attrdef_rel, &tuple->t_self);
1345 systable_endscan(scan);
1346 heap_close(attrdef_rel, RowExclusiveLock);
1348 /* Fix the pg_attribute row */
1349 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1351 tuple = SearchSysCacheCopy(ATTNUM,
1352 ObjectIdGetDatum(myrelid),
1353 Int16GetDatum(myattnum),
1355 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1356 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1359 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1361 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1363 /* keep the system catalog indexes current */
1364 CatalogUpdateIndexes(attr_rel, tuple);
1367 * Our update of the pg_attribute row will force a relcache rebuild, so
1368 * there's nothing else to do here.
1370 heap_close(attr_rel, RowExclusiveLock);
1372 /* Keep lock on attribute's rel until end of xact */
1373 relation_close(myrel, NoLock);
1377 * heap_drop_with_catalog - removes specified relation from catalogs
1379 * Note that this routine is not responsible for dropping objects that are
1380 * linked to the pg_class entry via dependencies (for example, indexes and
1381 * constraints). Those are deleted by the dependency-tracing logic in
1382 * dependency.c before control gets here. In general, therefore, this routine
1383 * should never be called directly; go through performDeletion() instead.
1386 heap_drop_with_catalog(Oid relid)
1391 * Open and lock the relation.
1393 rel = relation_open(relid, AccessExclusiveLock);
1396 * Schedule unlinking of the relation's physical files at commit.
1398 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1399 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1403 RelationOpenSmgr(rel);
1404 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1405 if (smgrexists(rel->rd_smgr, forknum))
1406 smgrscheduleunlink(rel->rd_smgr, forknum, rel->rd_istemp);
1407 RelationCloseSmgr(rel);
1411 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1412 * until transaction commit. This ensures no one else will try to do
1413 * something with the doomed relation.
1415 relation_close(rel, NoLock);
1418 * Forget any ON COMMIT action for the rel
1420 remove_on_commit_action(relid);
1423 * Flush the relation from the relcache. We want to do this before
1424 * starting to remove catalog entries, just to be certain that no relcache
1425 * entry rebuild will happen partway through. (That should not really
1426 * matter, since we don't do CommandCounterIncrement here, but let's be
1429 RelationForgetRelation(relid);
1432 * remove inheritance information
1434 RelationRemoveInheritance(relid);
1439 RemoveStatistics(relid, 0);
1442 * delete attribute tuples
1444 DeleteAttributeTuples(relid);
1447 * delete relation tuple
1449 DeleteRelationTuple(relid);
1454 * Store a default expression for column attnum of relation rel.
1457 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1464 static bool nulls[4] = {false, false, false, false};
1467 Form_pg_attribute attStruct;
1469 ObjectAddress colobject,
1473 * Flatten expression to string form for storage.
1475 adbin = nodeToString(expr);
1478 * Also deparse it to form the mostly-obsolete adsrc field.
1480 adsrc = deparse_expression(expr,
1481 deparse_context_for(RelationGetRelationName(rel),
1482 RelationGetRelid(rel)),
1486 * Make the pg_attrdef entry.
1488 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1489 values[Anum_pg_attrdef_adnum - 1] = attnum;
1490 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1491 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1493 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1495 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1496 attrdefOid = simple_heap_insert(adrel, tuple);
1498 CatalogUpdateIndexes(adrel, tuple);
1500 defobject.classId = AttrDefaultRelationId;
1501 defobject.objectId = attrdefOid;
1502 defobject.objectSubId = 0;
1504 heap_close(adrel, RowExclusiveLock);
1506 /* now can free some of the stuff allocated above */
1507 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1508 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1509 heap_freetuple(tuple);
1514 * Update the pg_attribute entry for the column to show that a default
1517 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1518 atttup = SearchSysCacheCopy(ATTNUM,
1519 ObjectIdGetDatum(RelationGetRelid(rel)),
1520 Int16GetDatum(attnum),
1522 if (!HeapTupleIsValid(atttup))
1523 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1524 attnum, RelationGetRelid(rel));
1525 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1526 if (!attStruct->atthasdef)
1528 attStruct->atthasdef = true;
1529 simple_heap_update(attrrel, &atttup->t_self, atttup);
1530 /* keep catalog indexes current */
1531 CatalogUpdateIndexes(attrrel, atttup);
1533 heap_close(attrrel, RowExclusiveLock);
1534 heap_freetuple(atttup);
1537 * Make a dependency so that the pg_attrdef entry goes away if the column
1538 * (or whole table) is deleted.
1540 colobject.classId = RelationRelationId;
1541 colobject.objectId = RelationGetRelid(rel);
1542 colobject.objectSubId = attnum;
1544 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1547 * Record dependencies on objects used in the expression, too.
1549 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1553 * Store a check-constraint expression for the given relation.
1555 * Caller is responsible for updating the count of constraints
1556 * in the pg_class entry for the relation.
1559 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1560 bool is_local, int inhcount)
1569 * Flatten expression to string form for storage.
1571 ccbin = nodeToString(expr);
1574 * Also deparse it to form the mostly-obsolete consrc field.
1576 ccsrc = deparse_expression(expr,
1577 deparse_context_for(RelationGetRelationName(rel),
1578 RelationGetRelid(rel)),
1582 * Find columns of rel that are used in expr
1584 * NB: pull_var_clause is okay here only because we don't allow subselects
1585 * in check constraints; it would fail to examine the contents of
1588 varList = pull_var_clause(expr, false);
1589 keycount = list_length(varList);
1596 attNos = (int16 *) palloc(keycount * sizeof(int16));
1597 foreach(vl, varList)
1599 Var *var = (Var *) lfirst(vl);
1602 for (j = 0; j < i; j++)
1603 if (attNos[j] == var->varattno)
1606 attNos[i++] = var->varattno;
1614 * Create the Check Constraint
1616 CreateConstraintEntry(ccname, /* Constraint Name */
1617 RelationGetNamespace(rel), /* namespace */
1618 CONSTRAINT_CHECK, /* Constraint Type */
1619 false, /* Is Deferrable */
1620 false, /* Is Deferred */
1621 RelationGetRelid(rel), /* relation */
1622 attNos, /* attrs in the constraint */
1623 keycount, /* # attrs in the constraint */
1624 InvalidOid, /* not a domain constraint */
1625 InvalidOid, /* Foreign key fields */
1634 InvalidOid, /* no associated index */
1635 expr, /* Tree form check constraint */
1636 ccbin, /* Binary form check constraint */
1637 ccsrc, /* Source form check constraint */
1638 is_local, /* conislocal */
1639 inhcount); /* coninhcount */
1646 * Store defaults and constraints (passed as a list of CookedConstraint).
1648 * NOTE: only pre-cooked expressions will be passed this way, which is to
1649 * say expressions inherited from an existing relation. Newly parsed
1650 * expressions can be added later, by direct calls to StoreAttrDefault
1651 * and StoreRelCheck (see AddRelationNewConstraints()).
1654 StoreConstraints(Relation rel, List *cooked_constraints)
1659 if (!cooked_constraints)
1660 return; /* nothing to do */
1663 * Deparsing of constraint expressions will fail unless the just-created
1664 * pg_attribute tuples for this relation are made visible. So, bump the
1665 * command counter. CAUTION: this will cause a relcache entry rebuild.
1667 CommandCounterIncrement();
1669 foreach(lc, cooked_constraints)
1671 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1673 switch (con->contype)
1675 case CONSTR_DEFAULT:
1676 StoreAttrDefault(rel, con->attnum, con->expr);
1679 StoreRelCheck(rel, con->name, con->expr,
1680 con->is_local, con->inhcount);
1684 elog(ERROR, "unrecognized constraint type: %d",
1685 (int) con->contype);
1690 SetRelationNumChecks(rel, numchecks);
1694 * AddRelationNewConstraints
1696 * Add new column default expressions and/or constraint check expressions
1697 * to an existing relation. This is defined to do both for efficiency in
1698 * DefineRelation, but of course you can do just one or the other by passing
1701 * rel: relation to be modified
1702 * newColDefaults: list of RawColumnDefault structures
1703 * newConstraints: list of Constraint nodes
1704 * allow_merge: TRUE if check constraints may be merged with existing ones
1705 * is_local: TRUE if definition is local, FALSE if it's inherited
1707 * All entries in newColDefaults will be processed. Entries in newConstraints
1708 * will be processed only if they are CONSTR_CHECK type.
1710 * Returns a list of CookedConstraint nodes that shows the cooked form of
1711 * the default and constraint expressions added to the relation.
1713 * NB: caller should have opened rel with AccessExclusiveLock, and should
1714 * hold that lock till end of transaction. Also, we assume the caller has
1715 * done a CommandCounterIncrement if necessary to make the relation's catalog
1719 AddRelationNewConstraints(Relation rel,
1720 List *newColDefaults,
1721 List *newConstraints,
1725 List *cookedConstraints = NIL;
1726 TupleDesc tupleDesc;
1727 TupleConstr *oldconstr;
1735 CookedConstraint *cooked;
1738 * Get info about existing constraints.
1740 tupleDesc = RelationGetDescr(rel);
1741 oldconstr = tupleDesc->constr;
1743 numoldchecks = oldconstr->num_check;
1748 * Create a dummy ParseState and insert the target relation as its sole
1749 * rangetable entry. We need a ParseState for transformExpr.
1751 pstate = make_parsestate(NULL);
1752 rte = addRangeTableEntryForRelation(pstate,
1757 addRTEtoQuery(pstate, rte, true, true, true);
1760 * Process column default expressions.
1762 foreach(cell, newColDefaults)
1764 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1765 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1767 expr = cookDefault(pstate, colDef->raw_default,
1768 atp->atttypid, atp->atttypmod,
1769 NameStr(atp->attname));
1772 * If the expression is just a NULL constant, we do not bother to make
1773 * an explicit pg_attrdef entry, since the default behavior is
1776 * Note a nonobvious property of this test: if the column is of a
1777 * domain type, what we'll get is not a bare null Const but a
1778 * CoerceToDomain expr, so we will not discard the default. This is
1779 * critical because the column default needs to be retained to
1780 * override any default that the domain might have.
1783 (IsA(expr, Const) &&((Const *) expr)->constisnull))
1786 StoreAttrDefault(rel, colDef->attnum, expr);
1788 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1789 cooked->contype = CONSTR_DEFAULT;
1790 cooked->name = NULL;
1791 cooked->attnum = colDef->attnum;
1792 cooked->expr = expr;
1793 cooked->is_local = is_local;
1794 cooked->inhcount = is_local ? 0 : 1;
1795 cookedConstraints = lappend(cookedConstraints, cooked);
1799 * Process constraint expressions.
1801 numchecks = numoldchecks;
1803 foreach(cell, newConstraints)
1805 Constraint *cdef = (Constraint *) lfirst(cell);
1808 if (cdef->contype != CONSTR_CHECK)
1811 if (cdef->raw_expr != NULL)
1813 Assert(cdef->cooked_expr == NULL);
1816 * Transform raw parsetree to executable expression, and verify
1817 * it's valid as a CHECK constraint.
1819 expr = cookConstraint(pstate, cdef->raw_expr,
1820 RelationGetRelationName(rel));
1824 Assert(cdef->cooked_expr != NULL);
1827 * Here, we assume the parser will only pass us valid CHECK
1828 * expressions, so we do no particular checking.
1830 expr = stringToNode(cdef->cooked_expr);
1834 * Check name uniqueness, or generate a name if none was given.
1836 if (cdef->name != NULL)
1840 ccname = cdef->name;
1841 /* Check against other new constraints */
1842 /* Needed because we don't do CommandCounterIncrement in loop */
1843 foreach(cell2, checknames)
1845 if (strcmp((char *) lfirst(cell2), ccname) == 0)
1847 (errcode(ERRCODE_DUPLICATE_OBJECT),
1848 errmsg("check constraint \"%s\" already exists",
1852 /* save name for future checks */
1853 checknames = lappend(checknames, ccname);
1856 * Check against pre-existing constraints. If we are allowed
1857 * to merge with an existing constraint, there's no more to
1858 * do here. (We omit the duplicate constraint from the result,
1859 * which is what ATAddCheckConstraint wants.)
1861 if (MergeWithExistingConstraint(rel, ccname, expr,
1862 allow_merge, is_local))
1868 * When generating a name, we want to create "tab_col_check" for a
1869 * column constraint and "tab_check" for a table constraint. We
1870 * no longer have any info about the syntactic positioning of the
1871 * constraint phrase, so we approximate this by seeing whether the
1872 * expression references more than one column. (If the user
1873 * played by the rules, the result is the same...)
1875 * Note: pull_var_clause() doesn't descend into sublinks, but we
1876 * eliminated those above; and anyway this only needs to be an
1877 * approximate answer.
1882 vars = pull_var_clause(expr, false);
1884 /* eliminate duplicates */
1885 vars = list_union(NIL, vars);
1887 if (list_length(vars) == 1)
1888 colname = get_attname(RelationGetRelid(rel),
1889 ((Var *) linitial(vars))->varattno);
1893 ccname = ChooseConstraintName(RelationGetRelationName(rel),
1896 RelationGetNamespace(rel),
1899 /* save name for future checks */
1900 checknames = lappend(checknames, ccname);
1906 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
1910 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1911 cooked->contype = CONSTR_CHECK;
1912 cooked->name = ccname;
1914 cooked->expr = expr;
1915 cooked->is_local = is_local;
1916 cooked->inhcount = is_local ? 0 : 1;
1917 cookedConstraints = lappend(cookedConstraints, cooked);
1921 * Update the count of constraints in the relation's pg_class tuple. We do
1922 * this even if there was no change, in order to ensure that an SI update
1923 * message is sent out for the pg_class tuple, which will force other
1924 * backends to rebuild their relcache entries for the rel. (This is
1925 * critical if we added defaults but not constraints.)
1927 SetRelationNumChecks(rel, numchecks);
1929 return cookedConstraints;
1933 * Check for a pre-existing check constraint that conflicts with a proposed
1934 * new one, and either adjust its conislocal/coninhcount settings or throw
1937 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1938 * got a so-far-unique name, or throws error if conflict.
1941 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
1942 bool allow_merge, bool is_local)
1946 SysScanDesc conscan;
1947 ScanKeyData skey[2];
1950 /* Search for a pg_constraint entry with same name and relation */
1951 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
1955 ScanKeyInit(&skey[0],
1956 Anum_pg_constraint_conname,
1957 BTEqualStrategyNumber, F_NAMEEQ,
1958 CStringGetDatum(ccname));
1960 ScanKeyInit(&skey[1],
1961 Anum_pg_constraint_connamespace,
1962 BTEqualStrategyNumber, F_OIDEQ,
1963 ObjectIdGetDatum(RelationGetNamespace(rel)));
1965 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
1966 SnapshotNow, 2, skey);
1968 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
1970 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
1972 if (con->conrelid == RelationGetRelid(rel))
1974 /* Found it. Conflicts if not identical check constraint */
1975 if (con->contype == CONSTRAINT_CHECK)
1980 val = fastgetattr(tup,
1981 Anum_pg_constraint_conbin,
1982 conDesc->rd_att, &isnull);
1984 elog(ERROR, "null conbin for rel %s",
1985 RelationGetRelationName(rel));
1986 if (equal(expr, stringToNode(TextDatumGetCString(val))))
1989 if (!found || !allow_merge)
1991 (errcode(ERRCODE_DUPLICATE_OBJECT),
1992 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1993 ccname, RelationGetRelationName(rel))));
1994 /* OK to update the tuple */
1996 (errmsg("merging constraint \"%s\" with inherited definition",
1998 tup = heap_copytuple(tup);
1999 con = (Form_pg_constraint) GETSTRUCT(tup);
2001 con->conislocal = true;
2004 simple_heap_update(conDesc, &tup->t_self, tup);
2005 CatalogUpdateIndexes(conDesc, tup);
2010 systable_endscan(conscan);
2011 heap_close(conDesc, RowExclusiveLock);
2017 * Update the count of constraints in the relation's pg_class tuple.
2019 * Caller had better hold exclusive lock on the relation.
2021 * An important side effect is that a SI update message will be sent out for
2022 * the pg_class tuple, which will force other backends to rebuild their
2023 * relcache entries for the rel. Also, this backend will rebuild its
2024 * own relcache entry at the next CommandCounterIncrement.
2027 SetRelationNumChecks(Relation rel, int numchecks)
2031 Form_pg_class relStruct;
2033 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2034 reltup = SearchSysCacheCopy(RELOID,
2035 ObjectIdGetDatum(RelationGetRelid(rel)),
2037 if (!HeapTupleIsValid(reltup))
2038 elog(ERROR, "cache lookup failed for relation %u",
2039 RelationGetRelid(rel));
2040 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2042 if (relStruct->relchecks != numchecks)
2044 relStruct->relchecks = numchecks;
2046 simple_heap_update(relrel, &reltup->t_self, reltup);
2048 /* keep catalog indexes current */
2049 CatalogUpdateIndexes(relrel, reltup);
2053 /* Skip the disk update, but force relcache inval anyway */
2054 CacheInvalidateRelcache(rel);
2057 heap_freetuple(reltup);
2058 heap_close(relrel, RowExclusiveLock);
2062 * Take a raw default and convert it to a cooked format ready for
2065 * Parse state should be set up to recognize any vars that might appear
2066 * in the expression. (Even though we plan to reject vars, it's more
2067 * user-friendly to give the correct error message than "unknown var".)
2069 * If atttypid is not InvalidOid, coerce the expression to the specified
2070 * type (and typmod atttypmod). attname is only needed in this case:
2071 * it is used in the error message, if any.
2074 cookDefault(ParseState *pstate,
2082 Assert(raw_default != NULL);
2085 * Transform raw parsetree to executable expression.
2087 expr = transformExpr(pstate, raw_default);
2090 * Make sure default expr does not refer to any vars.
2092 if (contain_var_clause(expr))
2094 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2095 errmsg("cannot use column references in default expression")));
2098 * It can't return a set either.
2100 if (expression_returns_set(expr))
2102 (errcode(ERRCODE_DATATYPE_MISMATCH),
2103 errmsg("default expression must not return a set")));
2106 * No subplans or aggregates, either...
2108 if (pstate->p_hasSubLinks)
2110 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2111 errmsg("cannot use subquery in default expression")));
2112 if (pstate->p_hasAggs)
2114 (errcode(ERRCODE_GROUPING_ERROR),
2115 errmsg("cannot use aggregate function in default expression")));
2118 * Coerce the expression to the correct type and typmod, if given. This
2119 * should match the parser's processing of non-defaulted expressions ---
2120 * see transformAssignedExpr().
2122 if (OidIsValid(atttypid))
2124 Oid type_id = exprType(expr);
2126 expr = coerce_to_target_type(pstate, expr, type_id,
2127 atttypid, atttypmod,
2128 COERCION_ASSIGNMENT,
2129 COERCE_IMPLICIT_CAST,
2133 (errcode(ERRCODE_DATATYPE_MISMATCH),
2134 errmsg("column \"%s\" is of type %s"
2135 " but default expression is of type %s",
2137 format_type_be(atttypid),
2138 format_type_be(type_id)),
2139 errhint("You will need to rewrite or cast the expression.")));
2146 * Take a raw CHECK constraint expression and convert it to a cooked format
2147 * ready for storage.
2149 * Parse state must be set up to recognize any vars that might appear
2150 * in the expression.
2153 cookConstraint(ParseState *pstate,
2154 Node *raw_constraint,
2160 * Transform raw parsetree to executable expression.
2162 expr = transformExpr(pstate, raw_constraint);
2165 * Make sure it yields a boolean result.
2167 expr = coerce_to_boolean(pstate, expr, "CHECK");
2170 * Make sure no outside relations are referred to.
2172 if (list_length(pstate->p_rtable) != 1)
2174 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2175 errmsg("only table \"%s\" can be referenced in check constraint",
2179 * No subplans or aggregates, either...
2181 if (pstate->p_hasSubLinks)
2183 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2184 errmsg("cannot use subquery in check constraint")));
2185 if (pstate->p_hasAggs)
2187 (errcode(ERRCODE_GROUPING_ERROR),
2188 errmsg("cannot use aggregate function in check constraint")));
2195 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2197 * If attnum is zero, remove all entries for rel; else remove only the one
2201 RemoveStatistics(Oid relid, AttrNumber attnum)
2203 Relation pgstatistic;
2209 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2211 ScanKeyInit(&key[0],
2212 Anum_pg_statistic_starelid,
2213 BTEqualStrategyNumber, F_OIDEQ,
2214 ObjectIdGetDatum(relid));
2220 ScanKeyInit(&key[1],
2221 Anum_pg_statistic_staattnum,
2222 BTEqualStrategyNumber, F_INT2EQ,
2223 Int16GetDatum(attnum));
2227 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumIndexId, true,
2228 SnapshotNow, nkeys, key);
2230 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2231 simple_heap_delete(pgstatistic, &tuple->t_self);
2233 systable_endscan(scan);
2235 heap_close(pgstatistic, RowExclusiveLock);
2240 * RelationTruncateIndexes - truncate all indexes associated
2241 * with the heap relation to zero tuples.
2243 * The routine will truncate and then reconstruct the indexes on
2244 * the specified relation. Caller must hold exclusive lock on rel.
2247 RelationTruncateIndexes(Relation heapRelation)
2251 /* Ask the relcache to produce a list of the indexes of the rel */
2252 foreach(indlist, RelationGetIndexList(heapRelation))
2254 Oid indexId = lfirst_oid(indlist);
2255 Relation currentIndex;
2256 IndexInfo *indexInfo;
2258 /* Open the index relation; use exclusive lock, just to be sure */
2259 currentIndex = index_open(indexId, AccessExclusiveLock);
2261 /* Fetch info needed for index_build */
2262 indexInfo = BuildIndexInfo(currentIndex);
2265 * Now truncate the actual file (and discard buffers). The indexam
2266 * is responsible for truncating the FSM in index_build(), if
2269 RelationTruncate(currentIndex, 0);
2271 /* Initialize the index and rebuild */
2272 /* Note: we do not need to re-establish pkey setting */
2273 index_build(heapRelation, currentIndex, indexInfo, false);
2275 /* We're done with this index */
2276 index_close(currentIndex, NoLock);
2283 * This routine deletes all data within all the specified relations.
2285 * This is not transaction-safe! There is another, transaction-safe
2286 * implementation in commands/tablecmds.c. We now use this only for
2287 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2290 heap_truncate(List *relids)
2292 List *relations = NIL;
2295 /* Open relations for processing, and grab exclusive access on each */
2296 foreach(cell, relids)
2298 Oid rid = lfirst_oid(cell);
2302 rel = heap_open(rid, AccessExclusiveLock);
2303 relations = lappend(relations, rel);
2305 /* If there is a toast table, add it to the list too */
2306 toastrelid = rel->rd_rel->reltoastrelid;
2307 if (OidIsValid(toastrelid))
2309 rel = heap_open(toastrelid, AccessExclusiveLock);
2310 relations = lappend(relations, rel);
2314 /* Don't allow truncate on tables that are referenced by foreign keys */
2315 heap_truncate_check_FKs(relations, true);
2318 foreach(cell, relations)
2320 Relation rel = lfirst(cell);
2322 /* Truncate the FSM and actual file (and discard buffers) */
2323 FreeSpaceMapTruncateRel(rel, 0);
2324 RelationTruncate(rel, 0);
2326 /* If this relation has indexes, truncate the indexes too */
2327 RelationTruncateIndexes(rel);
2330 * Close the relation, but keep exclusive lock on it until commit.
2332 heap_close(rel, NoLock);
2337 * heap_truncate_check_FKs
2338 * Check for foreign keys referencing a list of relations that
2339 * are to be truncated, and raise error if there are any
2341 * We disallow such FKs (except self-referential ones) since the whole point
2342 * of TRUNCATE is to not scan the individual rows to be thrown away.
2344 * This is split out so it can be shared by both implementations of truncate.
2345 * Caller should already hold a suitable lock on the relations.
2347 * tempTables is only used to select an appropriate error message.
2350 heap_truncate_check_FKs(List *relations, bool tempTables)
2357 * Build a list of OIDs of the interesting relations.
2359 * If a relation has no triggers, then it can neither have FKs nor be
2360 * referenced by a FK from another table, so we can ignore it.
2362 foreach(cell, relations)
2364 Relation rel = lfirst(cell);
2366 if (rel->rd_rel->relhastriggers)
2367 oids = lappend_oid(oids, RelationGetRelid(rel));
2371 * Fast path: if no relation has triggers, none has FKs either.
2377 * Otherwise, must scan pg_constraint. We make one pass with all the
2378 * relations considered; if this finds nothing, then all is well.
2380 dependents = heap_truncate_find_FKs(oids);
2381 if (dependents == NIL)
2385 * Otherwise we repeat the scan once per relation to identify a particular
2386 * pair of relations to complain about. This is pretty slow, but
2387 * performance shouldn't matter much in a failure path. The reason for
2388 * doing things this way is to ensure that the message produced is not
2389 * dependent on chance row locations within pg_constraint.
2393 Oid relid = lfirst_oid(cell);
2396 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2398 foreach(cell2, dependents)
2400 Oid relid2 = lfirst_oid(cell2);
2402 if (!list_member_oid(oids, relid2))
2404 char *relname = get_rel_name(relid);
2405 char *relname2 = get_rel_name(relid2);
2409 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2410 errmsg("unsupported ON COMMIT and foreign key combination"),
2411 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2412 relname2, relname)));
2415 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2416 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2417 errdetail("Table \"%s\" references \"%s\".",
2419 errhint("Truncate table \"%s\" at the same time, "
2420 "or use TRUNCATE ... CASCADE.",
2428 * heap_truncate_find_FKs
2429 * Find relations having foreign keys referencing any of the given rels
2431 * Input and result are both lists of relation OIDs. The result contains
2432 * no duplicates, does *not* include any rels that were already in the input
2433 * list, and is sorted in OID order. (The last property is enforced mainly
2434 * to guarantee consistent behavior in the regression tests; we don't want
2435 * behavior to change depending on chance locations of rows in pg_constraint.)
2437 * Note: caller should already have appropriate lock on all rels mentioned
2438 * in relationIds. Since adding or dropping an FK requires exclusive lock
2439 * on both rels, this ensures that the answer will be stable.
2442 heap_truncate_find_FKs(List *relationIds)
2446 SysScanDesc fkeyScan;
2450 * Must scan pg_constraint. Right now, it is a seqscan because there is
2451 * no available index on confrelid.
2453 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2455 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2456 SnapshotNow, 0, NULL);
2458 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2460 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2462 /* Not a foreign key */
2463 if (con->contype != CONSTRAINT_FOREIGN)
2466 /* Not referencing one of our list of tables */
2467 if (!list_member_oid(relationIds, con->confrelid))
2470 /* Add referencer unless already in input or result list */
2471 if (!list_member_oid(relationIds, con->conrelid))
2472 result = insert_ordered_unique_oid(result, con->conrelid);
2475 systable_endscan(fkeyScan);
2476 heap_close(fkeyRel, AccessShareLock);
2482 * insert_ordered_unique_oid
2483 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2484 * and eliminating duplicates
2486 * Building the ordered list this way is O(N^2), but with a pretty small
2487 * constant, so for the number of entries we expect it will probably be
2488 * faster than trying to apply qsort(). It seems unlikely someone would be
2489 * trying to truncate a table with thousands of dependent tables ...
2492 insert_ordered_unique_oid(List *list, Oid datum)
2496 /* Does the datum belong at the front? */
2497 if (list == NIL || datum < linitial_oid(list))
2498 return lcons_oid(datum, list);
2499 /* Does it match the first entry? */
2500 if (datum == linitial_oid(list))
2501 return list; /* duplicate, so don't insert */
2502 /* No, so find the entry it belongs after */
2503 prev = list_head(list);
2506 ListCell *curr = lnext(prev);
2508 if (curr == NULL || datum < lfirst_oid(curr))
2509 break; /* it belongs after 'prev', before 'curr' */
2511 if (datum == lfirst_oid(curr))
2512 return list; /* duplicate, so don't insert */
2516 /* Insert datum into list after 'prev' */
2517 lappend_cell_oid(list, prev, datum);