1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2011, 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/objectaccess.h"
44 #include "catalog/pg_attrdef.h"
45 #include "catalog/pg_constraint.h"
46 #include "catalog/pg_foreign_table.h"
47 #include "catalog/pg_inherits.h"
48 #include "catalog/pg_namespace.h"
49 #include "catalog/pg_statistic.h"
50 #include "catalog/pg_tablespace.h"
51 #include "catalog/pg_type.h"
52 #include "catalog/pg_type_fn.h"
53 #include "catalog/storage.h"
54 #include "commands/tablecmds.h"
55 #include "commands/typecmds.h"
56 #include "miscadmin.h"
57 #include "nodes/nodeFuncs.h"
58 #include "optimizer/var.h"
59 #include "parser/parse_coerce.h"
60 #include "parser/parse_expr.h"
61 #include "parser/parse_relation.h"
62 #include "storage/bufmgr.h"
63 #include "storage/freespace.h"
64 #include "storage/smgr.h"
65 #include "utils/acl.h"
66 #include "utils/builtins.h"
67 #include "utils/fmgroids.h"
68 #include "utils/inval.h"
69 #include "utils/lsyscache.h"
70 #include "utils/relcache.h"
71 #include "utils/snapmgr.h"
72 #include "utils/syscache.h"
73 #include "utils/tqual.h"
76 /* Kluge for upgrade-in-place support */
77 Oid binary_upgrade_next_heap_relfilenode = InvalidOid;
78 Oid binary_upgrade_next_toast_relfilenode = InvalidOid;
80 static void AddNewRelationTuple(Relation pg_class_desc,
81 Relation new_rel_desc,
89 static Oid AddNewRelationType(const char *typeName,
96 static void RelationRemoveInheritance(Oid relid);
97 static void StoreRelCheck(Relation rel, char *ccname, Node *expr,
98 bool is_local, int inhcount);
99 static void StoreConstraints(Relation rel, List *cooked_constraints);
100 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
101 bool allow_merge, bool is_local);
102 static void SetRelationNumChecks(Relation rel, int numchecks);
103 static Node *cookConstraint(ParseState *pstate,
104 Node *raw_constraint,
106 static List *insert_ordered_unique_oid(List *list, Oid datum);
109 /* ----------------------------------------------------------------
110 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
112 * these should all be moved to someplace in the lib/catalog
113 * module, if not obliterated first.
114 * ----------------------------------------------------------------
120 * Should the system special case these attributes in the future?
121 * Advantage: consume much less space in the ATTRIBUTE relation.
122 * Disadvantage: special cases will be all over the place.
126 * The initializers below do not include the attoptions or attacl fields,
127 * but that's OK - we're never going to reference anything beyond the
128 * fixed-size portion of the structure anyway.
131 static FormData_pg_attribute a1 = {
132 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
133 SelfItemPointerAttributeNumber, 0, -1, -1,
134 false, 'p', 's', true, false, false, true, 0
137 static FormData_pg_attribute a2 = {
138 0, {"oid"}, OIDOID, 0, sizeof(Oid),
139 ObjectIdAttributeNumber, 0, -1, -1,
140 true, 'p', 'i', true, false, false, true, 0
143 static FormData_pg_attribute a3 = {
144 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
145 MinTransactionIdAttributeNumber, 0, -1, -1,
146 true, 'p', 'i', true, false, false, true, 0
149 static FormData_pg_attribute a4 = {
150 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
151 MinCommandIdAttributeNumber, 0, -1, -1,
152 true, 'p', 'i', true, false, false, true, 0
155 static FormData_pg_attribute a5 = {
156 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
157 MaxTransactionIdAttributeNumber, 0, -1, -1,
158 true, 'p', 'i', true, false, false, true, 0
161 static FormData_pg_attribute a6 = {
162 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
163 MaxCommandIdAttributeNumber, 0, -1, -1,
164 true, 'p', 'i', true, false, false, true, 0
168 * We decided to call this attribute "tableoid" rather than say
169 * "classoid" on the basis that in the future there may be more than one
170 * table of a particular class/type. In any case table is still the word
173 static FormData_pg_attribute a7 = {
174 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
175 TableOidAttributeNumber, 0, -1, -1,
176 true, 'p', 'i', true, false, false, true, 0
179 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
182 * This function returns a Form_pg_attribute pointer for a system attribute.
183 * Note that we elog if the presented attno is invalid, which would only
184 * happen if there's a problem upstream.
187 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
189 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
190 elog(ERROR, "invalid system attribute number %d", attno);
191 if (attno == ObjectIdAttributeNumber && !relhasoids)
192 elog(ERROR, "invalid system attribute number %d", attno);
193 return SysAtt[-attno - 1];
197 * If the given name is a system attribute name, return a Form_pg_attribute
198 * pointer for a prototype definition. If not, return NULL.
201 SystemAttributeByName(const char *attname, bool relhasoids)
205 for (j = 0; j < (int) lengthof(SysAtt); j++)
207 Form_pg_attribute att = SysAtt[j];
209 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
211 if (strcmp(NameStr(att->attname), attname) == 0)
220 /* ----------------------------------------------------------------
221 * XXX END OF UGLY HARD CODED BADNESS XXX
222 * ---------------------------------------------------------------- */
225 /* ----------------------------------------------------------------
226 * heap_create - Create an uncataloged heap relation
228 * Note API change: the caller must now always provide the OID
229 * to use for the relation.
231 * rel->rd_rel is initialized by RelationBuildLocalRelation,
232 * and is mostly zeroes at return.
233 * ----------------------------------------------------------------
236 heap_create(const char *relname,
243 bool shared_relation,
244 bool mapped_relation,
245 bool allow_system_table_mods)
250 /* The caller must have provided an OID for the relation. */
251 Assert(OidIsValid(relid));
256 if (!allow_system_table_mods &&
257 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
258 IsNormalProcessingMode())
260 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
261 errmsg("permission denied to create \"%s.%s\"",
262 get_namespace_name(relnamespace), relname),
263 errdetail("System catalog modifications are currently disallowed.")));
266 * Decide if we need storage or not, and handle a couple other special
267 * cases for particular relkinds.
272 case RELKIND_COMPOSITE_TYPE:
273 case RELKIND_FOREIGN_TABLE:
274 create_storage = false;
277 * Force reltablespace to zero if the relation has no physical
278 * storage. This is mainly just for cleanliness' sake.
280 reltablespace = InvalidOid;
282 case RELKIND_SEQUENCE:
283 create_storage = true;
286 * Force reltablespace to zero for sequences, since we don't
287 * support moving them around into different tablespaces.
289 reltablespace = InvalidOid;
292 create_storage = true;
297 * Never allow a pg_class entry to explicitly specify the database's
298 * default tablespace in reltablespace; force it to zero instead. This
299 * ensures that if the database is cloned with a different default
300 * tablespace, the pg_class entry will still match where CREATE DATABASE
301 * will put the physically copied relation.
303 * Yes, this is a bit of a hack.
305 if (reltablespace == MyDatabaseTableSpace)
306 reltablespace = InvalidOid;
309 * build the relcache entry.
311 rel = RelationBuildLocalRelation(relname,
321 * Have the storage manager create the relation's disk file, if needed.
323 * We only create the main fork here, other forks will be created on
328 RelationOpenSmgr(rel);
329 RelationCreateStorage(rel->rd_node, relpersistence);
335 /* ----------------------------------------------------------------
336 * heap_create_with_catalog - Create a cataloged relation
338 * this is done in multiple steps:
340 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
341 * descriptor contains a valid set of attribute names and types
343 * 2) pg_class is opened and get_relname_relid()
344 * performs a scan to ensure that no relation with the
345 * same name already exists.
347 * 3) heap_create() is called to create the new relation on disk.
349 * 4) TypeCreate() is called to define a new type corresponding
350 * to the new relation.
352 * 5) AddNewRelationTuple() is called to register the
353 * relation in pg_class.
355 * 6) AddNewAttributeTuples() is called to register the
356 * new relation's schema in pg_attribute.
358 * 7) StoreConstraints is called () - vadim 08/22/97
360 * 8) the relations are closed and the new relation's oid
363 * ----------------------------------------------------------------
366 /* --------------------------------
367 * CheckAttributeNamesTypes
369 * this is used to make certain the tuple descriptor contains a
370 * valid set of attribute names and datatypes. a problem simply
371 * generates ereport(ERROR) which aborts the current transaction.
372 * --------------------------------
375 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
376 bool allow_system_table_mods)
380 int natts = tupdesc->natts;
382 /* Sanity check on column count */
383 if (natts < 0 || natts > MaxHeapAttributeNumber)
385 (errcode(ERRCODE_TOO_MANY_COLUMNS),
386 errmsg("tables can have at most %d columns",
387 MaxHeapAttributeNumber)));
390 * first check for collision with system attribute names
392 * Skip this for a view or type relation, since those don't have system
395 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
397 for (i = 0; i < natts; i++)
399 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
400 tupdesc->tdhasoid) != NULL)
402 (errcode(ERRCODE_DUPLICATE_COLUMN),
403 errmsg("column name \"%s\" conflicts with a system column name",
404 NameStr(tupdesc->attrs[i]->attname))));
409 * next check for repeated attribute names
411 for (i = 1; i < natts; i++)
413 for (j = 0; j < i; j++)
415 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
416 NameStr(tupdesc->attrs[i]->attname)) == 0)
418 (errcode(ERRCODE_DUPLICATE_COLUMN),
419 errmsg("column name \"%s\" specified more than once",
420 NameStr(tupdesc->attrs[j]->attname))));
425 * next check the attribute types
427 for (i = 0; i < natts; i++)
429 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
430 tupdesc->attrs[i]->atttypid,
431 allow_system_table_mods);
435 /* --------------------------------
438 * Verify that the proposed datatype of an attribute is legal.
439 * This is needed because there are types (and pseudo-types)
440 * in the catalogs that we do not support as elements of real tuples.
441 * --------------------------------
444 CheckAttributeType(const char *attname, Oid atttypid,
445 bool allow_system_table_mods)
447 char att_typtype = get_typtype(atttypid);
449 if (atttypid == UNKNOWNOID)
452 * Warn user, but don't fail, if column to be created has UNKNOWN type
453 * (usually as a result of a 'retrieve into' - jolly)
456 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
457 errmsg("column \"%s\" has type \"unknown\"", attname),
458 errdetail("Proceeding with relation creation anyway.")));
460 else if (att_typtype == TYPTYPE_PSEUDO)
463 * Refuse any attempt to create a pseudo-type column, except for a
464 * special hack for pg_statistic: allow ANYARRAY when modifying system
465 * catalogs (this allows creating pg_statistic and cloning it during
468 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
470 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
471 errmsg("column \"%s\" has pseudo-type %s",
472 attname, format_type_be(atttypid))));
474 else if (att_typtype == TYPTYPE_COMPOSITE)
477 * For a composite type, recurse into its attributes. You might think
478 * this isn't necessary, but since we allow system catalogs to break
479 * the rule, we have to guard against the case.
485 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
487 tupdesc = RelationGetDescr(relation);
489 for (i = 0; i < tupdesc->natts; i++)
491 Form_pg_attribute attr = tupdesc->attrs[i];
493 if (attr->attisdropped)
495 CheckAttributeType(NameStr(attr->attname), attr->atttypid,
496 allow_system_table_mods);
499 relation_close(relation, AccessShareLock);
504 * InsertPgAttributeTuple
505 * Construct and insert a new tuple in pg_attribute.
507 * Caller has already opened and locked pg_attribute. new_attribute is the
508 * attribute to insert (but we ignore attacl and attoptions, which are always
509 * initialized to NULL).
511 * indstate is the index state for CatalogIndexInsert. It can be passed as
512 * NULL, in which case we'll fetch the necessary info. (Don't do this when
513 * inserting multiple attributes, because it's a tad more expensive.)
516 InsertPgAttributeTuple(Relation pg_attribute_rel,
517 Form_pg_attribute new_attribute,
518 CatalogIndexState indstate)
520 Datum values[Natts_pg_attribute];
521 bool nulls[Natts_pg_attribute];
524 /* This is a tad tedious, but way cleaner than what we used to do... */
525 memset(values, 0, sizeof(values));
526 memset(nulls, false, sizeof(nulls));
528 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
529 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
530 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
531 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
532 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
533 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
534 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
535 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
536 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
537 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
538 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
539 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
540 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
541 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
542 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
543 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
544 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
546 /* start out with empty permissions and empty options */
547 nulls[Anum_pg_attribute_attacl - 1] = true;
548 nulls[Anum_pg_attribute_attoptions - 1] = true;
550 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
552 /* finally insert the new tuple, update the indexes, and clean up */
553 simple_heap_insert(pg_attribute_rel, tup);
555 if (indstate != NULL)
556 CatalogIndexInsert(indstate, tup);
558 CatalogUpdateIndexes(pg_attribute_rel, tup);
563 /* --------------------------------
564 * AddNewAttributeTuples
566 * this registers the new relation's schema by adding
567 * tuples to pg_attribute.
568 * --------------------------------
571 AddNewAttributeTuples(Oid new_rel_oid,
577 Form_pg_attribute attr;
580 CatalogIndexState indstate;
581 int natts = tupdesc->natts;
582 ObjectAddress myself,
586 * open pg_attribute and its indexes.
588 rel = heap_open(AttributeRelationId, RowExclusiveLock);
590 indstate = CatalogOpenIndexes(rel);
593 * First we add the user attributes. This is also a convenient place to
594 * add dependencies on their datatypes.
596 for (i = 0; i < natts; i++)
598 attr = tupdesc->attrs[i];
599 /* Fill in the correct relation OID */
600 attr->attrelid = new_rel_oid;
601 /* Make sure these are OK, too */
602 attr->attstattarget = -1;
603 attr->attcacheoff = -1;
605 InsertPgAttributeTuple(rel, attr, indstate);
607 /* Add dependency info */
608 myself.classId = RelationRelationId;
609 myself.objectId = new_rel_oid;
610 myself.objectSubId = i + 1;
611 referenced.classId = TypeRelationId;
612 referenced.objectId = attr->atttypid;
613 referenced.objectSubId = 0;
614 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
618 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
619 * all for a view or type relation. We don't bother with making datatype
620 * dependencies here, since presumably all these types are pinned.
622 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
624 for (i = 0; i < (int) lengthof(SysAtt); i++)
626 FormData_pg_attribute attStruct;
628 /* skip OID where appropriate */
629 if (!tupdesc->tdhasoid &&
630 SysAtt[i]->attnum == ObjectIdAttributeNumber)
633 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
635 /* Fill in the correct relation OID in the copied tuple */
636 attStruct.attrelid = new_rel_oid;
638 /* Fill in correct inheritance info for the OID column */
639 if (attStruct.attnum == ObjectIdAttributeNumber)
641 attStruct.attislocal = oidislocal;
642 attStruct.attinhcount = oidinhcount;
645 InsertPgAttributeTuple(rel, &attStruct, indstate);
652 CatalogCloseIndexes(indstate);
654 heap_close(rel, RowExclusiveLock);
657 /* --------------------------------
660 * Construct and insert a new tuple in pg_class.
662 * Caller has already opened and locked pg_class.
663 * Tuple data is taken from new_rel_desc->rd_rel, except for the
664 * variable-width fields which are not present in a cached reldesc.
665 * relacl and reloptions are passed in Datum form (to avoid having
666 * to reference the data types in heap.h). Pass (Datum) 0 to set them
668 * --------------------------------
671 InsertPgClassTuple(Relation pg_class_desc,
672 Relation new_rel_desc,
677 Form_pg_class rd_rel = new_rel_desc->rd_rel;
678 Datum values[Natts_pg_class];
679 bool nulls[Natts_pg_class];
682 /* This is a tad tedious, but way cleaner than what we used to do... */
683 memset(values, 0, sizeof(values));
684 memset(nulls, false, sizeof(nulls));
686 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
687 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
688 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
689 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
690 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
691 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
692 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
693 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
694 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
695 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
696 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
697 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
698 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
699 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
700 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
701 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
702 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
703 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
704 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
705 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
706 values[Anum_pg_class_relhasexclusion - 1] = BoolGetDatum(rd_rel->relhasexclusion);
707 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
708 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
709 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
710 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
711 if (relacl != (Datum) 0)
712 values[Anum_pg_class_relacl - 1] = relacl;
714 nulls[Anum_pg_class_relacl - 1] = true;
715 if (reloptions != (Datum) 0)
716 values[Anum_pg_class_reloptions - 1] = reloptions;
718 nulls[Anum_pg_class_reloptions - 1] = true;
720 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
723 * The new tuple must have the oid already chosen for the rel. Sure would
724 * be embarrassing to do this sort of thing in polite company.
726 HeapTupleSetOid(tup, new_rel_oid);
728 /* finally insert the new tuple, update the indexes, and clean up */
729 simple_heap_insert(pg_class_desc, tup);
731 CatalogUpdateIndexes(pg_class_desc, tup);
736 /* --------------------------------
737 * AddNewRelationTuple
739 * this registers the new relation in the catalogs by
740 * adding a tuple to pg_class.
741 * --------------------------------
744 AddNewRelationTuple(Relation pg_class_desc,
745 Relation new_rel_desc,
754 Form_pg_class new_rel_reltup;
757 * first we update some of the information in our uncataloged relation's
758 * relation descriptor.
760 new_rel_reltup = new_rel_desc->rd_rel;
764 case RELKIND_RELATION:
766 case RELKIND_TOASTVALUE:
767 /* The relation is real, but as yet empty */
768 new_rel_reltup->relpages = 0;
769 new_rel_reltup->reltuples = 0;
771 case RELKIND_SEQUENCE:
772 /* Sequences always have a known size */
773 new_rel_reltup->relpages = 1;
774 new_rel_reltup->reltuples = 1;
777 /* Views, etc, have no disk storage */
778 new_rel_reltup->relpages = 0;
779 new_rel_reltup->reltuples = 0;
783 /* Initialize relfrozenxid */
784 if (relkind == RELKIND_RELATION ||
785 relkind == RELKIND_TOASTVALUE)
788 * Initialize to the minimum XID that could put tuples in the table.
789 * We know that no xacts older than RecentXmin are still running, so
792 new_rel_reltup->relfrozenxid = RecentXmin;
797 * Other relation types will not contain XIDs, so set relfrozenxid to
798 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
799 * we force its xmin to be FrozenTransactionId always; see
800 * commands/sequence.c.)
802 new_rel_reltup->relfrozenxid = InvalidTransactionId;
805 new_rel_reltup->relowner = relowner;
806 new_rel_reltup->reltype = new_type_oid;
807 new_rel_reltup->reloftype = reloftype;
808 new_rel_reltup->relkind = relkind;
810 new_rel_desc->rd_att->tdtypeid = new_type_oid;
812 /* Now build and insert the tuple */
813 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
818 /* --------------------------------
819 * AddNewRelationType -
821 * define a composite type corresponding to the new relation
822 * --------------------------------
825 AddNewRelationType(const char *typeName,
834 TypeCreate(new_row_type, /* optional predetermined OID */
835 typeName, /* type name */
836 typeNamespace, /* type namespace */
837 new_rel_oid, /* relation oid */
838 new_rel_kind, /* relation kind */
839 ownerid, /* owner's ID */
840 -1, /* internal size (varlena) */
841 TYPTYPE_COMPOSITE, /* type-type (composite) */
842 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
843 false, /* composite types are never preferred */
844 DEFAULT_TYPDELIM, /* default array delimiter */
845 F_RECORD_IN, /* input procedure */
846 F_RECORD_OUT, /* output procedure */
847 F_RECORD_RECV, /* receive procedure */
848 F_RECORD_SEND, /* send procedure */
849 InvalidOid, /* typmodin procedure - none */
850 InvalidOid, /* typmodout procedure - none */
851 InvalidOid, /* analyze procedure - default */
852 InvalidOid, /* array element type - irrelevant */
853 false, /* this is not an array type */
854 new_array_type, /* array type if any */
855 InvalidOid, /* domain base type - irrelevant */
856 NULL, /* default value - none */
857 NULL, /* default binary representation */
858 false, /* passed by reference */
859 'd', /* alignment - must be the largest! */
860 'x', /* fully TOASTable */
862 0, /* array dimensions for typBaseType */
863 false); /* Type NOT NULL */
866 /* --------------------------------
867 * heap_create_with_catalog
869 * creates a new cataloged relation. see comments above.
872 * relname: name to give to new rel
873 * relnamespace: OID of namespace it goes in
874 * reltablespace: OID of tablespace it goes in
875 * relid: OID to assign to new rel, or InvalidOid to select a new OID
876 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
877 * ownerid: OID of new rel's owner
878 * tupdesc: tuple descriptor (source of column definitions)
879 * cooked_constraints: list of precooked check constraints and defaults
880 * relkind: relkind for new rel
881 * shared_relation: TRUE if it's to be a shared relation
882 * mapped_relation: TRUE if the relation will use the relfilenode map
883 * oidislocal: TRUE if oid column (if any) should be marked attislocal
884 * oidinhcount: attinhcount to assign to oid column (if any)
885 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
886 * reloptions: reloptions in Datum form, or (Datum) 0 if none
887 * use_user_acl: TRUE if should look for user-defined default permissions;
888 * if FALSE, relacl is always set NULL
889 * allow_system_table_mods: TRUE to allow creation in system namespaces
891 * Returns the OID of the new relation
892 * --------------------------------
895 heap_create_with_catalog(const char *relname,
903 List *cooked_constraints,
906 bool shared_relation,
907 bool mapped_relation,
910 OnCommitAction oncommit,
913 bool allow_system_table_mods,
916 Relation pg_class_desc;
917 Relation new_rel_desc;
922 Oid new_array_oid = InvalidOid;
924 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
929 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
931 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
934 * If the relation already exists, it's an error, unless the user specifies
935 * "IF NOT EXISTS". In that case, we just print a notice and do nothing
938 existing_relid = get_relname_relid(relname, relnamespace);
939 if (existing_relid != InvalidOid)
944 (errcode(ERRCODE_DUPLICATE_TABLE),
945 errmsg("relation \"%s\" already exists, skipping",
947 heap_close(pg_class_desc, RowExclusiveLock);
951 (errcode(ERRCODE_DUPLICATE_TABLE),
952 errmsg("relation \"%s\" already exists", relname)));
956 * Since we are going to create a rowtype as well, also check for
957 * collision with an existing type name. If there is one and it's an
958 * autogenerated array, we can rename it out of the way; otherwise we can
959 * at least give a good error message.
961 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
962 CStringGetDatum(relname),
963 ObjectIdGetDatum(relnamespace));
964 if (OidIsValid(old_type_oid))
966 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
968 (errcode(ERRCODE_DUPLICATE_OBJECT),
969 errmsg("type \"%s\" already exists", relname),
970 errhint("A relation has an associated type of the same name, "
971 "so you must use a name that doesn't conflict "
972 "with any existing type.")));
976 * Shared relations must be in pg_global (last-ditch check)
978 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
979 elog(ERROR, "shared relations must be placed in pg_global tablespace");
982 * Allocate an OID for the relation, unless we were told what to use.
984 * The OID will be the relfilenode as well, so make sure it doesn't
985 * collide with either pg_class OIDs or existing physical files.
987 if (!OidIsValid(relid))
989 /* Use binary-upgrade overrides if applicable */
990 if (OidIsValid(binary_upgrade_next_heap_relfilenode) &&
991 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
992 relkind == RELKIND_VIEW || relkind == RELKIND_COMPOSITE_TYPE ||
993 relkind == RELKIND_FOREIGN_TABLE))
995 relid = binary_upgrade_next_heap_relfilenode;
996 binary_upgrade_next_heap_relfilenode = InvalidOid;
998 else if (OidIsValid(binary_upgrade_next_toast_relfilenode) &&
999 relkind == RELKIND_TOASTVALUE)
1001 relid = binary_upgrade_next_toast_relfilenode;
1002 binary_upgrade_next_toast_relfilenode = InvalidOid;
1005 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1010 * Determine the relation's initial permissions.
1016 case RELKIND_RELATION:
1018 case RELKIND_FOREIGN_TABLE:
1019 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1022 case RELKIND_SEQUENCE:
1023 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1035 * Create the relcache entry (mostly dummy at this point) and the physical
1036 * disk file. (If we fail further down, it's the smgr's responsibility to
1037 * remove the disk file again.)
1039 new_rel_desc = heap_create(relname,
1048 allow_system_table_mods);
1050 Assert(relid == RelationGetRelid(new_rel_desc));
1053 * Decide whether to create an array type over the relation's rowtype. We
1054 * do not create any array types for system catalogs (ie, those made
1055 * during initdb). We create array types for regular relations, views,
1056 * composite types and foreign tables ... but not, eg, for toast tables or
1059 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1060 relkind == RELKIND_VIEW ||
1061 relkind == RELKIND_FOREIGN_TABLE ||
1062 relkind == RELKIND_COMPOSITE_TYPE))
1063 new_array_oid = AssignTypeArrayOid();
1066 * Since defining a relation also defines a complex type, we add a new
1067 * system type corresponding to the new relation. The OID of the type can
1068 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1069 * generate a new OID for it.
1071 * NOTE: we could get a unique-index failure here, in case someone else is
1072 * creating the same type name in parallel but hadn't committed yet when
1073 * we checked for a duplicate name above.
1075 new_type_oid = AddNewRelationType(relname,
1084 * Now make the array type if wanted.
1086 if (OidIsValid(new_array_oid))
1090 relarrayname = makeArrayTypeName(relname, relnamespace);
1092 TypeCreate(new_array_oid, /* force the type's OID to this */
1093 relarrayname, /* Array type name */
1094 relnamespace, /* Same namespace as parent */
1095 InvalidOid, /* Not composite, no relationOid */
1096 0, /* relkind, also N/A here */
1097 ownerid, /* owner's ID */
1098 -1, /* Internal size (varlena) */
1099 TYPTYPE_BASE, /* Not composite - typelem is */
1100 TYPCATEGORY_ARRAY, /* type-category (array) */
1101 false, /* array types are never preferred */
1102 DEFAULT_TYPDELIM, /* default array delimiter */
1103 F_ARRAY_IN, /* array input proc */
1104 F_ARRAY_OUT, /* array output proc */
1105 F_ARRAY_RECV, /* array recv (bin) proc */
1106 F_ARRAY_SEND, /* array send (bin) proc */
1107 InvalidOid, /* typmodin procedure - none */
1108 InvalidOid, /* typmodout procedure - none */
1109 InvalidOid, /* analyze procedure - default */
1110 new_type_oid, /* array element type - the rowtype */
1111 true, /* yes, this is an array type */
1112 InvalidOid, /* this has no array type */
1113 InvalidOid, /* domain base type - irrelevant */
1114 NULL, /* default value - none */
1115 NULL, /* default binary representation */
1116 false, /* passed by reference */
1117 'd', /* alignment - must be the largest! */
1118 'x', /* fully TOASTable */
1120 0, /* array dimensions for typBaseType */
1121 false); /* Type NOT NULL */
1123 pfree(relarrayname);
1127 * now create an entry in pg_class for the relation.
1129 * NOTE: we could get a unique-index failure here, in case someone else is
1130 * creating the same relation name in parallel but hadn't committed yet
1131 * when we checked for a duplicate name above.
1133 AddNewRelationTuple(pg_class_desc,
1140 PointerGetDatum(relacl),
1144 * now add tuples to pg_attribute for the attributes in our new relation.
1146 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1147 oidislocal, oidinhcount);
1150 * Make a dependency link to force the relation to be deleted if its
1151 * namespace is. Also make a dependency link to its owner, as well as
1152 * dependencies for any roles mentioned in the default ACL.
1154 * For composite types, these dependencies are tracked for the pg_type
1155 * entry, so we needn't record them here. Likewise, TOAST tables don't
1156 * need a namespace dependency (they live in a pinned namespace) nor an
1157 * owner dependency (they depend indirectly through the parent table), nor
1158 * should they have any ACL entries.
1160 * Also, skip this in bootstrap mode, since we don't make dependencies
1161 * while bootstrapping.
1163 if (relkind != RELKIND_COMPOSITE_TYPE &&
1164 relkind != RELKIND_TOASTVALUE &&
1165 !IsBootstrapProcessingMode())
1167 ObjectAddress myself,
1170 myself.classId = RelationRelationId;
1171 myself.objectId = relid;
1172 myself.objectSubId = 0;
1173 referenced.classId = NamespaceRelationId;
1174 referenced.objectId = relnamespace;
1175 referenced.objectSubId = 0;
1176 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1178 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1182 referenced.classId = TypeRelationId;
1183 referenced.objectId = reloftypeid;
1184 referenced.objectSubId = 0;
1185 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1193 nnewmembers = aclmembers(relacl, &newmembers);
1194 updateAclDependencies(RelationRelationId, relid, 0,
1197 nnewmembers, newmembers);
1201 /* Post creation hook for new relation */
1202 InvokeObjectAccessHook(OAT_POST_CREATE, RelationRelationId, relid, 0);
1205 * Store any supplied constraints and defaults.
1207 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1208 * entry, so the relation must be valid and self-consistent at this point.
1209 * In particular, there are not yet constraints and defaults anywhere.
1211 StoreConstraints(new_rel_desc, cooked_constraints);
1214 * If there's a special on-commit action, remember it
1216 if (oncommit != ONCOMMIT_NOOP)
1217 register_on_commit_action(relid, oncommit);
1220 * If this is an unlogged relation, it needs an init fork so that it
1221 * can be correctly reinitialized on restart. Since we're going to
1222 * do an immediate sync, we ony need to xlog this if archiving or
1223 * streaming is enabled. And the immediate sync is required, because
1224 * otherwise there's no guarantee that this will hit the disk before
1225 * the next checkpoint moves the redo pointer.
1227 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1229 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_TOASTVALUE);
1231 smgrcreate(new_rel_desc->rd_smgr, INIT_FORKNUM, false);
1233 log_smgrcreate(&new_rel_desc->rd_smgr->smgr_rnode.node,
1235 smgrimmedsync(new_rel_desc->rd_smgr, INIT_FORKNUM);
1239 * ok, the relation has been cataloged, so close our relations and return
1240 * the OID of the newly created relation.
1242 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1243 heap_close(pg_class_desc, RowExclusiveLock);
1250 * RelationRemoveInheritance
1252 * Formerly, this routine checked for child relations and aborted the
1253 * deletion if any were found. Now we rely on the dependency mechanism
1254 * to check for or delete child relations. By the time we get here,
1255 * there are no children and we need only remove any pg_inherits rows
1256 * linking this relation to its parent(s).
1259 RelationRemoveInheritance(Oid relid)
1261 Relation catalogRelation;
1266 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1269 Anum_pg_inherits_inhrelid,
1270 BTEqualStrategyNumber, F_OIDEQ,
1271 ObjectIdGetDatum(relid));
1273 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1274 SnapshotNow, 1, &key);
1276 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1277 simple_heap_delete(catalogRelation, &tuple->t_self);
1279 systable_endscan(scan);
1280 heap_close(catalogRelation, RowExclusiveLock);
1284 * DeleteRelationTuple
1286 * Remove pg_class row for the given relid.
1288 * Note: this is shared by relation deletion and index deletion. It's
1289 * not intended for use anyplace else.
1292 DeleteRelationTuple(Oid relid)
1294 Relation pg_class_desc;
1297 /* Grab an appropriate lock on the pg_class relation */
1298 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1300 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1301 if (!HeapTupleIsValid(tup))
1302 elog(ERROR, "cache lookup failed for relation %u", relid);
1304 /* delete the relation tuple from pg_class, and finish up */
1305 simple_heap_delete(pg_class_desc, &tup->t_self);
1307 ReleaseSysCache(tup);
1309 heap_close(pg_class_desc, RowExclusiveLock);
1313 * DeleteAttributeTuples
1315 * Remove pg_attribute rows for the given relid.
1317 * Note: this is shared by relation deletion and index deletion. It's
1318 * not intended for use anyplace else.
1321 DeleteAttributeTuples(Oid relid)
1328 /* Grab an appropriate lock on the pg_attribute relation */
1329 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1331 /* Use the index to scan only attributes of the target relation */
1332 ScanKeyInit(&key[0],
1333 Anum_pg_attribute_attrelid,
1334 BTEqualStrategyNumber, F_OIDEQ,
1335 ObjectIdGetDatum(relid));
1337 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1338 SnapshotNow, 1, key);
1340 /* Delete all the matching tuples */
1341 while ((atttup = systable_getnext(scan)) != NULL)
1342 simple_heap_delete(attrel, &atttup->t_self);
1344 /* Clean up after the scan */
1345 systable_endscan(scan);
1346 heap_close(attrel, RowExclusiveLock);
1350 * RemoveAttributeById
1352 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1353 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1354 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1355 * is handled by dependency.c.)
1358 RemoveAttributeById(Oid relid, AttrNumber attnum)
1363 Form_pg_attribute attStruct;
1364 char newattname[NAMEDATALEN];
1367 * Grab an exclusive lock on the target table, which we will NOT release
1368 * until end of transaction. (In the simple case where we are directly
1369 * dropping this column, AlterTableDropColumn already did this ... but
1370 * when cascading from a drop of some other object, we may not have any
1373 rel = relation_open(relid, AccessExclusiveLock);
1375 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1377 tuple = SearchSysCacheCopy2(ATTNUM,
1378 ObjectIdGetDatum(relid),
1379 Int16GetDatum(attnum));
1380 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1381 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1383 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1387 /* System attribute (probably OID) ... just delete the row */
1389 simple_heap_delete(attr_rel, &tuple->t_self);
1393 /* Dropping user attributes is lots harder */
1395 /* Mark the attribute as dropped */
1396 attStruct->attisdropped = true;
1399 * Set the type OID to invalid. A dropped attribute's type link
1400 * cannot be relied on (once the attribute is dropped, the type might
1401 * be too). Fortunately we do not need the type row --- the only
1402 * really essential information is the type's typlen and typalign,
1403 * which are preserved in the attribute's attlen and attalign. We set
1404 * atttypid to zero here as a means of catching code that incorrectly
1405 * expects it to be valid.
1407 attStruct->atttypid = InvalidOid;
1409 /* Remove any NOT NULL constraint the column may have */
1410 attStruct->attnotnull = false;
1412 /* We don't want to keep stats for it anymore */
1413 attStruct->attstattarget = 0;
1416 * Change the column name to something that isn't likely to conflict
1418 snprintf(newattname, sizeof(newattname),
1419 "........pg.dropped.%d........", attnum);
1420 namestrcpy(&(attStruct->attname), newattname);
1422 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1424 /* keep the system catalog indexes current */
1425 CatalogUpdateIndexes(attr_rel, tuple);
1429 * Because updating the pg_attribute row will trigger a relcache flush for
1430 * the target relation, we need not do anything else to notify other
1431 * backends of the change.
1434 heap_close(attr_rel, RowExclusiveLock);
1437 RemoveStatistics(relid, attnum);
1439 relation_close(rel, NoLock);
1445 * If the specified relation/attribute has a default, remove it.
1446 * (If no default, raise error if complain is true, else return quietly.)
1449 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1450 DropBehavior behavior, bool complain)
1452 Relation attrdef_rel;
1453 ScanKeyData scankeys[2];
1458 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1460 ScanKeyInit(&scankeys[0],
1461 Anum_pg_attrdef_adrelid,
1462 BTEqualStrategyNumber, F_OIDEQ,
1463 ObjectIdGetDatum(relid));
1464 ScanKeyInit(&scankeys[1],
1465 Anum_pg_attrdef_adnum,
1466 BTEqualStrategyNumber, F_INT2EQ,
1467 Int16GetDatum(attnum));
1469 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1470 SnapshotNow, 2, scankeys);
1472 /* There should be at most one matching tuple, but we loop anyway */
1473 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1475 ObjectAddress object;
1477 object.classId = AttrDefaultRelationId;
1478 object.objectId = HeapTupleGetOid(tuple);
1479 object.objectSubId = 0;
1481 performDeletion(&object, behavior);
1486 systable_endscan(scan);
1487 heap_close(attrdef_rel, RowExclusiveLock);
1489 if (complain && !found)
1490 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1495 * RemoveAttrDefaultById
1497 * Remove a pg_attrdef entry specified by OID. This is the guts of
1498 * attribute-default removal. Note it should be called via performDeletion,
1502 RemoveAttrDefaultById(Oid attrdefId)
1504 Relation attrdef_rel;
1507 ScanKeyData scankeys[1];
1511 AttrNumber myattnum;
1513 /* Grab an appropriate lock on the pg_attrdef relation */
1514 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1516 /* Find the pg_attrdef tuple */
1517 ScanKeyInit(&scankeys[0],
1518 ObjectIdAttributeNumber,
1519 BTEqualStrategyNumber, F_OIDEQ,
1520 ObjectIdGetDatum(attrdefId));
1522 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1523 SnapshotNow, 1, scankeys);
1525 tuple = systable_getnext(scan);
1526 if (!HeapTupleIsValid(tuple))
1527 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1529 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1530 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1532 /* Get an exclusive lock on the relation owning the attribute */
1533 myrel = relation_open(myrelid, AccessExclusiveLock);
1535 /* Now we can delete the pg_attrdef row */
1536 simple_heap_delete(attrdef_rel, &tuple->t_self);
1538 systable_endscan(scan);
1539 heap_close(attrdef_rel, RowExclusiveLock);
1541 /* Fix the pg_attribute row */
1542 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1544 tuple = SearchSysCacheCopy2(ATTNUM,
1545 ObjectIdGetDatum(myrelid),
1546 Int16GetDatum(myattnum));
1547 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1548 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1551 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1553 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1555 /* keep the system catalog indexes current */
1556 CatalogUpdateIndexes(attr_rel, tuple);
1559 * Our update of the pg_attribute row will force a relcache rebuild, so
1560 * there's nothing else to do here.
1562 heap_close(attr_rel, RowExclusiveLock);
1564 /* Keep lock on attribute's rel until end of xact */
1565 relation_close(myrel, NoLock);
1569 * heap_drop_with_catalog - removes specified relation from catalogs
1571 * Note that this routine is not responsible for dropping objects that are
1572 * linked to the pg_class entry via dependencies (for example, indexes and
1573 * constraints). Those are deleted by the dependency-tracing logic in
1574 * dependency.c before control gets here. In general, therefore, this routine
1575 * should never be called directly; go through performDeletion() instead.
1578 heap_drop_with_catalog(Oid relid)
1583 * Open and lock the relation.
1585 rel = relation_open(relid, AccessExclusiveLock);
1588 * There can no longer be anyone *else* touching the relation, but we
1589 * might still have open queries or cursors in our own session.
1591 if (rel->rd_refcnt != 1)
1593 (errcode(ERRCODE_OBJECT_IN_USE),
1594 errmsg("cannot drop \"%s\" because "
1595 "it is being used by active queries in this session",
1596 RelationGetRelationName(rel))));
1599 * Delete pg_foreign_table tuple first.
1601 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1606 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1608 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1609 if (!HeapTupleIsValid(tuple))
1610 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1612 simple_heap_delete(rel, &tuple->t_self);
1614 ReleaseSysCache(tuple);
1615 heap_close(rel, RowExclusiveLock);
1619 * Schedule unlinking of the relation's physical files at commit.
1621 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1622 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1623 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1625 RelationDropStorage(rel);
1629 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1630 * until transaction commit. This ensures no one else will try to do
1631 * something with the doomed relation.
1633 relation_close(rel, NoLock);
1636 * Forget any ON COMMIT action for the rel
1638 remove_on_commit_action(relid);
1641 * Flush the relation from the relcache. We want to do this before
1642 * starting to remove catalog entries, just to be certain that no relcache
1643 * entry rebuild will happen partway through. (That should not really
1644 * matter, since we don't do CommandCounterIncrement here, but let's be
1647 RelationForgetRelation(relid);
1650 * remove inheritance information
1652 RelationRemoveInheritance(relid);
1657 RemoveStatistics(relid, 0);
1660 * delete attribute tuples
1662 DeleteAttributeTuples(relid);
1665 * delete relation tuple
1667 DeleteRelationTuple(relid);
1672 * Store a default expression for column attnum of relation rel.
1675 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1682 static bool nulls[4] = {false, false, false, false};
1685 Form_pg_attribute attStruct;
1687 ObjectAddress colobject,
1691 * Flatten expression to string form for storage.
1693 adbin = nodeToString(expr);
1696 * Also deparse it to form the mostly-obsolete adsrc field.
1698 adsrc = deparse_expression(expr,
1699 deparse_context_for(RelationGetRelationName(rel),
1700 RelationGetRelid(rel)),
1704 * Make the pg_attrdef entry.
1706 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1707 values[Anum_pg_attrdef_adnum - 1] = attnum;
1708 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1709 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1711 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1713 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1714 attrdefOid = simple_heap_insert(adrel, tuple);
1716 CatalogUpdateIndexes(adrel, tuple);
1718 defobject.classId = AttrDefaultRelationId;
1719 defobject.objectId = attrdefOid;
1720 defobject.objectSubId = 0;
1722 heap_close(adrel, RowExclusiveLock);
1724 /* now can free some of the stuff allocated above */
1725 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1726 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1727 heap_freetuple(tuple);
1732 * Update the pg_attribute entry for the column to show that a default
1735 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1736 atttup = SearchSysCacheCopy2(ATTNUM,
1737 ObjectIdGetDatum(RelationGetRelid(rel)),
1738 Int16GetDatum(attnum));
1739 if (!HeapTupleIsValid(atttup))
1740 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1741 attnum, RelationGetRelid(rel));
1742 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1743 if (!attStruct->atthasdef)
1745 attStruct->atthasdef = true;
1746 simple_heap_update(attrrel, &atttup->t_self, atttup);
1747 /* keep catalog indexes current */
1748 CatalogUpdateIndexes(attrrel, atttup);
1750 heap_close(attrrel, RowExclusiveLock);
1751 heap_freetuple(atttup);
1754 * Make a dependency so that the pg_attrdef entry goes away if the column
1755 * (or whole table) is deleted.
1757 colobject.classId = RelationRelationId;
1758 colobject.objectId = RelationGetRelid(rel);
1759 colobject.objectSubId = attnum;
1761 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1764 * Record dependencies on objects used in the expression, too.
1766 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1770 * Store a check-constraint expression for the given relation.
1772 * Caller is responsible for updating the count of constraints
1773 * in the pg_class entry for the relation.
1776 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1777 bool is_local, int inhcount)
1786 * Flatten expression to string form for storage.
1788 ccbin = nodeToString(expr);
1791 * Also deparse it to form the mostly-obsolete consrc field.
1793 ccsrc = deparse_expression(expr,
1794 deparse_context_for(RelationGetRelationName(rel),
1795 RelationGetRelid(rel)),
1799 * Find columns of rel that are used in expr
1801 * NB: pull_var_clause is okay here only because we don't allow subselects
1802 * in check constraints; it would fail to examine the contents of
1805 varList = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
1806 keycount = list_length(varList);
1813 attNos = (int16 *) palloc(keycount * sizeof(int16));
1814 foreach(vl, varList)
1816 Var *var = (Var *) lfirst(vl);
1819 for (j = 0; j < i; j++)
1820 if (attNos[j] == var->varattno)
1823 attNos[i++] = var->varattno;
1831 * Create the Check Constraint
1833 CreateConstraintEntry(ccname, /* Constraint Name */
1834 RelationGetNamespace(rel), /* namespace */
1835 CONSTRAINT_CHECK, /* Constraint Type */
1836 false, /* Is Deferrable */
1837 false, /* Is Deferred */
1838 RelationGetRelid(rel), /* relation */
1839 attNos, /* attrs in the constraint */
1840 keycount, /* # attrs in the constraint */
1841 InvalidOid, /* not a domain constraint */
1842 InvalidOid, /* no associated index */
1843 InvalidOid, /* Foreign key fields */
1852 NULL, /* not an exclusion constraint */
1853 expr, /* Tree form of check constraint */
1854 ccbin, /* Binary form of check constraint */
1855 ccsrc, /* Source form of check constraint */
1856 is_local, /* conislocal */
1857 inhcount); /* coninhcount */
1864 * Store defaults and constraints (passed as a list of CookedConstraint).
1866 * NOTE: only pre-cooked expressions will be passed this way, which is to
1867 * say expressions inherited from an existing relation. Newly parsed
1868 * expressions can be added later, by direct calls to StoreAttrDefault
1869 * and StoreRelCheck (see AddRelationNewConstraints()).
1872 StoreConstraints(Relation rel, List *cooked_constraints)
1877 if (!cooked_constraints)
1878 return; /* nothing to do */
1881 * Deparsing of constraint expressions will fail unless the just-created
1882 * pg_attribute tuples for this relation are made visible. So, bump the
1883 * command counter. CAUTION: this will cause a relcache entry rebuild.
1885 CommandCounterIncrement();
1887 foreach(lc, cooked_constraints)
1889 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1891 switch (con->contype)
1893 case CONSTR_DEFAULT:
1894 StoreAttrDefault(rel, con->attnum, con->expr);
1897 StoreRelCheck(rel, con->name, con->expr,
1898 con->is_local, con->inhcount);
1902 elog(ERROR, "unrecognized constraint type: %d",
1903 (int) con->contype);
1908 SetRelationNumChecks(rel, numchecks);
1912 * AddRelationNewConstraints
1914 * Add new column default expressions and/or constraint check expressions
1915 * to an existing relation. This is defined to do both for efficiency in
1916 * DefineRelation, but of course you can do just one or the other by passing
1919 * rel: relation to be modified
1920 * newColDefaults: list of RawColumnDefault structures
1921 * newConstraints: list of Constraint nodes
1922 * allow_merge: TRUE if check constraints may be merged with existing ones
1923 * is_local: TRUE if definition is local, FALSE if it's inherited
1925 * All entries in newColDefaults will be processed. Entries in newConstraints
1926 * will be processed only if they are CONSTR_CHECK type.
1928 * Returns a list of CookedConstraint nodes that shows the cooked form of
1929 * the default and constraint expressions added to the relation.
1931 * NB: caller should have opened rel with AccessExclusiveLock, and should
1932 * hold that lock till end of transaction. Also, we assume the caller has
1933 * done a CommandCounterIncrement if necessary to make the relation's catalog
1937 AddRelationNewConstraints(Relation rel,
1938 List *newColDefaults,
1939 List *newConstraints,
1943 List *cookedConstraints = NIL;
1944 TupleDesc tupleDesc;
1945 TupleConstr *oldconstr;
1953 CookedConstraint *cooked;
1956 * Get info about existing constraints.
1958 tupleDesc = RelationGetDescr(rel);
1959 oldconstr = tupleDesc->constr;
1961 numoldchecks = oldconstr->num_check;
1966 * Create a dummy ParseState and insert the target relation as its sole
1967 * rangetable entry. We need a ParseState for transformExpr.
1969 pstate = make_parsestate(NULL);
1970 rte = addRangeTableEntryForRelation(pstate,
1975 addRTEtoQuery(pstate, rte, true, true, true);
1978 * Process column default expressions.
1980 foreach(cell, newColDefaults)
1982 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1983 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1985 expr = cookDefault(pstate, colDef->raw_default,
1986 atp->atttypid, atp->atttypmod,
1987 NameStr(atp->attname));
1990 * If the expression is just a NULL constant, we do not bother to make
1991 * an explicit pg_attrdef entry, since the default behavior is
1994 * Note a nonobvious property of this test: if the column is of a
1995 * domain type, what we'll get is not a bare null Const but a
1996 * CoerceToDomain expr, so we will not discard the default. This is
1997 * critical because the column default needs to be retained to
1998 * override any default that the domain might have.
2001 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2004 StoreAttrDefault(rel, colDef->attnum, expr);
2006 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2007 cooked->contype = CONSTR_DEFAULT;
2008 cooked->name = NULL;
2009 cooked->attnum = colDef->attnum;
2010 cooked->expr = expr;
2011 cooked->is_local = is_local;
2012 cooked->inhcount = is_local ? 0 : 1;
2013 cookedConstraints = lappend(cookedConstraints, cooked);
2017 * Process constraint expressions.
2019 numchecks = numoldchecks;
2021 foreach(cell, newConstraints)
2023 Constraint *cdef = (Constraint *) lfirst(cell);
2026 if (cdef->contype != CONSTR_CHECK)
2029 if (cdef->raw_expr != NULL)
2031 Assert(cdef->cooked_expr == NULL);
2034 * Transform raw parsetree to executable expression, and verify
2035 * it's valid as a CHECK constraint.
2037 expr = cookConstraint(pstate, cdef->raw_expr,
2038 RelationGetRelationName(rel));
2042 Assert(cdef->cooked_expr != NULL);
2045 * Here, we assume the parser will only pass us valid CHECK
2046 * expressions, so we do no particular checking.
2048 expr = stringToNode(cdef->cooked_expr);
2052 * Check name uniqueness, or generate a name if none was given.
2054 if (cdef->conname != NULL)
2058 ccname = cdef->conname;
2059 /* Check against other new constraints */
2060 /* Needed because we don't do CommandCounterIncrement in loop */
2061 foreach(cell2, checknames)
2063 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2065 (errcode(ERRCODE_DUPLICATE_OBJECT),
2066 errmsg("check constraint \"%s\" already exists",
2070 /* save name for future checks */
2071 checknames = lappend(checknames, ccname);
2074 * Check against pre-existing constraints. If we are allowed to
2075 * merge with an existing constraint, there's no more to do here.
2076 * (We omit the duplicate constraint from the result, which is
2077 * what ATAddCheckConstraint wants.)
2079 if (MergeWithExistingConstraint(rel, ccname, expr,
2080 allow_merge, is_local))
2086 * When generating a name, we want to create "tab_col_check" for a
2087 * column constraint and "tab_check" for a table constraint. We
2088 * no longer have any info about the syntactic positioning of the
2089 * constraint phrase, so we approximate this by seeing whether the
2090 * expression references more than one column. (If the user
2091 * played by the rules, the result is the same...)
2093 * Note: pull_var_clause() doesn't descend into sublinks, but we
2094 * eliminated those above; and anyway this only needs to be an
2095 * approximate answer.
2100 vars = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
2102 /* eliminate duplicates */
2103 vars = list_union(NIL, vars);
2105 if (list_length(vars) == 1)
2106 colname = get_attname(RelationGetRelid(rel),
2107 ((Var *) linitial(vars))->varattno);
2111 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2114 RelationGetNamespace(rel),
2117 /* save name for future checks */
2118 checknames = lappend(checknames, ccname);
2124 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
2128 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2129 cooked->contype = CONSTR_CHECK;
2130 cooked->name = ccname;
2132 cooked->expr = expr;
2133 cooked->is_local = is_local;
2134 cooked->inhcount = is_local ? 0 : 1;
2135 cookedConstraints = lappend(cookedConstraints, cooked);
2139 * Update the count of constraints in the relation's pg_class tuple. We do
2140 * this even if there was no change, in order to ensure that an SI update
2141 * message is sent out for the pg_class tuple, which will force other
2142 * backends to rebuild their relcache entries for the rel. (This is
2143 * critical if we added defaults but not constraints.)
2145 SetRelationNumChecks(rel, numchecks);
2147 return cookedConstraints;
2151 * Check for a pre-existing check constraint that conflicts with a proposed
2152 * new one, and either adjust its conislocal/coninhcount settings or throw
2155 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2156 * got a so-far-unique name, or throws error if conflict.
2159 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2160 bool allow_merge, bool is_local)
2164 SysScanDesc conscan;
2165 ScanKeyData skey[2];
2168 /* Search for a pg_constraint entry with same name and relation */
2169 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2173 ScanKeyInit(&skey[0],
2174 Anum_pg_constraint_conname,
2175 BTEqualStrategyNumber, F_NAMEEQ,
2176 CStringGetDatum(ccname));
2178 ScanKeyInit(&skey[1],
2179 Anum_pg_constraint_connamespace,
2180 BTEqualStrategyNumber, F_OIDEQ,
2181 ObjectIdGetDatum(RelationGetNamespace(rel)));
2183 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2184 SnapshotNow, 2, skey);
2186 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2188 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2190 if (con->conrelid == RelationGetRelid(rel))
2192 /* Found it. Conflicts if not identical check constraint */
2193 if (con->contype == CONSTRAINT_CHECK)
2198 val = fastgetattr(tup,
2199 Anum_pg_constraint_conbin,
2200 conDesc->rd_att, &isnull);
2202 elog(ERROR, "null conbin for rel %s",
2203 RelationGetRelationName(rel));
2204 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2207 if (!found || !allow_merge)
2209 (errcode(ERRCODE_DUPLICATE_OBJECT),
2210 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2211 ccname, RelationGetRelationName(rel))));
2212 /* OK to update the tuple */
2214 (errmsg("merging constraint \"%s\" with inherited definition",
2216 tup = heap_copytuple(tup);
2217 con = (Form_pg_constraint) GETSTRUCT(tup);
2219 con->conislocal = true;
2222 simple_heap_update(conDesc, &tup->t_self, tup);
2223 CatalogUpdateIndexes(conDesc, tup);
2228 systable_endscan(conscan);
2229 heap_close(conDesc, RowExclusiveLock);
2235 * Update the count of constraints in the relation's pg_class tuple.
2237 * Caller had better hold exclusive lock on the relation.
2239 * An important side effect is that a SI update message will be sent out for
2240 * the pg_class tuple, which will force other backends to rebuild their
2241 * relcache entries for the rel. Also, this backend will rebuild its
2242 * own relcache entry at the next CommandCounterIncrement.
2245 SetRelationNumChecks(Relation rel, int numchecks)
2249 Form_pg_class relStruct;
2251 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2252 reltup = SearchSysCacheCopy1(RELOID,
2253 ObjectIdGetDatum(RelationGetRelid(rel)));
2254 if (!HeapTupleIsValid(reltup))
2255 elog(ERROR, "cache lookup failed for relation %u",
2256 RelationGetRelid(rel));
2257 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2259 if (relStruct->relchecks != numchecks)
2261 relStruct->relchecks = numchecks;
2263 simple_heap_update(relrel, &reltup->t_self, reltup);
2265 /* keep catalog indexes current */
2266 CatalogUpdateIndexes(relrel, reltup);
2270 /* Skip the disk update, but force relcache inval anyway */
2271 CacheInvalidateRelcache(rel);
2274 heap_freetuple(reltup);
2275 heap_close(relrel, RowExclusiveLock);
2279 * Take a raw default and convert it to a cooked format ready for
2282 * Parse state should be set up to recognize any vars that might appear
2283 * in the expression. (Even though we plan to reject vars, it's more
2284 * user-friendly to give the correct error message than "unknown var".)
2286 * If atttypid is not InvalidOid, coerce the expression to the specified
2287 * type (and typmod atttypmod). attname is only needed in this case:
2288 * it is used in the error message, if any.
2291 cookDefault(ParseState *pstate,
2299 Assert(raw_default != NULL);
2302 * Transform raw parsetree to executable expression.
2304 expr = transformExpr(pstate, raw_default);
2307 * Make sure default expr does not refer to any vars.
2309 if (contain_var_clause(expr))
2311 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2312 errmsg("cannot use column references in default expression")));
2315 * It can't return a set either.
2317 if (expression_returns_set(expr))
2319 (errcode(ERRCODE_DATATYPE_MISMATCH),
2320 errmsg("default expression must not return a set")));
2323 * No subplans or aggregates, either...
2325 if (pstate->p_hasSubLinks)
2327 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2328 errmsg("cannot use subquery in default expression")));
2329 if (pstate->p_hasAggs)
2331 (errcode(ERRCODE_GROUPING_ERROR),
2332 errmsg("cannot use aggregate function in default expression")));
2333 if (pstate->p_hasWindowFuncs)
2335 (errcode(ERRCODE_WINDOWING_ERROR),
2336 errmsg("cannot use window function in default expression")));
2339 * Coerce the expression to the correct type and typmod, if given. This
2340 * should match the parser's processing of non-defaulted expressions ---
2341 * see transformAssignedExpr().
2343 if (OidIsValid(atttypid))
2345 Oid type_id = exprType(expr);
2347 expr = coerce_to_target_type(pstate, expr, type_id,
2348 atttypid, atttypmod,
2349 COERCION_ASSIGNMENT,
2350 COERCE_IMPLICIT_CAST,
2354 (errcode(ERRCODE_DATATYPE_MISMATCH),
2355 errmsg("column \"%s\" is of type %s"
2356 " but default expression is of type %s",
2358 format_type_be(atttypid),
2359 format_type_be(type_id)),
2360 errhint("You will need to rewrite or cast the expression.")));
2367 * Take a raw CHECK constraint expression and convert it to a cooked format
2368 * ready for storage.
2370 * Parse state must be set up to recognize any vars that might appear
2371 * in the expression.
2374 cookConstraint(ParseState *pstate,
2375 Node *raw_constraint,
2381 * Transform raw parsetree to executable expression.
2383 expr = transformExpr(pstate, raw_constraint);
2386 * Make sure it yields a boolean result.
2388 expr = coerce_to_boolean(pstate, expr, "CHECK");
2391 * Make sure no outside relations are referred to.
2393 if (list_length(pstate->p_rtable) != 1)
2395 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2396 errmsg("only table \"%s\" can be referenced in check constraint",
2400 * No subplans or aggregates, either...
2402 if (pstate->p_hasSubLinks)
2404 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2405 errmsg("cannot use subquery in check constraint")));
2406 if (pstate->p_hasAggs)
2408 (errcode(ERRCODE_GROUPING_ERROR),
2409 errmsg("cannot use aggregate function in check constraint")));
2410 if (pstate->p_hasWindowFuncs)
2412 (errcode(ERRCODE_WINDOWING_ERROR),
2413 errmsg("cannot use window function in check constraint")));
2420 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2422 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2426 RemoveStatistics(Oid relid, AttrNumber attnum)
2428 Relation pgstatistic;
2434 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2436 ScanKeyInit(&key[0],
2437 Anum_pg_statistic_starelid,
2438 BTEqualStrategyNumber, F_OIDEQ,
2439 ObjectIdGetDatum(relid));
2445 ScanKeyInit(&key[1],
2446 Anum_pg_statistic_staattnum,
2447 BTEqualStrategyNumber, F_INT2EQ,
2448 Int16GetDatum(attnum));
2452 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2453 SnapshotNow, nkeys, key);
2455 /* we must loop even when attnum != 0, in case of inherited stats */
2456 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2457 simple_heap_delete(pgstatistic, &tuple->t_self);
2459 systable_endscan(scan);
2461 heap_close(pgstatistic, RowExclusiveLock);
2466 * RelationTruncateIndexes - truncate all indexes associated
2467 * with the heap relation to zero tuples.
2469 * The routine will truncate and then reconstruct the indexes on
2470 * the specified relation. Caller must hold exclusive lock on rel.
2473 RelationTruncateIndexes(Relation heapRelation)
2477 /* Ask the relcache to produce a list of the indexes of the rel */
2478 foreach(indlist, RelationGetIndexList(heapRelation))
2480 Oid indexId = lfirst_oid(indlist);
2481 Relation currentIndex;
2482 IndexInfo *indexInfo;
2484 /* Open the index relation; use exclusive lock, just to be sure */
2485 currentIndex = index_open(indexId, AccessExclusiveLock);
2487 /* Fetch info needed for index_build */
2488 indexInfo = BuildIndexInfo(currentIndex);
2491 * Now truncate the actual file (and discard buffers).
2493 RelationTruncate(currentIndex, 0);
2495 /* Initialize the index and rebuild */
2496 /* Note: we do not need to re-establish pkey setting */
2497 index_build(heapRelation, currentIndex, indexInfo, false);
2499 /* We're done with this index */
2500 index_close(currentIndex, NoLock);
2507 * This routine deletes all data within all the specified relations.
2509 * This is not transaction-safe! There is another, transaction-safe
2510 * implementation in commands/tablecmds.c. We now use this only for
2511 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2514 heap_truncate(List *relids)
2516 List *relations = NIL;
2519 /* Open relations for processing, and grab exclusive access on each */
2520 foreach(cell, relids)
2522 Oid rid = lfirst_oid(cell);
2525 rel = heap_open(rid, AccessExclusiveLock);
2526 relations = lappend(relations, rel);
2529 /* Don't allow truncate on tables that are referenced by foreign keys */
2530 heap_truncate_check_FKs(relations, true);
2533 foreach(cell, relations)
2535 Relation rel = lfirst(cell);
2537 /* Truncate the relation */
2538 heap_truncate_one_rel(rel);
2540 /* Close the relation, but keep exclusive lock on it until commit */
2541 heap_close(rel, NoLock);
2546 * heap_truncate_one_rel
2548 * This routine deletes all data within the specified relation.
2550 * This is not transaction-safe, because the truncation is done immediately
2551 * and cannot be rolled back later. Caller is responsible for having
2552 * checked permissions etc, and must have obtained AccessExclusiveLock.
2555 heap_truncate_one_rel(Relation rel)
2559 /* Truncate the actual file (and discard buffers) */
2560 RelationTruncate(rel, 0);
2562 /* If the relation has indexes, truncate the indexes too */
2563 RelationTruncateIndexes(rel);
2565 /* If there is a toast table, truncate that too */
2566 toastrelid = rel->rd_rel->reltoastrelid;
2567 if (OidIsValid(toastrelid))
2569 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2571 RelationTruncate(toastrel, 0);
2572 RelationTruncateIndexes(toastrel);
2573 /* keep the lock... */
2574 heap_close(toastrel, NoLock);
2579 * heap_truncate_check_FKs
2580 * Check for foreign keys referencing a list of relations that
2581 * are to be truncated, and raise error if there are any
2583 * We disallow such FKs (except self-referential ones) since the whole point
2584 * of TRUNCATE is to not scan the individual rows to be thrown away.
2586 * This is split out so it can be shared by both implementations of truncate.
2587 * Caller should already hold a suitable lock on the relations.
2589 * tempTables is only used to select an appropriate error message.
2592 heap_truncate_check_FKs(List *relations, bool tempTables)
2599 * Build a list of OIDs of the interesting relations.
2601 * If a relation has no triggers, then it can neither have FKs nor be
2602 * referenced by a FK from another table, so we can ignore it.
2604 foreach(cell, relations)
2606 Relation rel = lfirst(cell);
2608 if (rel->rd_rel->relhastriggers)
2609 oids = lappend_oid(oids, RelationGetRelid(rel));
2613 * Fast path: if no relation has triggers, none has FKs either.
2619 * Otherwise, must scan pg_constraint. We make one pass with all the
2620 * relations considered; if this finds nothing, then all is well.
2622 dependents = heap_truncate_find_FKs(oids);
2623 if (dependents == NIL)
2627 * Otherwise we repeat the scan once per relation to identify a particular
2628 * pair of relations to complain about. This is pretty slow, but
2629 * performance shouldn't matter much in a failure path. The reason for
2630 * doing things this way is to ensure that the message produced is not
2631 * dependent on chance row locations within pg_constraint.
2635 Oid relid = lfirst_oid(cell);
2638 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2640 foreach(cell2, dependents)
2642 Oid relid2 = lfirst_oid(cell2);
2644 if (!list_member_oid(oids, relid2))
2646 char *relname = get_rel_name(relid);
2647 char *relname2 = get_rel_name(relid2);
2651 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2652 errmsg("unsupported ON COMMIT and foreign key combination"),
2653 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2654 relname2, relname)));
2657 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2658 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2659 errdetail("Table \"%s\" references \"%s\".",
2661 errhint("Truncate table \"%s\" at the same time, "
2662 "or use TRUNCATE ... CASCADE.",
2670 * heap_truncate_find_FKs
2671 * Find relations having foreign keys referencing any of the given rels
2673 * Input and result are both lists of relation OIDs. The result contains
2674 * no duplicates, does *not* include any rels that were already in the input
2675 * list, and is sorted in OID order. (The last property is enforced mainly
2676 * to guarantee consistent behavior in the regression tests; we don't want
2677 * behavior to change depending on chance locations of rows in pg_constraint.)
2679 * Note: caller should already have appropriate lock on all rels mentioned
2680 * in relationIds. Since adding or dropping an FK requires exclusive lock
2681 * on both rels, this ensures that the answer will be stable.
2684 heap_truncate_find_FKs(List *relationIds)
2688 SysScanDesc fkeyScan;
2692 * Must scan pg_constraint. Right now, it is a seqscan because there is
2693 * no available index on confrelid.
2695 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2697 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2698 SnapshotNow, 0, NULL);
2700 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2702 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2704 /* Not a foreign key */
2705 if (con->contype != CONSTRAINT_FOREIGN)
2708 /* Not referencing one of our list of tables */
2709 if (!list_member_oid(relationIds, con->confrelid))
2712 /* Add referencer unless already in input or result list */
2713 if (!list_member_oid(relationIds, con->conrelid))
2714 result = insert_ordered_unique_oid(result, con->conrelid);
2717 systable_endscan(fkeyScan);
2718 heap_close(fkeyRel, AccessShareLock);
2724 * insert_ordered_unique_oid
2725 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2726 * and eliminating duplicates
2728 * Building the ordered list this way is O(N^2), but with a pretty small
2729 * constant, so for the number of entries we expect it will probably be
2730 * faster than trying to apply qsort(). It seems unlikely someone would be
2731 * trying to truncate a table with thousands of dependent tables ...
2734 insert_ordered_unique_oid(List *list, Oid datum)
2738 /* Does the datum belong at the front? */
2739 if (list == NIL || datum < linitial_oid(list))
2740 return lcons_oid(datum, list);
2741 /* Does it match the first entry? */
2742 if (datum == linitial_oid(list))
2743 return list; /* duplicate, so don't insert */
2744 /* No, so find the entry it belongs after */
2745 prev = list_head(list);
2748 ListCell *curr = lnext(prev);
2750 if (curr == NULL || datum < lfirst_oid(curr))
2751 break; /* it belongs after 'prev', before 'curr' */
2753 if (datum == lfirst_oid(curr))
2754 return list; /* duplicate, so don't insert */
2758 /* Insert datum into list after 'prev' */
2759 lappend_cell_oid(list, prev, datum);