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.298 2006/04/30 01:08:06 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 "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "optimizer/clauses.h"
50 #include "optimizer/planmain.h"
51 #include "optimizer/var.h"
52 #include "parser/parse_coerce.h"
53 #include "parser/parse_expr.h"
54 #include "parser/parse_relation.h"
55 #include "rewrite/rewriteRemove.h"
56 #include "storage/smgr.h"
57 #include "utils/builtins.h"
58 #include "utils/fmgroids.h"
59 #include "utils/inval.h"
60 #include "utils/lsyscache.h"
61 #include "utils/relcache.h"
62 #include "utils/syscache.h"
65 static void AddNewRelationTuple(Relation pg_class_desc,
66 Relation new_rel_desc,
67 Oid new_rel_oid, Oid new_type_oid,
70 static Oid AddNewRelationType(const char *typeName,
74 static void RelationRemoveInheritance(Oid relid);
75 static void StoreRelCheck(Relation rel, char *ccname, char *ccbin);
76 static void StoreConstraints(Relation rel, TupleDesc tupdesc);
77 static void SetRelationNumChecks(Relation rel, int numchecks);
80 /* ----------------------------------------------------------------
81 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
83 * these should all be moved to someplace in the lib/catalog
84 * module, if not obliterated first.
85 * ----------------------------------------------------------------
91 * Should the system special case these attributes in the future?
92 * Advantage: consume much less space in the ATTRIBUTE relation.
93 * Disadvantage: special cases will be all over the place.
96 static FormData_pg_attribute a1 = {
97 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
98 SelfItemPointerAttributeNumber, 0, -1, -1,
99 false, 'p', 's', true, false, false, true, 0
102 static FormData_pg_attribute a2 = {
103 0, {"oid"}, OIDOID, 0, sizeof(Oid),
104 ObjectIdAttributeNumber, 0, -1, -1,
105 true, 'p', 'i', true, false, false, true, 0
108 static FormData_pg_attribute a3 = {
109 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
110 MinTransactionIdAttributeNumber, 0, -1, -1,
111 true, 'p', 'i', true, false, false, true, 0
114 static FormData_pg_attribute a4 = {
115 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
116 MinCommandIdAttributeNumber, 0, -1, -1,
117 true, 'p', 'i', true, false, false, true, 0
120 static FormData_pg_attribute a5 = {
121 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
122 MaxTransactionIdAttributeNumber, 0, -1, -1,
123 true, 'p', 'i', true, false, false, true, 0
126 static FormData_pg_attribute a6 = {
127 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
128 MaxCommandIdAttributeNumber, 0, -1, -1,
129 true, 'p', 'i', true, false, false, true, 0
133 * We decided to call this attribute "tableoid" rather than say
134 * "classoid" on the basis that in the future there may be more than one
135 * table of a particular class/type. In any case table is still the word
138 static FormData_pg_attribute a7 = {
139 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
140 TableOidAttributeNumber, 0, -1, -1,
141 true, 'p', 'i', true, false, false, true, 0
144 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
147 * This function returns a Form_pg_attribute pointer for a system attribute.
148 * Note that we elog if the presented attno is invalid, which would only
149 * happen if there's a problem upstream.
152 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
154 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
155 elog(ERROR, "invalid system attribute number %d", attno);
156 if (attno == ObjectIdAttributeNumber && !relhasoids)
157 elog(ERROR, "invalid system attribute number %d", attno);
158 return SysAtt[-attno - 1];
162 * If the given name is a system attribute name, return a Form_pg_attribute
163 * pointer for a prototype definition. If not, return NULL.
166 SystemAttributeByName(const char *attname, bool relhasoids)
170 for (j = 0; j < (int) lengthof(SysAtt); j++)
172 Form_pg_attribute att = SysAtt[j];
174 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
176 if (strcmp(NameStr(att->attname), attname) == 0)
185 /* ----------------------------------------------------------------
186 * XXX END OF UGLY HARD CODED BADNESS XXX
187 * ---------------------------------------------------------------- */
190 /* ----------------------------------------------------------------
191 * heap_create - Create an uncataloged heap relation
193 * Note API change: the caller must now always provide the OID
194 * to use for the relation.
196 * rel->rd_rel is initialized by RelationBuildLocalRelation,
197 * and is mostly zeroes at return.
198 * ----------------------------------------------------------------
201 heap_create(const char *relname,
207 bool shared_relation,
208 bool allow_system_table_mods)
213 /* The caller must have provided an OID for the relation. */
214 Assert(OidIsValid(relid));
219 if (!allow_system_table_mods &&
220 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
221 IsNormalProcessingMode())
223 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
224 errmsg("permission denied to create \"%s.%s\"",
225 get_namespace_name(relnamespace), relname),
226 errdetail("System catalog modifications are currently disallowed.")));
229 * Decide if we need storage or not, and handle a couple other special
230 * cases for particular relkinds.
235 case RELKIND_COMPOSITE_TYPE:
236 create_storage = false;
239 * Force reltablespace to zero if the relation has no physical
240 * storage. This is mainly just for cleanliness' sake.
242 reltablespace = InvalidOid;
244 case RELKIND_SEQUENCE:
245 create_storage = true;
248 * Force reltablespace to zero for sequences, since we don't
249 * support moving them around into different tablespaces.
251 reltablespace = InvalidOid;
254 create_storage = true;
259 * Never allow a pg_class entry to explicitly specify the database's
260 * default tablespace in reltablespace; force it to zero instead. This
261 * ensures that if the database is cloned with a different default
262 * tablespace, the pg_class entry will still match where CREATE DATABASE
263 * will put the physically copied relation.
265 * Yes, this is a bit of a hack.
267 if (reltablespace == MyDatabaseTableSpace)
268 reltablespace = InvalidOid;
271 * build the relcache entry.
273 rel = RelationBuildLocalRelation(relname,
281 * have the storage manager create the relation's disk file, if needed.
285 Assert(rel->rd_smgr == NULL);
286 RelationOpenSmgr(rel);
287 smgrcreate(rel->rd_smgr, rel->rd_istemp, false);
293 /* ----------------------------------------------------------------
294 * heap_create_with_catalog - Create a cataloged relation
296 * this is done in multiple steps:
298 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
299 * descriptor contains a valid set of attribute names and types
301 * 2) pg_class is opened and get_relname_relid()
302 * performs a scan to ensure that no relation with the
303 * same name already exists.
305 * 3) heap_create() is called to create the new relation on disk.
307 * 4) TypeCreate() is called to define a new type corresponding
308 * to the new relation.
310 * 5) AddNewRelationTuple() is called to register the
311 * relation in pg_class.
313 * 6) AddNewAttributeTuples() is called to register the
314 * new relation's schema in pg_attribute.
316 * 7) StoreConstraints is called () - vadim 08/22/97
318 * 8) the relations are closed and the new relation's oid
321 * ----------------------------------------------------------------
324 /* --------------------------------
325 * CheckAttributeNamesTypes
327 * this is used to make certain the tuple descriptor contains a
328 * valid set of attribute names and datatypes. a problem simply
329 * generates ereport(ERROR) which aborts the current transaction.
330 * --------------------------------
333 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
337 int natts = tupdesc->natts;
339 /* Sanity check on column count */
340 if (natts < 0 || natts > MaxHeapAttributeNumber)
342 (errcode(ERRCODE_TOO_MANY_COLUMNS),
343 errmsg("tables can have at most %d columns",
344 MaxHeapAttributeNumber)));
347 * first check for collision with system attribute names
349 * Skip this for a view or type relation, since those don't have system
352 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
354 for (i = 0; i < natts; i++)
356 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
357 tupdesc->tdhasoid) != NULL)
359 (errcode(ERRCODE_DUPLICATE_COLUMN),
360 errmsg("column name \"%s\" conflicts with a system column name",
361 NameStr(tupdesc->attrs[i]->attname))));
366 * next check for repeated attribute names
368 for (i = 1; i < natts; i++)
370 for (j = 0; j < i; j++)
372 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
373 NameStr(tupdesc->attrs[i]->attname)) == 0)
375 (errcode(ERRCODE_DUPLICATE_COLUMN),
376 errmsg("column name \"%s\" is duplicated",
377 NameStr(tupdesc->attrs[j]->attname))));
382 * next check the attribute types
384 for (i = 0; i < natts; i++)
386 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
387 tupdesc->attrs[i]->atttypid);
391 /* --------------------------------
394 * Verify that the proposed datatype of an attribute is legal.
395 * This is needed because there are types (and pseudo-types)
396 * in the catalogs that we do not support as elements of real tuples.
397 * --------------------------------
400 CheckAttributeType(const char *attname, Oid atttypid)
402 char att_typtype = get_typtype(atttypid);
405 * Warn user, but don't fail, if column to be created has UNKNOWN type
406 * (usually as a result of a 'retrieve into' - jolly)
408 * Refuse any attempt to create a pseudo-type column.
410 if (atttypid == UNKNOWNOID)
412 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
413 errmsg("column \"%s\" has type \"unknown\"", attname),
414 errdetail("Proceeding with relation creation anyway.")));
415 else if (att_typtype == 'p')
417 /* Special hack for pg_statistic: allow ANYARRAY during initdb */
418 if (atttypid != ANYARRAYOID || IsUnderPostmaster)
420 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
421 errmsg("column \"%s\" has pseudo-type %s",
422 attname, format_type_be(atttypid))));
426 /* --------------------------------
427 * AddNewAttributeTuples
429 * this registers the new relation's schema by adding
430 * tuples to pg_attribute.
431 * --------------------------------
434 AddNewAttributeTuples(Oid new_rel_oid,
440 const Form_pg_attribute *dpp;
444 CatalogIndexState indstate;
445 int natts = tupdesc->natts;
446 ObjectAddress myself,
450 * open pg_attribute and its indexes.
452 rel = heap_open(AttributeRelationId, RowExclusiveLock);
454 indstate = CatalogOpenIndexes(rel);
457 * First we add the user attributes. This is also a convenient place to
458 * add dependencies on their datatypes.
460 dpp = tupdesc->attrs;
461 for (i = 0; i < natts; i++)
463 /* Fill in the correct relation OID */
464 (*dpp)->attrelid = new_rel_oid;
465 /* Make sure these are OK, too */
466 (*dpp)->attstattarget = -1;
467 (*dpp)->attcacheoff = -1;
469 tup = heap_addheader(Natts_pg_attribute,
471 ATTRIBUTE_TUPLE_SIZE,
474 simple_heap_insert(rel, tup);
476 CatalogIndexInsert(indstate, tup);
480 myself.classId = RelationRelationId;
481 myself.objectId = new_rel_oid;
482 myself.objectSubId = i + 1;
483 referenced.classId = TypeRelationId;
484 referenced.objectId = (*dpp)->atttypid;
485 referenced.objectSubId = 0;
486 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
492 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
493 * all for a view or type relation. We don't bother with making datatype
494 * dependencies here, since presumably all these types are pinned.
496 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
499 for (i = 0; i < -1 - FirstLowInvalidHeapAttributeNumber; i++)
501 if (tupdesc->tdhasoid ||
502 (*dpp)->attnum != ObjectIdAttributeNumber)
504 Form_pg_attribute attStruct;
506 tup = heap_addheader(Natts_pg_attribute,
508 ATTRIBUTE_TUPLE_SIZE,
510 attStruct = (Form_pg_attribute) GETSTRUCT(tup);
512 /* Fill in the correct relation OID in the copied tuple */
513 attStruct->attrelid = new_rel_oid;
515 /* Fill in correct inheritance info for the OID column */
516 if (attStruct->attnum == ObjectIdAttributeNumber)
518 attStruct->attislocal = oidislocal;
519 attStruct->attinhcount = oidinhcount;
523 * Unneeded since they should be OK in the constant data
526 /* attStruct->attstattarget = 0; */
527 /* attStruct->attcacheoff = -1; */
529 simple_heap_insert(rel, tup);
531 CatalogIndexInsert(indstate, tup);
542 CatalogCloseIndexes(indstate);
544 heap_close(rel, RowExclusiveLock);
547 /* --------------------------------
548 * AddNewRelationTuple
550 * this registers the new relation in the catalogs by
551 * adding a tuple to pg_class.
552 * --------------------------------
555 AddNewRelationTuple(Relation pg_class_desc,
556 Relation new_rel_desc,
562 Form_pg_class new_rel_reltup;
566 * first we update some of the information in our uncataloged relation's
567 * relation descriptor.
569 new_rel_reltup = new_rel_desc->rd_rel;
573 case RELKIND_RELATION:
575 case RELKIND_TOASTVALUE:
576 /* The relation is real, but as yet empty */
577 new_rel_reltup->relpages = 0;
578 new_rel_reltup->reltuples = 0;
580 case RELKIND_SEQUENCE:
581 /* Sequences always have a known size */
582 new_rel_reltup->relpages = 1;
583 new_rel_reltup->reltuples = 1;
586 /* Views, etc, have no disk storage */
587 new_rel_reltup->relpages = 0;
588 new_rel_reltup->reltuples = 0;
592 new_rel_reltup->relowner = relowner;
593 new_rel_reltup->reltype = new_type_oid;
594 new_rel_reltup->relkind = relkind;
596 new_rel_desc->rd_att->tdtypeid = new_type_oid;
599 * now form a tuple to add to pg_class
600 * XXX Natts_pg_class_fixed is a hack - see pg_class.h
603 tup = heap_addheader(Natts_pg_class_fixed,
606 (void *) new_rel_reltup);
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.
663 * --------------------------------
666 heap_create_with_catalog(const char *relname,
673 bool shared_relation,
676 OnCommitAction oncommit,
677 bool allow_system_table_mods)
679 Relation pg_class_desc;
680 Relation new_rel_desc;
683 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
688 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
690 CheckAttributeNamesTypes(tupdesc, relkind);
692 if (get_relname_relid(relname, relnamespace))
694 (errcode(ERRCODE_DUPLICATE_TABLE),
695 errmsg("relation \"%s\" already exists", relname)));
698 * Allocate an OID for the relation, unless we were told what to use.
700 * The OID will be the relfilenode as well, so make sure it doesn't
701 * collide with either pg_class OIDs or existing physical files.
703 if (!OidIsValid(relid))
704 relid = GetNewRelFileNode(reltablespace, shared_relation,
708 * Create the relcache entry (mostly dummy at this point) and the physical
709 * disk file. (If we fail further down, it's the smgr's responsibility to
710 * remove the disk file again.)
712 new_rel_desc = heap_create(relname,
719 allow_system_table_mods);
721 Assert(relid == RelationGetRelid(new_rel_desc));
724 * since defining a relation also defines a complex type, we add a new
725 * system type corresponding to the new relation.
727 * NOTE: we could get a unique-index failure here, in case the same name
728 * has already been used for a type.
730 new_type_oid = AddNewRelationType(relname,
736 * now create an entry in pg_class for the relation.
738 * NOTE: we could get a unique-index failure here, in case someone else is
739 * creating the same relation name in parallel but hadn't committed yet
740 * when we checked for a duplicate name above.
742 AddNewRelationTuple(pg_class_desc,
750 * now add tuples to pg_attribute for the attributes in our new relation.
752 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
753 oidislocal, oidinhcount);
756 * make a dependency link to force the relation to be deleted if its
757 * namespace is. Skip this in bootstrap mode, since we don't make
758 * dependencies while bootstrapping.
760 * Also make a dependency link to its owner.
762 if (!IsBootstrapProcessingMode())
764 ObjectAddress myself,
767 myself.classId = RelationRelationId;
768 myself.objectId = relid;
769 myself.objectSubId = 0;
770 referenced.classId = NamespaceRelationId;
771 referenced.objectId = relnamespace;
772 referenced.objectSubId = 0;
773 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
776 * For composite types, the dependency on owner is tracked for the
777 * pg_type entry, so don't record it here. All other relkinds need
778 * their ownership tracked.
780 if (relkind != RELKIND_COMPOSITE_TYPE)
781 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
785 * store constraints and defaults passed in the tupdesc, if any.
787 * NB: this may do a CommandCounterIncrement and rebuild the relcache
788 * entry, so the relation must be valid and self-consistent at this point.
789 * In particular, there are not yet constraints and defaults anywhere.
791 StoreConstraints(new_rel_desc, tupdesc);
794 * If there's a special on-commit action, remember it
796 if (oncommit != ONCOMMIT_NOOP)
797 register_on_commit_action(relid, oncommit);
800 * ok, the relation has been cataloged, so close our relations and return
801 * the OID of the newly created relation.
803 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
804 heap_close(pg_class_desc, RowExclusiveLock);
811 * RelationRemoveInheritance
813 * Formerly, this routine checked for child relations and aborted the
814 * deletion if any were found. Now we rely on the dependency mechanism
815 * to check for or delete child relations. By the time we get here,
816 * there are no children and we need only remove any pg_inherits rows
817 * linking this relation to its parent(s).
820 RelationRemoveInheritance(Oid relid)
822 Relation catalogRelation;
827 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
830 Anum_pg_inherits_inhrelid,
831 BTEqualStrategyNumber, F_OIDEQ,
832 ObjectIdGetDatum(relid));
834 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
835 SnapshotNow, 1, &key);
837 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
838 simple_heap_delete(catalogRelation, &tuple->t_self);
840 systable_endscan(scan);
841 heap_close(catalogRelation, RowExclusiveLock);
845 * DeleteRelationTuple
847 * Remove pg_class row for the given relid.
849 * Note: this is shared by relation deletion and index deletion. It's
850 * not intended for use anyplace else.
853 DeleteRelationTuple(Oid relid)
855 Relation pg_class_desc;
858 /* Grab an appropriate lock on the pg_class relation */
859 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
861 tup = SearchSysCache(RELOID,
862 ObjectIdGetDatum(relid),
864 if (!HeapTupleIsValid(tup))
865 elog(ERROR, "cache lookup failed for relation %u", relid);
867 /* delete the relation tuple from pg_class, and finish up */
868 simple_heap_delete(pg_class_desc, &tup->t_self);
870 ReleaseSysCache(tup);
872 heap_close(pg_class_desc, RowExclusiveLock);
876 * DeleteAttributeTuples
878 * Remove pg_attribute rows for the given relid.
880 * Note: this is shared by relation deletion and index deletion. It's
881 * not intended for use anyplace else.
884 DeleteAttributeTuples(Oid relid)
891 /* Grab an appropriate lock on the pg_attribute relation */
892 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
894 /* Use the index to scan only attributes of the target relation */
896 Anum_pg_attribute_attrelid,
897 BTEqualStrategyNumber, F_OIDEQ,
898 ObjectIdGetDatum(relid));
900 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
901 SnapshotNow, 1, key);
903 /* Delete all the matching tuples */
904 while ((atttup = systable_getnext(scan)) != NULL)
905 simple_heap_delete(attrel, &atttup->t_self);
907 /* Clean up after the scan */
908 systable_endscan(scan);
909 heap_close(attrel, RowExclusiveLock);
913 * RemoveAttributeById
915 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
916 * deleted in pg_attribute. We also remove pg_statistic entries for it.
917 * (Everything else needed, such as getting rid of any pg_attrdef entry,
918 * is handled by dependency.c.)
921 RemoveAttributeById(Oid relid, AttrNumber attnum)
926 Form_pg_attribute attStruct;
927 char newattname[NAMEDATALEN];
930 * Grab an exclusive lock on the target table, which we will NOT release
931 * until end of transaction. (In the simple case where we are directly
932 * dropping this column, AlterTableDropColumn already did this ... but
933 * when cascading from a drop of some other object, we may not have any
936 rel = relation_open(relid, AccessExclusiveLock);
938 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
940 tuple = SearchSysCacheCopy(ATTNUM,
941 ObjectIdGetDatum(relid),
942 Int16GetDatum(attnum),
944 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
945 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
947 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
951 /* System attribute (probably OID) ... just delete the row */
953 simple_heap_delete(attr_rel, &tuple->t_self);
957 /* Dropping user attributes is lots harder */
959 /* Mark the attribute as dropped */
960 attStruct->attisdropped = true;
963 * Set the type OID to invalid. A dropped attribute's type link
964 * cannot be relied on (once the attribute is dropped, the type might
965 * be too). Fortunately we do not need the type row --- the only
966 * really essential information is the type's typlen and typalign,
967 * which are preserved in the attribute's attlen and attalign. We set
968 * atttypid to zero here as a means of catching code that incorrectly
969 * expects it to be valid.
971 attStruct->atttypid = InvalidOid;
973 /* Remove any NOT NULL constraint the column may have */
974 attStruct->attnotnull = false;
976 /* We don't want to keep stats for it anymore */
977 attStruct->attstattarget = 0;
980 * Change the column name to something that isn't likely to conflict
982 snprintf(newattname, sizeof(newattname),
983 "........pg.dropped.%d........", attnum);
984 namestrcpy(&(attStruct->attname), newattname);
986 simple_heap_update(attr_rel, &tuple->t_self, tuple);
988 /* keep the system catalog indexes current */
989 CatalogUpdateIndexes(attr_rel, tuple);
993 * Because updating the pg_attribute row will trigger a relcache flush for
994 * the target relation, we need not do anything else to notify other
995 * backends of the change.
998 heap_close(attr_rel, RowExclusiveLock);
1001 RemoveStatistics(relid, attnum);
1003 relation_close(rel, NoLock);
1009 * If the specified relation/attribute has a default, remove it.
1010 * (If no default, raise error if complain is true, else return quietly.)
1013 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1014 DropBehavior behavior, bool complain)
1016 Relation attrdef_rel;
1017 ScanKeyData scankeys[2];
1022 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1024 ScanKeyInit(&scankeys[0],
1025 Anum_pg_attrdef_adrelid,
1026 BTEqualStrategyNumber, F_OIDEQ,
1027 ObjectIdGetDatum(relid));
1028 ScanKeyInit(&scankeys[1],
1029 Anum_pg_attrdef_adnum,
1030 BTEqualStrategyNumber, F_INT2EQ,
1031 Int16GetDatum(attnum));
1033 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1034 SnapshotNow, 2, scankeys);
1036 /* There should be at most one matching tuple, but we loop anyway */
1037 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1039 ObjectAddress object;
1041 object.classId = AttrDefaultRelationId;
1042 object.objectId = HeapTupleGetOid(tuple);
1043 object.objectSubId = 0;
1045 performDeletion(&object, behavior);
1050 systable_endscan(scan);
1051 heap_close(attrdef_rel, RowExclusiveLock);
1053 if (complain && !found)
1054 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1059 * RemoveAttrDefaultById
1061 * Remove a pg_attrdef entry specified by OID. This is the guts of
1062 * attribute-default removal. Note it should be called via performDeletion,
1066 RemoveAttrDefaultById(Oid attrdefId)
1068 Relation attrdef_rel;
1071 ScanKeyData scankeys[1];
1075 AttrNumber myattnum;
1077 /* Grab an appropriate lock on the pg_attrdef relation */
1078 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1080 /* Find the pg_attrdef tuple */
1081 ScanKeyInit(&scankeys[0],
1082 ObjectIdAttributeNumber,
1083 BTEqualStrategyNumber, F_OIDEQ,
1084 ObjectIdGetDatum(attrdefId));
1086 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1087 SnapshotNow, 1, scankeys);
1089 tuple = systable_getnext(scan);
1090 if (!HeapTupleIsValid(tuple))
1091 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1093 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1094 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1096 /* Get an exclusive lock on the relation owning the attribute */
1097 myrel = relation_open(myrelid, AccessExclusiveLock);
1099 /* Now we can delete the pg_attrdef row */
1100 simple_heap_delete(attrdef_rel, &tuple->t_self);
1102 systable_endscan(scan);
1103 heap_close(attrdef_rel, RowExclusiveLock);
1105 /* Fix the pg_attribute row */
1106 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1108 tuple = SearchSysCacheCopy(ATTNUM,
1109 ObjectIdGetDatum(myrelid),
1110 Int16GetDatum(myattnum),
1112 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1113 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1116 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1118 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1120 /* keep the system catalog indexes current */
1121 CatalogUpdateIndexes(attr_rel, tuple);
1124 * Our update of the pg_attribute row will force a relcache rebuild, so
1125 * there's nothing else to do here.
1127 heap_close(attr_rel, RowExclusiveLock);
1129 /* Keep lock on attribute's rel until end of xact */
1130 relation_close(myrel, NoLock);
1134 * heap_drop_with_catalog - removes specified relation from catalogs
1136 * Note that this routine is not responsible for dropping objects that are
1137 * linked to the pg_class entry via dependencies (for example, indexes and
1138 * constraints). Those are deleted by the dependency-tracing logic in
1139 * dependency.c before control gets here. In general, therefore, this routine
1140 * should never be called directly; go through performDeletion() instead.
1143 heap_drop_with_catalog(Oid relid)
1148 * Open and lock the relation.
1150 rel = relation_open(relid, AccessExclusiveLock);
1153 * Schedule unlinking of the relation's physical file at commit.
1155 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1156 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1158 RelationOpenSmgr(rel);
1159 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
1163 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1164 * until transaction commit. This ensures no one else will try to do
1165 * something with the doomed relation.
1167 relation_close(rel, NoLock);
1170 * Forget any ON COMMIT action for the rel
1172 remove_on_commit_action(relid);
1175 * Flush the relation from the relcache. We want to do this before
1176 * starting to remove catalog entries, just to be certain that no relcache
1177 * entry rebuild will happen partway through. (That should not really
1178 * matter, since we don't do CommandCounterIncrement here, but let's be
1181 RelationForgetRelation(relid);
1184 * remove inheritance information
1186 RelationRemoveInheritance(relid);
1191 RemoveStatistics(relid, 0);
1194 * delete attribute tuples
1196 DeleteAttributeTuples(relid);
1199 * delete relation tuple
1201 DeleteRelationTuple(relid);
1206 * Store a default expression for column attnum of relation rel.
1207 * The expression must be presented as a nodeToString() string.
1210 StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin)
1217 static char nulls[4] = {' ', ' ', ' ', ' '};
1220 Form_pg_attribute attStruct;
1222 ObjectAddress colobject,
1226 * Need to construct source equivalent of given node-string.
1228 expr = stringToNode(adbin);
1233 adsrc = deparse_expression(expr,
1234 deparse_context_for(RelationGetRelationName(rel),
1235 RelationGetRelid(rel)),
1239 * Make the pg_attrdef entry.
1241 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1242 values[Anum_pg_attrdef_adnum - 1] = attnum;
1243 values[Anum_pg_attrdef_adbin - 1] = DirectFunctionCall1(textin,
1244 CStringGetDatum(adbin));
1245 values[Anum_pg_attrdef_adsrc - 1] = DirectFunctionCall1(textin,
1246 CStringGetDatum(adsrc));
1248 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1250 tuple = heap_formtuple(adrel->rd_att, values, nulls);
1251 attrdefOid = simple_heap_insert(adrel, tuple);
1253 CatalogUpdateIndexes(adrel, tuple);
1255 defobject.classId = AttrDefaultRelationId;
1256 defobject.objectId = attrdefOid;
1257 defobject.objectSubId = 0;
1259 heap_close(adrel, RowExclusiveLock);
1261 /* now can free some of the stuff allocated above */
1262 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1263 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1264 heap_freetuple(tuple);
1268 * Update the pg_attribute entry for the column to show that a default
1271 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1272 atttup = SearchSysCacheCopy(ATTNUM,
1273 ObjectIdGetDatum(RelationGetRelid(rel)),
1274 Int16GetDatum(attnum),
1276 if (!HeapTupleIsValid(atttup))
1277 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1278 attnum, RelationGetRelid(rel));
1279 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1280 if (!attStruct->atthasdef)
1282 attStruct->atthasdef = true;
1283 simple_heap_update(attrrel, &atttup->t_self, atttup);
1284 /* keep catalog indexes current */
1285 CatalogUpdateIndexes(attrrel, atttup);
1287 heap_close(attrrel, RowExclusiveLock);
1288 heap_freetuple(atttup);
1291 * Make a dependency so that the pg_attrdef entry goes away if the column
1292 * (or whole table) is deleted.
1294 colobject.classId = RelationRelationId;
1295 colobject.objectId = RelationGetRelid(rel);
1296 colobject.objectSubId = attnum;
1298 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1301 * Record dependencies on objects used in the expression, too.
1303 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1307 * Store a check-constraint expression for the given relation.
1308 * The expression must be presented as a nodeToString() string.
1310 * Caller is responsible for updating the count of constraints
1311 * in the pg_class entry for the relation.
1314 StoreRelCheck(Relation rel, char *ccname, char *ccbin)
1323 * Convert condition to an expression tree.
1325 expr = stringToNode(ccbin);
1330 ccsrc = deparse_expression(expr,
1331 deparse_context_for(RelationGetRelationName(rel),
1332 RelationGetRelid(rel)),
1336 * Find columns of rel that are used in ccbin
1338 * NB: pull_var_clause is okay here only because we don't allow subselects
1339 * in check constraints; it would fail to examine the contents of
1342 varList = pull_var_clause(expr, false);
1343 keycount = list_length(varList);
1350 attNos = (int16 *) palloc(keycount * sizeof(int16));
1351 foreach(vl, varList)
1353 Var *var = (Var *) lfirst(vl);
1356 for (j = 0; j < i; j++)
1357 if (attNos[j] == var->varattno)
1360 attNos[i++] = var->varattno;
1368 * Create the Check Constraint
1370 CreateConstraintEntry(ccname, /* Constraint Name */
1371 RelationGetNamespace(rel), /* namespace */
1372 CONSTRAINT_CHECK, /* Constraint Type */
1373 false, /* Is Deferrable */
1374 false, /* Is Deferred */
1375 RelationGetRelid(rel), /* relation */
1376 attNos, /* attrs in the constraint */
1377 keycount, /* # attrs in the constraint */
1378 InvalidOid, /* not a domain constraint */
1379 InvalidOid, /* Foreign key fields */
1385 InvalidOid, /* no associated index */
1386 expr, /* Tree form check constraint */
1387 ccbin, /* Binary form check constraint */
1388 ccsrc); /* Source form check constraint */
1394 * Store defaults and constraints passed in via the tuple constraint struct.
1396 * NOTE: only pre-cooked expressions will be passed this way, which is to
1397 * say expressions inherited from an existing relation. Newly parsed
1398 * expressions can be added later, by direct calls to StoreAttrDefault
1399 * and StoreRelCheck (see AddRelationRawConstraints()).
1402 StoreConstraints(Relation rel, TupleDesc tupdesc)
1404 TupleConstr *constr = tupdesc->constr;
1408 return; /* nothing to do */
1411 * Deparsing of constraint expressions will fail unless the just-created
1412 * pg_attribute tuples for this relation are made visible. So, bump the
1413 * command counter. CAUTION: this will cause a relcache entry rebuild.
1415 CommandCounterIncrement();
1417 for (i = 0; i < constr->num_defval; i++)
1418 StoreAttrDefault(rel, constr->defval[i].adnum,
1419 constr->defval[i].adbin);
1421 for (i = 0; i < constr->num_check; i++)
1422 StoreRelCheck(rel, constr->check[i].ccname,
1423 constr->check[i].ccbin);
1425 if (constr->num_check > 0)
1426 SetRelationNumChecks(rel, constr->num_check);
1430 * AddRelationRawConstraints
1432 * Add raw (not-yet-transformed) column default expressions and/or constraint
1433 * check expressions to an existing relation. This is defined to do both
1434 * for efficiency in DefineRelation, but of course you can do just one or
1435 * the other by passing empty lists.
1437 * rel: relation to be modified
1438 * rawColDefaults: list of RawColumnDefault structures
1439 * rawConstraints: list of Constraint nodes
1441 * All entries in rawColDefaults will be processed. Entries in rawConstraints
1442 * will be processed only if they are CONSTR_CHECK type and contain a "raw"
1445 * Returns a list of CookedConstraint nodes that shows the cooked form of
1446 * the default and constraint expressions added to the relation.
1448 * NB: caller should have opened rel with AccessExclusiveLock, and should
1449 * hold that lock till end of transaction. Also, we assume the caller has
1450 * done a CommandCounterIncrement if necessary to make the relation's catalog
1454 AddRelationRawConstraints(Relation rel,
1455 List *rawColDefaults,
1456 List *rawConstraints)
1458 List *cookedConstraints = NIL;
1459 TupleDesc tupleDesc;
1460 TupleConstr *oldconstr;
1468 CookedConstraint *cooked;
1471 * Get info about existing constraints.
1473 tupleDesc = RelationGetDescr(rel);
1474 oldconstr = tupleDesc->constr;
1476 numoldchecks = oldconstr->num_check;
1481 * Create a dummy ParseState and insert the target relation as its sole
1482 * rangetable entry. We need a ParseState for transformExpr.
1484 pstate = make_parsestate(NULL);
1485 rte = addRangeTableEntryForRelation(pstate,
1490 addRTEtoQuery(pstate, rte, true, true, true);
1493 * Process column default expressions.
1495 foreach(cell, rawColDefaults)
1497 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1498 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1500 expr = cookDefault(pstate, colDef->raw_default,
1501 atp->atttypid, atp->atttypmod,
1502 NameStr(atp->attname));
1504 StoreAttrDefault(rel, colDef->attnum, nodeToString(expr));
1506 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1507 cooked->contype = CONSTR_DEFAULT;
1508 cooked->name = NULL;
1509 cooked->attnum = colDef->attnum;
1510 cooked->expr = expr;
1511 cookedConstraints = lappend(cookedConstraints, cooked);
1515 * Process constraint expressions.
1517 numchecks = numoldchecks;
1519 foreach(cell, rawConstraints)
1521 Constraint *cdef = (Constraint *) lfirst(cell);
1524 if (cdef->contype != CONSTR_CHECK || cdef->raw_expr == NULL)
1526 Assert(cdef->cooked_expr == NULL);
1529 * Transform raw parsetree to executable expression.
1531 expr = transformExpr(pstate, cdef->raw_expr);
1534 * Make sure it yields a boolean result.
1536 expr = coerce_to_boolean(pstate, expr, "CHECK");
1539 * Make sure no outside relations are referred to.
1541 if (list_length(pstate->p_rtable) != 1)
1543 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1544 errmsg("only table \"%s\" can be referenced in check constraint",
1545 RelationGetRelationName(rel))));
1548 * No subplans or aggregates, either...
1550 if (pstate->p_hasSubLinks)
1552 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1553 errmsg("cannot use subquery in check constraint")));
1554 if (pstate->p_hasAggs)
1556 (errcode(ERRCODE_GROUPING_ERROR),
1557 errmsg("cannot use aggregate function in check constraint")));
1560 * Check name uniqueness, or generate a name if none was given.
1562 if (cdef->name != NULL)
1566 ccname = cdef->name;
1567 /* Check against pre-existing constraints */
1568 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
1569 RelationGetRelid(rel),
1570 RelationGetNamespace(rel),
1573 (errcode(ERRCODE_DUPLICATE_OBJECT),
1574 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1575 ccname, RelationGetRelationName(rel))));
1576 /* Check against other new constraints */
1577 /* Needed because we don't do CommandCounterIncrement in loop */
1578 foreach(cell2, checknames)
1580 if (strcmp((char *) lfirst(cell2), ccname) == 0)
1582 (errcode(ERRCODE_DUPLICATE_OBJECT),
1583 errmsg("check constraint \"%s\" already exists",
1590 * When generating a name, we want to create "tab_col_check" for a
1591 * column constraint and "tab_check" for a table constraint. We
1592 * no longer have any info about the syntactic positioning of the
1593 * constraint phrase, so we approximate this by seeing whether the
1594 * expression references more than one column. (If the user
1595 * played by the rules, the result is the same...)
1597 * Note: pull_var_clause() doesn't descend into sublinks, but we
1598 * eliminated those above; and anyway this only needs to be an
1599 * approximate answer.
1604 vars = pull_var_clause(expr, false);
1606 /* eliminate duplicates */
1607 vars = list_union(NIL, vars);
1609 if (list_length(vars) == 1)
1610 colname = get_attname(RelationGetRelid(rel),
1611 ((Var *) linitial(vars))->varattno);
1615 ccname = ChooseConstraintName(RelationGetRelationName(rel),
1618 RelationGetNamespace(rel),
1622 /* save name for future checks */
1623 checknames = lappend(checknames, ccname);
1628 StoreRelCheck(rel, ccname, nodeToString(expr));
1632 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1633 cooked->contype = CONSTR_CHECK;
1634 cooked->name = ccname;
1636 cooked->expr = expr;
1637 cookedConstraints = lappend(cookedConstraints, cooked);
1641 * Update the count of constraints in the relation's pg_class tuple. We do
1642 * this even if there was no change, in order to ensure that an SI update
1643 * message is sent out for the pg_class tuple, which will force other
1644 * backends to rebuild their relcache entries for the rel. (This is
1645 * critical if we added defaults but not constraints.)
1647 SetRelationNumChecks(rel, numchecks);
1649 return cookedConstraints;
1653 * Update the count of constraints in the relation's pg_class tuple.
1655 * Caller had better hold exclusive lock on the relation.
1657 * An important side effect is that a SI update message will be sent out for
1658 * the pg_class tuple, which will force other backends to rebuild their
1659 * relcache entries for the rel. Also, this backend will rebuild its
1660 * own relcache entry at the next CommandCounterIncrement.
1663 SetRelationNumChecks(Relation rel, int numchecks)
1667 Form_pg_class relStruct;
1669 relrel = heap_open(RelationRelationId, RowExclusiveLock);
1670 reltup = SearchSysCacheCopy(RELOID,
1671 ObjectIdGetDatum(RelationGetRelid(rel)),
1673 if (!HeapTupleIsValid(reltup))
1674 elog(ERROR, "cache lookup failed for relation %u",
1675 RelationGetRelid(rel));
1676 relStruct = (Form_pg_class) GETSTRUCT(reltup);
1678 if (relStruct->relchecks != numchecks)
1680 relStruct->relchecks = numchecks;
1682 simple_heap_update(relrel, &reltup->t_self, reltup);
1684 /* keep catalog indexes current */
1685 CatalogUpdateIndexes(relrel, reltup);
1689 /* Skip the disk update, but force relcache inval anyway */
1690 CacheInvalidateRelcache(rel);
1693 heap_freetuple(reltup);
1694 heap_close(relrel, RowExclusiveLock);
1698 * Take a raw default and convert it to a cooked format ready for
1701 * Parse state should be set up to recognize any vars that might appear
1702 * in the expression. (Even though we plan to reject vars, it's more
1703 * user-friendly to give the correct error message than "unknown var".)
1705 * If atttypid is not InvalidOid, coerce the expression to the specified
1706 * type (and typmod atttypmod). attname is only needed in this case:
1707 * it is used in the error message, if any.
1710 cookDefault(ParseState *pstate,
1718 Assert(raw_default != NULL);
1721 * Transform raw parsetree to executable expression.
1723 expr = transformExpr(pstate, raw_default);
1726 * Make sure default expr does not refer to any vars.
1728 if (contain_var_clause(expr))
1730 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1731 errmsg("cannot use column references in default expression")));
1734 * It can't return a set either.
1736 if (expression_returns_set(expr))
1738 (errcode(ERRCODE_DATATYPE_MISMATCH),
1739 errmsg("default expression must not return a set")));
1742 * No subplans or aggregates, either...
1744 if (pstate->p_hasSubLinks)
1746 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1747 errmsg("cannot use subquery in default expression")));
1748 if (pstate->p_hasAggs)
1750 (errcode(ERRCODE_GROUPING_ERROR),
1751 errmsg("cannot use aggregate function in default expression")));
1754 * Coerce the expression to the correct type and typmod, if given. This
1755 * should match the parser's processing of non-defaulted expressions ---
1756 * see updateTargetListEntry().
1758 if (OidIsValid(atttypid))
1760 Oid type_id = exprType(expr);
1762 expr = coerce_to_target_type(pstate, expr, type_id,
1763 atttypid, atttypmod,
1764 COERCION_ASSIGNMENT,
1765 COERCE_IMPLICIT_CAST);
1768 (errcode(ERRCODE_DATATYPE_MISMATCH),
1769 errmsg("column \"%s\" is of type %s"
1770 " but default expression is of type %s",
1772 format_type_be(atttypid),
1773 format_type_be(type_id)),
1774 errhint("You will need to rewrite or cast the expression.")));
1782 * Removes all constraints on a relation that match the given name.
1784 * It is the responsibility of the calling function to acquire a suitable
1785 * lock on the relation.
1787 * Returns: The number of constraints removed.
1790 RemoveRelConstraints(Relation rel, const char *constrName,
1791 DropBehavior behavior)
1795 SysScanDesc conscan;
1799 /* Grab an appropriate lock on the pg_constraint relation */
1800 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
1802 /* Use the index to scan only constraints of the target relation */
1803 ScanKeyInit(&key[0],
1804 Anum_pg_constraint_conrelid,
1805 BTEqualStrategyNumber, F_OIDEQ,
1806 ObjectIdGetDatum(RelationGetRelid(rel)));
1808 conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true,
1809 SnapshotNow, 1, key);
1812 * Scan over the result set, removing any matching entries.
1814 while ((contup = systable_getnext(conscan)) != NULL)
1816 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
1818 if (strcmp(NameStr(con->conname), constrName) == 0)
1820 ObjectAddress conobj;
1822 conobj.classId = ConstraintRelationId;
1823 conobj.objectId = HeapTupleGetOid(contup);
1824 conobj.objectSubId = 0;
1826 performDeletion(&conobj, behavior);
1832 /* Clean up after the scan */
1833 systable_endscan(conscan);
1834 heap_close(conrel, RowExclusiveLock);
1841 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
1843 * If attnum is zero, remove all entries for rel; else remove only the one
1847 RemoveStatistics(Oid relid, AttrNumber attnum)
1849 Relation pgstatistic;
1855 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
1857 ScanKeyInit(&key[0],
1858 Anum_pg_statistic_starelid,
1859 BTEqualStrategyNumber, F_OIDEQ,
1860 ObjectIdGetDatum(relid));
1866 ScanKeyInit(&key[1],
1867 Anum_pg_statistic_staattnum,
1868 BTEqualStrategyNumber, F_INT2EQ,
1869 Int16GetDatum(attnum));
1873 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumIndexId, true,
1874 SnapshotNow, nkeys, key);
1876 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1877 simple_heap_delete(pgstatistic, &tuple->t_self);
1879 systable_endscan(scan);
1881 heap_close(pgstatistic, RowExclusiveLock);
1886 * RelationTruncateIndexes - truncate all
1887 * indexes associated with the heap relation to zero tuples.
1889 * The routine will truncate and then reconstruct the indexes on
1890 * the relation specified by the heapId parameter.
1893 RelationTruncateIndexes(Oid heapId)
1895 Relation heapRelation;
1899 * Open the heap rel. We need grab no lock because we assume
1900 * heap_truncate is holding an exclusive lock on the heap rel.
1902 heapRelation = heap_open(heapId, NoLock);
1904 /* Ask the relcache to produce a list of the indexes of the rel */
1905 foreach(indlist, RelationGetIndexList(heapRelation))
1907 Oid indexId = lfirst_oid(indlist);
1908 Relation currentIndex;
1909 IndexInfo *indexInfo;
1911 /* Open the index relation */
1912 currentIndex = index_open(indexId);
1914 /* Obtain exclusive lock on it, just to be sure */
1915 LockRelation(currentIndex, AccessExclusiveLock);
1917 /* Fetch info needed for index_build */
1918 indexInfo = BuildIndexInfo(currentIndex);
1920 /* Now truncate the actual file (and discard buffers) */
1921 RelationTruncate(currentIndex, 0);
1923 /* Initialize the index and rebuild */
1924 index_build(heapRelation, currentIndex, indexInfo);
1927 * index_build will close both the heap and index relations (but not
1928 * give up the locks we hold on them). We're done with this index,
1929 * but we must re-open the heap rel.
1931 heapRelation = heap_open(heapId, NoLock);
1934 /* Finish by closing the heap rel again */
1935 heap_close(heapRelation, NoLock);
1941 * This routine deletes all data within all the specified relations.
1943 * This is not transaction-safe! There is another, transaction-safe
1944 * implementation in commands/tablecmds.c. We now use this only for
1945 * ON COMMIT truncation of temporary tables, where it doesn't matter.
1948 heap_truncate(List *relids)
1950 List *relations = NIL;
1953 /* Open relations for processing, and grab exclusive access on each */
1954 foreach(cell, relids)
1956 Oid rid = lfirst_oid(cell);
1960 rel = heap_open(rid, AccessExclusiveLock);
1961 relations = lappend(relations, rel);
1963 /* If there is a toast table, add it to the list too */
1964 toastrelid = rel->rd_rel->reltoastrelid;
1965 if (OidIsValid(toastrelid))
1967 rel = heap_open(toastrelid, AccessExclusiveLock);
1968 relations = lappend(relations, rel);
1972 /* Don't allow truncate on tables that are referenced by foreign keys */
1973 heap_truncate_check_FKs(relations, true);
1976 foreach(cell, relations)
1978 Relation rel = lfirst(cell);
1980 /* Truncate the actual file (and discard buffers) */
1981 RelationTruncate(rel, 0);
1983 /* If this relation has indexes, truncate the indexes too */
1984 RelationTruncateIndexes(RelationGetRelid(rel));
1987 * Close the relation, but keep exclusive lock on it until commit.
1989 heap_close(rel, NoLock);
1994 * heap_truncate_check_FKs
1995 * Check for foreign keys referencing a list of relations that
1996 * are to be truncated
1998 * We disallow such FKs (except self-referential ones) since the whole point
1999 * of TRUNCATE is to not scan the individual rows to be thrown away.
2001 * This is split out so it can be shared by both implementations of truncate.
2002 * Caller should already hold a suitable lock on the relations.
2004 * tempTables is only used to select an appropriate error message.
2007 heap_truncate_check_FKs(List *relations, bool tempTables)
2012 SysScanDesc fkeyScan;
2016 * Build a list of OIDs of the interesting relations.
2018 * If a relation has no triggers, then it can neither have FKs nor be
2019 * referenced by a FK from another table, so we can ignore it.
2021 foreach(cell, relations)
2023 Relation rel = lfirst(cell);
2025 if (rel->rd_rel->reltriggers != 0)
2026 oids = lappend_oid(oids, RelationGetRelid(rel));
2030 * Fast path: if no relation has triggers, none has FKs either.
2036 * Otherwise, must scan pg_constraint. Right now, it is a seqscan because
2037 * there is no available index on confrelid.
2039 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2041 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2042 SnapshotNow, 0, NULL);
2044 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2046 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2048 /* Not a foreign key */
2049 if (con->contype != CONSTRAINT_FOREIGN)
2052 /* Not referencing one of our list of tables */
2053 if (!list_member_oid(oids, con->confrelid))
2056 /* The referencer should be in our list too */
2057 if (!list_member_oid(oids, con->conrelid))
2061 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2062 errmsg("unsupported ON COMMIT and foreign key combination"),
2063 errdetail("Table \"%s\" references \"%s\" via foreign key constraint \"%s\", but they do not have the same ON COMMIT setting.",
2064 get_rel_name(con->conrelid),
2065 get_rel_name(con->confrelid),
2066 NameStr(con->conname))));
2069 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2070 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2071 errdetail("Table \"%s\" references \"%s\" via foreign key constraint \"%s\".",
2072 get_rel_name(con->conrelid),
2073 get_rel_name(con->confrelid),
2074 NameStr(con->conname)),
2075 errhint("Truncate table \"%s\" at the same time, "
2076 "or use TRUNCATE ... CASCADE.",
2077 get_rel_name(con->conrelid))));
2081 systable_endscan(fkeyScan);
2082 heap_close(fkeyRel, AccessShareLock);
2086 * heap_truncate_find_FKs
2087 * Find relations having foreign keys referencing any relations that
2088 * are to be truncated
2090 * This is almost the same code as heap_truncate_check_FKs, but we don't
2091 * raise an error if we find such relations; instead we return a list of
2092 * their OIDs. Also note that the input is a list of OIDs not a list
2093 * of Relations. The result list does *not* include any rels that are
2094 * already in the input list.
2096 * Note: caller should already have exclusive lock on all rels mentioned
2097 * in relationIds. Since adding or dropping an FK requires exclusive lock
2098 * on both rels, this ensures that the answer will be stable.
2101 heap_truncate_find_FKs(List *relationIds)
2105 SysScanDesc fkeyScan;
2109 * Must scan pg_constraint. Right now, it is a seqscan because
2110 * there is no available index on confrelid.
2112 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2114 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2115 SnapshotNow, 0, NULL);
2117 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2119 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2121 /* Not a foreign key */
2122 if (con->contype != CONSTRAINT_FOREIGN)
2125 /* Not referencing one of our list of tables */
2126 if (!list_member_oid(relationIds, con->confrelid))
2129 /* Add referencer unless already in input or result list */
2130 if (!list_member_oid(relationIds, con->conrelid))
2131 result = list_append_unique_oid(result, con->conrelid);
2134 systable_endscan(fkeyScan);
2135 heap_close(fkeyRel, AccessShareLock);