1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/catalog/heap.c
15 * heap_create() - Create an uncataloged heap relation
16 * heap_create_with_catalog() - Create a cataloged relation
17 * heap_drop_with_catalog() - Removes named relation from catalogs
20 * this code taken from access/heap/create.c, which contains
21 * the old heap_create_with_catalog, amcreate, and amdestroy.
22 * those routines will soon call these routines using the function
24 * just like the poorly named "NewXXX" routines do. The
25 * "New" routines are all going to die soon, once and for all!
28 *-------------------------------------------------------------------------
32 #include "access/genam.h"
33 #include "access/heapam.h"
34 #include "access/sysattr.h"
35 #include "access/transam.h"
36 #include "access/xact.h"
37 #include "catalog/catalog.h"
38 #include "catalog/dependency.h"
39 #include "catalog/heap.h"
40 #include "catalog/index.h"
41 #include "catalog/indexing.h"
42 #include "catalog/namespace.h"
43 #include "catalog/pg_attrdef.h"
44 #include "catalog/pg_constraint.h"
45 #include "catalog/pg_inherits.h"
46 #include "catalog/pg_namespace.h"
47 #include "catalog/pg_statistic.h"
48 #include "catalog/pg_tablespace.h"
49 #include "catalog/pg_type.h"
50 #include "catalog/pg_type_fn.h"
51 #include "catalog/storage.h"
52 #include "commands/tablecmds.h"
53 #include "commands/typecmds.h"
54 #include "miscadmin.h"
55 #include "nodes/nodeFuncs.h"
56 #include "optimizer/var.h"
57 #include "parser/parse_coerce.h"
58 #include "parser/parse_expr.h"
59 #include "parser/parse_relation.h"
60 #include "storage/bufmgr.h"
61 #include "storage/freespace.h"
62 #include "storage/smgr.h"
63 #include "utils/acl.h"
64 #include "utils/builtins.h"
65 #include "utils/fmgroids.h"
66 #include "utils/inval.h"
67 #include "utils/lsyscache.h"
68 #include "utils/relcache.h"
69 #include "utils/snapmgr.h"
70 #include "utils/syscache.h"
71 #include "utils/tqual.h"
74 /* Kluge for upgrade-in-place support */
75 Oid binary_upgrade_next_heap_relfilenode = InvalidOid;
76 Oid binary_upgrade_next_toast_relfilenode = InvalidOid;
78 static void AddNewRelationTuple(Relation pg_class_desc,
79 Relation new_rel_desc,
87 static Oid AddNewRelationType(const char *typeName,
94 static void RelationRemoveInheritance(Oid relid);
95 static void StoreRelCheck(Relation rel, char *ccname, Node *expr,
96 bool is_local, int inhcount);
97 static void StoreConstraints(Relation rel, List *cooked_constraints);
98 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
99 bool allow_merge, bool is_local);
100 static void SetRelationNumChecks(Relation rel, int numchecks);
101 static Node *cookConstraint(ParseState *pstate,
102 Node *raw_constraint,
104 static List *insert_ordered_unique_oid(List *list, Oid datum);
107 /* ----------------------------------------------------------------
108 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
110 * these should all be moved to someplace in the lib/catalog
111 * module, if not obliterated first.
112 * ----------------------------------------------------------------
118 * Should the system special case these attributes in the future?
119 * Advantage: consume much less space in the ATTRIBUTE relation.
120 * Disadvantage: special cases will be all over the place.
124 * The initializers below do not include the attoptions or attacl fields,
125 * but that's OK - we're never going to reference anything beyond the
126 * fixed-size portion of the structure anyway.
129 static FormData_pg_attribute a1 = {
130 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
131 SelfItemPointerAttributeNumber, 0, -1, -1,
132 false, 'p', 's', true, false, false, true, 0
135 static FormData_pg_attribute a2 = {
136 0, {"oid"}, OIDOID, 0, sizeof(Oid),
137 ObjectIdAttributeNumber, 0, -1, -1,
138 true, 'p', 'i', true, false, false, true, 0
141 static FormData_pg_attribute a3 = {
142 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
143 MinTransactionIdAttributeNumber, 0, -1, -1,
144 true, 'p', 'i', true, false, false, true, 0
147 static FormData_pg_attribute a4 = {
148 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
149 MinCommandIdAttributeNumber, 0, -1, -1,
150 true, 'p', 'i', true, false, false, true, 0
153 static FormData_pg_attribute a5 = {
154 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
155 MaxTransactionIdAttributeNumber, 0, -1, -1,
156 true, 'p', 'i', true, false, false, true, 0
159 static FormData_pg_attribute a6 = {
160 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
161 MaxCommandIdAttributeNumber, 0, -1, -1,
162 true, 'p', 'i', true, false, false, true, 0
166 * We decided to call this attribute "tableoid" rather than say
167 * "classoid" on the basis that in the future there may be more than one
168 * table of a particular class/type. In any case table is still the word
171 static FormData_pg_attribute a7 = {
172 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
173 TableOidAttributeNumber, 0, -1, -1,
174 true, 'p', 'i', true, false, false, true, 0
177 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
180 * This function returns a Form_pg_attribute pointer for a system attribute.
181 * Note that we elog if the presented attno is invalid, which would only
182 * happen if there's a problem upstream.
185 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
187 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
188 elog(ERROR, "invalid system attribute number %d", attno);
189 if (attno == ObjectIdAttributeNumber && !relhasoids)
190 elog(ERROR, "invalid system attribute number %d", attno);
191 return SysAtt[-attno - 1];
195 * If the given name is a system attribute name, return a Form_pg_attribute
196 * pointer for a prototype definition. If not, return NULL.
199 SystemAttributeByName(const char *attname, bool relhasoids)
203 for (j = 0; j < (int) lengthof(SysAtt); j++)
205 Form_pg_attribute att = SysAtt[j];
207 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
209 if (strcmp(NameStr(att->attname), attname) == 0)
218 /* ----------------------------------------------------------------
219 * XXX END OF UGLY HARD CODED BADNESS XXX
220 * ---------------------------------------------------------------- */
223 /* ----------------------------------------------------------------
224 * heap_create - Create an uncataloged heap relation
226 * Note API change: the caller must now always provide the OID
227 * to use for the relation.
229 * rel->rd_rel is initialized by RelationBuildLocalRelation,
230 * and is mostly zeroes at return.
231 * ----------------------------------------------------------------
234 heap_create(const char *relname,
240 bool shared_relation,
241 bool mapped_relation,
242 bool allow_system_table_mods)
247 /* The caller must have provided an OID for the relation. */
248 Assert(OidIsValid(relid));
253 if (!allow_system_table_mods &&
254 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
255 IsNormalProcessingMode())
257 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
258 errmsg("permission denied to create \"%s.%s\"",
259 get_namespace_name(relnamespace), relname),
260 errdetail("System catalog modifications are currently disallowed.")));
263 * Decide if we need storage or not, and handle a couple other special
264 * cases for particular relkinds.
269 case RELKIND_COMPOSITE_TYPE:
270 create_storage = false;
273 * Force reltablespace to zero if the relation has no physical
274 * storage. This is mainly just for cleanliness' sake.
276 reltablespace = InvalidOid;
278 case RELKIND_SEQUENCE:
279 create_storage = true;
282 * Force reltablespace to zero for sequences, since we don't
283 * support moving them around into different tablespaces.
285 reltablespace = InvalidOid;
288 create_storage = true;
293 * Never allow a pg_class entry to explicitly specify the database's
294 * default tablespace in reltablespace; force it to zero instead. This
295 * ensures that if the database is cloned with a different default
296 * tablespace, the pg_class entry will still match where CREATE DATABASE
297 * will put the physically copied relation.
299 * Yes, this is a bit of a hack.
301 if (reltablespace == MyDatabaseTableSpace)
302 reltablespace = InvalidOid;
305 * build the relcache entry.
307 rel = RelationBuildLocalRelation(relname,
316 * Have the storage manager create the relation's disk file, if needed.
318 * We only create the main fork here, other forks will be created on
323 RelationOpenSmgr(rel);
324 RelationCreateStorage(rel->rd_node, rel->rd_istemp);
330 /* ----------------------------------------------------------------
331 * heap_create_with_catalog - Create a cataloged relation
333 * this is done in multiple steps:
335 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
336 * descriptor contains a valid set of attribute names and types
338 * 2) pg_class is opened and get_relname_relid()
339 * performs a scan to ensure that no relation with the
340 * same name already exists.
342 * 3) heap_create() is called to create the new relation on disk.
344 * 4) TypeCreate() is called to define a new type corresponding
345 * to the new relation.
347 * 5) AddNewRelationTuple() is called to register the
348 * relation in pg_class.
350 * 6) AddNewAttributeTuples() is called to register the
351 * new relation's schema in pg_attribute.
353 * 7) StoreConstraints is called () - vadim 08/22/97
355 * 8) the relations are closed and the new relation's oid
358 * ----------------------------------------------------------------
361 /* --------------------------------
362 * CheckAttributeNamesTypes
364 * this is used to make certain the tuple descriptor contains a
365 * valid set of attribute names and datatypes. a problem simply
366 * generates ereport(ERROR) which aborts the current transaction.
367 * --------------------------------
370 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
371 bool allow_system_table_mods)
375 int natts = tupdesc->natts;
377 /* Sanity check on column count */
378 if (natts < 0 || natts > MaxHeapAttributeNumber)
380 (errcode(ERRCODE_TOO_MANY_COLUMNS),
381 errmsg("tables can have at most %d columns",
382 MaxHeapAttributeNumber)));
385 * first check for collision with system attribute names
387 * Skip this for a view or type relation, since those don't have system
390 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
392 for (i = 0; i < natts; i++)
394 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
395 tupdesc->tdhasoid) != NULL)
397 (errcode(ERRCODE_DUPLICATE_COLUMN),
398 errmsg("column name \"%s\" conflicts with a system column name",
399 NameStr(tupdesc->attrs[i]->attname))));
404 * next check for repeated attribute names
406 for (i = 1; i < natts; i++)
408 for (j = 0; j < i; j++)
410 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
411 NameStr(tupdesc->attrs[i]->attname)) == 0)
413 (errcode(ERRCODE_DUPLICATE_COLUMN),
414 errmsg("column name \"%s\" specified more than once",
415 NameStr(tupdesc->attrs[j]->attname))));
420 * next check the attribute types
422 for (i = 0; i < natts; i++)
424 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
425 tupdesc->attrs[i]->atttypid,
426 allow_system_table_mods);
430 /* --------------------------------
433 * Verify that the proposed datatype of an attribute is legal.
434 * This is needed because there are types (and pseudo-types)
435 * in the catalogs that we do not support as elements of real tuples.
436 * --------------------------------
439 CheckAttributeType(const char *attname, Oid atttypid,
440 bool allow_system_table_mods)
442 char att_typtype = get_typtype(atttypid);
444 if (atttypid == UNKNOWNOID)
447 * Warn user, but don't fail, if column to be created has UNKNOWN type
448 * (usually as a result of a 'retrieve into' - jolly)
451 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
452 errmsg("column \"%s\" has type \"unknown\"", attname),
453 errdetail("Proceeding with relation creation anyway.")));
455 else if (att_typtype == TYPTYPE_PSEUDO)
458 * Refuse any attempt to create a pseudo-type column, except for a
459 * special hack for pg_statistic: allow ANYARRAY when modifying system
460 * catalogs (this allows creating pg_statistic and cloning it during
463 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
465 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
466 errmsg("column \"%s\" has pseudo-type %s",
467 attname, format_type_be(atttypid))));
469 else if (att_typtype == TYPTYPE_COMPOSITE)
472 * For a composite type, recurse into its attributes. You might think
473 * this isn't necessary, but since we allow system catalogs to break
474 * the rule, we have to guard against the case.
480 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
482 tupdesc = RelationGetDescr(relation);
484 for (i = 0; i < tupdesc->natts; i++)
486 Form_pg_attribute attr = tupdesc->attrs[i];
488 if (attr->attisdropped)
490 CheckAttributeType(NameStr(attr->attname), attr->atttypid,
491 allow_system_table_mods);
494 relation_close(relation, AccessShareLock);
499 * InsertPgAttributeTuple
500 * Construct and insert a new tuple in pg_attribute.
502 * Caller has already opened and locked pg_attribute. new_attribute is the
503 * attribute to insert (but we ignore attacl and attoptions, which are always
504 * initialized to NULL).
506 * indstate is the index state for CatalogIndexInsert. It can be passed as
507 * NULL, in which case we'll fetch the necessary info. (Don't do this when
508 * inserting multiple attributes, because it's a tad more expensive.)
511 InsertPgAttributeTuple(Relation pg_attribute_rel,
512 Form_pg_attribute new_attribute,
513 CatalogIndexState indstate)
515 Datum values[Natts_pg_attribute];
516 bool nulls[Natts_pg_attribute];
519 /* This is a tad tedious, but way cleaner than what we used to do... */
520 memset(values, 0, sizeof(values));
521 memset(nulls, false, sizeof(nulls));
523 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
524 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
525 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
526 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
527 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
528 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
529 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
530 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
531 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
532 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
533 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
534 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
535 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
536 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
537 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
538 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
539 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
541 /* start out with empty permissions and empty options */
542 nulls[Anum_pg_attribute_attacl - 1] = true;
543 nulls[Anum_pg_attribute_attoptions - 1] = true;
545 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
547 /* finally insert the new tuple, update the indexes, and clean up */
548 simple_heap_insert(pg_attribute_rel, tup);
550 if (indstate != NULL)
551 CatalogIndexInsert(indstate, tup);
553 CatalogUpdateIndexes(pg_attribute_rel, tup);
558 /* --------------------------------
559 * AddNewAttributeTuples
561 * this registers the new relation's schema by adding
562 * tuples to pg_attribute.
563 * --------------------------------
566 AddNewAttributeTuples(Oid new_rel_oid,
572 Form_pg_attribute attr;
575 CatalogIndexState indstate;
576 int natts = tupdesc->natts;
577 ObjectAddress myself,
581 * open pg_attribute and its indexes.
583 rel = heap_open(AttributeRelationId, RowExclusiveLock);
585 indstate = CatalogOpenIndexes(rel);
588 * First we add the user attributes. This is also a convenient place to
589 * add dependencies on their datatypes.
591 for (i = 0; i < natts; i++)
593 attr = tupdesc->attrs[i];
594 /* Fill in the correct relation OID */
595 attr->attrelid = new_rel_oid;
596 /* Make sure these are OK, too */
597 attr->attstattarget = -1;
598 attr->attcacheoff = -1;
600 InsertPgAttributeTuple(rel, attr, indstate);
602 /* Add dependency info */
603 myself.classId = RelationRelationId;
604 myself.objectId = new_rel_oid;
605 myself.objectSubId = i + 1;
606 referenced.classId = TypeRelationId;
607 referenced.objectId = attr->atttypid;
608 referenced.objectSubId = 0;
609 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
613 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
614 * all for a view or type relation. We don't bother with making datatype
615 * dependencies here, since presumably all these types are pinned.
617 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
619 for (i = 0; i < (int) lengthof(SysAtt); i++)
621 FormData_pg_attribute attStruct;
623 /* skip OID where appropriate */
624 if (!tupdesc->tdhasoid &&
625 SysAtt[i]->attnum == ObjectIdAttributeNumber)
628 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
630 /* Fill in the correct relation OID in the copied tuple */
631 attStruct.attrelid = new_rel_oid;
633 /* Fill in correct inheritance info for the OID column */
634 if (attStruct.attnum == ObjectIdAttributeNumber)
636 attStruct.attislocal = oidislocal;
637 attStruct.attinhcount = oidinhcount;
640 InsertPgAttributeTuple(rel, &attStruct, indstate);
647 CatalogCloseIndexes(indstate);
649 heap_close(rel, RowExclusiveLock);
652 /* --------------------------------
655 * Construct and insert a new tuple in pg_class.
657 * Caller has already opened and locked pg_class.
658 * Tuple data is taken from new_rel_desc->rd_rel, except for the
659 * variable-width fields which are not present in a cached reldesc.
660 * relacl and reloptions are passed in Datum form (to avoid having
661 * to reference the data types in heap.h). Pass (Datum) 0 to set them
663 * --------------------------------
666 InsertPgClassTuple(Relation pg_class_desc,
667 Relation new_rel_desc,
672 Form_pg_class rd_rel = new_rel_desc->rd_rel;
673 Datum values[Natts_pg_class];
674 bool nulls[Natts_pg_class];
677 /* This is a tad tedious, but way cleaner than what we used to do... */
678 memset(values, 0, sizeof(values));
679 memset(nulls, false, sizeof(nulls));
681 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
682 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
683 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
684 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
685 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
686 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
687 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
688 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
689 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
690 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
691 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
692 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
693 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
694 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
695 values[Anum_pg_class_relistemp - 1] = BoolGetDatum(rd_rel->relistemp);
696 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
697 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
698 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
699 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
700 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
701 values[Anum_pg_class_relhasexclusion - 1] = BoolGetDatum(rd_rel->relhasexclusion);
702 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
703 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
704 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
705 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
706 if (relacl != (Datum) 0)
707 values[Anum_pg_class_relacl - 1] = relacl;
709 nulls[Anum_pg_class_relacl - 1] = true;
710 if (reloptions != (Datum) 0)
711 values[Anum_pg_class_reloptions - 1] = reloptions;
713 nulls[Anum_pg_class_reloptions - 1] = true;
715 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
718 * The new tuple must have the oid already chosen for the rel. Sure would
719 * be embarrassing to do this sort of thing in polite company.
721 HeapTupleSetOid(tup, new_rel_oid);
723 /* finally insert the new tuple, update the indexes, and clean up */
724 simple_heap_insert(pg_class_desc, tup);
726 CatalogUpdateIndexes(pg_class_desc, tup);
731 /* --------------------------------
732 * AddNewRelationTuple
734 * this registers the new relation in the catalogs by
735 * adding a tuple to pg_class.
736 * --------------------------------
739 AddNewRelationTuple(Relation pg_class_desc,
740 Relation new_rel_desc,
749 Form_pg_class new_rel_reltup;
752 * first we update some of the information in our uncataloged relation's
753 * relation descriptor.
755 new_rel_reltup = new_rel_desc->rd_rel;
759 case RELKIND_RELATION:
761 case RELKIND_TOASTVALUE:
762 /* The relation is real, but as yet empty */
763 new_rel_reltup->relpages = 0;
764 new_rel_reltup->reltuples = 0;
766 case RELKIND_SEQUENCE:
767 /* Sequences always have a known size */
768 new_rel_reltup->relpages = 1;
769 new_rel_reltup->reltuples = 1;
772 /* Views, etc, have no disk storage */
773 new_rel_reltup->relpages = 0;
774 new_rel_reltup->reltuples = 0;
778 /* Initialize relfrozenxid */
779 if (relkind == RELKIND_RELATION ||
780 relkind == RELKIND_TOASTVALUE)
783 * Initialize to the minimum XID that could put tuples in the table.
784 * We know that no xacts older than RecentXmin are still running, so
787 new_rel_reltup->relfrozenxid = RecentXmin;
792 * Other relation types will not contain XIDs, so set relfrozenxid to
793 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
794 * we force its xmin to be FrozenTransactionId always; see
795 * commands/sequence.c.)
797 new_rel_reltup->relfrozenxid = InvalidTransactionId;
800 new_rel_reltup->relowner = relowner;
801 new_rel_reltup->reltype = new_type_oid;
802 new_rel_reltup->reloftype = reloftype;
803 new_rel_reltup->relkind = relkind;
805 new_rel_desc->rd_att->tdtypeid = new_type_oid;
807 /* Now build and insert the tuple */
808 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
813 /* --------------------------------
814 * AddNewRelationType -
816 * define a composite type corresponding to the new relation
817 * --------------------------------
820 AddNewRelationType(const char *typeName,
829 TypeCreate(new_row_type, /* optional predetermined OID */
830 typeName, /* type name */
831 typeNamespace, /* type namespace */
832 new_rel_oid, /* relation oid */
833 new_rel_kind, /* relation kind */
834 ownerid, /* owner's ID */
835 -1, /* internal size (varlena) */
836 TYPTYPE_COMPOSITE, /* type-type (composite) */
837 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
838 false, /* composite types are never preferred */
839 DEFAULT_TYPDELIM, /* default array delimiter */
840 F_RECORD_IN, /* input procedure */
841 F_RECORD_OUT, /* output procedure */
842 F_RECORD_RECV, /* receive procedure */
843 F_RECORD_SEND, /* send procedure */
844 InvalidOid, /* typmodin procedure - none */
845 InvalidOid, /* typmodout procedure - none */
846 InvalidOid, /* analyze procedure - default */
847 InvalidOid, /* array element type - irrelevant */
848 false, /* this is not an array type */
849 new_array_type, /* array type if any */
850 InvalidOid, /* domain base type - irrelevant */
851 NULL, /* default value - none */
852 NULL, /* default binary representation */
853 false, /* passed by reference */
854 'd', /* alignment - must be the largest! */
855 'x', /* fully TOASTable */
857 0, /* array dimensions for typBaseType */
858 false); /* Type NOT NULL */
861 /* --------------------------------
862 * heap_create_with_catalog
864 * creates a new cataloged relation. see comments above.
867 * relname: name to give to new rel
868 * relnamespace: OID of namespace it goes in
869 * reltablespace: OID of tablespace it goes in
870 * relid: OID to assign to new rel, or InvalidOid to select a new OID
871 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
872 * ownerid: OID of new rel's owner
873 * tupdesc: tuple descriptor (source of column definitions)
874 * cooked_constraints: list of precooked check constraints and defaults
875 * relkind: relkind for new rel
876 * shared_relation: TRUE if it's to be a shared relation
877 * mapped_relation: TRUE if the relation will use the relfilenode map
878 * oidislocal: TRUE if oid column (if any) should be marked attislocal
879 * oidinhcount: attinhcount to assign to oid column (if any)
880 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
881 * reloptions: reloptions in Datum form, or (Datum) 0 if none
882 * use_user_acl: TRUE if should look for user-defined default permissions;
883 * if FALSE, relacl is always set NULL
884 * allow_system_table_mods: TRUE to allow creation in system namespaces
886 * Returns the OID of the new relation
887 * --------------------------------
890 heap_create_with_catalog(const char *relname,
898 List *cooked_constraints,
900 bool shared_relation,
901 bool mapped_relation,
904 OnCommitAction oncommit,
907 bool allow_system_table_mods,
910 Relation pg_class_desc;
911 Relation new_rel_desc;
916 Oid new_array_oid = InvalidOid;
918 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
923 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
925 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
928 * If the relation already exists, it's an error, unless the user specifies
929 * "IF NOT EXISTS". In that case, we just print a notice and do nothing
932 existing_relid = get_relname_relid(relname, relnamespace);
933 if (existing_relid != InvalidOid)
938 (errcode(ERRCODE_DUPLICATE_TABLE),
939 errmsg("relation \"%s\" already exists, skipping",
941 heap_close(pg_class_desc, RowExclusiveLock);
945 (errcode(ERRCODE_DUPLICATE_TABLE),
946 errmsg("relation \"%s\" already exists", relname)));
950 * Since we are going to create a rowtype as well, also check for
951 * collision with an existing type name. If there is one and it's an
952 * autogenerated array, we can rename it out of the way; otherwise we can
953 * at least give a good error message.
955 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
956 CStringGetDatum(relname),
957 ObjectIdGetDatum(relnamespace));
958 if (OidIsValid(old_type_oid))
960 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
962 (errcode(ERRCODE_DUPLICATE_OBJECT),
963 errmsg("type \"%s\" already exists", relname),
964 errhint("A relation has an associated type of the same name, "
965 "so you must use a name that doesn't conflict "
966 "with any existing type.")));
970 * Shared relations must be in pg_global (last-ditch check)
972 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
973 elog(ERROR, "shared relations must be placed in pg_global tablespace");
976 * Allocate an OID for the relation, unless we were told what to use.
978 * The OID will be the relfilenode as well, so make sure it doesn't
979 * collide with either pg_class OIDs or existing physical files.
981 if (!OidIsValid(relid))
983 /* Use binary-upgrade overrides if applicable */
984 if (OidIsValid(binary_upgrade_next_heap_relfilenode) &&
985 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
986 relkind == RELKIND_VIEW || relkind == RELKIND_COMPOSITE_TYPE))
988 relid = binary_upgrade_next_heap_relfilenode;
989 binary_upgrade_next_heap_relfilenode = InvalidOid;
991 else if (OidIsValid(binary_upgrade_next_toast_relfilenode) &&
992 relkind == RELKIND_TOASTVALUE)
994 relid = binary_upgrade_next_toast_relfilenode;
995 binary_upgrade_next_toast_relfilenode = InvalidOid;
998 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
999 isTempOrToastNamespace(relnamespace) ?
1000 MyBackendId : InvalidBackendId);
1004 * Determine the relation's initial permissions.
1010 case RELKIND_RELATION:
1012 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1015 case RELKIND_SEQUENCE:
1016 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1028 * Create the relcache entry (mostly dummy at this point) and the physical
1029 * disk file. (If we fail further down, it's the smgr's responsibility to
1030 * remove the disk file again.)
1032 new_rel_desc = heap_create(relname,
1040 allow_system_table_mods);
1042 Assert(relid == RelationGetRelid(new_rel_desc));
1045 * Decide whether to create an array type over the relation's rowtype. We
1046 * do not create any array types for system catalogs (ie, those made
1047 * during initdb). We create array types for regular relations, views,
1048 * and composite types ... but not, eg, for toast tables or sequences.
1050 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1051 relkind == RELKIND_VIEW ||
1052 relkind == RELKIND_COMPOSITE_TYPE))
1053 new_array_oid = AssignTypeArrayOid();
1056 * Since defining a relation also defines a complex type, we add a new
1057 * system type corresponding to the new relation. The OID of the type can
1058 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1059 * generate a new OID for it.
1061 * NOTE: we could get a unique-index failure here, in case someone else is
1062 * creating the same type name in parallel but hadn't committed yet when
1063 * we checked for a duplicate name above.
1065 new_type_oid = AddNewRelationType(relname,
1074 * Now make the array type if wanted.
1076 if (OidIsValid(new_array_oid))
1080 relarrayname = makeArrayTypeName(relname, relnamespace);
1082 TypeCreate(new_array_oid, /* force the type's OID to this */
1083 relarrayname, /* Array type name */
1084 relnamespace, /* Same namespace as parent */
1085 InvalidOid, /* Not composite, no relationOid */
1086 0, /* relkind, also N/A here */
1087 ownerid, /* owner's ID */
1088 -1, /* Internal size (varlena) */
1089 TYPTYPE_BASE, /* Not composite - typelem is */
1090 TYPCATEGORY_ARRAY, /* type-category (array) */
1091 false, /* array types are never preferred */
1092 DEFAULT_TYPDELIM, /* default array delimiter */
1093 F_ARRAY_IN, /* array input proc */
1094 F_ARRAY_OUT, /* array output proc */
1095 F_ARRAY_RECV, /* array recv (bin) proc */
1096 F_ARRAY_SEND, /* array send (bin) proc */
1097 InvalidOid, /* typmodin procedure - none */
1098 InvalidOid, /* typmodout procedure - none */
1099 InvalidOid, /* analyze procedure - default */
1100 new_type_oid, /* array element type - the rowtype */
1101 true, /* yes, this is an array type */
1102 InvalidOid, /* this has no array type */
1103 InvalidOid, /* domain base type - irrelevant */
1104 NULL, /* default value - none */
1105 NULL, /* default binary representation */
1106 false, /* passed by reference */
1107 'd', /* alignment - must be the largest! */
1108 'x', /* fully TOASTable */
1110 0, /* array dimensions for typBaseType */
1111 false); /* Type NOT NULL */
1113 pfree(relarrayname);
1117 * now create an entry in pg_class for the relation.
1119 * NOTE: we could get a unique-index failure here, in case someone else is
1120 * creating the same relation name in parallel but hadn't committed yet
1121 * when we checked for a duplicate name above.
1123 AddNewRelationTuple(pg_class_desc,
1130 PointerGetDatum(relacl),
1134 * now add tuples to pg_attribute for the attributes in our new relation.
1136 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1137 oidislocal, oidinhcount);
1140 * Make a dependency link to force the relation to be deleted if its
1141 * namespace is. Also make a dependency link to its owner, as well as
1142 * dependencies for any roles mentioned in the default ACL.
1144 * For composite types, these dependencies are tracked for the pg_type
1145 * entry, so we needn't record them here. Likewise, TOAST tables don't
1146 * need a namespace dependency (they live in a pinned namespace) nor an
1147 * owner dependency (they depend indirectly through the parent table), nor
1148 * should they have any ACL entries.
1150 * Also, skip this in bootstrap mode, since we don't make dependencies
1151 * while bootstrapping.
1153 if (relkind != RELKIND_COMPOSITE_TYPE &&
1154 relkind != RELKIND_TOASTVALUE &&
1155 !IsBootstrapProcessingMode())
1157 ObjectAddress myself,
1160 myself.classId = RelationRelationId;
1161 myself.objectId = relid;
1162 myself.objectSubId = 0;
1163 referenced.classId = NamespaceRelationId;
1164 referenced.objectId = relnamespace;
1165 referenced.objectSubId = 0;
1166 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1168 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1172 referenced.classId = TypeRelationId;
1173 referenced.objectId = reloftypeid;
1174 referenced.objectSubId = 0;
1175 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1183 nnewmembers = aclmembers(relacl, &newmembers);
1184 updateAclDependencies(RelationRelationId, relid, 0,
1187 nnewmembers, newmembers);
1192 * Store any supplied constraints and defaults.
1194 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1195 * entry, so the relation must be valid and self-consistent at this point.
1196 * In particular, there are not yet constraints and defaults anywhere.
1198 StoreConstraints(new_rel_desc, cooked_constraints);
1201 * If there's a special on-commit action, remember it
1203 if (oncommit != ONCOMMIT_NOOP)
1204 register_on_commit_action(relid, oncommit);
1207 * ok, the relation has been cataloged, so close our relations and return
1208 * the OID of the newly created relation.
1210 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1211 heap_close(pg_class_desc, RowExclusiveLock);
1218 * RelationRemoveInheritance
1220 * Formerly, this routine checked for child relations and aborted the
1221 * deletion if any were found. Now we rely on the dependency mechanism
1222 * to check for or delete child relations. By the time we get here,
1223 * there are no children and we need only remove any pg_inherits rows
1224 * linking this relation to its parent(s).
1227 RelationRemoveInheritance(Oid relid)
1229 Relation catalogRelation;
1234 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1237 Anum_pg_inherits_inhrelid,
1238 BTEqualStrategyNumber, F_OIDEQ,
1239 ObjectIdGetDatum(relid));
1241 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1242 SnapshotNow, 1, &key);
1244 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1245 simple_heap_delete(catalogRelation, &tuple->t_self);
1247 systable_endscan(scan);
1248 heap_close(catalogRelation, RowExclusiveLock);
1252 * DeleteRelationTuple
1254 * Remove pg_class row for the given relid.
1256 * Note: this is shared by relation deletion and index deletion. It's
1257 * not intended for use anyplace else.
1260 DeleteRelationTuple(Oid relid)
1262 Relation pg_class_desc;
1265 /* Grab an appropriate lock on the pg_class relation */
1266 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1268 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1269 if (!HeapTupleIsValid(tup))
1270 elog(ERROR, "cache lookup failed for relation %u", relid);
1272 /* delete the relation tuple from pg_class, and finish up */
1273 simple_heap_delete(pg_class_desc, &tup->t_self);
1275 ReleaseSysCache(tup);
1277 heap_close(pg_class_desc, RowExclusiveLock);
1281 * DeleteAttributeTuples
1283 * Remove pg_attribute rows for the given relid.
1285 * Note: this is shared by relation deletion and index deletion. It's
1286 * not intended for use anyplace else.
1289 DeleteAttributeTuples(Oid relid)
1296 /* Grab an appropriate lock on the pg_attribute relation */
1297 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1299 /* Use the index to scan only attributes of the target relation */
1300 ScanKeyInit(&key[0],
1301 Anum_pg_attribute_attrelid,
1302 BTEqualStrategyNumber, F_OIDEQ,
1303 ObjectIdGetDatum(relid));
1305 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1306 SnapshotNow, 1, key);
1308 /* Delete all the matching tuples */
1309 while ((atttup = systable_getnext(scan)) != NULL)
1310 simple_heap_delete(attrel, &atttup->t_self);
1312 /* Clean up after the scan */
1313 systable_endscan(scan);
1314 heap_close(attrel, RowExclusiveLock);
1318 * RemoveAttributeById
1320 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1321 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1322 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1323 * is handled by dependency.c.)
1326 RemoveAttributeById(Oid relid, AttrNumber attnum)
1331 Form_pg_attribute attStruct;
1332 char newattname[NAMEDATALEN];
1335 * Grab an exclusive lock on the target table, which we will NOT release
1336 * until end of transaction. (In the simple case where we are directly
1337 * dropping this column, AlterTableDropColumn already did this ... but
1338 * when cascading from a drop of some other object, we may not have any
1341 rel = relation_open(relid, AccessExclusiveLock);
1343 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1345 tuple = SearchSysCacheCopy2(ATTNUM,
1346 ObjectIdGetDatum(relid),
1347 Int16GetDatum(attnum));
1348 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1349 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1351 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1355 /* System attribute (probably OID) ... just delete the row */
1357 simple_heap_delete(attr_rel, &tuple->t_self);
1361 /* Dropping user attributes is lots harder */
1363 /* Mark the attribute as dropped */
1364 attStruct->attisdropped = true;
1367 * Set the type OID to invalid. A dropped attribute's type link
1368 * cannot be relied on (once the attribute is dropped, the type might
1369 * be too). Fortunately we do not need the type row --- the only
1370 * really essential information is the type's typlen and typalign,
1371 * which are preserved in the attribute's attlen and attalign. We set
1372 * atttypid to zero here as a means of catching code that incorrectly
1373 * expects it to be valid.
1375 attStruct->atttypid = InvalidOid;
1377 /* Remove any NOT NULL constraint the column may have */
1378 attStruct->attnotnull = false;
1380 /* We don't want to keep stats for it anymore */
1381 attStruct->attstattarget = 0;
1384 * Change the column name to something that isn't likely to conflict
1386 snprintf(newattname, sizeof(newattname),
1387 "........pg.dropped.%d........", attnum);
1388 namestrcpy(&(attStruct->attname), newattname);
1390 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1392 /* keep the system catalog indexes current */
1393 CatalogUpdateIndexes(attr_rel, tuple);
1397 * Because updating the pg_attribute row will trigger a relcache flush for
1398 * the target relation, we need not do anything else to notify other
1399 * backends of the change.
1402 heap_close(attr_rel, RowExclusiveLock);
1405 RemoveStatistics(relid, attnum);
1407 relation_close(rel, NoLock);
1413 * If the specified relation/attribute has a default, remove it.
1414 * (If no default, raise error if complain is true, else return quietly.)
1417 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1418 DropBehavior behavior, bool complain)
1420 Relation attrdef_rel;
1421 ScanKeyData scankeys[2];
1426 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1428 ScanKeyInit(&scankeys[0],
1429 Anum_pg_attrdef_adrelid,
1430 BTEqualStrategyNumber, F_OIDEQ,
1431 ObjectIdGetDatum(relid));
1432 ScanKeyInit(&scankeys[1],
1433 Anum_pg_attrdef_adnum,
1434 BTEqualStrategyNumber, F_INT2EQ,
1435 Int16GetDatum(attnum));
1437 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1438 SnapshotNow, 2, scankeys);
1440 /* There should be at most one matching tuple, but we loop anyway */
1441 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1443 ObjectAddress object;
1445 object.classId = AttrDefaultRelationId;
1446 object.objectId = HeapTupleGetOid(tuple);
1447 object.objectSubId = 0;
1449 performDeletion(&object, behavior);
1454 systable_endscan(scan);
1455 heap_close(attrdef_rel, RowExclusiveLock);
1457 if (complain && !found)
1458 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1463 * RemoveAttrDefaultById
1465 * Remove a pg_attrdef entry specified by OID. This is the guts of
1466 * attribute-default removal. Note it should be called via performDeletion,
1470 RemoveAttrDefaultById(Oid attrdefId)
1472 Relation attrdef_rel;
1475 ScanKeyData scankeys[1];
1479 AttrNumber myattnum;
1481 /* Grab an appropriate lock on the pg_attrdef relation */
1482 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1484 /* Find the pg_attrdef tuple */
1485 ScanKeyInit(&scankeys[0],
1486 ObjectIdAttributeNumber,
1487 BTEqualStrategyNumber, F_OIDEQ,
1488 ObjectIdGetDatum(attrdefId));
1490 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1491 SnapshotNow, 1, scankeys);
1493 tuple = systable_getnext(scan);
1494 if (!HeapTupleIsValid(tuple))
1495 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1497 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1498 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1500 /* Get an exclusive lock on the relation owning the attribute */
1501 myrel = relation_open(myrelid, AccessExclusiveLock);
1503 /* Now we can delete the pg_attrdef row */
1504 simple_heap_delete(attrdef_rel, &tuple->t_self);
1506 systable_endscan(scan);
1507 heap_close(attrdef_rel, RowExclusiveLock);
1509 /* Fix the pg_attribute row */
1510 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1512 tuple = SearchSysCacheCopy2(ATTNUM,
1513 ObjectIdGetDatum(myrelid),
1514 Int16GetDatum(myattnum));
1515 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1516 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1519 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1521 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1523 /* keep the system catalog indexes current */
1524 CatalogUpdateIndexes(attr_rel, tuple);
1527 * Our update of the pg_attribute row will force a relcache rebuild, so
1528 * there's nothing else to do here.
1530 heap_close(attr_rel, RowExclusiveLock);
1532 /* Keep lock on attribute's rel until end of xact */
1533 relation_close(myrel, NoLock);
1537 * heap_drop_with_catalog - removes specified relation from catalogs
1539 * Note that this routine is not responsible for dropping objects that are
1540 * linked to the pg_class entry via dependencies (for example, indexes and
1541 * constraints). Those are deleted by the dependency-tracing logic in
1542 * dependency.c before control gets here. In general, therefore, this routine
1543 * should never be called directly; go through performDeletion() instead.
1546 heap_drop_with_catalog(Oid relid)
1551 * Open and lock the relation.
1553 rel = relation_open(relid, AccessExclusiveLock);
1556 * There can no longer be anyone *else* touching the relation, but we
1557 * might still have open queries or cursors in our own session.
1559 if (rel->rd_refcnt != 1)
1561 (errcode(ERRCODE_OBJECT_IN_USE),
1562 errmsg("cannot drop \"%s\" because "
1563 "it is being used by active queries in this session",
1564 RelationGetRelationName(rel))));
1567 * Schedule unlinking of the relation's physical files at commit.
1569 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1570 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1572 RelationDropStorage(rel);
1576 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1577 * until transaction commit. This ensures no one else will try to do
1578 * something with the doomed relation.
1580 relation_close(rel, NoLock);
1583 * Forget any ON COMMIT action for the rel
1585 remove_on_commit_action(relid);
1588 * Flush the relation from the relcache. We want to do this before
1589 * starting to remove catalog entries, just to be certain that no relcache
1590 * entry rebuild will happen partway through. (That should not really
1591 * matter, since we don't do CommandCounterIncrement here, but let's be
1594 RelationForgetRelation(relid);
1597 * remove inheritance information
1599 RelationRemoveInheritance(relid);
1604 RemoveStatistics(relid, 0);
1607 * delete attribute tuples
1609 DeleteAttributeTuples(relid);
1612 * delete relation tuple
1614 DeleteRelationTuple(relid);
1619 * Store a default expression for column attnum of relation rel.
1622 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1629 static bool nulls[4] = {false, false, false, false};
1632 Form_pg_attribute attStruct;
1634 ObjectAddress colobject,
1638 * Flatten expression to string form for storage.
1640 adbin = nodeToString(expr);
1643 * Also deparse it to form the mostly-obsolete adsrc field.
1645 adsrc = deparse_expression(expr,
1646 deparse_context_for(RelationGetRelationName(rel),
1647 RelationGetRelid(rel)),
1651 * Make the pg_attrdef entry.
1653 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1654 values[Anum_pg_attrdef_adnum - 1] = attnum;
1655 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1656 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1658 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1660 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1661 attrdefOid = simple_heap_insert(adrel, tuple);
1663 CatalogUpdateIndexes(adrel, tuple);
1665 defobject.classId = AttrDefaultRelationId;
1666 defobject.objectId = attrdefOid;
1667 defobject.objectSubId = 0;
1669 heap_close(adrel, RowExclusiveLock);
1671 /* now can free some of the stuff allocated above */
1672 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1673 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1674 heap_freetuple(tuple);
1679 * Update the pg_attribute entry for the column to show that a default
1682 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1683 atttup = SearchSysCacheCopy2(ATTNUM,
1684 ObjectIdGetDatum(RelationGetRelid(rel)),
1685 Int16GetDatum(attnum));
1686 if (!HeapTupleIsValid(atttup))
1687 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1688 attnum, RelationGetRelid(rel));
1689 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1690 if (!attStruct->atthasdef)
1692 attStruct->atthasdef = true;
1693 simple_heap_update(attrrel, &atttup->t_self, atttup);
1694 /* keep catalog indexes current */
1695 CatalogUpdateIndexes(attrrel, atttup);
1697 heap_close(attrrel, RowExclusiveLock);
1698 heap_freetuple(atttup);
1701 * Make a dependency so that the pg_attrdef entry goes away if the column
1702 * (or whole table) is deleted.
1704 colobject.classId = RelationRelationId;
1705 colobject.objectId = RelationGetRelid(rel);
1706 colobject.objectSubId = attnum;
1708 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1711 * Record dependencies on objects used in the expression, too.
1713 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1717 * Store a check-constraint expression for the given relation.
1719 * Caller is responsible for updating the count of constraints
1720 * in the pg_class entry for the relation.
1723 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1724 bool is_local, int inhcount)
1733 * Flatten expression to string form for storage.
1735 ccbin = nodeToString(expr);
1738 * Also deparse it to form the mostly-obsolete consrc field.
1740 ccsrc = deparse_expression(expr,
1741 deparse_context_for(RelationGetRelationName(rel),
1742 RelationGetRelid(rel)),
1746 * Find columns of rel that are used in expr
1748 * NB: pull_var_clause is okay here only because we don't allow subselects
1749 * in check constraints; it would fail to examine the contents of
1752 varList = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
1753 keycount = list_length(varList);
1760 attNos = (int16 *) palloc(keycount * sizeof(int16));
1761 foreach(vl, varList)
1763 Var *var = (Var *) lfirst(vl);
1766 for (j = 0; j < i; j++)
1767 if (attNos[j] == var->varattno)
1770 attNos[i++] = var->varattno;
1778 * Create the Check Constraint
1780 CreateConstraintEntry(ccname, /* Constraint Name */
1781 RelationGetNamespace(rel), /* namespace */
1782 CONSTRAINT_CHECK, /* Constraint Type */
1783 false, /* Is Deferrable */
1784 false, /* Is Deferred */
1785 RelationGetRelid(rel), /* relation */
1786 attNos, /* attrs in the constraint */
1787 keycount, /* # attrs in the constraint */
1788 InvalidOid, /* not a domain constraint */
1789 InvalidOid, /* no associated index */
1790 InvalidOid, /* Foreign key fields */
1799 NULL, /* not an exclusion constraint */
1800 expr, /* Tree form of check constraint */
1801 ccbin, /* Binary form of check constraint */
1802 ccsrc, /* Source form of check constraint */
1803 is_local, /* conislocal */
1804 inhcount); /* coninhcount */
1811 * Store defaults and constraints (passed as a list of CookedConstraint).
1813 * NOTE: only pre-cooked expressions will be passed this way, which is to
1814 * say expressions inherited from an existing relation. Newly parsed
1815 * expressions can be added later, by direct calls to StoreAttrDefault
1816 * and StoreRelCheck (see AddRelationNewConstraints()).
1819 StoreConstraints(Relation rel, List *cooked_constraints)
1824 if (!cooked_constraints)
1825 return; /* nothing to do */
1828 * Deparsing of constraint expressions will fail unless the just-created
1829 * pg_attribute tuples for this relation are made visible. So, bump the
1830 * command counter. CAUTION: this will cause a relcache entry rebuild.
1832 CommandCounterIncrement();
1834 foreach(lc, cooked_constraints)
1836 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1838 switch (con->contype)
1840 case CONSTR_DEFAULT:
1841 StoreAttrDefault(rel, con->attnum, con->expr);
1844 StoreRelCheck(rel, con->name, con->expr,
1845 con->is_local, con->inhcount);
1849 elog(ERROR, "unrecognized constraint type: %d",
1850 (int) con->contype);
1855 SetRelationNumChecks(rel, numchecks);
1859 * AddRelationNewConstraints
1861 * Add new column default expressions and/or constraint check expressions
1862 * to an existing relation. This is defined to do both for efficiency in
1863 * DefineRelation, but of course you can do just one or the other by passing
1866 * rel: relation to be modified
1867 * newColDefaults: list of RawColumnDefault structures
1868 * newConstraints: list of Constraint nodes
1869 * allow_merge: TRUE if check constraints may be merged with existing ones
1870 * is_local: TRUE if definition is local, FALSE if it's inherited
1872 * All entries in newColDefaults will be processed. Entries in newConstraints
1873 * will be processed only if they are CONSTR_CHECK type.
1875 * Returns a list of CookedConstraint nodes that shows the cooked form of
1876 * the default and constraint expressions added to the relation.
1878 * NB: caller should have opened rel with AccessExclusiveLock, and should
1879 * hold that lock till end of transaction. Also, we assume the caller has
1880 * done a CommandCounterIncrement if necessary to make the relation's catalog
1884 AddRelationNewConstraints(Relation rel,
1885 List *newColDefaults,
1886 List *newConstraints,
1890 List *cookedConstraints = NIL;
1891 TupleDesc tupleDesc;
1892 TupleConstr *oldconstr;
1900 CookedConstraint *cooked;
1903 * Get info about existing constraints.
1905 tupleDesc = RelationGetDescr(rel);
1906 oldconstr = tupleDesc->constr;
1908 numoldchecks = oldconstr->num_check;
1913 * Create a dummy ParseState and insert the target relation as its sole
1914 * rangetable entry. We need a ParseState for transformExpr.
1916 pstate = make_parsestate(NULL);
1917 rte = addRangeTableEntryForRelation(pstate,
1922 addRTEtoQuery(pstate, rte, true, true, true);
1925 * Process column default expressions.
1927 foreach(cell, newColDefaults)
1929 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1930 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1932 expr = cookDefault(pstate, colDef->raw_default,
1933 atp->atttypid, atp->atttypmod,
1934 NameStr(atp->attname));
1937 * If the expression is just a NULL constant, we do not bother to make
1938 * an explicit pg_attrdef entry, since the default behavior is
1941 * Note a nonobvious property of this test: if the column is of a
1942 * domain type, what we'll get is not a bare null Const but a
1943 * CoerceToDomain expr, so we will not discard the default. This is
1944 * critical because the column default needs to be retained to
1945 * override any default that the domain might have.
1948 (IsA(expr, Const) &&((Const *) expr)->constisnull))
1951 StoreAttrDefault(rel, colDef->attnum, expr);
1953 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1954 cooked->contype = CONSTR_DEFAULT;
1955 cooked->name = NULL;
1956 cooked->attnum = colDef->attnum;
1957 cooked->expr = expr;
1958 cooked->is_local = is_local;
1959 cooked->inhcount = is_local ? 0 : 1;
1960 cookedConstraints = lappend(cookedConstraints, cooked);
1964 * Process constraint expressions.
1966 numchecks = numoldchecks;
1968 foreach(cell, newConstraints)
1970 Constraint *cdef = (Constraint *) lfirst(cell);
1973 if (cdef->contype != CONSTR_CHECK)
1976 if (cdef->raw_expr != NULL)
1978 Assert(cdef->cooked_expr == NULL);
1981 * Transform raw parsetree to executable expression, and verify
1982 * it's valid as a CHECK constraint.
1984 expr = cookConstraint(pstate, cdef->raw_expr,
1985 RelationGetRelationName(rel));
1989 Assert(cdef->cooked_expr != NULL);
1992 * Here, we assume the parser will only pass us valid CHECK
1993 * expressions, so we do no particular checking.
1995 expr = stringToNode(cdef->cooked_expr);
1999 * Check name uniqueness, or generate a name if none was given.
2001 if (cdef->conname != NULL)
2005 ccname = cdef->conname;
2006 /* Check against other new constraints */
2007 /* Needed because we don't do CommandCounterIncrement in loop */
2008 foreach(cell2, checknames)
2010 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2012 (errcode(ERRCODE_DUPLICATE_OBJECT),
2013 errmsg("check constraint \"%s\" already exists",
2017 /* save name for future checks */
2018 checknames = lappend(checknames, ccname);
2021 * Check against pre-existing constraints. If we are allowed to
2022 * merge with an existing constraint, there's no more to do here.
2023 * (We omit the duplicate constraint from the result, which is
2024 * what ATAddCheckConstraint wants.)
2026 if (MergeWithExistingConstraint(rel, ccname, expr,
2027 allow_merge, is_local))
2033 * When generating a name, we want to create "tab_col_check" for a
2034 * column constraint and "tab_check" for a table constraint. We
2035 * no longer have any info about the syntactic positioning of the
2036 * constraint phrase, so we approximate this by seeing whether the
2037 * expression references more than one column. (If the user
2038 * played by the rules, the result is the same...)
2040 * Note: pull_var_clause() doesn't descend into sublinks, but we
2041 * eliminated those above; and anyway this only needs to be an
2042 * approximate answer.
2047 vars = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
2049 /* eliminate duplicates */
2050 vars = list_union(NIL, vars);
2052 if (list_length(vars) == 1)
2053 colname = get_attname(RelationGetRelid(rel),
2054 ((Var *) linitial(vars))->varattno);
2058 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2061 RelationGetNamespace(rel),
2064 /* save name for future checks */
2065 checknames = lappend(checknames, ccname);
2071 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
2075 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2076 cooked->contype = CONSTR_CHECK;
2077 cooked->name = ccname;
2079 cooked->expr = expr;
2080 cooked->is_local = is_local;
2081 cooked->inhcount = is_local ? 0 : 1;
2082 cookedConstraints = lappend(cookedConstraints, cooked);
2086 * Update the count of constraints in the relation's pg_class tuple. We do
2087 * this even if there was no change, in order to ensure that an SI update
2088 * message is sent out for the pg_class tuple, which will force other
2089 * backends to rebuild their relcache entries for the rel. (This is
2090 * critical if we added defaults but not constraints.)
2092 SetRelationNumChecks(rel, numchecks);
2094 return cookedConstraints;
2098 * Check for a pre-existing check constraint that conflicts with a proposed
2099 * new one, and either adjust its conislocal/coninhcount settings or throw
2102 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2103 * got a so-far-unique name, or throws error if conflict.
2106 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2107 bool allow_merge, bool is_local)
2111 SysScanDesc conscan;
2112 ScanKeyData skey[2];
2115 /* Search for a pg_constraint entry with same name and relation */
2116 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2120 ScanKeyInit(&skey[0],
2121 Anum_pg_constraint_conname,
2122 BTEqualStrategyNumber, F_NAMEEQ,
2123 CStringGetDatum(ccname));
2125 ScanKeyInit(&skey[1],
2126 Anum_pg_constraint_connamespace,
2127 BTEqualStrategyNumber, F_OIDEQ,
2128 ObjectIdGetDatum(RelationGetNamespace(rel)));
2130 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2131 SnapshotNow, 2, skey);
2133 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2135 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2137 if (con->conrelid == RelationGetRelid(rel))
2139 /* Found it. Conflicts if not identical check constraint */
2140 if (con->contype == CONSTRAINT_CHECK)
2145 val = fastgetattr(tup,
2146 Anum_pg_constraint_conbin,
2147 conDesc->rd_att, &isnull);
2149 elog(ERROR, "null conbin for rel %s",
2150 RelationGetRelationName(rel));
2151 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2154 if (!found || !allow_merge)
2156 (errcode(ERRCODE_DUPLICATE_OBJECT),
2157 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2158 ccname, RelationGetRelationName(rel))));
2159 /* OK to update the tuple */
2161 (errmsg("merging constraint \"%s\" with inherited definition",
2163 tup = heap_copytuple(tup);
2164 con = (Form_pg_constraint) GETSTRUCT(tup);
2166 con->conislocal = true;
2169 simple_heap_update(conDesc, &tup->t_self, tup);
2170 CatalogUpdateIndexes(conDesc, tup);
2175 systable_endscan(conscan);
2176 heap_close(conDesc, RowExclusiveLock);
2182 * Update the count of constraints in the relation's pg_class tuple.
2184 * Caller had better hold exclusive lock on the relation.
2186 * An important side effect is that a SI update message will be sent out for
2187 * the pg_class tuple, which will force other backends to rebuild their
2188 * relcache entries for the rel. Also, this backend will rebuild its
2189 * own relcache entry at the next CommandCounterIncrement.
2192 SetRelationNumChecks(Relation rel, int numchecks)
2196 Form_pg_class relStruct;
2198 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2199 reltup = SearchSysCacheCopy1(RELOID,
2200 ObjectIdGetDatum(RelationGetRelid(rel)));
2201 if (!HeapTupleIsValid(reltup))
2202 elog(ERROR, "cache lookup failed for relation %u",
2203 RelationGetRelid(rel));
2204 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2206 if (relStruct->relchecks != numchecks)
2208 relStruct->relchecks = numchecks;
2210 simple_heap_update(relrel, &reltup->t_self, reltup);
2212 /* keep catalog indexes current */
2213 CatalogUpdateIndexes(relrel, reltup);
2217 /* Skip the disk update, but force relcache inval anyway */
2218 CacheInvalidateRelcache(rel);
2221 heap_freetuple(reltup);
2222 heap_close(relrel, RowExclusiveLock);
2226 * Take a raw default and convert it to a cooked format ready for
2229 * Parse state should be set up to recognize any vars that might appear
2230 * in the expression. (Even though we plan to reject vars, it's more
2231 * user-friendly to give the correct error message than "unknown var".)
2233 * If atttypid is not InvalidOid, coerce the expression to the specified
2234 * type (and typmod atttypmod). attname is only needed in this case:
2235 * it is used in the error message, if any.
2238 cookDefault(ParseState *pstate,
2246 Assert(raw_default != NULL);
2249 * Transform raw parsetree to executable expression.
2251 expr = transformExpr(pstate, raw_default);
2254 * Make sure default expr does not refer to any vars.
2256 if (contain_var_clause(expr))
2258 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2259 errmsg("cannot use column references in default expression")));
2262 * It can't return a set either.
2264 if (expression_returns_set(expr))
2266 (errcode(ERRCODE_DATATYPE_MISMATCH),
2267 errmsg("default expression must not return a set")));
2270 * No subplans or aggregates, either...
2272 if (pstate->p_hasSubLinks)
2274 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2275 errmsg("cannot use subquery in default expression")));
2276 if (pstate->p_hasAggs)
2278 (errcode(ERRCODE_GROUPING_ERROR),
2279 errmsg("cannot use aggregate function in default expression")));
2280 if (pstate->p_hasWindowFuncs)
2282 (errcode(ERRCODE_WINDOWING_ERROR),
2283 errmsg("cannot use window function in default expression")));
2286 * Coerce the expression to the correct type and typmod, if given. This
2287 * should match the parser's processing of non-defaulted expressions ---
2288 * see transformAssignedExpr().
2290 if (OidIsValid(atttypid))
2292 Oid type_id = exprType(expr);
2294 expr = coerce_to_target_type(pstate, expr, type_id,
2295 atttypid, atttypmod,
2296 COERCION_ASSIGNMENT,
2297 COERCE_IMPLICIT_CAST,
2301 (errcode(ERRCODE_DATATYPE_MISMATCH),
2302 errmsg("column \"%s\" is of type %s"
2303 " but default expression is of type %s",
2305 format_type_be(atttypid),
2306 format_type_be(type_id)),
2307 errhint("You will need to rewrite or cast the expression.")));
2314 * Take a raw CHECK constraint expression and convert it to a cooked format
2315 * ready for storage.
2317 * Parse state must be set up to recognize any vars that might appear
2318 * in the expression.
2321 cookConstraint(ParseState *pstate,
2322 Node *raw_constraint,
2328 * Transform raw parsetree to executable expression.
2330 expr = transformExpr(pstate, raw_constraint);
2333 * Make sure it yields a boolean result.
2335 expr = coerce_to_boolean(pstate, expr, "CHECK");
2338 * Make sure no outside relations are referred to.
2340 if (list_length(pstate->p_rtable) != 1)
2342 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2343 errmsg("only table \"%s\" can be referenced in check constraint",
2347 * No subplans or aggregates, either...
2349 if (pstate->p_hasSubLinks)
2351 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2352 errmsg("cannot use subquery in check constraint")));
2353 if (pstate->p_hasAggs)
2355 (errcode(ERRCODE_GROUPING_ERROR),
2356 errmsg("cannot use aggregate function in check constraint")));
2357 if (pstate->p_hasWindowFuncs)
2359 (errcode(ERRCODE_WINDOWING_ERROR),
2360 errmsg("cannot use window function in check constraint")));
2367 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2369 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2373 RemoveStatistics(Oid relid, AttrNumber attnum)
2375 Relation pgstatistic;
2381 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2383 ScanKeyInit(&key[0],
2384 Anum_pg_statistic_starelid,
2385 BTEqualStrategyNumber, F_OIDEQ,
2386 ObjectIdGetDatum(relid));
2392 ScanKeyInit(&key[1],
2393 Anum_pg_statistic_staattnum,
2394 BTEqualStrategyNumber, F_INT2EQ,
2395 Int16GetDatum(attnum));
2399 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2400 SnapshotNow, nkeys, key);
2402 /* we must loop even when attnum != 0, in case of inherited stats */
2403 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2404 simple_heap_delete(pgstatistic, &tuple->t_self);
2406 systable_endscan(scan);
2408 heap_close(pgstatistic, RowExclusiveLock);
2413 * RelationTruncateIndexes - truncate all indexes associated
2414 * with the heap relation to zero tuples.
2416 * The routine will truncate and then reconstruct the indexes on
2417 * the specified relation. Caller must hold exclusive lock on rel.
2420 RelationTruncateIndexes(Relation heapRelation)
2424 /* Ask the relcache to produce a list of the indexes of the rel */
2425 foreach(indlist, RelationGetIndexList(heapRelation))
2427 Oid indexId = lfirst_oid(indlist);
2428 Relation currentIndex;
2429 IndexInfo *indexInfo;
2431 /* Open the index relation; use exclusive lock, just to be sure */
2432 currentIndex = index_open(indexId, AccessExclusiveLock);
2434 /* Fetch info needed for index_build */
2435 indexInfo = BuildIndexInfo(currentIndex);
2438 * Now truncate the actual file (and discard buffers).
2440 RelationTruncate(currentIndex, 0);
2442 /* Initialize the index and rebuild */
2443 /* Note: we do not need to re-establish pkey setting */
2444 index_build(heapRelation, currentIndex, indexInfo, false);
2446 /* We're done with this index */
2447 index_close(currentIndex, NoLock);
2454 * This routine deletes all data within all the specified relations.
2456 * This is not transaction-safe! There is another, transaction-safe
2457 * implementation in commands/tablecmds.c. We now use this only for
2458 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2461 heap_truncate(List *relids)
2463 List *relations = NIL;
2466 /* Open relations for processing, and grab exclusive access on each */
2467 foreach(cell, relids)
2469 Oid rid = lfirst_oid(cell);
2472 rel = heap_open(rid, AccessExclusiveLock);
2473 relations = lappend(relations, rel);
2476 /* Don't allow truncate on tables that are referenced by foreign keys */
2477 heap_truncate_check_FKs(relations, true);
2480 foreach(cell, relations)
2482 Relation rel = lfirst(cell);
2484 /* Truncate the relation */
2485 heap_truncate_one_rel(rel);
2487 /* Close the relation, but keep exclusive lock on it until commit */
2488 heap_close(rel, NoLock);
2493 * heap_truncate_one_rel
2495 * This routine deletes all data within the specified relation.
2497 * This is not transaction-safe, because the truncation is done immediately
2498 * and cannot be rolled back later. Caller is responsible for having
2499 * checked permissions etc, and must have obtained AccessExclusiveLock.
2502 heap_truncate_one_rel(Relation rel)
2506 /* Truncate the actual file (and discard buffers) */
2507 RelationTruncate(rel, 0);
2509 /* If the relation has indexes, truncate the indexes too */
2510 RelationTruncateIndexes(rel);
2512 /* If there is a toast table, truncate that too */
2513 toastrelid = rel->rd_rel->reltoastrelid;
2514 if (OidIsValid(toastrelid))
2516 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2518 RelationTruncate(toastrel, 0);
2519 RelationTruncateIndexes(toastrel);
2520 /* keep the lock... */
2521 heap_close(toastrel, NoLock);
2526 * heap_truncate_check_FKs
2527 * Check for foreign keys referencing a list of relations that
2528 * are to be truncated, and raise error if there are any
2530 * We disallow such FKs (except self-referential ones) since the whole point
2531 * of TRUNCATE is to not scan the individual rows to be thrown away.
2533 * This is split out so it can be shared by both implementations of truncate.
2534 * Caller should already hold a suitable lock on the relations.
2536 * tempTables is only used to select an appropriate error message.
2539 heap_truncate_check_FKs(List *relations, bool tempTables)
2546 * Build a list of OIDs of the interesting relations.
2548 * If a relation has no triggers, then it can neither have FKs nor be
2549 * referenced by a FK from another table, so we can ignore it.
2551 foreach(cell, relations)
2553 Relation rel = lfirst(cell);
2555 if (rel->rd_rel->relhastriggers)
2556 oids = lappend_oid(oids, RelationGetRelid(rel));
2560 * Fast path: if no relation has triggers, none has FKs either.
2566 * Otherwise, must scan pg_constraint. We make one pass with all the
2567 * relations considered; if this finds nothing, then all is well.
2569 dependents = heap_truncate_find_FKs(oids);
2570 if (dependents == NIL)
2574 * Otherwise we repeat the scan once per relation to identify a particular
2575 * pair of relations to complain about. This is pretty slow, but
2576 * performance shouldn't matter much in a failure path. The reason for
2577 * doing things this way is to ensure that the message produced is not
2578 * dependent on chance row locations within pg_constraint.
2582 Oid relid = lfirst_oid(cell);
2585 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2587 foreach(cell2, dependents)
2589 Oid relid2 = lfirst_oid(cell2);
2591 if (!list_member_oid(oids, relid2))
2593 char *relname = get_rel_name(relid);
2594 char *relname2 = get_rel_name(relid2);
2598 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2599 errmsg("unsupported ON COMMIT and foreign key combination"),
2600 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2601 relname2, relname)));
2604 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2605 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2606 errdetail("Table \"%s\" references \"%s\".",
2608 errhint("Truncate table \"%s\" at the same time, "
2609 "or use TRUNCATE ... CASCADE.",
2617 * heap_truncate_find_FKs
2618 * Find relations having foreign keys referencing any of the given rels
2620 * Input and result are both lists of relation OIDs. The result contains
2621 * no duplicates, does *not* include any rels that were already in the input
2622 * list, and is sorted in OID order. (The last property is enforced mainly
2623 * to guarantee consistent behavior in the regression tests; we don't want
2624 * behavior to change depending on chance locations of rows in pg_constraint.)
2626 * Note: caller should already have appropriate lock on all rels mentioned
2627 * in relationIds. Since adding or dropping an FK requires exclusive lock
2628 * on both rels, this ensures that the answer will be stable.
2631 heap_truncate_find_FKs(List *relationIds)
2635 SysScanDesc fkeyScan;
2639 * Must scan pg_constraint. Right now, it is a seqscan because there is
2640 * no available index on confrelid.
2642 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2644 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2645 SnapshotNow, 0, NULL);
2647 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2649 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2651 /* Not a foreign key */
2652 if (con->contype != CONSTRAINT_FOREIGN)
2655 /* Not referencing one of our list of tables */
2656 if (!list_member_oid(relationIds, con->confrelid))
2659 /* Add referencer unless already in input or result list */
2660 if (!list_member_oid(relationIds, con->conrelid))
2661 result = insert_ordered_unique_oid(result, con->conrelid);
2664 systable_endscan(fkeyScan);
2665 heap_close(fkeyRel, AccessShareLock);
2671 * insert_ordered_unique_oid
2672 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2673 * and eliminating duplicates
2675 * Building the ordered list this way is O(N^2), but with a pretty small
2676 * constant, so for the number of entries we expect it will probably be
2677 * faster than trying to apply qsort(). It seems unlikely someone would be
2678 * trying to truncate a table with thousands of dependent tables ...
2681 insert_ordered_unique_oid(List *list, Oid datum)
2685 /* Does the datum belong at the front? */
2686 if (list == NIL || datum < linitial_oid(list))
2687 return lcons_oid(datum, list);
2688 /* Does it match the first entry? */
2689 if (datum == linitial_oid(list))
2690 return list; /* duplicate, so don't insert */
2691 /* No, so find the entry it belongs after */
2692 prev = list_head(list);
2695 ListCell *curr = lnext(prev);
2697 if (curr == NULL || datum < lfirst_oid(curr))
2698 break; /* it belongs after 'prev', before 'curr' */
2700 if (datum == lfirst_oid(curr))
2701 return list; /* duplicate, so don't insert */
2705 /* Insert datum into list after 'prev' */
2706 lappend_cell_oid(list, prev, datum);