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 /* Potentially set by contrib/pg_upgrade_support functions */
77 Oid binary_upgrade_next_heap_pg_class_oid = InvalidOid;
78 Oid binary_upgrade_next_toast_pg_class_oid = 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);
545 values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
547 /* start out with empty permissions and empty options */
548 nulls[Anum_pg_attribute_attacl - 1] = true;
549 nulls[Anum_pg_attribute_attoptions - 1] = true;
551 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
553 /* finally insert the new tuple, update the indexes, and clean up */
554 simple_heap_insert(pg_attribute_rel, tup);
556 if (indstate != NULL)
557 CatalogIndexInsert(indstate, tup);
559 CatalogUpdateIndexes(pg_attribute_rel, tup);
564 /* --------------------------------
565 * AddNewAttributeTuples
567 * this registers the new relation's schema by adding
568 * tuples to pg_attribute.
569 * --------------------------------
572 AddNewAttributeTuples(Oid new_rel_oid,
578 Form_pg_attribute attr;
581 CatalogIndexState indstate;
582 int natts = tupdesc->natts;
583 ObjectAddress myself,
587 * open pg_attribute and its indexes.
589 rel = heap_open(AttributeRelationId, RowExclusiveLock);
591 indstate = CatalogOpenIndexes(rel);
594 * First we add the user attributes. This is also a convenient place to
595 * add dependencies on their datatypes.
597 for (i = 0; i < natts; i++)
599 attr = tupdesc->attrs[i];
600 /* Fill in the correct relation OID */
601 attr->attrelid = new_rel_oid;
602 /* Make sure these are OK, too */
603 attr->attstattarget = -1;
604 attr->attcacheoff = -1;
606 InsertPgAttributeTuple(rel, attr, indstate);
608 /* Add dependency info */
609 myself.classId = RelationRelationId;
610 myself.objectId = new_rel_oid;
611 myself.objectSubId = i + 1;
612 referenced.classId = TypeRelationId;
613 referenced.objectId = attr->atttypid;
614 referenced.objectSubId = 0;
615 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
619 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
620 * all for a view or type relation. We don't bother with making datatype
621 * dependencies here, since presumably all these types are pinned.
623 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
625 for (i = 0; i < (int) lengthof(SysAtt); i++)
627 FormData_pg_attribute attStruct;
629 /* skip OID where appropriate */
630 if (!tupdesc->tdhasoid &&
631 SysAtt[i]->attnum == ObjectIdAttributeNumber)
634 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
636 /* Fill in the correct relation OID in the copied tuple */
637 attStruct.attrelid = new_rel_oid;
639 /* Fill in correct inheritance info for the OID column */
640 if (attStruct.attnum == ObjectIdAttributeNumber)
642 attStruct.attislocal = oidislocal;
643 attStruct.attinhcount = oidinhcount;
646 InsertPgAttributeTuple(rel, &attStruct, indstate);
653 CatalogCloseIndexes(indstate);
655 heap_close(rel, RowExclusiveLock);
658 /* --------------------------------
661 * Construct and insert a new tuple in pg_class.
663 * Caller has already opened and locked pg_class.
664 * Tuple data is taken from new_rel_desc->rd_rel, except for the
665 * variable-width fields which are not present in a cached reldesc.
666 * relacl and reloptions are passed in Datum form (to avoid having
667 * to reference the data types in heap.h). Pass (Datum) 0 to set them
669 * --------------------------------
672 InsertPgClassTuple(Relation pg_class_desc,
673 Relation new_rel_desc,
678 Form_pg_class rd_rel = new_rel_desc->rd_rel;
679 Datum values[Natts_pg_class];
680 bool nulls[Natts_pg_class];
683 /* This is a tad tedious, but way cleaner than what we used to do... */
684 memset(values, 0, sizeof(values));
685 memset(nulls, false, sizeof(nulls));
687 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
688 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
689 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
690 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
691 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
692 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
693 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
694 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
695 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
696 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
697 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
698 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
699 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
700 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
701 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
702 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
703 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
704 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
705 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
706 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
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 */
864 InvalidOid); /* typcollation */
867 /* --------------------------------
868 * heap_create_with_catalog
870 * creates a new cataloged relation. see comments above.
873 * relname: name to give to new rel
874 * relnamespace: OID of namespace it goes in
875 * reltablespace: OID of tablespace it goes in
876 * relid: OID to assign to new rel, or InvalidOid to select a new OID
877 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
878 * ownerid: OID of new rel's owner
879 * tupdesc: tuple descriptor (source of column definitions)
880 * cooked_constraints: list of precooked check constraints and defaults
881 * relkind: relkind for new rel
882 * shared_relation: TRUE if it's to be a shared relation
883 * mapped_relation: TRUE if the relation will use the relfilenode map
884 * oidislocal: TRUE if oid column (if any) should be marked attislocal
885 * oidinhcount: attinhcount to assign to oid column (if any)
886 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
887 * reloptions: reloptions in Datum form, or (Datum) 0 if none
888 * use_user_acl: TRUE if should look for user-defined default permissions;
889 * if FALSE, relacl is always set NULL
890 * allow_system_table_mods: TRUE to allow creation in system namespaces
892 * Returns the OID of the new relation
893 * --------------------------------
896 heap_create_with_catalog(const char *relname,
904 List *cooked_constraints,
907 bool shared_relation,
908 bool mapped_relation,
911 OnCommitAction oncommit,
914 bool allow_system_table_mods,
917 Relation pg_class_desc;
918 Relation new_rel_desc;
923 Oid new_array_oid = InvalidOid;
925 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
930 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
932 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
935 * If the relation already exists, it's an error, unless the user specifies
936 * "IF NOT EXISTS". In that case, we just print a notice and do nothing
939 existing_relid = get_relname_relid(relname, relnamespace);
940 if (existing_relid != InvalidOid)
945 (errcode(ERRCODE_DUPLICATE_TABLE),
946 errmsg("relation \"%s\" already exists, skipping",
948 heap_close(pg_class_desc, RowExclusiveLock);
952 (errcode(ERRCODE_DUPLICATE_TABLE),
953 errmsg("relation \"%s\" already exists", relname)));
957 * Since we are going to create a rowtype as well, also check for
958 * collision with an existing type name. If there is one and it's an
959 * autogenerated array, we can rename it out of the way; otherwise we can
960 * at least give a good error message.
962 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
963 CStringGetDatum(relname),
964 ObjectIdGetDatum(relnamespace));
965 if (OidIsValid(old_type_oid))
967 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
969 (errcode(ERRCODE_DUPLICATE_OBJECT),
970 errmsg("type \"%s\" already exists", relname),
971 errhint("A relation has an associated type of the same name, "
972 "so you must use a name that doesn't conflict "
973 "with any existing type.")));
977 * Shared relations must be in pg_global (last-ditch check)
979 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
980 elog(ERROR, "shared relations must be placed in pg_global tablespace");
983 * Allocate an OID for the relation, unless we were told what to use.
985 * The OID will be the relfilenode as well, so make sure it doesn't
986 * collide with either pg_class OIDs or existing physical files.
988 if (!OidIsValid(relid))
991 * Use binary-upgrade override for pg_class.oid/relfilenode,
994 if (OidIsValid(binary_upgrade_next_heap_pg_class_oid) &&
995 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
996 relkind == RELKIND_VIEW || relkind == RELKIND_COMPOSITE_TYPE ||
997 relkind == RELKIND_FOREIGN_TABLE))
999 relid = binary_upgrade_next_heap_pg_class_oid;
1000 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1002 else if (OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1003 relkind == RELKIND_TOASTVALUE)
1005 relid = binary_upgrade_next_toast_pg_class_oid;
1006 binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1009 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1014 * Determine the relation's initial permissions.
1020 case RELKIND_RELATION:
1022 case RELKIND_FOREIGN_TABLE:
1023 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1026 case RELKIND_SEQUENCE:
1027 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1039 * Create the relcache entry (mostly dummy at this point) and the physical
1040 * disk file. (If we fail further down, it's the smgr's responsibility to
1041 * remove the disk file again.)
1043 new_rel_desc = heap_create(relname,
1052 allow_system_table_mods);
1054 Assert(relid == RelationGetRelid(new_rel_desc));
1057 * Decide whether to create an array type over the relation's rowtype. We
1058 * do not create any array types for system catalogs (ie, those made
1059 * during initdb). We create array types for regular relations, views,
1060 * composite types and foreign tables ... but not, eg, for toast tables or
1063 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1064 relkind == RELKIND_VIEW ||
1065 relkind == RELKIND_FOREIGN_TABLE ||
1066 relkind == RELKIND_COMPOSITE_TYPE))
1067 new_array_oid = AssignTypeArrayOid();
1070 * Since defining a relation also defines a complex type, we add a new
1071 * system type corresponding to the new relation. The OID of the type can
1072 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1073 * generate a new OID for it.
1075 * NOTE: we could get a unique-index failure here, in case someone else is
1076 * creating the same type name in parallel but hadn't committed yet when
1077 * we checked for a duplicate name above.
1079 new_type_oid = AddNewRelationType(relname,
1088 * Now make the array type if wanted.
1090 if (OidIsValid(new_array_oid))
1094 relarrayname = makeArrayTypeName(relname, relnamespace);
1096 TypeCreate(new_array_oid, /* force the type's OID to this */
1097 relarrayname, /* Array type name */
1098 relnamespace, /* Same namespace as parent */
1099 InvalidOid, /* Not composite, no relationOid */
1100 0, /* relkind, also N/A here */
1101 ownerid, /* owner's ID */
1102 -1, /* Internal size (varlena) */
1103 TYPTYPE_BASE, /* Not composite - typelem is */
1104 TYPCATEGORY_ARRAY, /* type-category (array) */
1105 false, /* array types are never preferred */
1106 DEFAULT_TYPDELIM, /* default array delimiter */
1107 F_ARRAY_IN, /* array input proc */
1108 F_ARRAY_OUT, /* array output proc */
1109 F_ARRAY_RECV, /* array recv (bin) proc */
1110 F_ARRAY_SEND, /* array send (bin) proc */
1111 InvalidOid, /* typmodin procedure - none */
1112 InvalidOid, /* typmodout procedure - none */
1113 InvalidOid, /* analyze procedure - default */
1114 new_type_oid, /* array element type - the rowtype */
1115 true, /* yes, this is an array type */
1116 InvalidOid, /* this has no array type */
1117 InvalidOid, /* domain base type - irrelevant */
1118 NULL, /* default value - none */
1119 NULL, /* default binary representation */
1120 false, /* passed by reference */
1121 'd', /* alignment - must be the largest! */
1122 'x', /* fully TOASTable */
1124 0, /* array dimensions for typBaseType */
1125 false, /* Type NOT NULL */
1126 InvalidOid); /* typcollation */
1128 pfree(relarrayname);
1132 * now create an entry in pg_class for the relation.
1134 * NOTE: we could get a unique-index failure here, in case someone else is
1135 * creating the same relation name in parallel but hadn't committed yet
1136 * when we checked for a duplicate name above.
1138 AddNewRelationTuple(pg_class_desc,
1145 PointerGetDatum(relacl),
1149 * now add tuples to pg_attribute for the attributes in our new relation.
1151 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1152 oidislocal, oidinhcount);
1155 * Make a dependency link to force the relation to be deleted if its
1156 * namespace is. Also make a dependency link to its owner, as well as
1157 * dependencies for any roles mentioned in the default ACL.
1159 * For composite types, these dependencies are tracked for the pg_type
1160 * entry, so we needn't record them here. Likewise, TOAST tables don't
1161 * need a namespace dependency (they live in a pinned namespace) nor an
1162 * owner dependency (they depend indirectly through the parent table), nor
1163 * should they have any ACL entries. The same applies for extension
1166 * Also, skip this in bootstrap mode, since we don't make dependencies
1167 * while bootstrapping.
1169 if (relkind != RELKIND_COMPOSITE_TYPE &&
1170 relkind != RELKIND_TOASTVALUE &&
1171 !IsBootstrapProcessingMode())
1173 ObjectAddress myself,
1176 myself.classId = RelationRelationId;
1177 myself.objectId = relid;
1178 myself.objectSubId = 0;
1179 referenced.classId = NamespaceRelationId;
1180 referenced.objectId = relnamespace;
1181 referenced.objectSubId = 0;
1182 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1184 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1186 recordDependencyOnCurrentExtension(&myself);
1190 referenced.classId = TypeRelationId;
1191 referenced.objectId = reloftypeid;
1192 referenced.objectSubId = 0;
1193 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1201 nnewmembers = aclmembers(relacl, &newmembers);
1202 updateAclDependencies(RelationRelationId, relid, 0,
1205 nnewmembers, newmembers);
1209 /* Post creation hook for new relation */
1210 InvokeObjectAccessHook(OAT_POST_CREATE, RelationRelationId, relid, 0);
1213 * Store any supplied constraints and defaults.
1215 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1216 * entry, so the relation must be valid and self-consistent at this point.
1217 * In particular, there are not yet constraints and defaults anywhere.
1219 StoreConstraints(new_rel_desc, cooked_constraints);
1222 * If there's a special on-commit action, remember it
1224 if (oncommit != ONCOMMIT_NOOP)
1225 register_on_commit_action(relid, oncommit);
1228 * If this is an unlogged relation, it needs an init fork so that it
1229 * can be correctly reinitialized on restart. Since we're going to
1230 * do an immediate sync, we ony need to xlog this if archiving or
1231 * streaming is enabled. And the immediate sync is required, because
1232 * otherwise there's no guarantee that this will hit the disk before
1233 * the next checkpoint moves the redo pointer.
1235 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1237 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_TOASTVALUE);
1239 smgrcreate(new_rel_desc->rd_smgr, INIT_FORKNUM, false);
1241 log_smgrcreate(&new_rel_desc->rd_smgr->smgr_rnode.node,
1243 smgrimmedsync(new_rel_desc->rd_smgr, INIT_FORKNUM);
1247 * ok, the relation has been cataloged, so close our relations and return
1248 * the OID of the newly created relation.
1250 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1251 heap_close(pg_class_desc, RowExclusiveLock);
1258 * RelationRemoveInheritance
1260 * Formerly, this routine checked for child relations and aborted the
1261 * deletion if any were found. Now we rely on the dependency mechanism
1262 * to check for or delete child relations. By the time we get here,
1263 * there are no children and we need only remove any pg_inherits rows
1264 * linking this relation to its parent(s).
1267 RelationRemoveInheritance(Oid relid)
1269 Relation catalogRelation;
1274 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1277 Anum_pg_inherits_inhrelid,
1278 BTEqualStrategyNumber, F_OIDEQ,
1279 ObjectIdGetDatum(relid));
1281 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1282 SnapshotNow, 1, &key);
1284 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1285 simple_heap_delete(catalogRelation, &tuple->t_self);
1287 systable_endscan(scan);
1288 heap_close(catalogRelation, RowExclusiveLock);
1292 * DeleteRelationTuple
1294 * Remove pg_class row for the given relid.
1296 * Note: this is shared by relation deletion and index deletion. It's
1297 * not intended for use anyplace else.
1300 DeleteRelationTuple(Oid relid)
1302 Relation pg_class_desc;
1305 /* Grab an appropriate lock on the pg_class relation */
1306 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1308 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1309 if (!HeapTupleIsValid(tup))
1310 elog(ERROR, "cache lookup failed for relation %u", relid);
1312 /* delete the relation tuple from pg_class, and finish up */
1313 simple_heap_delete(pg_class_desc, &tup->t_self);
1315 ReleaseSysCache(tup);
1317 heap_close(pg_class_desc, RowExclusiveLock);
1321 * DeleteAttributeTuples
1323 * Remove pg_attribute rows for the given relid.
1325 * Note: this is shared by relation deletion and index deletion. It's
1326 * not intended for use anyplace else.
1329 DeleteAttributeTuples(Oid relid)
1336 /* Grab an appropriate lock on the pg_attribute relation */
1337 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1339 /* Use the index to scan only attributes of the target relation */
1340 ScanKeyInit(&key[0],
1341 Anum_pg_attribute_attrelid,
1342 BTEqualStrategyNumber, F_OIDEQ,
1343 ObjectIdGetDatum(relid));
1345 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1346 SnapshotNow, 1, key);
1348 /* Delete all the matching tuples */
1349 while ((atttup = systable_getnext(scan)) != NULL)
1350 simple_heap_delete(attrel, &atttup->t_self);
1352 /* Clean up after the scan */
1353 systable_endscan(scan);
1354 heap_close(attrel, RowExclusiveLock);
1358 * RemoveAttributeById
1360 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1361 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1362 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1363 * is handled by dependency.c.)
1366 RemoveAttributeById(Oid relid, AttrNumber attnum)
1371 Form_pg_attribute attStruct;
1372 char newattname[NAMEDATALEN];
1375 * Grab an exclusive lock on the target table, which we will NOT release
1376 * until end of transaction. (In the simple case where we are directly
1377 * dropping this column, AlterTableDropColumn already did this ... but
1378 * when cascading from a drop of some other object, we may not have any
1381 rel = relation_open(relid, AccessExclusiveLock);
1383 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1385 tuple = SearchSysCacheCopy2(ATTNUM,
1386 ObjectIdGetDatum(relid),
1387 Int16GetDatum(attnum));
1388 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1389 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1391 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1395 /* System attribute (probably OID) ... just delete the row */
1397 simple_heap_delete(attr_rel, &tuple->t_self);
1401 /* Dropping user attributes is lots harder */
1403 /* Mark the attribute as dropped */
1404 attStruct->attisdropped = true;
1407 * Set the type OID to invalid. A dropped attribute's type link
1408 * cannot be relied on (once the attribute is dropped, the type might
1409 * be too). Fortunately we do not need the type row --- the only
1410 * really essential information is the type's typlen and typalign,
1411 * which are preserved in the attribute's attlen and attalign. We set
1412 * atttypid to zero here as a means of catching code that incorrectly
1413 * expects it to be valid.
1415 attStruct->atttypid = InvalidOid;
1417 /* Remove any NOT NULL constraint the column may have */
1418 attStruct->attnotnull = false;
1420 /* We don't want to keep stats for it anymore */
1421 attStruct->attstattarget = 0;
1424 * Change the column name to something that isn't likely to conflict
1426 snprintf(newattname, sizeof(newattname),
1427 "........pg.dropped.%d........", attnum);
1428 namestrcpy(&(attStruct->attname), newattname);
1430 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1432 /* keep the system catalog indexes current */
1433 CatalogUpdateIndexes(attr_rel, tuple);
1437 * Because updating the pg_attribute row will trigger a relcache flush for
1438 * the target relation, we need not do anything else to notify other
1439 * backends of the change.
1442 heap_close(attr_rel, RowExclusiveLock);
1445 RemoveStatistics(relid, attnum);
1447 relation_close(rel, NoLock);
1453 * If the specified relation/attribute has a default, remove it.
1454 * (If no default, raise error if complain is true, else return quietly.)
1457 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1458 DropBehavior behavior, bool complain)
1460 Relation attrdef_rel;
1461 ScanKeyData scankeys[2];
1466 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1468 ScanKeyInit(&scankeys[0],
1469 Anum_pg_attrdef_adrelid,
1470 BTEqualStrategyNumber, F_OIDEQ,
1471 ObjectIdGetDatum(relid));
1472 ScanKeyInit(&scankeys[1],
1473 Anum_pg_attrdef_adnum,
1474 BTEqualStrategyNumber, F_INT2EQ,
1475 Int16GetDatum(attnum));
1477 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1478 SnapshotNow, 2, scankeys);
1480 /* There should be at most one matching tuple, but we loop anyway */
1481 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1483 ObjectAddress object;
1485 object.classId = AttrDefaultRelationId;
1486 object.objectId = HeapTupleGetOid(tuple);
1487 object.objectSubId = 0;
1489 performDeletion(&object, behavior);
1494 systable_endscan(scan);
1495 heap_close(attrdef_rel, RowExclusiveLock);
1497 if (complain && !found)
1498 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1503 * RemoveAttrDefaultById
1505 * Remove a pg_attrdef entry specified by OID. This is the guts of
1506 * attribute-default removal. Note it should be called via performDeletion,
1510 RemoveAttrDefaultById(Oid attrdefId)
1512 Relation attrdef_rel;
1515 ScanKeyData scankeys[1];
1519 AttrNumber myattnum;
1521 /* Grab an appropriate lock on the pg_attrdef relation */
1522 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1524 /* Find the pg_attrdef tuple */
1525 ScanKeyInit(&scankeys[0],
1526 ObjectIdAttributeNumber,
1527 BTEqualStrategyNumber, F_OIDEQ,
1528 ObjectIdGetDatum(attrdefId));
1530 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1531 SnapshotNow, 1, scankeys);
1533 tuple = systable_getnext(scan);
1534 if (!HeapTupleIsValid(tuple))
1535 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1537 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1538 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1540 /* Get an exclusive lock on the relation owning the attribute */
1541 myrel = relation_open(myrelid, AccessExclusiveLock);
1543 /* Now we can delete the pg_attrdef row */
1544 simple_heap_delete(attrdef_rel, &tuple->t_self);
1546 systable_endscan(scan);
1547 heap_close(attrdef_rel, RowExclusiveLock);
1549 /* Fix the pg_attribute row */
1550 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1552 tuple = SearchSysCacheCopy2(ATTNUM,
1553 ObjectIdGetDatum(myrelid),
1554 Int16GetDatum(myattnum));
1555 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1556 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1559 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1561 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1563 /* keep the system catalog indexes current */
1564 CatalogUpdateIndexes(attr_rel, tuple);
1567 * Our update of the pg_attribute row will force a relcache rebuild, so
1568 * there's nothing else to do here.
1570 heap_close(attr_rel, RowExclusiveLock);
1572 /* Keep lock on attribute's rel until end of xact */
1573 relation_close(myrel, NoLock);
1577 * heap_drop_with_catalog - removes specified relation from catalogs
1579 * Note that this routine is not responsible for dropping objects that are
1580 * linked to the pg_class entry via dependencies (for example, indexes and
1581 * constraints). Those are deleted by the dependency-tracing logic in
1582 * dependency.c before control gets here. In general, therefore, this routine
1583 * should never be called directly; go through performDeletion() instead.
1586 heap_drop_with_catalog(Oid relid)
1591 * Open and lock the relation.
1593 rel = relation_open(relid, AccessExclusiveLock);
1596 * There can no longer be anyone *else* touching the relation, but we
1597 * might still have open queries or cursors in our own session.
1599 if (rel->rd_refcnt != 1)
1601 (errcode(ERRCODE_OBJECT_IN_USE),
1602 errmsg("cannot drop \"%s\" because "
1603 "it is being used by active queries in this session",
1604 RelationGetRelationName(rel))));
1607 * Delete pg_foreign_table tuple first.
1609 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1614 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1616 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1617 if (!HeapTupleIsValid(tuple))
1618 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1620 simple_heap_delete(rel, &tuple->t_self);
1622 ReleaseSysCache(tuple);
1623 heap_close(rel, RowExclusiveLock);
1627 * Schedule unlinking of the relation's physical files at commit.
1629 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1630 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1631 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1633 RelationDropStorage(rel);
1637 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1638 * until transaction commit. This ensures no one else will try to do
1639 * something with the doomed relation.
1641 relation_close(rel, NoLock);
1644 * Forget any ON COMMIT action for the rel
1646 remove_on_commit_action(relid);
1649 * Flush the relation from the relcache. We want to do this before
1650 * starting to remove catalog entries, just to be certain that no relcache
1651 * entry rebuild will happen partway through. (That should not really
1652 * matter, since we don't do CommandCounterIncrement here, but let's be
1655 RelationForgetRelation(relid);
1658 * remove inheritance information
1660 RelationRemoveInheritance(relid);
1665 RemoveStatistics(relid, 0);
1668 * delete attribute tuples
1670 DeleteAttributeTuples(relid);
1673 * delete relation tuple
1675 DeleteRelationTuple(relid);
1680 * Store a default expression for column attnum of relation rel.
1683 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1690 static bool nulls[4] = {false, false, false, false};
1693 Form_pg_attribute attStruct;
1695 ObjectAddress colobject,
1699 * Flatten expression to string form for storage.
1701 adbin = nodeToString(expr);
1704 * Also deparse it to form the mostly-obsolete adsrc field.
1706 adsrc = deparse_expression(expr,
1707 deparse_context_for(RelationGetRelationName(rel),
1708 RelationGetRelid(rel)),
1712 * Make the pg_attrdef entry.
1714 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1715 values[Anum_pg_attrdef_adnum - 1] = attnum;
1716 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1717 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1719 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1721 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1722 attrdefOid = simple_heap_insert(adrel, tuple);
1724 CatalogUpdateIndexes(adrel, tuple);
1726 defobject.classId = AttrDefaultRelationId;
1727 defobject.objectId = attrdefOid;
1728 defobject.objectSubId = 0;
1730 heap_close(adrel, RowExclusiveLock);
1732 /* now can free some of the stuff allocated above */
1733 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1734 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1735 heap_freetuple(tuple);
1740 * Update the pg_attribute entry for the column to show that a default
1743 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1744 atttup = SearchSysCacheCopy2(ATTNUM,
1745 ObjectIdGetDatum(RelationGetRelid(rel)),
1746 Int16GetDatum(attnum));
1747 if (!HeapTupleIsValid(atttup))
1748 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1749 attnum, RelationGetRelid(rel));
1750 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1751 if (!attStruct->atthasdef)
1753 attStruct->atthasdef = true;
1754 simple_heap_update(attrrel, &atttup->t_self, atttup);
1755 /* keep catalog indexes current */
1756 CatalogUpdateIndexes(attrrel, atttup);
1758 heap_close(attrrel, RowExclusiveLock);
1759 heap_freetuple(atttup);
1762 * Make a dependency so that the pg_attrdef entry goes away if the column
1763 * (or whole table) is deleted.
1765 colobject.classId = RelationRelationId;
1766 colobject.objectId = RelationGetRelid(rel);
1767 colobject.objectSubId = attnum;
1769 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1772 * Record dependencies on objects used in the expression, too.
1774 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1778 * Store a check-constraint expression for the given relation.
1780 * Caller is responsible for updating the count of constraints
1781 * in the pg_class entry for the relation.
1784 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1785 bool is_local, int inhcount)
1794 * Flatten expression to string form for storage.
1796 ccbin = nodeToString(expr);
1799 * Also deparse it to form the mostly-obsolete consrc field.
1801 ccsrc = deparse_expression(expr,
1802 deparse_context_for(RelationGetRelationName(rel),
1803 RelationGetRelid(rel)),
1807 * Find columns of rel that are used in expr
1809 * NB: pull_var_clause is okay here only because we don't allow subselects
1810 * in check constraints; it would fail to examine the contents of
1813 varList = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
1814 keycount = list_length(varList);
1821 attNos = (int16 *) palloc(keycount * sizeof(int16));
1822 foreach(vl, varList)
1824 Var *var = (Var *) lfirst(vl);
1827 for (j = 0; j < i; j++)
1828 if (attNos[j] == var->varattno)
1831 attNos[i++] = var->varattno;
1839 * Create the Check Constraint
1841 CreateConstraintEntry(ccname, /* Constraint Name */
1842 RelationGetNamespace(rel), /* namespace */
1843 CONSTRAINT_CHECK, /* Constraint Type */
1844 false, /* Is Deferrable */
1845 false, /* Is Deferred */
1846 true, /* Is Validated */
1847 RelationGetRelid(rel), /* relation */
1848 attNos, /* attrs in the constraint */
1849 keycount, /* # attrs in the constraint */
1850 InvalidOid, /* not a domain constraint */
1851 InvalidOid, /* no associated index */
1852 InvalidOid, /* Foreign key fields */
1861 NULL, /* not an exclusion constraint */
1862 expr, /* Tree form of check constraint */
1863 ccbin, /* Binary form of check constraint */
1864 ccsrc, /* Source form of check constraint */
1865 is_local, /* conislocal */
1866 inhcount); /* coninhcount */
1873 * Store defaults and constraints (passed as a list of CookedConstraint).
1875 * NOTE: only pre-cooked expressions will be passed this way, which is to
1876 * say expressions inherited from an existing relation. Newly parsed
1877 * expressions can be added later, by direct calls to StoreAttrDefault
1878 * and StoreRelCheck (see AddRelationNewConstraints()).
1881 StoreConstraints(Relation rel, List *cooked_constraints)
1886 if (!cooked_constraints)
1887 return; /* nothing to do */
1890 * Deparsing of constraint expressions will fail unless the just-created
1891 * pg_attribute tuples for this relation are made visible. So, bump the
1892 * command counter. CAUTION: this will cause a relcache entry rebuild.
1894 CommandCounterIncrement();
1896 foreach(lc, cooked_constraints)
1898 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1900 switch (con->contype)
1902 case CONSTR_DEFAULT:
1903 StoreAttrDefault(rel, con->attnum, con->expr);
1906 StoreRelCheck(rel, con->name, con->expr,
1907 con->is_local, con->inhcount);
1911 elog(ERROR, "unrecognized constraint type: %d",
1912 (int) con->contype);
1917 SetRelationNumChecks(rel, numchecks);
1921 * AddRelationNewConstraints
1923 * Add new column default expressions and/or constraint check expressions
1924 * to an existing relation. This is defined to do both for efficiency in
1925 * DefineRelation, but of course you can do just one or the other by passing
1928 * rel: relation to be modified
1929 * newColDefaults: list of RawColumnDefault structures
1930 * newConstraints: list of Constraint nodes
1931 * allow_merge: TRUE if check constraints may be merged with existing ones
1932 * is_local: TRUE if definition is local, FALSE if it's inherited
1934 * All entries in newColDefaults will be processed. Entries in newConstraints
1935 * will be processed only if they are CONSTR_CHECK type.
1937 * Returns a list of CookedConstraint nodes that shows the cooked form of
1938 * the default and constraint expressions added to the relation.
1940 * NB: caller should have opened rel with AccessExclusiveLock, and should
1941 * hold that lock till end of transaction. Also, we assume the caller has
1942 * done a CommandCounterIncrement if necessary to make the relation's catalog
1946 AddRelationNewConstraints(Relation rel,
1947 List *newColDefaults,
1948 List *newConstraints,
1952 List *cookedConstraints = NIL;
1953 TupleDesc tupleDesc;
1954 TupleConstr *oldconstr;
1962 CookedConstraint *cooked;
1965 * Get info about existing constraints.
1967 tupleDesc = RelationGetDescr(rel);
1968 oldconstr = tupleDesc->constr;
1970 numoldchecks = oldconstr->num_check;
1975 * Create a dummy ParseState and insert the target relation as its sole
1976 * rangetable entry. We need a ParseState for transformExpr.
1978 pstate = make_parsestate(NULL);
1979 rte = addRangeTableEntryForRelation(pstate,
1984 addRTEtoQuery(pstate, rte, true, true, true);
1987 * Process column default expressions.
1989 foreach(cell, newColDefaults)
1991 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1992 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1994 expr = cookDefault(pstate, colDef->raw_default,
1995 atp->atttypid, atp->atttypmod,
1996 NameStr(atp->attname));
1999 * If the expression is just a NULL constant, we do not bother to make
2000 * an explicit pg_attrdef entry, since the default behavior is
2003 * Note a nonobvious property of this test: if the column is of a
2004 * domain type, what we'll get is not a bare null Const but a
2005 * CoerceToDomain expr, so we will not discard the default. This is
2006 * critical because the column default needs to be retained to
2007 * override any default that the domain might have.
2010 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2013 StoreAttrDefault(rel, colDef->attnum, expr);
2015 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2016 cooked->contype = CONSTR_DEFAULT;
2017 cooked->name = NULL;
2018 cooked->attnum = colDef->attnum;
2019 cooked->expr = expr;
2020 cooked->is_local = is_local;
2021 cooked->inhcount = is_local ? 0 : 1;
2022 cookedConstraints = lappend(cookedConstraints, cooked);
2026 * Process constraint expressions.
2028 numchecks = numoldchecks;
2030 foreach(cell, newConstraints)
2032 Constraint *cdef = (Constraint *) lfirst(cell);
2035 if (cdef->contype != CONSTR_CHECK)
2038 if (cdef->raw_expr != NULL)
2040 Assert(cdef->cooked_expr == NULL);
2043 * Transform raw parsetree to executable expression, and verify
2044 * it's valid as a CHECK constraint.
2046 expr = cookConstraint(pstate, cdef->raw_expr,
2047 RelationGetRelationName(rel));
2051 Assert(cdef->cooked_expr != NULL);
2054 * Here, we assume the parser will only pass us valid CHECK
2055 * expressions, so we do no particular checking.
2057 expr = stringToNode(cdef->cooked_expr);
2061 * Check name uniqueness, or generate a name if none was given.
2063 if (cdef->conname != NULL)
2067 ccname = cdef->conname;
2068 /* Check against other new constraints */
2069 /* Needed because we don't do CommandCounterIncrement in loop */
2070 foreach(cell2, checknames)
2072 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2074 (errcode(ERRCODE_DUPLICATE_OBJECT),
2075 errmsg("check constraint \"%s\" already exists",
2079 /* save name for future checks */
2080 checknames = lappend(checknames, ccname);
2083 * Check against pre-existing constraints. If we are allowed to
2084 * merge with an existing constraint, there's no more to do here.
2085 * (We omit the duplicate constraint from the result, which is
2086 * what ATAddCheckConstraint wants.)
2088 if (MergeWithExistingConstraint(rel, ccname, expr,
2089 allow_merge, is_local))
2095 * When generating a name, we want to create "tab_col_check" for a
2096 * column constraint and "tab_check" for a table constraint. We
2097 * no longer have any info about the syntactic positioning of the
2098 * constraint phrase, so we approximate this by seeing whether the
2099 * expression references more than one column. (If the user
2100 * played by the rules, the result is the same...)
2102 * Note: pull_var_clause() doesn't descend into sublinks, but we
2103 * eliminated those above; and anyway this only needs to be an
2104 * approximate answer.
2109 vars = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
2111 /* eliminate duplicates */
2112 vars = list_union(NIL, vars);
2114 if (list_length(vars) == 1)
2115 colname = get_attname(RelationGetRelid(rel),
2116 ((Var *) linitial(vars))->varattno);
2120 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2123 RelationGetNamespace(rel),
2126 /* save name for future checks */
2127 checknames = lappend(checknames, ccname);
2133 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
2137 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2138 cooked->contype = CONSTR_CHECK;
2139 cooked->name = ccname;
2141 cooked->expr = expr;
2142 cooked->is_local = is_local;
2143 cooked->inhcount = is_local ? 0 : 1;
2144 cookedConstraints = lappend(cookedConstraints, cooked);
2148 * Update the count of constraints in the relation's pg_class tuple. We do
2149 * this even if there was no change, in order to ensure that an SI update
2150 * message is sent out for the pg_class tuple, which will force other
2151 * backends to rebuild their relcache entries for the rel. (This is
2152 * critical if we added defaults but not constraints.)
2154 SetRelationNumChecks(rel, numchecks);
2156 return cookedConstraints;
2160 * Check for a pre-existing check constraint that conflicts with a proposed
2161 * new one, and either adjust its conislocal/coninhcount settings or throw
2164 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2165 * got a so-far-unique name, or throws error if conflict.
2168 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2169 bool allow_merge, bool is_local)
2173 SysScanDesc conscan;
2174 ScanKeyData skey[2];
2177 /* Search for a pg_constraint entry with same name and relation */
2178 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2182 ScanKeyInit(&skey[0],
2183 Anum_pg_constraint_conname,
2184 BTEqualStrategyNumber, F_NAMEEQ,
2185 CStringGetDatum(ccname));
2187 ScanKeyInit(&skey[1],
2188 Anum_pg_constraint_connamespace,
2189 BTEqualStrategyNumber, F_OIDEQ,
2190 ObjectIdGetDatum(RelationGetNamespace(rel)));
2192 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2193 SnapshotNow, 2, skey);
2195 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2197 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2199 if (con->conrelid == RelationGetRelid(rel))
2201 /* Found it. Conflicts if not identical check constraint */
2202 if (con->contype == CONSTRAINT_CHECK)
2207 val = fastgetattr(tup,
2208 Anum_pg_constraint_conbin,
2209 conDesc->rd_att, &isnull);
2211 elog(ERROR, "null conbin for rel %s",
2212 RelationGetRelationName(rel));
2213 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2216 if (!found || !allow_merge)
2218 (errcode(ERRCODE_DUPLICATE_OBJECT),
2219 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2220 ccname, RelationGetRelationName(rel))));
2221 /* OK to update the tuple */
2223 (errmsg("merging constraint \"%s\" with inherited definition",
2225 tup = heap_copytuple(tup);
2226 con = (Form_pg_constraint) GETSTRUCT(tup);
2228 con->conislocal = true;
2231 simple_heap_update(conDesc, &tup->t_self, tup);
2232 CatalogUpdateIndexes(conDesc, tup);
2237 systable_endscan(conscan);
2238 heap_close(conDesc, RowExclusiveLock);
2244 * Update the count of constraints in the relation's pg_class tuple.
2246 * Caller had better hold exclusive lock on the relation.
2248 * An important side effect is that a SI update message will be sent out for
2249 * the pg_class tuple, which will force other backends to rebuild their
2250 * relcache entries for the rel. Also, this backend will rebuild its
2251 * own relcache entry at the next CommandCounterIncrement.
2254 SetRelationNumChecks(Relation rel, int numchecks)
2258 Form_pg_class relStruct;
2260 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2261 reltup = SearchSysCacheCopy1(RELOID,
2262 ObjectIdGetDatum(RelationGetRelid(rel)));
2263 if (!HeapTupleIsValid(reltup))
2264 elog(ERROR, "cache lookup failed for relation %u",
2265 RelationGetRelid(rel));
2266 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2268 if (relStruct->relchecks != numchecks)
2270 relStruct->relchecks = numchecks;
2272 simple_heap_update(relrel, &reltup->t_self, reltup);
2274 /* keep catalog indexes current */
2275 CatalogUpdateIndexes(relrel, reltup);
2279 /* Skip the disk update, but force relcache inval anyway */
2280 CacheInvalidateRelcache(rel);
2283 heap_freetuple(reltup);
2284 heap_close(relrel, RowExclusiveLock);
2288 * Take a raw default and convert it to a cooked format ready for
2291 * Parse state should be set up to recognize any vars that might appear
2292 * in the expression. (Even though we plan to reject vars, it's more
2293 * user-friendly to give the correct error message than "unknown var".)
2295 * If atttypid is not InvalidOid, coerce the expression to the specified
2296 * type (and typmod atttypmod). attname is only needed in this case:
2297 * it is used in the error message, if any.
2300 cookDefault(ParseState *pstate,
2308 Assert(raw_default != NULL);
2311 * Transform raw parsetree to executable expression.
2313 expr = transformExpr(pstate, raw_default);
2316 * Make sure default expr does not refer to any vars.
2318 if (contain_var_clause(expr))
2320 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2321 errmsg("cannot use column references in default expression")));
2324 * It can't return a set either.
2326 if (expression_returns_set(expr))
2328 (errcode(ERRCODE_DATATYPE_MISMATCH),
2329 errmsg("default expression must not return a set")));
2332 * No subplans or aggregates, either...
2334 if (pstate->p_hasSubLinks)
2336 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2337 errmsg("cannot use subquery in default expression")));
2338 if (pstate->p_hasAggs)
2340 (errcode(ERRCODE_GROUPING_ERROR),
2341 errmsg("cannot use aggregate function in default expression")));
2342 if (pstate->p_hasWindowFuncs)
2344 (errcode(ERRCODE_WINDOWING_ERROR),
2345 errmsg("cannot use window function in default expression")));
2348 * Coerce the expression to the correct type and typmod, if given. This
2349 * should match the parser's processing of non-defaulted expressions ---
2350 * see transformAssignedExpr().
2352 if (OidIsValid(atttypid))
2354 Oid type_id = exprType(expr);
2356 expr = coerce_to_target_type(pstate, expr, type_id,
2357 atttypid, atttypmod,
2358 COERCION_ASSIGNMENT,
2359 COERCE_IMPLICIT_CAST,
2363 (errcode(ERRCODE_DATATYPE_MISMATCH),
2364 errmsg("column \"%s\" is of type %s"
2365 " but default expression is of type %s",
2367 format_type_be(atttypid),
2368 format_type_be(type_id)),
2369 errhint("You will need to rewrite or cast the expression.")));
2376 * Take a raw CHECK constraint expression and convert it to a cooked format
2377 * ready for storage.
2379 * Parse state must be set up to recognize any vars that might appear
2380 * in the expression.
2383 cookConstraint(ParseState *pstate,
2384 Node *raw_constraint,
2390 * Transform raw parsetree to executable expression.
2392 expr = transformExpr(pstate, raw_constraint);
2395 * Make sure it yields a boolean result.
2397 expr = coerce_to_boolean(pstate, expr, "CHECK");
2400 * Make sure no outside relations are referred to.
2402 if (list_length(pstate->p_rtable) != 1)
2404 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2405 errmsg("only table \"%s\" can be referenced in check constraint",
2409 * No subplans or aggregates, either...
2411 if (pstate->p_hasSubLinks)
2413 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2414 errmsg("cannot use subquery in check constraint")));
2415 if (pstate->p_hasAggs)
2417 (errcode(ERRCODE_GROUPING_ERROR),
2418 errmsg("cannot use aggregate function in check constraint")));
2419 if (pstate->p_hasWindowFuncs)
2421 (errcode(ERRCODE_WINDOWING_ERROR),
2422 errmsg("cannot use window function in check constraint")));
2429 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2431 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2435 RemoveStatistics(Oid relid, AttrNumber attnum)
2437 Relation pgstatistic;
2443 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2445 ScanKeyInit(&key[0],
2446 Anum_pg_statistic_starelid,
2447 BTEqualStrategyNumber, F_OIDEQ,
2448 ObjectIdGetDatum(relid));
2454 ScanKeyInit(&key[1],
2455 Anum_pg_statistic_staattnum,
2456 BTEqualStrategyNumber, F_INT2EQ,
2457 Int16GetDatum(attnum));
2461 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2462 SnapshotNow, nkeys, key);
2464 /* we must loop even when attnum != 0, in case of inherited stats */
2465 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2466 simple_heap_delete(pgstatistic, &tuple->t_self);
2468 systable_endscan(scan);
2470 heap_close(pgstatistic, RowExclusiveLock);
2475 * RelationTruncateIndexes - truncate all indexes associated
2476 * with the heap relation to zero tuples.
2478 * The routine will truncate and then reconstruct the indexes on
2479 * the specified relation. Caller must hold exclusive lock on rel.
2482 RelationTruncateIndexes(Relation heapRelation)
2486 /* Ask the relcache to produce a list of the indexes of the rel */
2487 foreach(indlist, RelationGetIndexList(heapRelation))
2489 Oid indexId = lfirst_oid(indlist);
2490 Relation currentIndex;
2491 IndexInfo *indexInfo;
2493 /* Open the index relation; use exclusive lock, just to be sure */
2494 currentIndex = index_open(indexId, AccessExclusiveLock);
2496 /* Fetch info needed for index_build */
2497 indexInfo = BuildIndexInfo(currentIndex);
2500 * Now truncate the actual file (and discard buffers).
2502 RelationTruncate(currentIndex, 0);
2504 /* Initialize the index and rebuild */
2505 /* Note: we do not need to re-establish pkey setting */
2506 index_build(heapRelation, currentIndex, indexInfo, false);
2508 /* We're done with this index */
2509 index_close(currentIndex, NoLock);
2516 * This routine deletes all data within all the specified relations.
2518 * This is not transaction-safe! There is another, transaction-safe
2519 * implementation in commands/tablecmds.c. We now use this only for
2520 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2523 heap_truncate(List *relids)
2525 List *relations = NIL;
2528 /* Open relations for processing, and grab exclusive access on each */
2529 foreach(cell, relids)
2531 Oid rid = lfirst_oid(cell);
2534 rel = heap_open(rid, AccessExclusiveLock);
2535 relations = lappend(relations, rel);
2538 /* Don't allow truncate on tables that are referenced by foreign keys */
2539 heap_truncate_check_FKs(relations, true);
2542 foreach(cell, relations)
2544 Relation rel = lfirst(cell);
2546 /* Truncate the relation */
2547 heap_truncate_one_rel(rel);
2549 /* Close the relation, but keep exclusive lock on it until commit */
2550 heap_close(rel, NoLock);
2555 * heap_truncate_one_rel
2557 * This routine deletes all data within the specified relation.
2559 * This is not transaction-safe, because the truncation is done immediately
2560 * and cannot be rolled back later. Caller is responsible for having
2561 * checked permissions etc, and must have obtained AccessExclusiveLock.
2564 heap_truncate_one_rel(Relation rel)
2568 /* Truncate the actual file (and discard buffers) */
2569 RelationTruncate(rel, 0);
2571 /* If the relation has indexes, truncate the indexes too */
2572 RelationTruncateIndexes(rel);
2574 /* If there is a toast table, truncate that too */
2575 toastrelid = rel->rd_rel->reltoastrelid;
2576 if (OidIsValid(toastrelid))
2578 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2580 RelationTruncate(toastrel, 0);
2581 RelationTruncateIndexes(toastrel);
2582 /* keep the lock... */
2583 heap_close(toastrel, NoLock);
2588 * heap_truncate_check_FKs
2589 * Check for foreign keys referencing a list of relations that
2590 * are to be truncated, and raise error if there are any
2592 * We disallow such FKs (except self-referential ones) since the whole point
2593 * of TRUNCATE is to not scan the individual rows to be thrown away.
2595 * This is split out so it can be shared by both implementations of truncate.
2596 * Caller should already hold a suitable lock on the relations.
2598 * tempTables is only used to select an appropriate error message.
2601 heap_truncate_check_FKs(List *relations, bool tempTables)
2608 * Build a list of OIDs of the interesting relations.
2610 * If a relation has no triggers, then it can neither have FKs nor be
2611 * referenced by a FK from another table, so we can ignore it.
2613 foreach(cell, relations)
2615 Relation rel = lfirst(cell);
2617 if (rel->rd_rel->relhastriggers)
2618 oids = lappend_oid(oids, RelationGetRelid(rel));
2622 * Fast path: if no relation has triggers, none has FKs either.
2628 * Otherwise, must scan pg_constraint. We make one pass with all the
2629 * relations considered; if this finds nothing, then all is well.
2631 dependents = heap_truncate_find_FKs(oids);
2632 if (dependents == NIL)
2636 * Otherwise we repeat the scan once per relation to identify a particular
2637 * pair of relations to complain about. This is pretty slow, but
2638 * performance shouldn't matter much in a failure path. The reason for
2639 * doing things this way is to ensure that the message produced is not
2640 * dependent on chance row locations within pg_constraint.
2644 Oid relid = lfirst_oid(cell);
2647 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2649 foreach(cell2, dependents)
2651 Oid relid2 = lfirst_oid(cell2);
2653 if (!list_member_oid(oids, relid2))
2655 char *relname = get_rel_name(relid);
2656 char *relname2 = get_rel_name(relid2);
2660 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2661 errmsg("unsupported ON COMMIT and foreign key combination"),
2662 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2663 relname2, relname)));
2666 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2667 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2668 errdetail("Table \"%s\" references \"%s\".",
2670 errhint("Truncate table \"%s\" at the same time, "
2671 "or use TRUNCATE ... CASCADE.",
2679 * heap_truncate_find_FKs
2680 * Find relations having foreign keys referencing any of the given rels
2682 * Input and result are both lists of relation OIDs. The result contains
2683 * no duplicates, does *not* include any rels that were already in the input
2684 * list, and is sorted in OID order. (The last property is enforced mainly
2685 * to guarantee consistent behavior in the regression tests; we don't want
2686 * behavior to change depending on chance locations of rows in pg_constraint.)
2688 * Note: caller should already have appropriate lock on all rels mentioned
2689 * in relationIds. Since adding or dropping an FK requires exclusive lock
2690 * on both rels, this ensures that the answer will be stable.
2693 heap_truncate_find_FKs(List *relationIds)
2697 SysScanDesc fkeyScan;
2701 * Must scan pg_constraint. Right now, it is a seqscan because there is
2702 * no available index on confrelid.
2704 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2706 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2707 SnapshotNow, 0, NULL);
2709 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2711 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2713 /* Not a foreign key */
2714 if (con->contype != CONSTRAINT_FOREIGN)
2717 /* Not referencing one of our list of tables */
2718 if (!list_member_oid(relationIds, con->confrelid))
2721 /* Add referencer unless already in input or result list */
2722 if (!list_member_oid(relationIds, con->conrelid))
2723 result = insert_ordered_unique_oid(result, con->conrelid);
2726 systable_endscan(fkeyScan);
2727 heap_close(fkeyRel, AccessShareLock);
2733 * insert_ordered_unique_oid
2734 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2735 * and eliminating duplicates
2737 * Building the ordered list this way is O(N^2), but with a pretty small
2738 * constant, so for the number of entries we expect it will probably be
2739 * faster than trying to apply qsort(). It seems unlikely someone would be
2740 * trying to truncate a table with thousands of dependent tables ...
2743 insert_ordered_unique_oid(List *list, Oid datum)
2747 /* Does the datum belong at the front? */
2748 if (list == NIL || datum < linitial_oid(list))
2749 return lcons_oid(datum, list);
2750 /* Does it match the first entry? */
2751 if (datum == linitial_oid(list))
2752 return list; /* duplicate, so don't insert */
2753 /* No, so find the entry it belongs after */
2754 prev = list_head(list);
2757 ListCell *curr = lnext(prev);
2759 if (curr == NULL || datum < lfirst_oid(curr))
2760 break; /* it belongs after 'prev', before 'curr' */
2762 if (datum == lfirst_oid(curr))
2763 return list; /* duplicate, so don't insert */
2767 /* Insert datum into list after 'prev' */
2768 lappend_cell_oid(list, prev, datum);