1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.369 2010/02/03 01:14:16 tgl Exp $
15 * heap_create() - Create an uncataloged heap relation
16 * heap_create_with_catalog() - Create a cataloged relation
17 * heap_drop_with_catalog() - Removes named relation from catalogs
20 * this code taken from access/heap/create.c, which contains
21 * the old heap_create_with_catalog, amcreate, and amdestroy.
22 * those routines will soon call these routines using the function
24 * just like the poorly named "NewXXX" routines do. The
25 * "New" routines are all going to die soon, once and for all!
28 *-------------------------------------------------------------------------
32 #include "access/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/pg_attrdef.h"
43 #include "catalog/pg_constraint.h"
44 #include "catalog/pg_inherits.h"
45 #include "catalog/pg_namespace.h"
46 #include "catalog/pg_statistic.h"
47 #include "catalog/pg_tablespace.h"
48 #include "catalog/pg_type.h"
49 #include "catalog/pg_type_fn.h"
50 #include "catalog/storage.h"
51 #include "commands/tablecmds.h"
52 #include "commands/typecmds.h"
53 #include "miscadmin.h"
54 #include "nodes/nodeFuncs.h"
55 #include "optimizer/var.h"
56 #include "parser/parse_coerce.h"
57 #include "parser/parse_expr.h"
58 #include "parser/parse_relation.h"
59 #include "storage/bufmgr.h"
60 #include "storage/freespace.h"
61 #include "storage/smgr.h"
62 #include "utils/acl.h"
63 #include "utils/builtins.h"
64 #include "utils/fmgroids.h"
65 #include "utils/inval.h"
66 #include "utils/lsyscache.h"
67 #include "utils/relcache.h"
68 #include "utils/snapmgr.h"
69 #include "utils/syscache.h"
70 #include "utils/tqual.h"
73 /* Kluge for upgrade-in-place support */
74 Oid binary_upgrade_next_heap_relfilenode = InvalidOid;
75 Oid binary_upgrade_next_toast_relfilenode = InvalidOid;
77 static void AddNewRelationTuple(Relation pg_class_desc,
78 Relation new_rel_desc,
86 static Oid AddNewRelationType(const char *typeName,
93 static void RelationRemoveInheritance(Oid relid);
94 static void StoreRelCheck(Relation rel, char *ccname, Node *expr,
95 bool is_local, int inhcount);
96 static void StoreConstraints(Relation rel, List *cooked_constraints);
97 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
98 bool allow_merge, bool is_local);
99 static void SetRelationNumChecks(Relation rel, int numchecks);
100 static Node *cookConstraint(ParseState *pstate,
101 Node *raw_constraint,
103 static List *insert_ordered_unique_oid(List *list, Oid datum);
106 /* ----------------------------------------------------------------
107 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
109 * these should all be moved to someplace in the lib/catalog
110 * module, if not obliterated first.
111 * ----------------------------------------------------------------
117 * Should the system special case these attributes in the future?
118 * Advantage: consume much less space in the ATTRIBUTE relation.
119 * Disadvantage: special cases will be all over the place.
123 * The initializers below do not include the attoptions or attacl fields,
124 * but that's OK - we're never going to reference anything beyond the
125 * fixed-size portion of the structure anyway.
128 static FormData_pg_attribute a1 = {
129 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
130 SelfItemPointerAttributeNumber, 0, -1, -1,
131 false, 'p', 's', true, false, false, true, 0
134 static FormData_pg_attribute a2 = {
135 0, {"oid"}, OIDOID, 0, sizeof(Oid),
136 ObjectIdAttributeNumber, 0, -1, -1,
137 true, 'p', 'i', true, false, false, true, 0
140 static FormData_pg_attribute a3 = {
141 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
142 MinTransactionIdAttributeNumber, 0, -1, -1,
143 true, 'p', 'i', true, false, false, true, 0
146 static FormData_pg_attribute a4 = {
147 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
148 MinCommandIdAttributeNumber, 0, -1, -1,
149 true, 'p', 'i', true, false, false, true, 0
152 static FormData_pg_attribute a5 = {
153 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
154 MaxTransactionIdAttributeNumber, 0, -1, -1,
155 true, 'p', 'i', true, false, false, true, 0
158 static FormData_pg_attribute a6 = {
159 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
160 MaxCommandIdAttributeNumber, 0, -1, -1,
161 true, 'p', 'i', true, false, false, true, 0
165 * We decided to call this attribute "tableoid" rather than say
166 * "classoid" on the basis that in the future there may be more than one
167 * table of a particular class/type. In any case table is still the word
170 static FormData_pg_attribute a7 = {
171 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
172 TableOidAttributeNumber, 0, -1, -1,
173 true, 'p', 'i', true, false, false, true, 0
176 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
179 * This function returns a Form_pg_attribute pointer for a system attribute.
180 * Note that we elog if the presented attno is invalid, which would only
181 * happen if there's a problem upstream.
184 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
186 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
187 elog(ERROR, "invalid system attribute number %d", attno);
188 if (attno == ObjectIdAttributeNumber && !relhasoids)
189 elog(ERROR, "invalid system attribute number %d", attno);
190 return SysAtt[-attno - 1];
194 * If the given name is a system attribute name, return a Form_pg_attribute
195 * pointer for a prototype definition. If not, return NULL.
198 SystemAttributeByName(const char *attname, bool relhasoids)
202 for (j = 0; j < (int) lengthof(SysAtt); j++)
204 Form_pg_attribute att = SysAtt[j];
206 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
208 if (strcmp(NameStr(att->attname), attname) == 0)
217 /* ----------------------------------------------------------------
218 * XXX END OF UGLY HARD CODED BADNESS XXX
219 * ---------------------------------------------------------------- */
222 /* ----------------------------------------------------------------
223 * heap_create - Create an uncataloged heap relation
225 * Note API change: the caller must now always provide the OID
226 * to use for the relation.
228 * rel->rd_rel is initialized by RelationBuildLocalRelation,
229 * and is mostly zeroes at return.
230 * ----------------------------------------------------------------
233 heap_create(const char *relname,
239 bool shared_relation,
240 bool allow_system_table_mods)
245 /* The caller must have provided an OID for the relation. */
246 Assert(OidIsValid(relid));
251 if (!allow_system_table_mods &&
252 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
253 IsNormalProcessingMode())
255 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
256 errmsg("permission denied to create \"%s.%s\"",
257 get_namespace_name(relnamespace), relname),
258 errdetail("System catalog modifications are currently disallowed.")));
261 * Decide if we need storage or not, and handle a couple other special
262 * cases for particular relkinds.
267 case RELKIND_COMPOSITE_TYPE:
268 create_storage = false;
271 * Force reltablespace to zero if the relation has no physical
272 * storage. This is mainly just for cleanliness' sake.
274 reltablespace = InvalidOid;
276 case RELKIND_SEQUENCE:
277 create_storage = true;
280 * Force reltablespace to zero for sequences, since we don't
281 * support moving them around into different tablespaces.
283 reltablespace = InvalidOid;
286 create_storage = true;
291 * Never allow a pg_class entry to explicitly specify the database's
292 * default tablespace in reltablespace; force it to zero instead. This
293 * ensures that if the database is cloned with a different default
294 * tablespace, the pg_class entry will still match where CREATE DATABASE
295 * will put the physically copied relation.
297 * Yes, this is a bit of a hack.
299 if (reltablespace == MyDatabaseTableSpace)
300 reltablespace = InvalidOid;
303 * build the relcache entry.
305 rel = RelationBuildLocalRelation(relname,
313 * Have the storage manager create the relation's disk file, if needed.
315 * We only create the main fork here, other forks will be created on
320 RelationOpenSmgr(rel);
321 RelationCreateStorage(rel->rd_node, rel->rd_istemp);
327 /* ----------------------------------------------------------------
328 * heap_create_with_catalog - Create a cataloged relation
330 * this is done in multiple steps:
332 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
333 * descriptor contains a valid set of attribute names and types
335 * 2) pg_class is opened and get_relname_relid()
336 * performs a scan to ensure that no relation with the
337 * same name already exists.
339 * 3) heap_create() is called to create the new relation on disk.
341 * 4) TypeCreate() is called to define a new type corresponding
342 * to the new relation.
344 * 5) AddNewRelationTuple() is called to register the
345 * relation in pg_class.
347 * 6) AddNewAttributeTuples() is called to register the
348 * new relation's schema in pg_attribute.
350 * 7) StoreConstraints is called () - vadim 08/22/97
352 * 8) the relations are closed and the new relation's oid
355 * ----------------------------------------------------------------
358 /* --------------------------------
359 * CheckAttributeNamesTypes
361 * this is used to make certain the tuple descriptor contains a
362 * valid set of attribute names and datatypes. a problem simply
363 * generates ereport(ERROR) which aborts the current transaction.
364 * --------------------------------
367 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
371 int natts = tupdesc->natts;
373 /* Sanity check on column count */
374 if (natts < 0 || natts > MaxHeapAttributeNumber)
376 (errcode(ERRCODE_TOO_MANY_COLUMNS),
377 errmsg("tables can have at most %d columns",
378 MaxHeapAttributeNumber)));
381 * first check for collision with system attribute names
383 * Skip this for a view or type relation, since those don't have system
386 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
388 for (i = 0; i < natts; i++)
390 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
391 tupdesc->tdhasoid) != NULL)
393 (errcode(ERRCODE_DUPLICATE_COLUMN),
394 errmsg("column name \"%s\" conflicts with a system column name",
395 NameStr(tupdesc->attrs[i]->attname))));
400 * next check for repeated attribute names
402 for (i = 1; i < natts; i++)
404 for (j = 0; j < i; j++)
406 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
407 NameStr(tupdesc->attrs[i]->attname)) == 0)
409 (errcode(ERRCODE_DUPLICATE_COLUMN),
410 errmsg("column name \"%s\" specified more than once",
411 NameStr(tupdesc->attrs[j]->attname))));
416 * next check the attribute types
418 for (i = 0; i < natts; i++)
420 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
421 tupdesc->attrs[i]->atttypid);
425 /* --------------------------------
428 * Verify that the proposed datatype of an attribute is legal.
429 * This is needed because there are types (and pseudo-types)
430 * in the catalogs that we do not support as elements of real tuples.
431 * --------------------------------
434 CheckAttributeType(const char *attname, Oid atttypid)
436 char att_typtype = get_typtype(atttypid);
438 if (atttypid == UNKNOWNOID)
441 * Warn user, but don't fail, if column to be created has UNKNOWN type
442 * (usually as a result of a 'retrieve into' - jolly)
445 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
446 errmsg("column \"%s\" has type \"unknown\"", attname),
447 errdetail("Proceeding with relation creation anyway.")));
449 else if (att_typtype == TYPTYPE_PSEUDO)
452 * Refuse any attempt to create a pseudo-type column, except for a
453 * special hack for pg_statistic: allow ANYARRAY during initdb
455 if (atttypid != ANYARRAYOID || IsUnderPostmaster)
457 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
458 errmsg("column \"%s\" has pseudo-type %s",
459 attname, format_type_be(atttypid))));
461 else if (att_typtype == TYPTYPE_COMPOSITE)
464 * For a composite type, recurse into its attributes. You might think
465 * this isn't necessary, but since we allow system catalogs to break
466 * the rule, we have to guard against the case.
472 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
474 tupdesc = RelationGetDescr(relation);
476 for (i = 0; i < tupdesc->natts; i++)
478 Form_pg_attribute attr = tupdesc->attrs[i];
480 if (attr->attisdropped)
482 CheckAttributeType(NameStr(attr->attname), attr->atttypid);
485 relation_close(relation, AccessShareLock);
490 * InsertPgAttributeTuple
491 * Construct and insert a new tuple in pg_attribute.
493 * Caller has already opened and locked pg_attribute. new_attribute is the
494 * attribute to insert (but we ignore attacl and attoptions, which are always
495 * initialized to NULL).
497 * indstate is the index state for CatalogIndexInsert. It can be passed as
498 * NULL, in which case we'll fetch the necessary info. (Don't do this when
499 * inserting multiple attributes, because it's a tad more expensive.)
502 InsertPgAttributeTuple(Relation pg_attribute_rel,
503 Form_pg_attribute new_attribute,
504 CatalogIndexState indstate)
506 Datum values[Natts_pg_attribute];
507 bool nulls[Natts_pg_attribute];
510 /* This is a tad tedious, but way cleaner than what we used to do... */
511 memset(values, 0, sizeof(values));
512 memset(nulls, false, sizeof(nulls));
514 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
515 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
516 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
517 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
518 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
519 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
520 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
521 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
522 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
523 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
524 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
525 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
526 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
527 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
528 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
529 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
530 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
532 /* start out with empty permissions and empty options */
533 nulls[Anum_pg_attribute_attacl - 1] = true;
534 nulls[Anum_pg_attribute_attoptions - 1] = true;
536 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
538 /* finally insert the new tuple, update the indexes, and clean up */
539 simple_heap_insert(pg_attribute_rel, tup);
541 if (indstate != NULL)
542 CatalogIndexInsert(indstate, tup);
544 CatalogUpdateIndexes(pg_attribute_rel, tup);
549 /* --------------------------------
550 * AddNewAttributeTuples
552 * this registers the new relation's schema by adding
553 * tuples to pg_attribute.
554 * --------------------------------
557 AddNewAttributeTuples(Oid new_rel_oid,
563 Form_pg_attribute attr;
566 CatalogIndexState indstate;
567 int natts = tupdesc->natts;
568 ObjectAddress myself,
572 * open pg_attribute and its indexes.
574 rel = heap_open(AttributeRelationId, RowExclusiveLock);
576 indstate = CatalogOpenIndexes(rel);
579 * First we add the user attributes. This is also a convenient place to
580 * add dependencies on their datatypes.
582 for (i = 0; i < natts; i++)
584 attr = tupdesc->attrs[i];
585 /* Fill in the correct relation OID */
586 attr->attrelid = new_rel_oid;
587 /* Make sure these are OK, too */
588 attr->attstattarget = -1;
589 attr->attcacheoff = -1;
591 InsertPgAttributeTuple(rel, attr, indstate);
593 /* Add dependency info */
594 myself.classId = RelationRelationId;
595 myself.objectId = new_rel_oid;
596 myself.objectSubId = i + 1;
597 referenced.classId = TypeRelationId;
598 referenced.objectId = attr->atttypid;
599 referenced.objectSubId = 0;
600 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
604 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
605 * all for a view or type relation. We don't bother with making datatype
606 * dependencies here, since presumably all these types are pinned.
608 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
610 for (i = 0; i < (int) lengthof(SysAtt); i++)
612 FormData_pg_attribute attStruct;
614 /* skip OID where appropriate */
615 if (!tupdesc->tdhasoid &&
616 SysAtt[i]->attnum == ObjectIdAttributeNumber)
619 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
621 /* Fill in the correct relation OID in the copied tuple */
622 attStruct.attrelid = new_rel_oid;
624 /* Fill in correct inheritance info for the OID column */
625 if (attStruct.attnum == ObjectIdAttributeNumber)
627 attStruct.attislocal = oidislocal;
628 attStruct.attinhcount = oidinhcount;
631 InsertPgAttributeTuple(rel, &attStruct, indstate);
638 CatalogCloseIndexes(indstate);
640 heap_close(rel, RowExclusiveLock);
643 /* --------------------------------
646 * Construct and insert a new tuple in pg_class.
648 * Caller has already opened and locked pg_class.
649 * Tuple data is taken from new_rel_desc->rd_rel, except for the
650 * variable-width fields which are not present in a cached reldesc.
651 * relacl and reloptions are passed in Datum form (to avoid having
652 * to reference the data types in heap.h). Pass (Datum) 0 to set them
654 * --------------------------------
657 InsertPgClassTuple(Relation pg_class_desc,
658 Relation new_rel_desc,
663 Form_pg_class rd_rel = new_rel_desc->rd_rel;
664 Datum values[Natts_pg_class];
665 bool nulls[Natts_pg_class];
668 /* This is a tad tedious, but way cleaner than what we used to do... */
669 memset(values, 0, sizeof(values));
670 memset(nulls, false, sizeof(nulls));
672 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
673 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
674 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
675 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
676 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
677 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
678 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
679 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
680 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
681 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
682 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
683 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
684 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
685 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
686 values[Anum_pg_class_relistemp - 1] = BoolGetDatum(rd_rel->relistemp);
687 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
688 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
689 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
690 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
691 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
692 values[Anum_pg_class_relhasexclusion - 1] = BoolGetDatum(rd_rel->relhasexclusion);
693 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
694 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
695 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
696 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
697 if (relacl != (Datum) 0)
698 values[Anum_pg_class_relacl - 1] = relacl;
700 nulls[Anum_pg_class_relacl - 1] = true;
701 if (reloptions != (Datum) 0)
702 values[Anum_pg_class_reloptions - 1] = reloptions;
704 nulls[Anum_pg_class_reloptions - 1] = true;
706 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
709 * The new tuple must have the oid already chosen for the rel. Sure would
710 * be embarrassing to do this sort of thing in polite company.
712 HeapTupleSetOid(tup, new_rel_oid);
714 /* finally insert the new tuple, update the indexes, and clean up */
715 simple_heap_insert(pg_class_desc, tup);
717 CatalogUpdateIndexes(pg_class_desc, tup);
722 /* --------------------------------
723 * AddNewRelationTuple
725 * this registers the new relation in the catalogs by
726 * adding a tuple to pg_class.
727 * --------------------------------
730 AddNewRelationTuple(Relation pg_class_desc,
731 Relation new_rel_desc,
740 Form_pg_class new_rel_reltup;
743 * first we update some of the information in our uncataloged relation's
744 * relation descriptor.
746 new_rel_reltup = new_rel_desc->rd_rel;
750 case RELKIND_RELATION:
752 case RELKIND_TOASTVALUE:
753 /* The relation is real, but as yet empty */
754 new_rel_reltup->relpages = 0;
755 new_rel_reltup->reltuples = 0;
757 case RELKIND_SEQUENCE:
758 /* Sequences always have a known size */
759 new_rel_reltup->relpages = 1;
760 new_rel_reltup->reltuples = 1;
763 /* Views, etc, have no disk storage */
764 new_rel_reltup->relpages = 0;
765 new_rel_reltup->reltuples = 0;
769 /* Initialize relfrozenxid */
770 if (relkind == RELKIND_RELATION ||
771 relkind == RELKIND_TOASTVALUE)
774 * Initialize to the minimum XID that could put tuples in the table.
775 * We know that no xacts older than RecentXmin are still running, so
778 new_rel_reltup->relfrozenxid = RecentXmin;
783 * Other relation types will not contain XIDs, so set relfrozenxid to
784 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
785 * we force its xmin to be FrozenTransactionId always; see
786 * commands/sequence.c.)
788 new_rel_reltup->relfrozenxid = InvalidTransactionId;
791 new_rel_reltup->relowner = relowner;
792 new_rel_reltup->reltype = new_type_oid;
793 new_rel_reltup->reloftype = reloftype;
794 new_rel_reltup->relkind = relkind;
796 new_rel_desc->rd_att->tdtypeid = new_type_oid;
798 /* Now build and insert the tuple */
799 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
804 /* --------------------------------
805 * AddNewRelationType -
807 * define a composite type corresponding to the new relation
808 * --------------------------------
811 AddNewRelationType(const char *typeName,
820 TypeCreate(new_row_type, /* optional predetermined OID */
821 typeName, /* type name */
822 typeNamespace, /* type namespace */
823 new_rel_oid, /* relation oid */
824 new_rel_kind, /* relation kind */
825 ownerid, /* owner's ID */
826 -1, /* internal size (varlena) */
827 TYPTYPE_COMPOSITE, /* type-type (composite) */
828 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
829 false, /* composite types are never preferred */
830 DEFAULT_TYPDELIM, /* default array delimiter */
831 F_RECORD_IN, /* input procedure */
832 F_RECORD_OUT, /* output procedure */
833 F_RECORD_RECV, /* receive procedure */
834 F_RECORD_SEND, /* send procedure */
835 InvalidOid, /* typmodin procedure - none */
836 InvalidOid, /* typmodout procedure - none */
837 InvalidOid, /* analyze procedure - default */
838 InvalidOid, /* array element type - irrelevant */
839 false, /* this is not an array type */
840 new_array_type, /* array type if any */
841 InvalidOid, /* domain base type - irrelevant */
842 NULL, /* default value - none */
843 NULL, /* default binary representation */
844 false, /* passed by reference */
845 'd', /* alignment - must be the largest! */
846 'x', /* fully TOASTable */
848 0, /* array dimensions for typBaseType */
849 false); /* Type NOT NULL */
852 /* --------------------------------
853 * heap_create_with_catalog
855 * creates a new cataloged relation. see comments above.
858 * relname: name to give to new rel
859 * relnamespace: OID of namespace it goes in
860 * reltablespace: OID of tablespace it goes in
861 * relid: OID to assign to new rel, or InvalidOid to select a new OID
862 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
863 * ownerid: OID of new rel's owner
864 * tupdesc: tuple descriptor (source of column definitions)
865 * cooked_constraints: list of precooked check constraints and defaults
866 * relkind: relkind for new rel
867 * shared_relation: TRUE if it's to be a shared relation
868 * oidislocal: TRUE if oid column (if any) should be marked attislocal
869 * oidinhcount: attinhcount to assign to oid column (if any)
870 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
871 * reloptions: reloptions in Datum form, or (Datum) 0 if none
872 * use_user_acl: TRUE if should look for user-defined default permissions;
873 * if FALSE, relacl is always set NULL
874 * allow_system_table_mods: TRUE to allow creation in system namespaces
876 * Returns the OID of the new relation
877 * --------------------------------
880 heap_create_with_catalog(const char *relname,
888 List *cooked_constraints,
890 bool shared_relation,
893 OnCommitAction oncommit,
896 bool allow_system_table_mods)
898 Relation pg_class_desc;
899 Relation new_rel_desc;
903 Oid new_array_oid = InvalidOid;
905 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
910 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
912 CheckAttributeNamesTypes(tupdesc, relkind);
914 if (get_relname_relid(relname, relnamespace))
916 (errcode(ERRCODE_DUPLICATE_TABLE),
917 errmsg("relation \"%s\" already exists", relname)));
920 * Since we are going to create a rowtype as well, also check for
921 * collision with an existing type name. If there is one and it's an
922 * autogenerated array, we can rename it out of the way; otherwise we can
923 * at least give a good error message.
925 old_type_oid = GetSysCacheOid(TYPENAMENSP,
926 CStringGetDatum(relname),
927 ObjectIdGetDatum(relnamespace),
929 if (OidIsValid(old_type_oid))
931 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
933 (errcode(ERRCODE_DUPLICATE_OBJECT),
934 errmsg("type \"%s\" already exists", relname),
935 errhint("A relation has an associated type of the same name, "
936 "so you must use a name that doesn't conflict "
937 "with any existing type.")));
941 * Validate shared/non-shared tablespace (must check this before doing
942 * GetNewRelFileNode, to prevent Assert therein)
946 if (reltablespace != GLOBALTABLESPACE_OID)
947 /* elog since this is not a user-facing error */
949 "shared relations must be placed in pg_global tablespace");
953 if (reltablespace == GLOBALTABLESPACE_OID)
955 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
956 errmsg("only shared relations can be placed in pg_global tablespace")));
960 * Allocate an OID for the relation, unless we were told what to use.
962 * The OID will be the relfilenode as well, so make sure it doesn't
963 * collide with either pg_class OIDs or existing physical files.
965 if (!OidIsValid(relid))
967 /* Use binary-upgrade overrides if applicable */
968 if (OidIsValid(binary_upgrade_next_heap_relfilenode) &&
969 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
970 relkind == RELKIND_VIEW || relkind == RELKIND_COMPOSITE_TYPE))
972 relid = binary_upgrade_next_heap_relfilenode;
973 binary_upgrade_next_heap_relfilenode = InvalidOid;
975 else if (OidIsValid(binary_upgrade_next_toast_relfilenode) &&
976 relkind == RELKIND_TOASTVALUE)
978 relid = binary_upgrade_next_toast_relfilenode;
979 binary_upgrade_next_toast_relfilenode = InvalidOid;
982 relid = GetNewRelFileNode(reltablespace, shared_relation,
987 * Determine the relation's initial permissions.
993 case RELKIND_RELATION:
995 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
998 case RELKIND_SEQUENCE:
999 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1011 * Create the relcache entry (mostly dummy at this point) and the physical
1012 * disk file. (If we fail further down, it's the smgr's responsibility to
1013 * remove the disk file again.)
1015 new_rel_desc = heap_create(relname,
1022 allow_system_table_mods);
1024 Assert(relid == RelationGetRelid(new_rel_desc));
1027 * Decide whether to create an array type over the relation's rowtype. We
1028 * do not create any array types for system catalogs (ie, those made
1029 * during initdb). We create array types for regular relations, views,
1030 * and composite types ... but not, eg, for toast tables or sequences.
1032 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1033 relkind == RELKIND_VIEW ||
1034 relkind == RELKIND_COMPOSITE_TYPE))
1035 new_array_oid = AssignTypeArrayOid();
1038 * Since defining a relation also defines a complex type, we add a new
1039 * system type corresponding to the new relation. The OID of the type
1040 * can be preselected by the caller, but if reltypeid is InvalidOid,
1041 * we'll generate a new OID for it.
1043 * NOTE: we could get a unique-index failure here, in case someone else is
1044 * creating the same type name in parallel but hadn't committed yet when
1045 * we checked for a duplicate name above.
1047 new_type_oid = AddNewRelationType(relname,
1056 * Now make the array type if wanted.
1058 if (OidIsValid(new_array_oid))
1062 relarrayname = makeArrayTypeName(relname, relnamespace);
1064 TypeCreate(new_array_oid, /* force the type's OID to this */
1065 relarrayname, /* Array type name */
1066 relnamespace, /* Same namespace as parent */
1067 InvalidOid, /* Not composite, no relationOid */
1068 0, /* relkind, also N/A here */
1069 ownerid, /* owner's ID */
1070 -1, /* Internal size (varlena) */
1071 TYPTYPE_BASE, /* Not composite - typelem is */
1072 TYPCATEGORY_ARRAY, /* type-category (array) */
1073 false, /* array types are never preferred */
1074 DEFAULT_TYPDELIM, /* default array delimiter */
1075 F_ARRAY_IN, /* array input proc */
1076 F_ARRAY_OUT, /* array output proc */
1077 F_ARRAY_RECV, /* array recv (bin) proc */
1078 F_ARRAY_SEND, /* array send (bin) proc */
1079 InvalidOid, /* typmodin procedure - none */
1080 InvalidOid, /* typmodout procedure - none */
1081 InvalidOid, /* analyze procedure - default */
1082 new_type_oid, /* array element type - the rowtype */
1083 true, /* yes, this is an array type */
1084 InvalidOid, /* this has no array type */
1085 InvalidOid, /* domain base type - irrelevant */
1086 NULL, /* default value - none */
1087 NULL, /* default binary representation */
1088 false, /* passed by reference */
1089 'd', /* alignment - must be the largest! */
1090 'x', /* fully TOASTable */
1092 0, /* array dimensions for typBaseType */
1093 false); /* Type NOT NULL */
1095 pfree(relarrayname);
1099 * now create an entry in pg_class for the relation.
1101 * NOTE: we could get a unique-index failure here, in case someone else is
1102 * creating the same relation name in parallel but hadn't committed yet
1103 * when we checked for a duplicate name above.
1105 AddNewRelationTuple(pg_class_desc,
1112 PointerGetDatum(relacl),
1116 * now add tuples to pg_attribute for the attributes in our new relation.
1118 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1119 oidislocal, oidinhcount);
1122 * Make a dependency link to force the relation to be deleted if its
1123 * namespace is. Also make a dependency link to its owner, as well
1124 * as dependencies for any roles mentioned in the default ACL.
1126 * For composite types, these dependencies are tracked for the pg_type
1127 * entry, so we needn't record them here. Likewise, TOAST tables don't
1128 * need a namespace dependency (they live in a pinned namespace) nor an
1129 * owner dependency (they depend indirectly through the parent table),
1130 * nor should they have any ACL entries.
1132 * Also, skip this in bootstrap mode, since we don't make dependencies
1133 * while bootstrapping.
1135 if (relkind != RELKIND_COMPOSITE_TYPE &&
1136 relkind != RELKIND_TOASTVALUE &&
1137 !IsBootstrapProcessingMode())
1139 ObjectAddress myself,
1142 myself.classId = RelationRelationId;
1143 myself.objectId = relid;
1144 myself.objectSubId = 0;
1145 referenced.classId = NamespaceRelationId;
1146 referenced.objectId = relnamespace;
1147 referenced.objectSubId = 0;
1148 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1150 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1154 referenced.classId = TypeRelationId;
1155 referenced.objectId = reloftypeid;
1156 referenced.objectSubId = 0;
1157 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1165 nnewmembers = aclmembers(relacl, &newmembers);
1166 updateAclDependencies(RelationRelationId, relid, 0,
1169 nnewmembers, newmembers);
1174 * Store any supplied constraints and defaults.
1176 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1177 * entry, so the relation must be valid and self-consistent at this point.
1178 * In particular, there are not yet constraints and defaults anywhere.
1180 StoreConstraints(new_rel_desc, cooked_constraints);
1183 * If there's a special on-commit action, remember it
1185 if (oncommit != ONCOMMIT_NOOP)
1186 register_on_commit_action(relid, oncommit);
1189 * ok, the relation has been cataloged, so close our relations and return
1190 * the OID of the newly created relation.
1192 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1193 heap_close(pg_class_desc, RowExclusiveLock);
1200 * RelationRemoveInheritance
1202 * Formerly, this routine checked for child relations and aborted the
1203 * deletion if any were found. Now we rely on the dependency mechanism
1204 * to check for or delete child relations. By the time we get here,
1205 * there are no children and we need only remove any pg_inherits rows
1206 * linking this relation to its parent(s).
1209 RelationRemoveInheritance(Oid relid)
1211 Relation catalogRelation;
1216 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1219 Anum_pg_inherits_inhrelid,
1220 BTEqualStrategyNumber, F_OIDEQ,
1221 ObjectIdGetDatum(relid));
1223 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1224 SnapshotNow, 1, &key);
1226 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1227 simple_heap_delete(catalogRelation, &tuple->t_self);
1229 systable_endscan(scan);
1230 heap_close(catalogRelation, RowExclusiveLock);
1234 * DeleteRelationTuple
1236 * Remove pg_class row for the given relid.
1238 * Note: this is shared by relation deletion and index deletion. It's
1239 * not intended for use anyplace else.
1242 DeleteRelationTuple(Oid relid)
1244 Relation pg_class_desc;
1247 /* Grab an appropriate lock on the pg_class relation */
1248 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1250 tup = SearchSysCache(RELOID,
1251 ObjectIdGetDatum(relid),
1253 if (!HeapTupleIsValid(tup))
1254 elog(ERROR, "cache lookup failed for relation %u", relid);
1256 /* delete the relation tuple from pg_class, and finish up */
1257 simple_heap_delete(pg_class_desc, &tup->t_self);
1259 ReleaseSysCache(tup);
1261 heap_close(pg_class_desc, RowExclusiveLock);
1265 * DeleteAttributeTuples
1267 * Remove pg_attribute rows for the given relid.
1269 * Note: this is shared by relation deletion and index deletion. It's
1270 * not intended for use anyplace else.
1273 DeleteAttributeTuples(Oid relid)
1280 /* Grab an appropriate lock on the pg_attribute relation */
1281 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1283 /* Use the index to scan only attributes of the target relation */
1284 ScanKeyInit(&key[0],
1285 Anum_pg_attribute_attrelid,
1286 BTEqualStrategyNumber, F_OIDEQ,
1287 ObjectIdGetDatum(relid));
1289 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1290 SnapshotNow, 1, key);
1292 /* Delete all the matching tuples */
1293 while ((atttup = systable_getnext(scan)) != NULL)
1294 simple_heap_delete(attrel, &atttup->t_self);
1296 /* Clean up after the scan */
1297 systable_endscan(scan);
1298 heap_close(attrel, RowExclusiveLock);
1302 * RemoveAttributeById
1304 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1305 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1306 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1307 * is handled by dependency.c.)
1310 RemoveAttributeById(Oid relid, AttrNumber attnum)
1315 Form_pg_attribute attStruct;
1316 char newattname[NAMEDATALEN];
1319 * Grab an exclusive lock on the target table, which we will NOT release
1320 * until end of transaction. (In the simple case where we are directly
1321 * dropping this column, AlterTableDropColumn already did this ... but
1322 * when cascading from a drop of some other object, we may not have any
1325 rel = relation_open(relid, AccessExclusiveLock);
1327 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1329 tuple = SearchSysCacheCopy(ATTNUM,
1330 ObjectIdGetDatum(relid),
1331 Int16GetDatum(attnum),
1333 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1334 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1336 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1340 /* System attribute (probably OID) ... just delete the row */
1342 simple_heap_delete(attr_rel, &tuple->t_self);
1346 /* Dropping user attributes is lots harder */
1348 /* Mark the attribute as dropped */
1349 attStruct->attisdropped = true;
1352 * Set the type OID to invalid. A dropped attribute's type link
1353 * cannot be relied on (once the attribute is dropped, the type might
1354 * be too). Fortunately we do not need the type row --- the only
1355 * really essential information is the type's typlen and typalign,
1356 * which are preserved in the attribute's attlen and attalign. We set
1357 * atttypid to zero here as a means of catching code that incorrectly
1358 * expects it to be valid.
1360 attStruct->atttypid = InvalidOid;
1362 /* Remove any NOT NULL constraint the column may have */
1363 attStruct->attnotnull = false;
1365 /* We don't want to keep stats for it anymore */
1366 attStruct->attstattarget = 0;
1369 * Change the column name to something that isn't likely to conflict
1371 snprintf(newattname, sizeof(newattname),
1372 "........pg.dropped.%d........", attnum);
1373 namestrcpy(&(attStruct->attname), newattname);
1375 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1377 /* keep the system catalog indexes current */
1378 CatalogUpdateIndexes(attr_rel, tuple);
1382 * Because updating the pg_attribute row will trigger a relcache flush for
1383 * the target relation, we need not do anything else to notify other
1384 * backends of the change.
1387 heap_close(attr_rel, RowExclusiveLock);
1390 RemoveStatistics(relid, attnum);
1392 relation_close(rel, NoLock);
1398 * If the specified relation/attribute has a default, remove it.
1399 * (If no default, raise error if complain is true, else return quietly.)
1402 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1403 DropBehavior behavior, bool complain)
1405 Relation attrdef_rel;
1406 ScanKeyData scankeys[2];
1411 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1413 ScanKeyInit(&scankeys[0],
1414 Anum_pg_attrdef_adrelid,
1415 BTEqualStrategyNumber, F_OIDEQ,
1416 ObjectIdGetDatum(relid));
1417 ScanKeyInit(&scankeys[1],
1418 Anum_pg_attrdef_adnum,
1419 BTEqualStrategyNumber, F_INT2EQ,
1420 Int16GetDatum(attnum));
1422 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1423 SnapshotNow, 2, scankeys);
1425 /* There should be at most one matching tuple, but we loop anyway */
1426 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1428 ObjectAddress object;
1430 object.classId = AttrDefaultRelationId;
1431 object.objectId = HeapTupleGetOid(tuple);
1432 object.objectSubId = 0;
1434 performDeletion(&object, behavior);
1439 systable_endscan(scan);
1440 heap_close(attrdef_rel, RowExclusiveLock);
1442 if (complain && !found)
1443 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1448 * RemoveAttrDefaultById
1450 * Remove a pg_attrdef entry specified by OID. This is the guts of
1451 * attribute-default removal. Note it should be called via performDeletion,
1455 RemoveAttrDefaultById(Oid attrdefId)
1457 Relation attrdef_rel;
1460 ScanKeyData scankeys[1];
1464 AttrNumber myattnum;
1466 /* Grab an appropriate lock on the pg_attrdef relation */
1467 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1469 /* Find the pg_attrdef tuple */
1470 ScanKeyInit(&scankeys[0],
1471 ObjectIdAttributeNumber,
1472 BTEqualStrategyNumber, F_OIDEQ,
1473 ObjectIdGetDatum(attrdefId));
1475 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1476 SnapshotNow, 1, scankeys);
1478 tuple = systable_getnext(scan);
1479 if (!HeapTupleIsValid(tuple))
1480 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1482 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1483 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1485 /* Get an exclusive lock on the relation owning the attribute */
1486 myrel = relation_open(myrelid, AccessExclusiveLock);
1488 /* Now we can delete the pg_attrdef row */
1489 simple_heap_delete(attrdef_rel, &tuple->t_self);
1491 systable_endscan(scan);
1492 heap_close(attrdef_rel, RowExclusiveLock);
1494 /* Fix the pg_attribute row */
1495 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1497 tuple = SearchSysCacheCopy(ATTNUM,
1498 ObjectIdGetDatum(myrelid),
1499 Int16GetDatum(myattnum),
1501 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1502 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1505 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1507 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1509 /* keep the system catalog indexes current */
1510 CatalogUpdateIndexes(attr_rel, tuple);
1513 * Our update of the pg_attribute row will force a relcache rebuild, so
1514 * there's nothing else to do here.
1516 heap_close(attr_rel, RowExclusiveLock);
1518 /* Keep lock on attribute's rel until end of xact */
1519 relation_close(myrel, NoLock);
1523 * heap_drop_with_catalog - removes specified relation from catalogs
1525 * Note that this routine is not responsible for dropping objects that are
1526 * linked to the pg_class entry via dependencies (for example, indexes and
1527 * constraints). Those are deleted by the dependency-tracing logic in
1528 * dependency.c before control gets here. In general, therefore, this routine
1529 * should never be called directly; go through performDeletion() instead.
1532 heap_drop_with_catalog(Oid relid)
1537 * Open and lock the relation.
1539 rel = relation_open(relid, AccessExclusiveLock);
1542 * There can no longer be anyone *else* touching the relation, but we
1543 * might still have open queries or cursors in our own session.
1545 if (rel->rd_refcnt != 1)
1547 (errcode(ERRCODE_OBJECT_IN_USE),
1548 errmsg("cannot drop \"%s\" because "
1549 "it is being used by active queries in this session",
1550 RelationGetRelationName(rel))));
1553 * Schedule unlinking of the relation's physical files at commit.
1555 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1556 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1558 RelationDropStorage(rel);
1562 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1563 * until transaction commit. This ensures no one else will try to do
1564 * something with the doomed relation.
1566 relation_close(rel, NoLock);
1569 * Forget any ON COMMIT action for the rel
1571 remove_on_commit_action(relid);
1574 * Flush the relation from the relcache. We want to do this before
1575 * starting to remove catalog entries, just to be certain that no relcache
1576 * entry rebuild will happen partway through. (That should not really
1577 * matter, since we don't do CommandCounterIncrement here, but let's be
1580 RelationForgetRelation(relid);
1583 * remove inheritance information
1585 RelationRemoveInheritance(relid);
1590 RemoveStatistics(relid, 0);
1593 * delete attribute tuples
1595 DeleteAttributeTuples(relid);
1598 * delete relation tuple
1600 DeleteRelationTuple(relid);
1605 * Store a default expression for column attnum of relation rel.
1608 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1615 static bool nulls[4] = {false, false, false, false};
1618 Form_pg_attribute attStruct;
1620 ObjectAddress colobject,
1624 * Flatten expression to string form for storage.
1626 adbin = nodeToString(expr);
1629 * Also deparse it to form the mostly-obsolete adsrc field.
1631 adsrc = deparse_expression(expr,
1632 deparse_context_for(RelationGetRelationName(rel),
1633 RelationGetRelid(rel)),
1637 * Make the pg_attrdef entry.
1639 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1640 values[Anum_pg_attrdef_adnum - 1] = attnum;
1641 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1642 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1644 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1646 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1647 attrdefOid = simple_heap_insert(adrel, tuple);
1649 CatalogUpdateIndexes(adrel, tuple);
1651 defobject.classId = AttrDefaultRelationId;
1652 defobject.objectId = attrdefOid;
1653 defobject.objectSubId = 0;
1655 heap_close(adrel, RowExclusiveLock);
1657 /* now can free some of the stuff allocated above */
1658 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1659 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1660 heap_freetuple(tuple);
1665 * Update the pg_attribute entry for the column to show that a default
1668 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1669 atttup = SearchSysCacheCopy(ATTNUM,
1670 ObjectIdGetDatum(RelationGetRelid(rel)),
1671 Int16GetDatum(attnum),
1673 if (!HeapTupleIsValid(atttup))
1674 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1675 attnum, RelationGetRelid(rel));
1676 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1677 if (!attStruct->atthasdef)
1679 attStruct->atthasdef = true;
1680 simple_heap_update(attrrel, &atttup->t_self, atttup);
1681 /* keep catalog indexes current */
1682 CatalogUpdateIndexes(attrrel, atttup);
1684 heap_close(attrrel, RowExclusiveLock);
1685 heap_freetuple(atttup);
1688 * Make a dependency so that the pg_attrdef entry goes away if the column
1689 * (or whole table) is deleted.
1691 colobject.classId = RelationRelationId;
1692 colobject.objectId = RelationGetRelid(rel);
1693 colobject.objectSubId = attnum;
1695 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1698 * Record dependencies on objects used in the expression, too.
1700 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1704 * Store a check-constraint expression for the given relation.
1706 * Caller is responsible for updating the count of constraints
1707 * in the pg_class entry for the relation.
1710 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1711 bool is_local, int inhcount)
1720 * Flatten expression to string form for storage.
1722 ccbin = nodeToString(expr);
1725 * Also deparse it to form the mostly-obsolete consrc field.
1727 ccsrc = deparse_expression(expr,
1728 deparse_context_for(RelationGetRelationName(rel),
1729 RelationGetRelid(rel)),
1733 * Find columns of rel that are used in expr
1735 * NB: pull_var_clause is okay here only because we don't allow subselects
1736 * in check constraints; it would fail to examine the contents of
1739 varList = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
1740 keycount = list_length(varList);
1747 attNos = (int16 *) palloc(keycount * sizeof(int16));
1748 foreach(vl, varList)
1750 Var *var = (Var *) lfirst(vl);
1753 for (j = 0; j < i; j++)
1754 if (attNos[j] == var->varattno)
1757 attNos[i++] = var->varattno;
1765 * Create the Check Constraint
1767 CreateConstraintEntry(ccname, /* Constraint Name */
1768 RelationGetNamespace(rel), /* namespace */
1769 CONSTRAINT_CHECK, /* Constraint Type */
1770 false, /* Is Deferrable */
1771 false, /* Is Deferred */
1772 RelationGetRelid(rel), /* relation */
1773 attNos, /* attrs in the constraint */
1774 keycount, /* # attrs in the constraint */
1775 InvalidOid, /* not a domain constraint */
1776 InvalidOid, /* no associated index */
1777 InvalidOid, /* Foreign key fields */
1786 NULL, /* not an exclusion constraint */
1787 expr, /* Tree form of check constraint */
1788 ccbin, /* Binary form of check constraint */
1789 ccsrc, /* Source form of check constraint */
1790 is_local, /* conislocal */
1791 inhcount); /* coninhcount */
1798 * Store defaults and constraints (passed as a list of CookedConstraint).
1800 * NOTE: only pre-cooked expressions will be passed this way, which is to
1801 * say expressions inherited from an existing relation. Newly parsed
1802 * expressions can be added later, by direct calls to StoreAttrDefault
1803 * and StoreRelCheck (see AddRelationNewConstraints()).
1806 StoreConstraints(Relation rel, List *cooked_constraints)
1811 if (!cooked_constraints)
1812 return; /* nothing to do */
1815 * Deparsing of constraint expressions will fail unless the just-created
1816 * pg_attribute tuples for this relation are made visible. So, bump the
1817 * command counter. CAUTION: this will cause a relcache entry rebuild.
1819 CommandCounterIncrement();
1821 foreach(lc, cooked_constraints)
1823 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1825 switch (con->contype)
1827 case CONSTR_DEFAULT:
1828 StoreAttrDefault(rel, con->attnum, con->expr);
1831 StoreRelCheck(rel, con->name, con->expr,
1832 con->is_local, con->inhcount);
1836 elog(ERROR, "unrecognized constraint type: %d",
1837 (int) con->contype);
1842 SetRelationNumChecks(rel, numchecks);
1846 * AddRelationNewConstraints
1848 * Add new column default expressions and/or constraint check expressions
1849 * to an existing relation. This is defined to do both for efficiency in
1850 * DefineRelation, but of course you can do just one or the other by passing
1853 * rel: relation to be modified
1854 * newColDefaults: list of RawColumnDefault structures
1855 * newConstraints: list of Constraint nodes
1856 * allow_merge: TRUE if check constraints may be merged with existing ones
1857 * is_local: TRUE if definition is local, FALSE if it's inherited
1859 * All entries in newColDefaults will be processed. Entries in newConstraints
1860 * will be processed only if they are CONSTR_CHECK type.
1862 * Returns a list of CookedConstraint nodes that shows the cooked form of
1863 * the default and constraint expressions added to the relation.
1865 * NB: caller should have opened rel with AccessExclusiveLock, and should
1866 * hold that lock till end of transaction. Also, we assume the caller has
1867 * done a CommandCounterIncrement if necessary to make the relation's catalog
1871 AddRelationNewConstraints(Relation rel,
1872 List *newColDefaults,
1873 List *newConstraints,
1877 List *cookedConstraints = NIL;
1878 TupleDesc tupleDesc;
1879 TupleConstr *oldconstr;
1887 CookedConstraint *cooked;
1890 * Get info about existing constraints.
1892 tupleDesc = RelationGetDescr(rel);
1893 oldconstr = tupleDesc->constr;
1895 numoldchecks = oldconstr->num_check;
1900 * Create a dummy ParseState and insert the target relation as its sole
1901 * rangetable entry. We need a ParseState for transformExpr.
1903 pstate = make_parsestate(NULL);
1904 rte = addRangeTableEntryForRelation(pstate,
1909 addRTEtoQuery(pstate, rte, true, true, true);
1912 * Process column default expressions.
1914 foreach(cell, newColDefaults)
1916 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1917 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1919 expr = cookDefault(pstate, colDef->raw_default,
1920 atp->atttypid, atp->atttypmod,
1921 NameStr(atp->attname));
1924 * If the expression is just a NULL constant, we do not bother to make
1925 * an explicit pg_attrdef entry, since the default behavior is
1928 * Note a nonobvious property of this test: if the column is of a
1929 * domain type, what we'll get is not a bare null Const but a
1930 * CoerceToDomain expr, so we will not discard the default. This is
1931 * critical because the column default needs to be retained to
1932 * override any default that the domain might have.
1935 (IsA(expr, Const) &&((Const *) expr)->constisnull))
1938 StoreAttrDefault(rel, colDef->attnum, expr);
1940 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1941 cooked->contype = CONSTR_DEFAULT;
1942 cooked->name = NULL;
1943 cooked->attnum = colDef->attnum;
1944 cooked->expr = expr;
1945 cooked->is_local = is_local;
1946 cooked->inhcount = is_local ? 0 : 1;
1947 cookedConstraints = lappend(cookedConstraints, cooked);
1951 * Process constraint expressions.
1953 numchecks = numoldchecks;
1955 foreach(cell, newConstraints)
1957 Constraint *cdef = (Constraint *) lfirst(cell);
1960 if (cdef->contype != CONSTR_CHECK)
1963 if (cdef->raw_expr != NULL)
1965 Assert(cdef->cooked_expr == NULL);
1968 * Transform raw parsetree to executable expression, and verify
1969 * it's valid as a CHECK constraint.
1971 expr = cookConstraint(pstate, cdef->raw_expr,
1972 RelationGetRelationName(rel));
1976 Assert(cdef->cooked_expr != NULL);
1979 * Here, we assume the parser will only pass us valid CHECK
1980 * expressions, so we do no particular checking.
1982 expr = stringToNode(cdef->cooked_expr);
1986 * Check name uniqueness, or generate a name if none was given.
1988 if (cdef->conname != NULL)
1992 ccname = cdef->conname;
1993 /* Check against other new constraints */
1994 /* Needed because we don't do CommandCounterIncrement in loop */
1995 foreach(cell2, checknames)
1997 if (strcmp((char *) lfirst(cell2), ccname) == 0)
1999 (errcode(ERRCODE_DUPLICATE_OBJECT),
2000 errmsg("check constraint \"%s\" already exists",
2004 /* save name for future checks */
2005 checknames = lappend(checknames, ccname);
2008 * Check against pre-existing constraints. If we are allowed to
2009 * merge with an existing constraint, there's no more to do here.
2010 * (We omit the duplicate constraint from the result, which is
2011 * what ATAddCheckConstraint wants.)
2013 if (MergeWithExistingConstraint(rel, ccname, expr,
2014 allow_merge, is_local))
2020 * When generating a name, we want to create "tab_col_check" for a
2021 * column constraint and "tab_check" for a table constraint. We
2022 * no longer have any info about the syntactic positioning of the
2023 * constraint phrase, so we approximate this by seeing whether the
2024 * expression references more than one column. (If the user
2025 * played by the rules, the result is the same...)
2027 * Note: pull_var_clause() doesn't descend into sublinks, but we
2028 * eliminated those above; and anyway this only needs to be an
2029 * approximate answer.
2034 vars = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
2036 /* eliminate duplicates */
2037 vars = list_union(NIL, vars);
2039 if (list_length(vars) == 1)
2040 colname = get_attname(RelationGetRelid(rel),
2041 ((Var *) linitial(vars))->varattno);
2045 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2048 RelationGetNamespace(rel),
2051 /* save name for future checks */
2052 checknames = lappend(checknames, ccname);
2058 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
2062 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2063 cooked->contype = CONSTR_CHECK;
2064 cooked->name = ccname;
2066 cooked->expr = expr;
2067 cooked->is_local = is_local;
2068 cooked->inhcount = is_local ? 0 : 1;
2069 cookedConstraints = lappend(cookedConstraints, cooked);
2073 * Update the count of constraints in the relation's pg_class tuple. We do
2074 * this even if there was no change, in order to ensure that an SI update
2075 * message is sent out for the pg_class tuple, which will force other
2076 * backends to rebuild their relcache entries for the rel. (This is
2077 * critical if we added defaults but not constraints.)
2079 SetRelationNumChecks(rel, numchecks);
2081 return cookedConstraints;
2085 * Check for a pre-existing check constraint that conflicts with a proposed
2086 * new one, and either adjust its conislocal/coninhcount settings or throw
2089 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2090 * got a so-far-unique name, or throws error if conflict.
2093 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2094 bool allow_merge, bool is_local)
2098 SysScanDesc conscan;
2099 ScanKeyData skey[2];
2102 /* Search for a pg_constraint entry with same name and relation */
2103 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2107 ScanKeyInit(&skey[0],
2108 Anum_pg_constraint_conname,
2109 BTEqualStrategyNumber, F_NAMEEQ,
2110 CStringGetDatum(ccname));
2112 ScanKeyInit(&skey[1],
2113 Anum_pg_constraint_connamespace,
2114 BTEqualStrategyNumber, F_OIDEQ,
2115 ObjectIdGetDatum(RelationGetNamespace(rel)));
2117 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2118 SnapshotNow, 2, skey);
2120 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2122 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2124 if (con->conrelid == RelationGetRelid(rel))
2126 /* Found it. Conflicts if not identical check constraint */
2127 if (con->contype == CONSTRAINT_CHECK)
2132 val = fastgetattr(tup,
2133 Anum_pg_constraint_conbin,
2134 conDesc->rd_att, &isnull);
2136 elog(ERROR, "null conbin for rel %s",
2137 RelationGetRelationName(rel));
2138 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2141 if (!found || !allow_merge)
2143 (errcode(ERRCODE_DUPLICATE_OBJECT),
2144 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2145 ccname, RelationGetRelationName(rel))));
2146 /* OK to update the tuple */
2148 (errmsg("merging constraint \"%s\" with inherited definition",
2150 tup = heap_copytuple(tup);
2151 con = (Form_pg_constraint) GETSTRUCT(tup);
2153 con->conislocal = true;
2156 simple_heap_update(conDesc, &tup->t_self, tup);
2157 CatalogUpdateIndexes(conDesc, tup);
2162 systable_endscan(conscan);
2163 heap_close(conDesc, RowExclusiveLock);
2169 * Update the count of constraints in the relation's pg_class tuple.
2171 * Caller had better hold exclusive lock on the relation.
2173 * An important side effect is that a SI update message will be sent out for
2174 * the pg_class tuple, which will force other backends to rebuild their
2175 * relcache entries for the rel. Also, this backend will rebuild its
2176 * own relcache entry at the next CommandCounterIncrement.
2179 SetRelationNumChecks(Relation rel, int numchecks)
2183 Form_pg_class relStruct;
2185 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2186 reltup = SearchSysCacheCopy(RELOID,
2187 ObjectIdGetDatum(RelationGetRelid(rel)),
2189 if (!HeapTupleIsValid(reltup))
2190 elog(ERROR, "cache lookup failed for relation %u",
2191 RelationGetRelid(rel));
2192 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2194 if (relStruct->relchecks != numchecks)
2196 relStruct->relchecks = numchecks;
2198 simple_heap_update(relrel, &reltup->t_self, reltup);
2200 /* keep catalog indexes current */
2201 CatalogUpdateIndexes(relrel, reltup);
2205 /* Skip the disk update, but force relcache inval anyway */
2206 CacheInvalidateRelcache(rel);
2209 heap_freetuple(reltup);
2210 heap_close(relrel, RowExclusiveLock);
2214 * Take a raw default and convert it to a cooked format ready for
2217 * Parse state should be set up to recognize any vars that might appear
2218 * in the expression. (Even though we plan to reject vars, it's more
2219 * user-friendly to give the correct error message than "unknown var".)
2221 * If atttypid is not InvalidOid, coerce the expression to the specified
2222 * type (and typmod atttypmod). attname is only needed in this case:
2223 * it is used in the error message, if any.
2226 cookDefault(ParseState *pstate,
2234 Assert(raw_default != NULL);
2237 * Transform raw parsetree to executable expression.
2239 expr = transformExpr(pstate, raw_default);
2242 * Make sure default expr does not refer to any vars.
2244 if (contain_var_clause(expr))
2246 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2247 errmsg("cannot use column references in default expression")));
2250 * It can't return a set either.
2252 if (expression_returns_set(expr))
2254 (errcode(ERRCODE_DATATYPE_MISMATCH),
2255 errmsg("default expression must not return a set")));
2258 * No subplans or aggregates, either...
2260 if (pstate->p_hasSubLinks)
2262 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2263 errmsg("cannot use subquery in default expression")));
2264 if (pstate->p_hasAggs)
2266 (errcode(ERRCODE_GROUPING_ERROR),
2267 errmsg("cannot use aggregate function in default expression")));
2268 if (pstate->p_hasWindowFuncs)
2270 (errcode(ERRCODE_WINDOWING_ERROR),
2271 errmsg("cannot use window function in default expression")));
2274 * Coerce the expression to the correct type and typmod, if given. This
2275 * should match the parser's processing of non-defaulted expressions ---
2276 * see transformAssignedExpr().
2278 if (OidIsValid(atttypid))
2280 Oid type_id = exprType(expr);
2282 expr = coerce_to_target_type(pstate, expr, type_id,
2283 atttypid, atttypmod,
2284 COERCION_ASSIGNMENT,
2285 COERCE_IMPLICIT_CAST,
2289 (errcode(ERRCODE_DATATYPE_MISMATCH),
2290 errmsg("column \"%s\" is of type %s"
2291 " but default expression is of type %s",
2293 format_type_be(atttypid),
2294 format_type_be(type_id)),
2295 errhint("You will need to rewrite or cast the expression.")));
2302 * Take a raw CHECK constraint expression and convert it to a cooked format
2303 * ready for storage.
2305 * Parse state must be set up to recognize any vars that might appear
2306 * in the expression.
2309 cookConstraint(ParseState *pstate,
2310 Node *raw_constraint,
2316 * Transform raw parsetree to executable expression.
2318 expr = transformExpr(pstate, raw_constraint);
2321 * Make sure it yields a boolean result.
2323 expr = coerce_to_boolean(pstate, expr, "CHECK");
2326 * Make sure no outside relations are referred to.
2328 if (list_length(pstate->p_rtable) != 1)
2330 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2331 errmsg("only table \"%s\" can be referenced in check constraint",
2335 * No subplans or aggregates, either...
2337 if (pstate->p_hasSubLinks)
2339 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2340 errmsg("cannot use subquery in check constraint")));
2341 if (pstate->p_hasAggs)
2343 (errcode(ERRCODE_GROUPING_ERROR),
2344 errmsg("cannot use aggregate function in check constraint")));
2345 if (pstate->p_hasWindowFuncs)
2347 (errcode(ERRCODE_WINDOWING_ERROR),
2348 errmsg("cannot use window function in check constraint")));
2355 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2357 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2361 RemoveStatistics(Oid relid, AttrNumber attnum)
2363 Relation pgstatistic;
2369 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2371 ScanKeyInit(&key[0],
2372 Anum_pg_statistic_starelid,
2373 BTEqualStrategyNumber, F_OIDEQ,
2374 ObjectIdGetDatum(relid));
2380 ScanKeyInit(&key[1],
2381 Anum_pg_statistic_staattnum,
2382 BTEqualStrategyNumber, F_INT2EQ,
2383 Int16GetDatum(attnum));
2387 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2388 SnapshotNow, nkeys, key);
2390 /* we must loop even when attnum != 0, in case of inherited stats */
2391 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2392 simple_heap_delete(pgstatistic, &tuple->t_self);
2394 systable_endscan(scan);
2396 heap_close(pgstatistic, RowExclusiveLock);
2401 * RelationTruncateIndexes - truncate all indexes associated
2402 * with the heap relation to zero tuples.
2404 * The routine will truncate and then reconstruct the indexes on
2405 * the specified relation. Caller must hold exclusive lock on rel.
2408 RelationTruncateIndexes(Relation heapRelation)
2412 /* Ask the relcache to produce a list of the indexes of the rel */
2413 foreach(indlist, RelationGetIndexList(heapRelation))
2415 Oid indexId = lfirst_oid(indlist);
2416 Relation currentIndex;
2417 IndexInfo *indexInfo;
2419 /* Open the index relation; use exclusive lock, just to be sure */
2420 currentIndex = index_open(indexId, AccessExclusiveLock);
2422 /* Fetch info needed for index_build */
2423 indexInfo = BuildIndexInfo(currentIndex);
2426 * Now truncate the actual file (and discard buffers).
2428 RelationTruncate(currentIndex, 0);
2430 /* Initialize the index and rebuild */
2431 /* Note: we do not need to re-establish pkey setting */
2432 index_build(heapRelation, currentIndex, indexInfo, false);
2434 /* We're done with this index */
2435 index_close(currentIndex, NoLock);
2442 * This routine deletes all data within all the specified relations.
2444 * This is not transaction-safe! There is another, transaction-safe
2445 * implementation in commands/tablecmds.c. We now use this only for
2446 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2449 heap_truncate(List *relids)
2451 List *relations = NIL;
2454 /* Open relations for processing, and grab exclusive access on each */
2455 foreach(cell, relids)
2457 Oid rid = lfirst_oid(cell);
2460 rel = heap_open(rid, AccessExclusiveLock);
2461 relations = lappend(relations, rel);
2464 /* Don't allow truncate on tables that are referenced by foreign keys */
2465 heap_truncate_check_FKs(relations, true);
2468 foreach(cell, relations)
2470 Relation rel = lfirst(cell);
2472 /* Truncate the relation */
2473 heap_truncate_one_rel(rel);
2475 /* Close the relation, but keep exclusive lock on it until commit */
2476 heap_close(rel, NoLock);
2481 * heap_truncate_one_rel
2483 * This routine deletes all data within the specified relation.
2485 * This is not transaction-safe, because the truncation is done immediately
2486 * and cannot be rolled back later. Caller is responsible for having
2487 * checked permissions etc, and must have obtained AccessExclusiveLock.
2490 heap_truncate_one_rel(Relation rel)
2494 /* Truncate the actual file (and discard buffers) */
2495 RelationTruncate(rel, 0);
2497 /* If the relation has indexes, truncate the indexes too */
2498 RelationTruncateIndexes(rel);
2500 /* If there is a toast table, truncate that too */
2501 toastrelid = rel->rd_rel->reltoastrelid;
2502 if (OidIsValid(toastrelid))
2504 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2506 RelationTruncate(toastrel, 0);
2507 RelationTruncateIndexes(toastrel);
2508 /* keep the lock... */
2509 heap_close(toastrel, NoLock);
2514 * heap_truncate_check_FKs
2515 * Check for foreign keys referencing a list of relations that
2516 * are to be truncated, and raise error if there are any
2518 * We disallow such FKs (except self-referential ones) since the whole point
2519 * of TRUNCATE is to not scan the individual rows to be thrown away.
2521 * This is split out so it can be shared by both implementations of truncate.
2522 * Caller should already hold a suitable lock on the relations.
2524 * tempTables is only used to select an appropriate error message.
2527 heap_truncate_check_FKs(List *relations, bool tempTables)
2534 * Build a list of OIDs of the interesting relations.
2536 * If a relation has no triggers, then it can neither have FKs nor be
2537 * referenced by a FK from another table, so we can ignore it.
2539 foreach(cell, relations)
2541 Relation rel = lfirst(cell);
2543 if (rel->rd_rel->relhastriggers)
2544 oids = lappend_oid(oids, RelationGetRelid(rel));
2548 * Fast path: if no relation has triggers, none has FKs either.
2554 * Otherwise, must scan pg_constraint. We make one pass with all the
2555 * relations considered; if this finds nothing, then all is well.
2557 dependents = heap_truncate_find_FKs(oids);
2558 if (dependents == NIL)
2562 * Otherwise we repeat the scan once per relation to identify a particular
2563 * pair of relations to complain about. This is pretty slow, but
2564 * performance shouldn't matter much in a failure path. The reason for
2565 * doing things this way is to ensure that the message produced is not
2566 * dependent on chance row locations within pg_constraint.
2570 Oid relid = lfirst_oid(cell);
2573 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2575 foreach(cell2, dependents)
2577 Oid relid2 = lfirst_oid(cell2);
2579 if (!list_member_oid(oids, relid2))
2581 char *relname = get_rel_name(relid);
2582 char *relname2 = get_rel_name(relid2);
2586 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2587 errmsg("unsupported ON COMMIT and foreign key combination"),
2588 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2589 relname2, relname)));
2592 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2593 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2594 errdetail("Table \"%s\" references \"%s\".",
2596 errhint("Truncate table \"%s\" at the same time, "
2597 "or use TRUNCATE ... CASCADE.",
2605 * heap_truncate_find_FKs
2606 * Find relations having foreign keys referencing any of the given rels
2608 * Input and result are both lists of relation OIDs. The result contains
2609 * no duplicates, does *not* include any rels that were already in the input
2610 * list, and is sorted in OID order. (The last property is enforced mainly
2611 * to guarantee consistent behavior in the regression tests; we don't want
2612 * behavior to change depending on chance locations of rows in pg_constraint.)
2614 * Note: caller should already have appropriate lock on all rels mentioned
2615 * in relationIds. Since adding or dropping an FK requires exclusive lock
2616 * on both rels, this ensures that the answer will be stable.
2619 heap_truncate_find_FKs(List *relationIds)
2623 SysScanDesc fkeyScan;
2627 * Must scan pg_constraint. Right now, it is a seqscan because there is
2628 * no available index on confrelid.
2630 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2632 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2633 SnapshotNow, 0, NULL);
2635 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2637 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2639 /* Not a foreign key */
2640 if (con->contype != CONSTRAINT_FOREIGN)
2643 /* Not referencing one of our list of tables */
2644 if (!list_member_oid(relationIds, con->confrelid))
2647 /* Add referencer unless already in input or result list */
2648 if (!list_member_oid(relationIds, con->conrelid))
2649 result = insert_ordered_unique_oid(result, con->conrelid);
2652 systable_endscan(fkeyScan);
2653 heap_close(fkeyRel, AccessShareLock);
2659 * insert_ordered_unique_oid
2660 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2661 * and eliminating duplicates
2663 * Building the ordered list this way is O(N^2), but with a pretty small
2664 * constant, so for the number of entries we expect it will probably be
2665 * faster than trying to apply qsort(). It seems unlikely someone would be
2666 * trying to truncate a table with thousands of dependent tables ...
2669 insert_ordered_unique_oid(List *list, Oid datum)
2673 /* Does the datum belong at the front? */
2674 if (list == NIL || datum < linitial_oid(list))
2675 return lcons_oid(datum, list);
2676 /* Does it match the first entry? */
2677 if (datum == linitial_oid(list))
2678 return list; /* duplicate, so don't insert */
2679 /* No, so find the entry it belongs after */
2680 prev = list_head(list);
2683 ListCell *curr = lnext(prev);
2685 if (curr == NULL || datum < lfirst_oid(curr))
2686 break; /* it belongs after 'prev', before 'curr' */
2688 if (datum == lfirst_oid(curr))
2689 return list; /* duplicate, so don't insert */
2693 /* Insert datum into list after 'prev' */
2694 lappend_cell_oid(list, prev, datum);