1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2006, 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.303 2006/07/02 02:23:19 momjian 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/heapam.h"
33 #include "access/genam.h"
34 #include "catalog/catalog.h"
35 #include "catalog/dependency.h"
36 #include "catalog/heap.h"
37 #include "catalog/index.h"
38 #include "catalog/indexing.h"
39 #include "catalog/pg_attrdef.h"
40 #include "catalog/pg_constraint.h"
41 #include "catalog/pg_inherits.h"
42 #include "catalog/pg_namespace.h"
43 #include "catalog/pg_statistic.h"
44 #include "catalog/pg_type.h"
45 #include "commands/tablecmds.h"
46 #include "commands/trigger.h"
47 #include "commands/defrem.h"
48 #include "miscadmin.h"
49 #include "nodes/makefuncs.h"
50 #include "optimizer/clauses.h"
51 #include "optimizer/planmain.h"
52 #include "optimizer/var.h"
53 #include "parser/parse_coerce.h"
54 #include "parser/parse_clause.h"
55 #include "parser/parse_expr.h"
56 #include "parser/parse_relation.h"
57 #include "rewrite/rewriteRemove.h"
58 #include "storage/smgr.h"
59 #include "utils/catcache.h"
60 #include "utils/builtins.h"
61 #include "utils/fmgroids.h"
62 #include "utils/inval.h"
63 #include "utils/lsyscache.h"
64 #include "utils/memutils.h"
65 #include "utils/relcache.h"
66 #include "utils/syscache.h"
69 static void AddNewRelationTuple(Relation pg_class_desc,
70 Relation new_rel_desc,
71 Oid new_rel_oid, Oid new_type_oid,
75 static Oid AddNewRelationType(const char *typeName,
79 static void RelationRemoveInheritance(Oid relid);
80 static void StoreRelCheck(Relation rel, char *ccname, char *ccbin);
81 static void StoreConstraints(Relation rel, TupleDesc tupdesc);
82 static void SetRelationNumChecks(Relation rel, int numchecks);
83 static List *insert_ordered_unique_oid(List *list, Oid datum);
86 /* ----------------------------------------------------------------
87 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
89 * these should all be moved to someplace in the lib/catalog
90 * module, if not obliterated first.
91 * ----------------------------------------------------------------
97 * Should the system special case these attributes in the future?
98 * Advantage: consume much less space in the ATTRIBUTE relation.
99 * Disadvantage: special cases will be all over the place.
102 static FormData_pg_attribute a1 = {
103 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
104 SelfItemPointerAttributeNumber, 0, -1, -1,
105 false, 'p', 's', true, false, false, true, 0
108 static FormData_pg_attribute a2 = {
109 0, {"oid"}, OIDOID, 0, sizeof(Oid),
110 ObjectIdAttributeNumber, 0, -1, -1,
111 true, 'p', 'i', true, false, false, true, 0
114 static FormData_pg_attribute a3 = {
115 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
116 MinTransactionIdAttributeNumber, 0, -1, -1,
117 true, 'p', 'i', true, false, false, true, 0
120 static FormData_pg_attribute a4 = {
121 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
122 MinCommandIdAttributeNumber, 0, -1, -1,
123 true, 'p', 'i', true, false, false, true, 0
126 static FormData_pg_attribute a5 = {
127 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
128 MaxTransactionIdAttributeNumber, 0, -1, -1,
129 true, 'p', 'i', true, false, false, true, 0
132 static FormData_pg_attribute a6 = {
133 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
134 MaxCommandIdAttributeNumber, 0, -1, -1,
135 true, 'p', 'i', true, false, false, true, 0
139 * We decided to call this attribute "tableoid" rather than say
140 * "classoid" on the basis that in the future there may be more than one
141 * table of a particular class/type. In any case table is still the word
144 static FormData_pg_attribute a7 = {
145 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
146 TableOidAttributeNumber, 0, -1, -1,
147 true, 'p', 'i', true, false, false, true, 0
150 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
153 * This function returns a Form_pg_attribute pointer for a system attribute.
154 * Note that we elog if the presented attno is invalid, which would only
155 * happen if there's a problem upstream.
158 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
160 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
161 elog(ERROR, "invalid system attribute number %d", attno);
162 if (attno == ObjectIdAttributeNumber && !relhasoids)
163 elog(ERROR, "invalid system attribute number %d", attno);
164 return SysAtt[-attno - 1];
168 * If the given name is a system attribute name, return a Form_pg_attribute
169 * pointer for a prototype definition. If not, return NULL.
172 SystemAttributeByName(const char *attname, bool relhasoids)
176 for (j = 0; j < (int) lengthof(SysAtt); j++)
178 Form_pg_attribute att = SysAtt[j];
180 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
182 if (strcmp(NameStr(att->attname), attname) == 0)
191 /* ----------------------------------------------------------------
192 * XXX END OF UGLY HARD CODED BADNESS XXX
193 * ---------------------------------------------------------------- */
196 /* ----------------------------------------------------------------
197 * heap_create - Create an uncataloged heap relation
199 * Note API change: the caller must now always provide the OID
200 * to use for the relation.
202 * rel->rd_rel is initialized by RelationBuildLocalRelation,
203 * and is mostly zeroes at return.
204 * ----------------------------------------------------------------
207 heap_create(const char *relname,
213 bool shared_relation,
214 bool allow_system_table_mods)
219 /* The caller must have provided an OID for the relation. */
220 Assert(OidIsValid(relid));
225 if (!allow_system_table_mods &&
226 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
227 IsNormalProcessingMode())
229 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
230 errmsg("permission denied to create \"%s.%s\"",
231 get_namespace_name(relnamespace), relname),
232 errdetail("System catalog modifications are currently disallowed.")));
235 * Decide if we need storage or not, and handle a couple other special
236 * cases for particular relkinds.
241 case RELKIND_COMPOSITE_TYPE:
242 create_storage = false;
245 * Force reltablespace to zero if the relation has no physical
246 * storage. This is mainly just for cleanliness' sake.
248 reltablespace = InvalidOid;
250 case RELKIND_SEQUENCE:
251 create_storage = true;
254 * Force reltablespace to zero for sequences, since we don't
255 * support moving them around into different tablespaces.
257 reltablespace = InvalidOid;
260 create_storage = true;
265 * Never allow a pg_class entry to explicitly specify the database's
266 * default tablespace in reltablespace; force it to zero instead. This
267 * ensures that if the database is cloned with a different default
268 * tablespace, the pg_class entry will still match where CREATE DATABASE
269 * will put the physically copied relation.
271 * Yes, this is a bit of a hack.
273 if (reltablespace == MyDatabaseTableSpace)
274 reltablespace = InvalidOid;
277 * build the relcache entry.
279 rel = RelationBuildLocalRelation(relname,
287 * have the storage manager create the relation's disk file, if needed.
291 Assert(rel->rd_smgr == NULL);
292 RelationOpenSmgr(rel);
293 smgrcreate(rel->rd_smgr, rel->rd_istemp, false);
299 /* ----------------------------------------------------------------
300 * heap_create_with_catalog - Create a cataloged relation
302 * this is done in multiple steps:
304 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
305 * descriptor contains a valid set of attribute names and types
307 * 2) pg_class is opened and get_relname_relid()
308 * performs a scan to ensure that no relation with the
309 * same name already exists.
311 * 3) heap_create() is called to create the new relation on disk.
313 * 4) TypeCreate() is called to define a new type corresponding
314 * to the new relation.
316 * 5) AddNewRelationTuple() is called to register the
317 * relation in pg_class.
319 * 6) AddNewAttributeTuples() is called to register the
320 * new relation's schema in pg_attribute.
322 * 7) StoreConstraints is called () - vadim 08/22/97
324 * 8) the relations are closed and the new relation's oid
327 * ----------------------------------------------------------------
330 /* --------------------------------
331 * CheckAttributeNamesTypes
333 * this is used to make certain the tuple descriptor contains a
334 * valid set of attribute names and datatypes. a problem simply
335 * generates ereport(ERROR) which aborts the current transaction.
336 * --------------------------------
339 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
343 int natts = tupdesc->natts;
345 /* Sanity check on column count */
346 if (natts < 0 || natts > MaxHeapAttributeNumber)
348 (errcode(ERRCODE_TOO_MANY_COLUMNS),
349 errmsg("tables can have at most %d columns",
350 MaxHeapAttributeNumber)));
353 * first check for collision with system attribute names
355 * Skip this for a view or type relation, since those don't have system
358 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
360 for (i = 0; i < natts; i++)
362 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
363 tupdesc->tdhasoid) != NULL)
365 (errcode(ERRCODE_DUPLICATE_COLUMN),
366 errmsg("column name \"%s\" conflicts with a system column name",
367 NameStr(tupdesc->attrs[i]->attname))));
372 * next check for repeated attribute names
374 for (i = 1; i < natts; i++)
376 for (j = 0; j < i; j++)
378 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
379 NameStr(tupdesc->attrs[i]->attname)) == 0)
381 (errcode(ERRCODE_DUPLICATE_COLUMN),
382 errmsg("column name \"%s\" is duplicated",
383 NameStr(tupdesc->attrs[j]->attname))));
388 * next check the attribute types
390 for (i = 0; i < natts; i++)
392 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
393 tupdesc->attrs[i]->atttypid);
397 /* --------------------------------
400 * Verify that the proposed datatype of an attribute is legal.
401 * This is needed because there are types (and pseudo-types)
402 * in the catalogs that we do not support as elements of real tuples.
403 * --------------------------------
406 CheckAttributeType(const char *attname, Oid atttypid)
408 char att_typtype = get_typtype(atttypid);
411 * Warn user, but don't fail, if column to be created has UNKNOWN type
412 * (usually as a result of a 'retrieve into' - jolly)
414 * Refuse any attempt to create a pseudo-type column.
416 if (atttypid == UNKNOWNOID)
418 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
419 errmsg("column \"%s\" has type \"unknown\"", attname),
420 errdetail("Proceeding with relation creation anyway.")));
421 else if (att_typtype == 'p')
423 /* Special hack for pg_statistic: allow ANYARRAY during initdb */
424 if (atttypid != ANYARRAYOID || IsUnderPostmaster)
426 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
427 errmsg("column \"%s\" has pseudo-type %s",
428 attname, format_type_be(atttypid))));
432 /* --------------------------------
433 * AddNewAttributeTuples
435 * this registers the new relation's schema by adding
436 * tuples to pg_attribute.
437 * --------------------------------
440 AddNewAttributeTuples(Oid new_rel_oid,
446 const Form_pg_attribute *dpp;
450 CatalogIndexState indstate;
451 int natts = tupdesc->natts;
452 ObjectAddress myself,
456 * open pg_attribute and its indexes.
458 rel = heap_open(AttributeRelationId, RowExclusiveLock);
460 indstate = CatalogOpenIndexes(rel);
463 * First we add the user attributes. This is also a convenient place to
464 * add dependencies on their datatypes.
466 dpp = tupdesc->attrs;
467 for (i = 0; i < natts; i++)
469 /* Fill in the correct relation OID */
470 (*dpp)->attrelid = new_rel_oid;
471 /* Make sure these are OK, too */
472 (*dpp)->attstattarget = -1;
473 (*dpp)->attcacheoff = -1;
475 tup = heap_addheader(Natts_pg_attribute,
477 ATTRIBUTE_TUPLE_SIZE,
480 simple_heap_insert(rel, tup);
482 CatalogIndexInsert(indstate, tup);
486 myself.classId = RelationRelationId;
487 myself.objectId = new_rel_oid;
488 myself.objectSubId = i + 1;
489 referenced.classId = TypeRelationId;
490 referenced.objectId = (*dpp)->atttypid;
491 referenced.objectSubId = 0;
492 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
498 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
499 * all for a view or type relation. We don't bother with making datatype
500 * dependencies here, since presumably all these types are pinned.
502 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
505 for (i = 0; i < -1 - FirstLowInvalidHeapAttributeNumber; i++)
507 if (tupdesc->tdhasoid ||
508 (*dpp)->attnum != ObjectIdAttributeNumber)
510 Form_pg_attribute attStruct;
512 tup = heap_addheader(Natts_pg_attribute,
514 ATTRIBUTE_TUPLE_SIZE,
516 attStruct = (Form_pg_attribute) GETSTRUCT(tup);
518 /* Fill in the correct relation OID in the copied tuple */
519 attStruct->attrelid = new_rel_oid;
521 /* Fill in correct inheritance info for the OID column */
522 if (attStruct->attnum == ObjectIdAttributeNumber)
524 attStruct->attislocal = oidislocal;
525 attStruct->attinhcount = oidinhcount;
529 * Unneeded since they should be OK in the constant data
532 /* attStruct->attstattarget = 0; */
533 /* attStruct->attcacheoff = -1; */
535 simple_heap_insert(rel, tup);
537 CatalogIndexInsert(indstate, tup);
548 CatalogCloseIndexes(indstate);
550 heap_close(rel, RowExclusiveLock);
553 /* --------------------------------
554 * AddNewRelationTuple
556 * this registers the new relation in the catalogs by
557 * adding a tuple to pg_class.
558 * --------------------------------
561 AddNewRelationTuple(Relation pg_class_desc,
562 Relation new_rel_desc,
569 Form_pg_class new_rel_reltup;
573 * first we update some of the information in our uncataloged relation's
574 * relation descriptor.
576 new_rel_reltup = new_rel_desc->rd_rel;
580 case RELKIND_RELATION:
582 case RELKIND_TOASTVALUE:
583 /* The relation is real, but as yet empty */
584 new_rel_reltup->relpages = 0;
585 new_rel_reltup->reltuples = 0;
587 case RELKIND_SEQUENCE:
588 /* Sequences always have a known size */
589 new_rel_reltup->relpages = 1;
590 new_rel_reltup->reltuples = 1;
593 /* Views, etc, have no disk storage */
594 new_rel_reltup->relpages = 0;
595 new_rel_reltup->reltuples = 0;
599 new_rel_reltup->relowner = relowner;
600 new_rel_reltup->reltype = new_type_oid;
601 new_rel_reltup->relkind = relkind;
603 new_rel_desc->rd_att->tdtypeid = new_type_oid;
605 /* now form a tuple to add to pg_class */
606 tup = build_class_tuple(new_rel_reltup, options);
608 /* force tuple to have the desired OID */
609 HeapTupleSetOid(tup, new_rel_oid);
612 * finally insert the new tuple, update the indexes, and clean up.
614 simple_heap_insert(pg_class_desc, tup);
616 CatalogUpdateIndexes(pg_class_desc, tup);
622 /* --------------------------------
623 * AddNewRelationType -
625 * define a composite type corresponding to the new relation
626 * --------------------------------
629 AddNewRelationType(const char *typeName,
635 TypeCreate(typeName, /* type name */
636 typeNamespace, /* type namespace */
637 new_rel_oid, /* relation oid */
638 new_rel_kind, /* relation kind */
639 -1, /* internal size (varlena) */
640 'c', /* type-type (complex) */
641 ',', /* default array delimiter */
642 F_RECORD_IN, /* input procedure */
643 F_RECORD_OUT, /* output procedure */
644 F_RECORD_RECV, /* receive procedure */
645 F_RECORD_SEND, /* send procedure */
646 InvalidOid, /* analyze procedure - default */
647 InvalidOid, /* array element type - irrelevant */
648 InvalidOid, /* domain base type - irrelevant */
649 NULL, /* default value - none */
650 NULL, /* default binary representation */
651 false, /* passed by reference */
652 'd', /* alignment - must be the largest! */
653 'x', /* fully TOASTable */
655 0, /* array dimensions for typBaseType */
656 false); /* Type NOT NULL */
659 /* --------------------------------
660 * heap_create_with_catalog
662 * creates a new cataloged relation. see comments above.
664 * if opaque is specified, it must be allocated in CacheMemoryContext.
665 * --------------------------------
668 heap_create_with_catalog(const char *relname,
675 bool shared_relation,
678 OnCommitAction oncommit,
679 bool allow_system_table_mods,
682 Relation pg_class_desc;
683 Relation new_rel_desc;
684 bytea *new_rel_options;
687 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
692 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
694 CheckAttributeNamesTypes(tupdesc, relkind);
696 if (get_relname_relid(relname, relnamespace))
698 (errcode(ERRCODE_DUPLICATE_TABLE),
699 errmsg("relation \"%s\" already exists", relname)));
702 * Parse options to check if option is valid.
704 new_rel_options = heap_option(relkind, options);
705 Assert(!new_rel_options ||
706 GetMemoryChunkContext(new_rel_options) == CacheMemoryContext);
709 * Allocate an OID for the relation, unless we were told what to use.
711 * The OID will be the relfilenode as well, so make sure it doesn't
712 * collide with either pg_class OIDs or existing physical files.
714 if (!OidIsValid(relid))
715 relid = GetNewRelFileNode(reltablespace, shared_relation,
719 * Create the relcache entry (mostly dummy at this point) and the physical
720 * disk file. (If we fail further down, it's the smgr's responsibility to
721 * remove the disk file again.)
723 new_rel_desc = heap_create(relname,
730 allow_system_table_mods);
731 new_rel_desc->rd_options = new_rel_options;
733 Assert(relid == RelationGetRelid(new_rel_desc));
736 * since defining a relation also defines a complex type, we add a new
737 * system type corresponding to the new relation.
739 * NOTE: we could get a unique-index failure here, in case the same name
740 * has already been used for a type.
742 new_type_oid = AddNewRelationType(relname,
748 * now create an entry in pg_class for the relation.
750 * NOTE: we could get a unique-index failure here, in case someone else is
751 * creating the same relation name in parallel but hadn't committed yet
752 * when we checked for a duplicate name above.
754 AddNewRelationTuple(pg_class_desc,
763 * now add tuples to pg_attribute for the attributes in our new relation.
765 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
766 oidislocal, oidinhcount);
769 * make a dependency link to force the relation to be deleted if its
770 * namespace is. Skip this in bootstrap mode, since we don't make
771 * dependencies while bootstrapping.
773 * Also make a dependency link to its owner.
775 if (!IsBootstrapProcessingMode())
777 ObjectAddress myself,
780 myself.classId = RelationRelationId;
781 myself.objectId = relid;
782 myself.objectSubId = 0;
783 referenced.classId = NamespaceRelationId;
784 referenced.objectId = relnamespace;
785 referenced.objectSubId = 0;
786 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
789 * For composite types, the dependency on owner is tracked for the
790 * pg_type entry, so don't record it here. All other relkinds need
791 * their ownership tracked.
793 if (relkind != RELKIND_COMPOSITE_TYPE)
794 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
798 * store constraints and defaults passed in the tupdesc, if any.
800 * NB: this may do a CommandCounterIncrement and rebuild the relcache
801 * entry, so the relation must be valid and self-consistent at this point.
802 * In particular, there are not yet constraints and defaults anywhere.
804 StoreConstraints(new_rel_desc, tupdesc);
807 * If there's a special on-commit action, remember it
809 if (oncommit != ONCOMMIT_NOOP)
810 register_on_commit_action(relid, oncommit);
813 * ok, the relation has been cataloged, so close our relations and return
814 * the OID of the newly created relation.
816 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
817 heap_close(pg_class_desc, RowExclusiveLock);
824 * RelationRemoveInheritance
826 * Formerly, this routine checked for child relations and aborted the
827 * deletion if any were found. Now we rely on the dependency mechanism
828 * to check for or delete child relations. By the time we get here,
829 * there are no children and we need only remove any pg_inherits rows
830 * linking this relation to its parent(s).
833 RelationRemoveInheritance(Oid relid)
835 Relation catalogRelation;
840 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
843 Anum_pg_inherits_inhrelid,
844 BTEqualStrategyNumber, F_OIDEQ,
845 ObjectIdGetDatum(relid));
847 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
848 SnapshotNow, 1, &key);
850 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
851 simple_heap_delete(catalogRelation, &tuple->t_self);
853 systable_endscan(scan);
854 heap_close(catalogRelation, RowExclusiveLock);
858 * DeleteRelationTuple
860 * Remove pg_class row for the given relid.
862 * Note: this is shared by relation deletion and index deletion. It's
863 * not intended for use anyplace else.
866 DeleteRelationTuple(Oid relid)
868 Relation pg_class_desc;
871 /* Grab an appropriate lock on the pg_class relation */
872 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
874 tup = SearchSysCache(RELOID,
875 ObjectIdGetDatum(relid),
877 if (!HeapTupleIsValid(tup))
878 elog(ERROR, "cache lookup failed for relation %u", relid);
880 /* delete the relation tuple from pg_class, and finish up */
881 simple_heap_delete(pg_class_desc, &tup->t_self);
883 ReleaseSysCache(tup);
885 heap_close(pg_class_desc, RowExclusiveLock);
889 * DeleteAttributeTuples
891 * Remove pg_attribute rows for the given relid.
893 * Note: this is shared by relation deletion and index deletion. It's
894 * not intended for use anyplace else.
897 DeleteAttributeTuples(Oid relid)
904 /* Grab an appropriate lock on the pg_attribute relation */
905 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
907 /* Use the index to scan only attributes of the target relation */
909 Anum_pg_attribute_attrelid,
910 BTEqualStrategyNumber, F_OIDEQ,
911 ObjectIdGetDatum(relid));
913 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
914 SnapshotNow, 1, key);
916 /* Delete all the matching tuples */
917 while ((atttup = systable_getnext(scan)) != NULL)
918 simple_heap_delete(attrel, &atttup->t_self);
920 /* Clean up after the scan */
921 systable_endscan(scan);
922 heap_close(attrel, RowExclusiveLock);
926 * RemoveAttributeById
928 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
929 * deleted in pg_attribute. We also remove pg_statistic entries for it.
930 * (Everything else needed, such as getting rid of any pg_attrdef entry,
931 * is handled by dependency.c.)
934 RemoveAttributeById(Oid relid, AttrNumber attnum)
939 Form_pg_attribute attStruct;
940 char newattname[NAMEDATALEN];
943 * Grab an exclusive lock on the target table, which we will NOT release
944 * until end of transaction. (In the simple case where we are directly
945 * dropping this column, AlterTableDropColumn already did this ... but
946 * when cascading from a drop of some other object, we may not have any
949 rel = relation_open(relid, AccessExclusiveLock);
951 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
953 tuple = SearchSysCacheCopy(ATTNUM,
954 ObjectIdGetDatum(relid),
955 Int16GetDatum(attnum),
957 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
958 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
960 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
964 /* System attribute (probably OID) ... just delete the row */
966 simple_heap_delete(attr_rel, &tuple->t_self);
970 /* Dropping user attributes is lots harder */
972 /* Mark the attribute as dropped */
973 attStruct->attisdropped = true;
976 * Set the type OID to invalid. A dropped attribute's type link
977 * cannot be relied on (once the attribute is dropped, the type might
978 * be too). Fortunately we do not need the type row --- the only
979 * really essential information is the type's typlen and typalign,
980 * which are preserved in the attribute's attlen and attalign. We set
981 * atttypid to zero here as a means of catching code that incorrectly
982 * expects it to be valid.
984 attStruct->atttypid = InvalidOid;
986 /* Remove any NOT NULL constraint the column may have */
987 attStruct->attnotnull = false;
989 /* We don't want to keep stats for it anymore */
990 attStruct->attstattarget = 0;
993 * Change the column name to something that isn't likely to conflict
995 snprintf(newattname, sizeof(newattname),
996 "........pg.dropped.%d........", attnum);
997 namestrcpy(&(attStruct->attname), newattname);
999 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1001 /* keep the system catalog indexes current */
1002 CatalogUpdateIndexes(attr_rel, tuple);
1006 * Because updating the pg_attribute row will trigger a relcache flush for
1007 * the target relation, we need not do anything else to notify other
1008 * backends of the change.
1011 heap_close(attr_rel, RowExclusiveLock);
1014 RemoveStatistics(relid, attnum);
1016 relation_close(rel, NoLock);
1022 * If the specified relation/attribute has a default, remove it.
1023 * (If no default, raise error if complain is true, else return quietly.)
1026 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1027 DropBehavior behavior, bool complain)
1029 Relation attrdef_rel;
1030 ScanKeyData scankeys[2];
1035 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1037 ScanKeyInit(&scankeys[0],
1038 Anum_pg_attrdef_adrelid,
1039 BTEqualStrategyNumber, F_OIDEQ,
1040 ObjectIdGetDatum(relid));
1041 ScanKeyInit(&scankeys[1],
1042 Anum_pg_attrdef_adnum,
1043 BTEqualStrategyNumber, F_INT2EQ,
1044 Int16GetDatum(attnum));
1046 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1047 SnapshotNow, 2, scankeys);
1049 /* There should be at most one matching tuple, but we loop anyway */
1050 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1052 ObjectAddress object;
1054 object.classId = AttrDefaultRelationId;
1055 object.objectId = HeapTupleGetOid(tuple);
1056 object.objectSubId = 0;
1058 performDeletion(&object, behavior);
1063 systable_endscan(scan);
1064 heap_close(attrdef_rel, RowExclusiveLock);
1066 if (complain && !found)
1067 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1072 * RemoveAttrDefaultById
1074 * Remove a pg_attrdef entry specified by OID. This is the guts of
1075 * attribute-default removal. Note it should be called via performDeletion,
1079 RemoveAttrDefaultById(Oid attrdefId)
1081 Relation attrdef_rel;
1084 ScanKeyData scankeys[1];
1088 AttrNumber myattnum;
1090 /* Grab an appropriate lock on the pg_attrdef relation */
1091 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1093 /* Find the pg_attrdef tuple */
1094 ScanKeyInit(&scankeys[0],
1095 ObjectIdAttributeNumber,
1096 BTEqualStrategyNumber, F_OIDEQ,
1097 ObjectIdGetDatum(attrdefId));
1099 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1100 SnapshotNow, 1, scankeys);
1102 tuple = systable_getnext(scan);
1103 if (!HeapTupleIsValid(tuple))
1104 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1106 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1107 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1109 /* Get an exclusive lock on the relation owning the attribute */
1110 myrel = relation_open(myrelid, AccessExclusiveLock);
1112 /* Now we can delete the pg_attrdef row */
1113 simple_heap_delete(attrdef_rel, &tuple->t_self);
1115 systable_endscan(scan);
1116 heap_close(attrdef_rel, RowExclusiveLock);
1118 /* Fix the pg_attribute row */
1119 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1121 tuple = SearchSysCacheCopy(ATTNUM,
1122 ObjectIdGetDatum(myrelid),
1123 Int16GetDatum(myattnum),
1125 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1126 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1129 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1131 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1133 /* keep the system catalog indexes current */
1134 CatalogUpdateIndexes(attr_rel, tuple);
1137 * Our update of the pg_attribute row will force a relcache rebuild, so
1138 * there's nothing else to do here.
1140 heap_close(attr_rel, RowExclusiveLock);
1142 /* Keep lock on attribute's rel until end of xact */
1143 relation_close(myrel, NoLock);
1147 * heap_drop_with_catalog - removes specified relation from catalogs
1149 * Note that this routine is not responsible for dropping objects that are
1150 * linked to the pg_class entry via dependencies (for example, indexes and
1151 * constraints). Those are deleted by the dependency-tracing logic in
1152 * dependency.c before control gets here. In general, therefore, this routine
1153 * should never be called directly; go through performDeletion() instead.
1156 heap_drop_with_catalog(Oid relid)
1161 * Open and lock the relation.
1163 rel = relation_open(relid, AccessExclusiveLock);
1166 * Schedule unlinking of the relation's physical file at commit.
1168 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1169 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1171 RelationOpenSmgr(rel);
1172 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
1176 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1177 * until transaction commit. This ensures no one else will try to do
1178 * something with the doomed relation.
1180 relation_close(rel, NoLock);
1183 * Forget any ON COMMIT action for the rel
1185 remove_on_commit_action(relid);
1188 * Flush the relation from the relcache. We want to do this before
1189 * starting to remove catalog entries, just to be certain that no relcache
1190 * entry rebuild will happen partway through. (That should not really
1191 * matter, since we don't do CommandCounterIncrement here, but let's be
1194 RelationForgetRelation(relid);
1197 * remove inheritance information
1199 RelationRemoveInheritance(relid);
1204 RemoveStatistics(relid, 0);
1207 * delete attribute tuples
1209 DeleteAttributeTuples(relid);
1212 * delete relation tuple
1214 DeleteRelationTuple(relid);
1219 * Store a default expression for column attnum of relation rel.
1220 * The expression must be presented as a nodeToString() string.
1223 StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin)
1230 static char nulls[4] = {' ', ' ', ' ', ' '};
1233 Form_pg_attribute attStruct;
1235 ObjectAddress colobject,
1239 * Need to construct source equivalent of given node-string.
1241 expr = stringToNode(adbin);
1246 adsrc = deparse_expression(expr,
1247 deparse_context_for(RelationGetRelationName(rel),
1248 RelationGetRelid(rel)),
1252 * Make the pg_attrdef entry.
1254 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1255 values[Anum_pg_attrdef_adnum - 1] = attnum;
1256 values[Anum_pg_attrdef_adbin - 1] = DirectFunctionCall1(textin,
1257 CStringGetDatum(adbin));
1258 values[Anum_pg_attrdef_adsrc - 1] = DirectFunctionCall1(textin,
1259 CStringGetDatum(adsrc));
1261 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1263 tuple = heap_formtuple(adrel->rd_att, values, nulls);
1264 attrdefOid = simple_heap_insert(adrel, tuple);
1266 CatalogUpdateIndexes(adrel, tuple);
1268 defobject.classId = AttrDefaultRelationId;
1269 defobject.objectId = attrdefOid;
1270 defobject.objectSubId = 0;
1272 heap_close(adrel, RowExclusiveLock);
1274 /* now can free some of the stuff allocated above */
1275 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1276 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1277 heap_freetuple(tuple);
1281 * Update the pg_attribute entry for the column to show that a default
1284 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1285 atttup = SearchSysCacheCopy(ATTNUM,
1286 ObjectIdGetDatum(RelationGetRelid(rel)),
1287 Int16GetDatum(attnum),
1289 if (!HeapTupleIsValid(atttup))
1290 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1291 attnum, RelationGetRelid(rel));
1292 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1293 if (!attStruct->atthasdef)
1295 attStruct->atthasdef = true;
1296 simple_heap_update(attrrel, &atttup->t_self, atttup);
1297 /* keep catalog indexes current */
1298 CatalogUpdateIndexes(attrrel, atttup);
1300 heap_close(attrrel, RowExclusiveLock);
1301 heap_freetuple(atttup);
1304 * Make a dependency so that the pg_attrdef entry goes away if the column
1305 * (or whole table) is deleted.
1307 colobject.classId = RelationRelationId;
1308 colobject.objectId = RelationGetRelid(rel);
1309 colobject.objectSubId = attnum;
1311 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1314 * Record dependencies on objects used in the expression, too.
1316 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1320 * Store a check-constraint expression for the given relation.
1321 * The expression must be presented as a nodeToString() string.
1323 * Caller is responsible for updating the count of constraints
1324 * in the pg_class entry for the relation.
1327 StoreRelCheck(Relation rel, char *ccname, char *ccbin)
1336 * Convert condition to an expression tree.
1338 expr = stringToNode(ccbin);
1343 ccsrc = deparse_expression(expr,
1344 deparse_context_for(RelationGetRelationName(rel),
1345 RelationGetRelid(rel)),
1349 * Find columns of rel that are used in ccbin
1351 * NB: pull_var_clause is okay here only because we don't allow subselects
1352 * in check constraints; it would fail to examine the contents of
1355 varList = pull_var_clause(expr, false);
1356 keycount = list_length(varList);
1363 attNos = (int16 *) palloc(keycount * sizeof(int16));
1364 foreach(vl, varList)
1366 Var *var = (Var *) lfirst(vl);
1369 for (j = 0; j < i; j++)
1370 if (attNos[j] == var->varattno)
1373 attNos[i++] = var->varattno;
1381 * Create the Check Constraint
1383 CreateConstraintEntry(ccname, /* Constraint Name */
1384 RelationGetNamespace(rel), /* namespace */
1385 CONSTRAINT_CHECK, /* Constraint Type */
1386 false, /* Is Deferrable */
1387 false, /* Is Deferred */
1388 RelationGetRelid(rel), /* relation */
1389 attNos, /* attrs in the constraint */
1390 keycount, /* # attrs in the constraint */
1391 InvalidOid, /* not a domain constraint */
1392 InvalidOid, /* Foreign key fields */
1398 InvalidOid, /* no associated index */
1399 expr, /* Tree form check constraint */
1400 ccbin, /* Binary form check constraint */
1401 ccsrc); /* Source form check constraint */
1407 * Store defaults and constraints passed in via the tuple constraint struct.
1409 * NOTE: only pre-cooked expressions will be passed this way, which is to
1410 * say expressions inherited from an existing relation. Newly parsed
1411 * expressions can be added later, by direct calls to StoreAttrDefault
1412 * and StoreRelCheck (see AddRelationRawConstraints()).
1415 StoreConstraints(Relation rel, TupleDesc tupdesc)
1417 TupleConstr *constr = tupdesc->constr;
1421 return; /* nothing to do */
1424 * Deparsing of constraint expressions will fail unless the just-created
1425 * pg_attribute tuples for this relation are made visible. So, bump the
1426 * command counter. CAUTION: this will cause a relcache entry rebuild.
1428 CommandCounterIncrement();
1430 for (i = 0; i < constr->num_defval; i++)
1431 StoreAttrDefault(rel, constr->defval[i].adnum,
1432 constr->defval[i].adbin);
1434 for (i = 0; i < constr->num_check; i++)
1435 StoreRelCheck(rel, constr->check[i].ccname,
1436 constr->check[i].ccbin);
1438 if (constr->num_check > 0)
1439 SetRelationNumChecks(rel, constr->num_check);
1443 * AddRelationRawConstraints
1445 * Add raw (not-yet-transformed) column default expressions and/or constraint
1446 * check expressions to an existing relation. This is defined to do both
1447 * for efficiency in DefineRelation, but of course you can do just one or
1448 * the other by passing empty lists.
1450 * rel: relation to be modified
1451 * rawColDefaults: list of RawColumnDefault structures
1452 * rawConstraints: list of Constraint nodes
1454 * All entries in rawColDefaults will be processed. Entries in rawConstraints
1455 * will be processed only if they are CONSTR_CHECK type and contain a "raw"
1458 * Returns a list of CookedConstraint nodes that shows the cooked form of
1459 * the default and constraint expressions added to the relation.
1461 * NB: caller should have opened rel with AccessExclusiveLock, and should
1462 * hold that lock till end of transaction. Also, we assume the caller has
1463 * done a CommandCounterIncrement if necessary to make the relation's catalog
1467 AddRelationRawConstraints(Relation rel,
1468 List *rawColDefaults,
1469 List *rawConstraints)
1471 List *cookedConstraints = NIL;
1472 TupleDesc tupleDesc;
1473 TupleConstr *oldconstr;
1481 CookedConstraint *cooked;
1484 * Get info about existing constraints.
1486 tupleDesc = RelationGetDescr(rel);
1487 oldconstr = tupleDesc->constr;
1489 numoldchecks = oldconstr->num_check;
1494 * Create a dummy ParseState and insert the target relation as its sole
1495 * rangetable entry. We need a ParseState for transformExpr.
1497 pstate = make_parsestate(NULL);
1498 rte = addRangeTableEntryForRelation(pstate,
1503 addRTEtoQuery(pstate, rte, true, true, true);
1506 * Process column default expressions.
1508 foreach(cell, rawColDefaults)
1510 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1511 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1513 expr = cookDefault(pstate, colDef->raw_default,
1514 atp->atttypid, atp->atttypmod,
1515 NameStr(atp->attname));
1517 StoreAttrDefault(rel, colDef->attnum, nodeToString(expr));
1519 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1520 cooked->contype = CONSTR_DEFAULT;
1521 cooked->name = NULL;
1522 cooked->attnum = colDef->attnum;
1523 cooked->expr = expr;
1524 cookedConstraints = lappend(cookedConstraints, cooked);
1528 * Process constraint expressions.
1530 numchecks = numoldchecks;
1532 foreach(cell, rawConstraints)
1534 Constraint *cdef = (Constraint *) lfirst(cell);
1537 if (cdef->contype != CONSTR_CHECK || cdef->raw_expr == NULL)
1539 Assert(cdef->cooked_expr == NULL);
1542 * Transform raw parsetree to executable expression.
1544 expr = transformExpr(pstate, cdef->raw_expr);
1547 * Make sure it yields a boolean result.
1549 expr = coerce_to_boolean(pstate, expr, "CHECK");
1552 * Make sure no outside relations are referred to.
1554 if (list_length(pstate->p_rtable) != 1)
1556 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1557 errmsg("only table \"%s\" can be referenced in check constraint",
1558 RelationGetRelationName(rel))));
1561 * No subplans or aggregates, either...
1563 if (pstate->p_hasSubLinks)
1565 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1566 errmsg("cannot use subquery in check constraint")));
1567 if (pstate->p_hasAggs)
1569 (errcode(ERRCODE_GROUPING_ERROR),
1570 errmsg("cannot use aggregate function in check constraint")));
1573 * Check name uniqueness, or generate a name if none was given.
1575 if (cdef->name != NULL)
1579 ccname = cdef->name;
1580 /* Check against pre-existing constraints */
1581 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
1582 RelationGetRelid(rel),
1583 RelationGetNamespace(rel),
1586 (errcode(ERRCODE_DUPLICATE_OBJECT),
1587 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1588 ccname, RelationGetRelationName(rel))));
1589 /* Check against other new constraints */
1590 /* Needed because we don't do CommandCounterIncrement in loop */
1591 foreach(cell2, checknames)
1593 if (strcmp((char *) lfirst(cell2), ccname) == 0)
1595 (errcode(ERRCODE_DUPLICATE_OBJECT),
1596 errmsg("check constraint \"%s\" already exists",
1603 * When generating a name, we want to create "tab_col_check" for a
1604 * column constraint and "tab_check" for a table constraint. We
1605 * no longer have any info about the syntactic positioning of the
1606 * constraint phrase, so we approximate this by seeing whether the
1607 * expression references more than one column. (If the user
1608 * played by the rules, the result is the same...)
1610 * Note: pull_var_clause() doesn't descend into sublinks, but we
1611 * eliminated those above; and anyway this only needs to be an
1612 * approximate answer.
1617 vars = pull_var_clause(expr, false);
1619 /* eliminate duplicates */
1620 vars = list_union(NIL, vars);
1622 if (list_length(vars) == 1)
1623 colname = get_attname(RelationGetRelid(rel),
1624 ((Var *) linitial(vars))->varattno);
1628 ccname = ChooseConstraintName(RelationGetRelationName(rel),
1631 RelationGetNamespace(rel),
1635 /* save name for future checks */
1636 checknames = lappend(checknames, ccname);
1641 StoreRelCheck(rel, ccname, nodeToString(expr));
1645 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1646 cooked->contype = CONSTR_CHECK;
1647 cooked->name = ccname;
1649 cooked->expr = expr;
1650 cookedConstraints = lappend(cookedConstraints, cooked);
1654 * Update the count of constraints in the relation's pg_class tuple. We do
1655 * this even if there was no change, in order to ensure that an SI update
1656 * message is sent out for the pg_class tuple, which will force other
1657 * backends to rebuild their relcache entries for the rel. (This is
1658 * critical if we added defaults but not constraints.)
1660 SetRelationNumChecks(rel, numchecks);
1662 return cookedConstraints;
1666 * Update the count of constraints in the relation's pg_class tuple.
1668 * Caller had better hold exclusive lock on the relation.
1670 * An important side effect is that a SI update message will be sent out for
1671 * the pg_class tuple, which will force other backends to rebuild their
1672 * relcache entries for the rel. Also, this backend will rebuild its
1673 * own relcache entry at the next CommandCounterIncrement.
1676 SetRelationNumChecks(Relation rel, int numchecks)
1680 Form_pg_class relStruct;
1682 relrel = heap_open(RelationRelationId, RowExclusiveLock);
1683 reltup = SearchSysCacheCopy(RELOID,
1684 ObjectIdGetDatum(RelationGetRelid(rel)),
1686 if (!HeapTupleIsValid(reltup))
1687 elog(ERROR, "cache lookup failed for relation %u",
1688 RelationGetRelid(rel));
1689 relStruct = (Form_pg_class) GETSTRUCT(reltup);
1691 if (relStruct->relchecks != numchecks)
1693 relStruct->relchecks = numchecks;
1695 simple_heap_update(relrel, &reltup->t_self, reltup);
1697 /* keep catalog indexes current */
1698 CatalogUpdateIndexes(relrel, reltup);
1702 /* Skip the disk update, but force relcache inval anyway */
1703 CacheInvalidateRelcache(rel);
1706 heap_freetuple(reltup);
1707 heap_close(relrel, RowExclusiveLock);
1711 * Take a raw default and convert it to a cooked format ready for
1714 * Parse state should be set up to recognize any vars that might appear
1715 * in the expression. (Even though we plan to reject vars, it's more
1716 * user-friendly to give the correct error message than "unknown var".)
1718 * If atttypid is not InvalidOid, coerce the expression to the specified
1719 * type (and typmod atttypmod). attname is only needed in this case:
1720 * it is used in the error message, if any.
1723 cookDefault(ParseState *pstate,
1731 Assert(raw_default != NULL);
1734 * Transform raw parsetree to executable expression.
1736 expr = transformExpr(pstate, raw_default);
1739 * Make sure default expr does not refer to any vars.
1741 if (contain_var_clause(expr))
1743 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1744 errmsg("cannot use column references in default expression")));
1747 * It can't return a set either.
1749 if (expression_returns_set(expr))
1751 (errcode(ERRCODE_DATATYPE_MISMATCH),
1752 errmsg("default expression must not return a set")));
1755 * No subplans or aggregates, either...
1757 if (pstate->p_hasSubLinks)
1759 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1760 errmsg("cannot use subquery in default expression")));
1761 if (pstate->p_hasAggs)
1763 (errcode(ERRCODE_GROUPING_ERROR),
1764 errmsg("cannot use aggregate function in default expression")));
1767 * Coerce the expression to the correct type and typmod, if given. This
1768 * should match the parser's processing of non-defaulted expressions ---
1769 * see updateTargetListEntry().
1771 if (OidIsValid(atttypid))
1773 Oid type_id = exprType(expr);
1775 expr = coerce_to_target_type(pstate, expr, type_id,
1776 atttypid, atttypmod,
1777 COERCION_ASSIGNMENT,
1778 COERCE_IMPLICIT_CAST);
1781 (errcode(ERRCODE_DATATYPE_MISMATCH),
1782 errmsg("column \"%s\" is of type %s"
1783 " but default expression is of type %s",
1785 format_type_be(atttypid),
1786 format_type_be(type_id)),
1787 errhint("You will need to rewrite or cast the expression.")));
1795 * Removes all constraints on a relation that match the given name.
1797 * It is the responsibility of the calling function to acquire a suitable
1798 * lock on the relation.
1800 * Returns: The number of constraints removed.
1803 RemoveRelConstraints(Relation rel, const char *constrName,
1804 DropBehavior behavior)
1808 SysScanDesc conscan;
1812 /* Grab an appropriate lock on the pg_constraint relation */
1813 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
1815 /* Use the index to scan only constraints of the target relation */
1816 ScanKeyInit(&key[0],
1817 Anum_pg_constraint_conrelid,
1818 BTEqualStrategyNumber, F_OIDEQ,
1819 ObjectIdGetDatum(RelationGetRelid(rel)));
1821 conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true,
1822 SnapshotNow, 1, key);
1825 * Scan over the result set, removing any matching entries.
1827 while ((contup = systable_getnext(conscan)) != NULL)
1829 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
1831 if (strcmp(NameStr(con->conname), constrName) == 0)
1833 ObjectAddress conobj;
1835 conobj.classId = ConstraintRelationId;
1836 conobj.objectId = HeapTupleGetOid(contup);
1837 conobj.objectSubId = 0;
1839 performDeletion(&conobj, behavior);
1845 /* Clean up after the scan */
1846 systable_endscan(conscan);
1847 heap_close(conrel, RowExclusiveLock);
1854 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
1856 * If attnum is zero, remove all entries for rel; else remove only the one
1860 RemoveStatistics(Oid relid, AttrNumber attnum)
1862 Relation pgstatistic;
1868 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
1870 ScanKeyInit(&key[0],
1871 Anum_pg_statistic_starelid,
1872 BTEqualStrategyNumber, F_OIDEQ,
1873 ObjectIdGetDatum(relid));
1879 ScanKeyInit(&key[1],
1880 Anum_pg_statistic_staattnum,
1881 BTEqualStrategyNumber, F_INT2EQ,
1882 Int16GetDatum(attnum));
1886 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumIndexId, true,
1887 SnapshotNow, nkeys, key);
1889 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1890 simple_heap_delete(pgstatistic, &tuple->t_self);
1892 systable_endscan(scan);
1894 heap_close(pgstatistic, RowExclusiveLock);
1899 * RelationTruncateIndexes - truncate all
1900 * indexes associated with the heap relation to zero tuples.
1902 * The routine will truncate and then reconstruct the indexes on
1903 * the relation specified by the heapId parameter.
1906 RelationTruncateIndexes(Oid heapId)
1908 Relation heapRelation;
1912 * Open the heap rel. We need grab no lock because we assume
1913 * heap_truncate is holding an exclusive lock on the heap rel.
1915 heapRelation = heap_open(heapId, NoLock);
1917 /* Ask the relcache to produce a list of the indexes of the rel */
1918 foreach(indlist, RelationGetIndexList(heapRelation))
1920 Oid indexId = lfirst_oid(indlist);
1921 Relation currentIndex;
1922 IndexInfo *indexInfo;
1924 /* Open the index relation */
1925 currentIndex = index_open(indexId);
1927 /* Obtain exclusive lock on it, just to be sure */
1928 LockRelation(currentIndex, AccessExclusiveLock);
1930 /* Fetch info needed for index_build */
1931 indexInfo = BuildIndexInfo(currentIndex);
1933 /* Now truncate the actual file (and discard buffers) */
1934 RelationTruncate(currentIndex, 0);
1936 /* Initialize the index and rebuild */
1937 /* Note: we do not need to re-establish pkey or toast settings */
1938 index_build(heapRelation, currentIndex, indexInfo, false, false);
1940 /* We're done with this index */
1941 index_close(currentIndex);
1944 /* And now done with the heap; but keep lock until commit */
1945 heap_close(heapRelation, NoLock);
1951 * This routine deletes all data within all the specified relations.
1953 * This is not transaction-safe! There is another, transaction-safe
1954 * implementation in commands/tablecmds.c. We now use this only for
1955 * ON COMMIT truncation of temporary tables, where it doesn't matter.
1958 heap_truncate(List *relids)
1960 List *relations = NIL;
1963 /* Open relations for processing, and grab exclusive access on each */
1964 foreach(cell, relids)
1966 Oid rid = lfirst_oid(cell);
1970 rel = heap_open(rid, AccessExclusiveLock);
1971 relations = lappend(relations, rel);
1973 /* If there is a toast table, add it to the list too */
1974 toastrelid = rel->rd_rel->reltoastrelid;
1975 if (OidIsValid(toastrelid))
1977 rel = heap_open(toastrelid, AccessExclusiveLock);
1978 relations = lappend(relations, rel);
1982 /* Don't allow truncate on tables that are referenced by foreign keys */
1983 heap_truncate_check_FKs(relations, true);
1986 foreach(cell, relations)
1988 Relation rel = lfirst(cell);
1990 /* Truncate the actual file (and discard buffers) */
1991 RelationTruncate(rel, 0);
1993 /* If this relation has indexes, truncate the indexes too */
1994 RelationTruncateIndexes(RelationGetRelid(rel));
1997 * Close the relation, but keep exclusive lock on it until commit.
1999 heap_close(rel, NoLock);
2004 * heap_truncate_check_FKs
2005 * Check for foreign keys referencing a list of relations that
2006 * are to be truncated, and raise error if there are any
2008 * We disallow such FKs (except self-referential ones) since the whole point
2009 * of TRUNCATE is to not scan the individual rows to be thrown away.
2011 * This is split out so it can be shared by both implementations of truncate.
2012 * Caller should already hold a suitable lock on the relations.
2014 * tempTables is only used to select an appropriate error message.
2017 heap_truncate_check_FKs(List *relations, bool tempTables)
2024 * Build a list of OIDs of the interesting relations.
2026 * If a relation has no triggers, then it can neither have FKs nor be
2027 * referenced by a FK from another table, so we can ignore it.
2029 foreach(cell, relations)
2031 Relation rel = lfirst(cell);
2033 if (rel->rd_rel->reltriggers != 0)
2034 oids = lappend_oid(oids, RelationGetRelid(rel));
2038 * Fast path: if no relation has triggers, none has FKs either.
2044 * Otherwise, must scan pg_constraint. We make one pass with all the
2045 * relations considered; if this finds nothing, then all is well.
2047 dependents = heap_truncate_find_FKs(oids);
2048 if (dependents == NIL)
2052 * Otherwise we repeat the scan once per relation to identify a particular
2053 * pair of relations to complain about. This is pretty slow, but
2054 * performance shouldn't matter much in a failure path. The reason for
2055 * doing things this way is to ensure that the message produced is not
2056 * dependent on chance row locations within pg_constraint.
2060 Oid relid = lfirst_oid(cell);
2063 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2065 foreach(cell2, dependents)
2067 Oid relid2 = lfirst_oid(cell2);
2069 if (!list_member_oid(oids, relid2))
2071 char *relname = get_rel_name(relid);
2072 char *relname2 = get_rel_name(relid2);
2076 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2077 errmsg("unsupported ON COMMIT and foreign key combination"),
2078 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2079 relname2, relname)));
2082 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2083 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2084 errdetail("Table \"%s\" references \"%s\".",
2086 errhint("Truncate table \"%s\" at the same time, "
2087 "or use TRUNCATE ... CASCADE.",
2095 * heap_truncate_find_FKs
2096 * Find relations having foreign keys referencing any of the given rels
2098 * Input and result are both lists of relation OIDs. The result contains
2099 * no duplicates, does *not* include any rels that were already in the input
2100 * list, and is sorted in OID order. (The last property is enforced mainly
2101 * to guarantee consistent behavior in the regression tests; we don't want
2102 * behavior to change depending on chance locations of rows in pg_constraint.)
2104 * Note: caller should already have appropriate lock on all rels mentioned
2105 * in relationIds. Since adding or dropping an FK requires exclusive lock
2106 * on both rels, this ensures that the answer will be stable.
2109 heap_truncate_find_FKs(List *relationIds)
2113 SysScanDesc fkeyScan;
2117 * Must scan pg_constraint. Right now, it is a seqscan because
2118 * there is no available index on confrelid.
2120 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2122 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2123 SnapshotNow, 0, NULL);
2125 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2127 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2129 /* Not a foreign key */
2130 if (con->contype != CONSTRAINT_FOREIGN)
2133 /* Not referencing one of our list of tables */
2134 if (!list_member_oid(relationIds, con->confrelid))
2137 /* Add referencer unless already in input or result list */
2138 if (!list_member_oid(relationIds, con->conrelid))
2139 result = insert_ordered_unique_oid(result, con->conrelid);
2142 systable_endscan(fkeyScan);
2143 heap_close(fkeyRel, AccessShareLock);
2149 * insert_ordered_unique_oid
2150 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2151 * and eliminating duplicates
2153 * Building the ordered list this way is O(N^2), but with a pretty small
2154 * constant, so for the number of entries we expect it will probably be
2155 * faster than trying to apply qsort(). It seems unlikely someone would be
2156 * trying to truncate a table with thousands of dependent tables ...
2159 insert_ordered_unique_oid(List *list, Oid datum)
2163 /* Does the datum belong at the front? */
2164 if (list == NIL || datum < linitial_oid(list))
2165 return lcons_oid(datum, list);
2166 /* Does it match the first entry? */
2167 if (datum == linitial_oid(list))
2168 return list; /* duplicate, so don't insert */
2169 /* No, so find the entry it belongs after */
2170 prev = list_head(list);
2173 ListCell *curr = lnext(prev);
2175 if (curr == NULL || datum < lfirst_oid(curr))
2176 break; /* it belongs after 'prev', before 'curr' */
2178 if (datum == lfirst_oid(curr))
2179 return list; /* duplicate, so don't insert */
2183 /* Insert datum into list after 'prev' */
2184 lappend_cell_oid(list, prev, datum);