1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.314 2006/11/05 22:42:08 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/transam.h"
35 #include "access/xact.h"
36 #include "catalog/catalog.h"
37 #include "catalog/dependency.h"
38 #include "catalog/heap.h"
39 #include "catalog/index.h"
40 #include "catalog/indexing.h"
41 #include "catalog/pg_attrdef.h"
42 #include "catalog/pg_constraint.h"
43 #include "catalog/pg_inherits.h"
44 #include "catalog/pg_namespace.h"
45 #include "catalog/pg_statistic.h"
46 #include "catalog/pg_type.h"
47 #include "commands/tablecmds.h"
48 #include "miscadmin.h"
49 #include "optimizer/clauses.h"
50 #include "optimizer/var.h"
51 #include "parser/parse_coerce.h"
52 #include "parser/parse_expr.h"
53 #include "parser/parse_relation.h"
54 #include "storage/smgr.h"
55 #include "utils/builtins.h"
56 #include "utils/fmgroids.h"
57 #include "utils/inval.h"
58 #include "utils/lsyscache.h"
59 #include "utils/relcache.h"
60 #include "utils/syscache.h"
63 static void AddNewRelationTuple(Relation pg_class_desc,
64 Relation new_rel_desc,
65 Oid new_rel_oid, Oid new_type_oid,
69 static Oid AddNewRelationType(const char *typeName,
73 static void RelationRemoveInheritance(Oid relid);
74 static void StoreRelCheck(Relation rel, char *ccname, char *ccbin);
75 static void StoreConstraints(Relation rel, TupleDesc tupdesc);
76 static void SetRelationNumChecks(Relation rel, int numchecks);
77 static List *insert_ordered_unique_oid(List *list, Oid datum);
80 /* ----------------------------------------------------------------
81 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
83 * these should all be moved to someplace in the lib/catalog
84 * module, if not obliterated first.
85 * ----------------------------------------------------------------
91 * Should the system special case these attributes in the future?
92 * Advantage: consume much less space in the ATTRIBUTE relation.
93 * Disadvantage: special cases will be all over the place.
96 static FormData_pg_attribute a1 = {
97 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
98 SelfItemPointerAttributeNumber, 0, -1, -1,
99 false, 'p', 's', true, false, false, true, 0
102 static FormData_pg_attribute a2 = {
103 0, {"oid"}, OIDOID, 0, sizeof(Oid),
104 ObjectIdAttributeNumber, 0, -1, -1,
105 true, 'p', 'i', true, false, false, true, 0
108 static FormData_pg_attribute a3 = {
109 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
110 MinTransactionIdAttributeNumber, 0, -1, -1,
111 true, 'p', 'i', true, false, false, true, 0
114 static FormData_pg_attribute a4 = {
115 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
116 MinCommandIdAttributeNumber, 0, -1, -1,
117 true, 'p', 'i', true, false, false, true, 0
120 static FormData_pg_attribute a5 = {
121 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
122 MaxTransactionIdAttributeNumber, 0, -1, -1,
123 true, 'p', 'i', true, false, false, true, 0
126 static FormData_pg_attribute a6 = {
127 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
128 MaxCommandIdAttributeNumber, 0, -1, -1,
129 true, 'p', 'i', true, false, false, true, 0
133 * We decided to call this attribute "tableoid" rather than say
134 * "classoid" on the basis that in the future there may be more than one
135 * table of a particular class/type. In any case table is still the word
138 static FormData_pg_attribute a7 = {
139 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
140 TableOidAttributeNumber, 0, -1, -1,
141 true, 'p', 'i', true, false, false, true, 0
144 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
147 * This function returns a Form_pg_attribute pointer for a system attribute.
148 * Note that we elog if the presented attno is invalid, which would only
149 * happen if there's a problem upstream.
152 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
154 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
155 elog(ERROR, "invalid system attribute number %d", attno);
156 if (attno == ObjectIdAttributeNumber && !relhasoids)
157 elog(ERROR, "invalid system attribute number %d", attno);
158 return SysAtt[-attno - 1];
162 * If the given name is a system attribute name, return a Form_pg_attribute
163 * pointer for a prototype definition. If not, return NULL.
166 SystemAttributeByName(const char *attname, bool relhasoids)
170 for (j = 0; j < (int) lengthof(SysAtt); j++)
172 Form_pg_attribute att = SysAtt[j];
174 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
176 if (strcmp(NameStr(att->attname), attname) == 0)
185 /* ----------------------------------------------------------------
186 * XXX END OF UGLY HARD CODED BADNESS XXX
187 * ---------------------------------------------------------------- */
190 /* ----------------------------------------------------------------
191 * heap_create - Create an uncataloged heap relation
193 * Note API change: the caller must now always provide the OID
194 * to use for the relation.
196 * rel->rd_rel is initialized by RelationBuildLocalRelation,
197 * and is mostly zeroes at return.
198 * ----------------------------------------------------------------
201 heap_create(const char *relname,
207 bool shared_relation,
208 bool allow_system_table_mods)
213 /* The caller must have provided an OID for the relation. */
214 Assert(OidIsValid(relid));
219 if (!allow_system_table_mods &&
220 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
221 IsNormalProcessingMode())
223 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
224 errmsg("permission denied to create \"%s.%s\"",
225 get_namespace_name(relnamespace), relname),
226 errdetail("System catalog modifications are currently disallowed.")));
229 * Decide if we need storage or not, and handle a couple other special
230 * cases for particular relkinds.
235 case RELKIND_COMPOSITE_TYPE:
236 create_storage = false;
239 * Force reltablespace to zero if the relation has no physical
240 * storage. This is mainly just for cleanliness' sake.
242 reltablespace = InvalidOid;
244 case RELKIND_SEQUENCE:
245 create_storage = true;
248 * Force reltablespace to zero for sequences, since we don't
249 * support moving them around into different tablespaces.
251 reltablespace = InvalidOid;
254 create_storage = true;
259 * Never allow a pg_class entry to explicitly specify the database's
260 * default tablespace in reltablespace; force it to zero instead. This
261 * ensures that if the database is cloned with a different default
262 * tablespace, the pg_class entry will still match where CREATE DATABASE
263 * will put the physically copied relation.
265 * Yes, this is a bit of a hack.
267 if (reltablespace == MyDatabaseTableSpace)
268 reltablespace = InvalidOid;
271 * build the relcache entry.
273 rel = RelationBuildLocalRelation(relname,
281 * have the storage manager create the relation's disk file, if needed.
285 Assert(rel->rd_smgr == NULL);
286 RelationOpenSmgr(rel);
287 smgrcreate(rel->rd_smgr, rel->rd_istemp, false);
293 /* ----------------------------------------------------------------
294 * heap_create_with_catalog - Create a cataloged relation
296 * this is done in multiple steps:
298 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
299 * descriptor contains a valid set of attribute names and types
301 * 2) pg_class is opened and get_relname_relid()
302 * performs a scan to ensure that no relation with the
303 * same name already exists.
305 * 3) heap_create() is called to create the new relation on disk.
307 * 4) TypeCreate() is called to define a new type corresponding
308 * to the new relation.
310 * 5) AddNewRelationTuple() is called to register the
311 * relation in pg_class.
313 * 6) AddNewAttributeTuples() is called to register the
314 * new relation's schema in pg_attribute.
316 * 7) StoreConstraints is called () - vadim 08/22/97
318 * 8) the relations are closed and the new relation's oid
321 * ----------------------------------------------------------------
324 /* --------------------------------
325 * CheckAttributeNamesTypes
327 * this is used to make certain the tuple descriptor contains a
328 * valid set of attribute names and datatypes. a problem simply
329 * generates ereport(ERROR) which aborts the current transaction.
330 * --------------------------------
333 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
337 int natts = tupdesc->natts;
339 /* Sanity check on column count */
340 if (natts < 0 || natts > MaxHeapAttributeNumber)
342 (errcode(ERRCODE_TOO_MANY_COLUMNS),
343 errmsg("tables can have at most %d columns",
344 MaxHeapAttributeNumber)));
347 * first check for collision with system attribute names
349 * Skip this for a view or type relation, since those don't have system
352 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
354 for (i = 0; i < natts; i++)
356 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
357 tupdesc->tdhasoid) != NULL)
359 (errcode(ERRCODE_DUPLICATE_COLUMN),
360 errmsg("column name \"%s\" conflicts with a system column name",
361 NameStr(tupdesc->attrs[i]->attname))));
366 * next check for repeated attribute names
368 for (i = 1; i < natts; i++)
370 for (j = 0; j < i; j++)
372 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
373 NameStr(tupdesc->attrs[i]->attname)) == 0)
375 (errcode(ERRCODE_DUPLICATE_COLUMN),
376 errmsg("column name \"%s\" is duplicated",
377 NameStr(tupdesc->attrs[j]->attname))));
382 * next check the attribute types
384 for (i = 0; i < natts; i++)
386 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
387 tupdesc->attrs[i]->atttypid);
391 /* --------------------------------
394 * Verify that the proposed datatype of an attribute is legal.
395 * This is needed because there are types (and pseudo-types)
396 * in the catalogs that we do not support as elements of real tuples.
397 * --------------------------------
400 CheckAttributeType(const char *attname, Oid atttypid)
402 char att_typtype = get_typtype(atttypid);
405 * Warn user, but don't fail, if column to be created has UNKNOWN type
406 * (usually as a result of a 'retrieve into' - jolly)
408 * Refuse any attempt to create a pseudo-type column.
410 if (atttypid == UNKNOWNOID)
412 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
413 errmsg("column \"%s\" has type \"unknown\"", attname),
414 errdetail("Proceeding with relation creation anyway.")));
415 else if (att_typtype == 'p')
417 /* Special hack for pg_statistic: allow ANYARRAY during initdb */
418 if (atttypid != ANYARRAYOID || IsUnderPostmaster)
420 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
421 errmsg("column \"%s\" has pseudo-type %s",
422 attname, format_type_be(atttypid))));
426 /* --------------------------------
427 * AddNewAttributeTuples
429 * this registers the new relation's schema by adding
430 * tuples to pg_attribute.
431 * --------------------------------
434 AddNewAttributeTuples(Oid new_rel_oid,
440 const Form_pg_attribute *dpp;
444 CatalogIndexState indstate;
445 int natts = tupdesc->natts;
446 ObjectAddress myself,
450 * open pg_attribute and its indexes.
452 rel = heap_open(AttributeRelationId, RowExclusiveLock);
454 indstate = CatalogOpenIndexes(rel);
457 * First we add the user attributes. This is also a convenient place to
458 * add dependencies on their datatypes.
460 dpp = tupdesc->attrs;
461 for (i = 0; i < natts; i++)
463 /* Fill in the correct relation OID */
464 (*dpp)->attrelid = new_rel_oid;
465 /* Make sure these are OK, too */
466 (*dpp)->attstattarget = -1;
467 (*dpp)->attcacheoff = -1;
469 tup = heap_addheader(Natts_pg_attribute,
471 ATTRIBUTE_TUPLE_SIZE,
474 simple_heap_insert(rel, tup);
476 CatalogIndexInsert(indstate, tup);
480 myself.classId = RelationRelationId;
481 myself.objectId = new_rel_oid;
482 myself.objectSubId = i + 1;
483 referenced.classId = TypeRelationId;
484 referenced.objectId = (*dpp)->atttypid;
485 referenced.objectSubId = 0;
486 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
492 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
493 * all for a view or type relation. We don't bother with making datatype
494 * dependencies here, since presumably all these types are pinned.
496 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
499 for (i = 0; i < -1 - FirstLowInvalidHeapAttributeNumber; i++)
501 if (tupdesc->tdhasoid ||
502 (*dpp)->attnum != ObjectIdAttributeNumber)
504 Form_pg_attribute attStruct;
506 tup = heap_addheader(Natts_pg_attribute,
508 ATTRIBUTE_TUPLE_SIZE,
510 attStruct = (Form_pg_attribute) GETSTRUCT(tup);
512 /* Fill in the correct relation OID in the copied tuple */
513 attStruct->attrelid = new_rel_oid;
515 /* Fill in correct inheritance info for the OID column */
516 if (attStruct->attnum == ObjectIdAttributeNumber)
518 attStruct->attislocal = oidislocal;
519 attStruct->attinhcount = oidinhcount;
523 * Unneeded since they should be OK in the constant data
526 /* attStruct->attstattarget = 0; */
527 /* attStruct->attcacheoff = -1; */
529 simple_heap_insert(rel, tup);
531 CatalogIndexInsert(indstate, tup);
542 CatalogCloseIndexes(indstate);
544 heap_close(rel, RowExclusiveLock);
547 /* --------------------------------
550 * Construct and insert a new tuple in pg_class.
552 * Caller has already opened and locked pg_class.
553 * Tuple data is taken from new_rel_desc->rd_rel, except for the
554 * variable-width fields which are not present in a cached reldesc.
555 * We always initialize relacl to NULL (i.e., default permissions),
556 * and reloptions is set to the passed-in text array (if any).
557 * --------------------------------
560 InsertPgClassTuple(Relation pg_class_desc,
561 Relation new_rel_desc,
565 Form_pg_class rd_rel = new_rel_desc->rd_rel;
566 Datum values[Natts_pg_class];
567 char nulls[Natts_pg_class];
570 /* This is a tad tedious, but way cleaner than what we used to do... */
571 memset(values, 0, sizeof(values));
572 memset(nulls, ' ', sizeof(nulls));
574 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
575 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
576 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
577 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
578 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
579 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
580 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
581 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
582 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
583 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
584 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
585 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
586 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
587 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
588 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
589 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
590 values[Anum_pg_class_reltriggers - 1] = Int16GetDatum(rd_rel->reltriggers);
591 values[Anum_pg_class_relukeys - 1] = Int16GetDatum(rd_rel->relukeys);
592 values[Anum_pg_class_relfkeys - 1] = Int16GetDatum(rd_rel->relfkeys);
593 values[Anum_pg_class_relrefs - 1] = Int16GetDatum(rd_rel->relrefs);
594 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
595 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
596 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
597 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
598 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
599 /* start out with empty permissions */
600 nulls[Anum_pg_class_relacl - 1] = 'n';
601 if (reloptions != (Datum) 0)
602 values[Anum_pg_class_reloptions - 1] = reloptions;
604 nulls[Anum_pg_class_reloptions - 1] = 'n';
606 tup = heap_formtuple(RelationGetDescr(pg_class_desc), values, nulls);
609 * The new tuple must have the oid already chosen for the rel. Sure would
610 * be embarrassing to do this sort of thing in polite company.
612 HeapTupleSetOid(tup, new_rel_oid);
614 /* finally insert the new tuple, update the indexes, and clean up */
615 simple_heap_insert(pg_class_desc, tup);
617 CatalogUpdateIndexes(pg_class_desc, tup);
622 /* --------------------------------
623 * AddNewRelationTuple
625 * this registers the new relation in the catalogs by
626 * adding a tuple to pg_class.
627 * --------------------------------
630 AddNewRelationTuple(Relation pg_class_desc,
631 Relation new_rel_desc,
638 Form_pg_class new_rel_reltup;
641 * first we update some of the information in our uncataloged relation's
642 * relation descriptor.
644 new_rel_reltup = new_rel_desc->rd_rel;
648 case RELKIND_RELATION:
650 case RELKIND_TOASTVALUE:
651 /* The relation is real, but as yet empty */
652 new_rel_reltup->relpages = 0;
653 new_rel_reltup->reltuples = 0;
655 case RELKIND_SEQUENCE:
656 /* Sequences always have a known size */
657 new_rel_reltup->relpages = 1;
658 new_rel_reltup->reltuples = 1;
661 /* Views, etc, have no disk storage */
662 new_rel_reltup->relpages = 0;
663 new_rel_reltup->reltuples = 0;
667 /* Initialize relfrozenxid */
668 if (relkind == RELKIND_RELATION ||
669 relkind == RELKIND_TOASTVALUE)
672 * Initialize to the minimum XID that could put tuples in the table.
673 * We know that no xacts older than RecentXmin are still running,
676 if (!IsBootstrapProcessingMode())
677 new_rel_reltup->relfrozenxid = RecentXmin;
679 new_rel_reltup->relfrozenxid = FirstNormalTransactionId;
684 * Other relation types will not contain XIDs, so set relfrozenxid
685 * to InvalidTransactionId. (Note: a sequence does contain a tuple,
686 * but we force its xmin to be FrozenTransactionId always; see
687 * commands/sequence.c.)
689 new_rel_reltup->relfrozenxid = InvalidTransactionId;
692 new_rel_reltup->relowner = relowner;
693 new_rel_reltup->reltype = new_type_oid;
694 new_rel_reltup->relkind = relkind;
696 new_rel_desc->rd_att->tdtypeid = new_type_oid;
698 /* Now build and insert the tuple */
699 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid, reloptions);
703 /* --------------------------------
704 * AddNewRelationType -
706 * define a composite type corresponding to the new relation
707 * --------------------------------
710 AddNewRelationType(const char *typeName,
716 TypeCreate(typeName, /* type name */
717 typeNamespace, /* type namespace */
718 new_rel_oid, /* relation oid */
719 new_rel_kind, /* relation kind */
720 -1, /* internal size (varlena) */
721 'c', /* type-type (complex) */
722 ',', /* default array delimiter */
723 F_RECORD_IN, /* input procedure */
724 F_RECORD_OUT, /* output procedure */
725 F_RECORD_RECV, /* receive procedure */
726 F_RECORD_SEND, /* send procedure */
727 InvalidOid, /* analyze procedure - default */
728 InvalidOid, /* array element type - irrelevant */
729 InvalidOid, /* domain base type - irrelevant */
730 NULL, /* default value - none */
731 NULL, /* default binary representation */
732 false, /* passed by reference */
733 'd', /* alignment - must be the largest! */
734 'x', /* fully TOASTable */
736 0, /* array dimensions for typBaseType */
737 false); /* Type NOT NULL */
740 /* --------------------------------
741 * heap_create_with_catalog
743 * creates a new cataloged relation. see comments above.
744 * --------------------------------
747 heap_create_with_catalog(const char *relname,
754 bool shared_relation,
757 OnCommitAction oncommit,
759 bool allow_system_table_mods)
761 Relation pg_class_desc;
762 Relation new_rel_desc;
765 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
770 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
772 CheckAttributeNamesTypes(tupdesc, relkind);
774 if (get_relname_relid(relname, relnamespace))
776 (errcode(ERRCODE_DUPLICATE_TABLE),
777 errmsg("relation \"%s\" already exists", relname)));
780 * Allocate an OID for the relation, unless we were told what to use.
782 * The OID will be the relfilenode as well, so make sure it doesn't
783 * collide with either pg_class OIDs or existing physical files.
785 if (!OidIsValid(relid))
786 relid = GetNewRelFileNode(reltablespace, shared_relation,
790 * Create the relcache entry (mostly dummy at this point) and the physical
791 * disk file. (If we fail further down, it's the smgr's responsibility to
792 * remove the disk file again.)
794 new_rel_desc = heap_create(relname,
801 allow_system_table_mods);
803 Assert(relid == RelationGetRelid(new_rel_desc));
806 * since defining a relation also defines a complex type, we add a new
807 * system type corresponding to the new relation.
809 * NOTE: we could get a unique-index failure here, in case the same name
810 * has already been used for a type.
812 new_type_oid = AddNewRelationType(relname,
818 * now create an entry in pg_class for the relation.
820 * NOTE: we could get a unique-index failure here, in case someone else is
821 * creating the same relation name in parallel but hadn't committed yet
822 * when we checked for a duplicate name above.
824 AddNewRelationTuple(pg_class_desc,
833 * now add tuples to pg_attribute for the attributes in our new relation.
835 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
836 oidislocal, oidinhcount);
839 * make a dependency link to force the relation to be deleted if its
840 * namespace is. Skip this in bootstrap mode, since we don't make
841 * dependencies while bootstrapping.
843 * Also make a dependency link to its owner.
845 if (!IsBootstrapProcessingMode())
847 ObjectAddress myself,
850 myself.classId = RelationRelationId;
851 myself.objectId = relid;
852 myself.objectSubId = 0;
853 referenced.classId = NamespaceRelationId;
854 referenced.objectId = relnamespace;
855 referenced.objectSubId = 0;
856 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
859 * For composite types, the dependency on owner is tracked for the
860 * pg_type entry, so don't record it here. All other relkinds need
861 * their ownership tracked.
863 if (relkind != RELKIND_COMPOSITE_TYPE)
864 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
868 * store constraints and defaults passed in the tupdesc, if any.
870 * NB: this may do a CommandCounterIncrement and rebuild the relcache
871 * entry, so the relation must be valid and self-consistent at this point.
872 * In particular, there are not yet constraints and defaults anywhere.
874 StoreConstraints(new_rel_desc, tupdesc);
877 * If there's a special on-commit action, remember it
879 if (oncommit != ONCOMMIT_NOOP)
880 register_on_commit_action(relid, oncommit);
883 * ok, the relation has been cataloged, so close our relations and return
884 * the OID of the newly created relation.
886 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
887 heap_close(pg_class_desc, RowExclusiveLock);
894 * RelationRemoveInheritance
896 * Formerly, this routine checked for child relations and aborted the
897 * deletion if any were found. Now we rely on the dependency mechanism
898 * to check for or delete child relations. By the time we get here,
899 * there are no children and we need only remove any pg_inherits rows
900 * linking this relation to its parent(s).
903 RelationRemoveInheritance(Oid relid)
905 Relation catalogRelation;
910 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
913 Anum_pg_inherits_inhrelid,
914 BTEqualStrategyNumber, F_OIDEQ,
915 ObjectIdGetDatum(relid));
917 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
918 SnapshotNow, 1, &key);
920 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
921 simple_heap_delete(catalogRelation, &tuple->t_self);
923 systable_endscan(scan);
924 heap_close(catalogRelation, RowExclusiveLock);
928 * DeleteRelationTuple
930 * Remove pg_class row for the given relid.
932 * Note: this is shared by relation deletion and index deletion. It's
933 * not intended for use anyplace else.
936 DeleteRelationTuple(Oid relid)
938 Relation pg_class_desc;
941 /* Grab an appropriate lock on the pg_class relation */
942 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
944 tup = SearchSysCache(RELOID,
945 ObjectIdGetDatum(relid),
947 if (!HeapTupleIsValid(tup))
948 elog(ERROR, "cache lookup failed for relation %u", relid);
950 /* delete the relation tuple from pg_class, and finish up */
951 simple_heap_delete(pg_class_desc, &tup->t_self);
953 ReleaseSysCache(tup);
955 heap_close(pg_class_desc, RowExclusiveLock);
959 * DeleteAttributeTuples
961 * Remove pg_attribute rows for the given relid.
963 * Note: this is shared by relation deletion and index deletion. It's
964 * not intended for use anyplace else.
967 DeleteAttributeTuples(Oid relid)
974 /* Grab an appropriate lock on the pg_attribute relation */
975 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
977 /* Use the index to scan only attributes of the target relation */
979 Anum_pg_attribute_attrelid,
980 BTEqualStrategyNumber, F_OIDEQ,
981 ObjectIdGetDatum(relid));
983 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
984 SnapshotNow, 1, key);
986 /* Delete all the matching tuples */
987 while ((atttup = systable_getnext(scan)) != NULL)
988 simple_heap_delete(attrel, &atttup->t_self);
990 /* Clean up after the scan */
991 systable_endscan(scan);
992 heap_close(attrel, RowExclusiveLock);
996 * RemoveAttributeById
998 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
999 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1000 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1001 * is handled by dependency.c.)
1004 RemoveAttributeById(Oid relid, AttrNumber attnum)
1009 Form_pg_attribute attStruct;
1010 char newattname[NAMEDATALEN];
1013 * Grab an exclusive lock on the target table, which we will NOT release
1014 * until end of transaction. (In the simple case where we are directly
1015 * dropping this column, AlterTableDropColumn already did this ... but
1016 * when cascading from a drop of some other object, we may not have any
1019 rel = relation_open(relid, AccessExclusiveLock);
1021 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1023 tuple = SearchSysCacheCopy(ATTNUM,
1024 ObjectIdGetDatum(relid),
1025 Int16GetDatum(attnum),
1027 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1028 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1030 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1034 /* System attribute (probably OID) ... just delete the row */
1036 simple_heap_delete(attr_rel, &tuple->t_self);
1040 /* Dropping user attributes is lots harder */
1042 /* Mark the attribute as dropped */
1043 attStruct->attisdropped = true;
1046 * Set the type OID to invalid. A dropped attribute's type link
1047 * cannot be relied on (once the attribute is dropped, the type might
1048 * be too). Fortunately we do not need the type row --- the only
1049 * really essential information is the type's typlen and typalign,
1050 * which are preserved in the attribute's attlen and attalign. We set
1051 * atttypid to zero here as a means of catching code that incorrectly
1052 * expects it to be valid.
1054 attStruct->atttypid = InvalidOid;
1056 /* Remove any NOT NULL constraint the column may have */
1057 attStruct->attnotnull = false;
1059 /* We don't want to keep stats for it anymore */
1060 attStruct->attstattarget = 0;
1063 * Change the column name to something that isn't likely to conflict
1065 snprintf(newattname, sizeof(newattname),
1066 "........pg.dropped.%d........", attnum);
1067 namestrcpy(&(attStruct->attname), newattname);
1069 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1071 /* keep the system catalog indexes current */
1072 CatalogUpdateIndexes(attr_rel, tuple);
1076 * Because updating the pg_attribute row will trigger a relcache flush for
1077 * the target relation, we need not do anything else to notify other
1078 * backends of the change.
1081 heap_close(attr_rel, RowExclusiveLock);
1084 RemoveStatistics(relid, attnum);
1086 relation_close(rel, NoLock);
1092 * If the specified relation/attribute has a default, remove it.
1093 * (If no default, raise error if complain is true, else return quietly.)
1096 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1097 DropBehavior behavior, bool complain)
1099 Relation attrdef_rel;
1100 ScanKeyData scankeys[2];
1105 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1107 ScanKeyInit(&scankeys[0],
1108 Anum_pg_attrdef_adrelid,
1109 BTEqualStrategyNumber, F_OIDEQ,
1110 ObjectIdGetDatum(relid));
1111 ScanKeyInit(&scankeys[1],
1112 Anum_pg_attrdef_adnum,
1113 BTEqualStrategyNumber, F_INT2EQ,
1114 Int16GetDatum(attnum));
1116 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1117 SnapshotNow, 2, scankeys);
1119 /* There should be at most one matching tuple, but we loop anyway */
1120 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1122 ObjectAddress object;
1124 object.classId = AttrDefaultRelationId;
1125 object.objectId = HeapTupleGetOid(tuple);
1126 object.objectSubId = 0;
1128 performDeletion(&object, behavior);
1133 systable_endscan(scan);
1134 heap_close(attrdef_rel, RowExclusiveLock);
1136 if (complain && !found)
1137 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1142 * RemoveAttrDefaultById
1144 * Remove a pg_attrdef entry specified by OID. This is the guts of
1145 * attribute-default removal. Note it should be called via performDeletion,
1149 RemoveAttrDefaultById(Oid attrdefId)
1151 Relation attrdef_rel;
1154 ScanKeyData scankeys[1];
1158 AttrNumber myattnum;
1160 /* Grab an appropriate lock on the pg_attrdef relation */
1161 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1163 /* Find the pg_attrdef tuple */
1164 ScanKeyInit(&scankeys[0],
1165 ObjectIdAttributeNumber,
1166 BTEqualStrategyNumber, F_OIDEQ,
1167 ObjectIdGetDatum(attrdefId));
1169 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1170 SnapshotNow, 1, scankeys);
1172 tuple = systable_getnext(scan);
1173 if (!HeapTupleIsValid(tuple))
1174 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1176 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1177 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1179 /* Get an exclusive lock on the relation owning the attribute */
1180 myrel = relation_open(myrelid, AccessExclusiveLock);
1182 /* Now we can delete the pg_attrdef row */
1183 simple_heap_delete(attrdef_rel, &tuple->t_self);
1185 systable_endscan(scan);
1186 heap_close(attrdef_rel, RowExclusiveLock);
1188 /* Fix the pg_attribute row */
1189 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1191 tuple = SearchSysCacheCopy(ATTNUM,
1192 ObjectIdGetDatum(myrelid),
1193 Int16GetDatum(myattnum),
1195 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1196 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1199 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1201 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1203 /* keep the system catalog indexes current */
1204 CatalogUpdateIndexes(attr_rel, tuple);
1207 * Our update of the pg_attribute row will force a relcache rebuild, so
1208 * there's nothing else to do here.
1210 heap_close(attr_rel, RowExclusiveLock);
1212 /* Keep lock on attribute's rel until end of xact */
1213 relation_close(myrel, NoLock);
1217 * heap_drop_with_catalog - removes specified relation from catalogs
1219 * Note that this routine is not responsible for dropping objects that are
1220 * linked to the pg_class entry via dependencies (for example, indexes and
1221 * constraints). Those are deleted by the dependency-tracing logic in
1222 * dependency.c before control gets here. In general, therefore, this routine
1223 * should never be called directly; go through performDeletion() instead.
1226 heap_drop_with_catalog(Oid relid)
1231 * Open and lock the relation.
1233 rel = relation_open(relid, AccessExclusiveLock);
1236 * Schedule unlinking of the relation's physical file at commit.
1238 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1239 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1241 RelationOpenSmgr(rel);
1242 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
1246 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1247 * until transaction commit. This ensures no one else will try to do
1248 * something with the doomed relation.
1250 relation_close(rel, NoLock);
1253 * Forget any ON COMMIT action for the rel
1255 remove_on_commit_action(relid);
1258 * Flush the relation from the relcache. We want to do this before
1259 * starting to remove catalog entries, just to be certain that no relcache
1260 * entry rebuild will happen partway through. (That should not really
1261 * matter, since we don't do CommandCounterIncrement here, but let's be
1264 RelationForgetRelation(relid);
1267 * remove inheritance information
1269 RelationRemoveInheritance(relid);
1274 RemoveStatistics(relid, 0);
1277 * delete attribute tuples
1279 DeleteAttributeTuples(relid);
1282 * delete relation tuple
1284 DeleteRelationTuple(relid);
1289 * Store a default expression for column attnum of relation rel.
1290 * The expression must be presented as a nodeToString() string.
1293 StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin)
1300 static char nulls[4] = {' ', ' ', ' ', ' '};
1303 Form_pg_attribute attStruct;
1305 ObjectAddress colobject,
1309 * Need to construct source equivalent of given node-string.
1311 expr = stringToNode(adbin);
1316 adsrc = deparse_expression(expr,
1317 deparse_context_for(RelationGetRelationName(rel),
1318 RelationGetRelid(rel)),
1322 * Make the pg_attrdef entry.
1324 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1325 values[Anum_pg_attrdef_adnum - 1] = attnum;
1326 values[Anum_pg_attrdef_adbin - 1] = DirectFunctionCall1(textin,
1327 CStringGetDatum(adbin));
1328 values[Anum_pg_attrdef_adsrc - 1] = DirectFunctionCall1(textin,
1329 CStringGetDatum(adsrc));
1331 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1333 tuple = heap_formtuple(adrel->rd_att, values, nulls);
1334 attrdefOid = simple_heap_insert(adrel, tuple);
1336 CatalogUpdateIndexes(adrel, tuple);
1338 defobject.classId = AttrDefaultRelationId;
1339 defobject.objectId = attrdefOid;
1340 defobject.objectSubId = 0;
1342 heap_close(adrel, RowExclusiveLock);
1344 /* now can free some of the stuff allocated above */
1345 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1346 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1347 heap_freetuple(tuple);
1351 * Update the pg_attribute entry for the column to show that a default
1354 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1355 atttup = SearchSysCacheCopy(ATTNUM,
1356 ObjectIdGetDatum(RelationGetRelid(rel)),
1357 Int16GetDatum(attnum),
1359 if (!HeapTupleIsValid(atttup))
1360 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1361 attnum, RelationGetRelid(rel));
1362 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1363 if (!attStruct->atthasdef)
1365 attStruct->atthasdef = true;
1366 simple_heap_update(attrrel, &atttup->t_self, atttup);
1367 /* keep catalog indexes current */
1368 CatalogUpdateIndexes(attrrel, atttup);
1370 heap_close(attrrel, RowExclusiveLock);
1371 heap_freetuple(atttup);
1374 * Make a dependency so that the pg_attrdef entry goes away if the column
1375 * (or whole table) is deleted.
1377 colobject.classId = RelationRelationId;
1378 colobject.objectId = RelationGetRelid(rel);
1379 colobject.objectSubId = attnum;
1381 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1384 * Record dependencies on objects used in the expression, too.
1386 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1390 * Store a check-constraint expression for the given relation.
1391 * The expression must be presented as a nodeToString() string.
1393 * Caller is responsible for updating the count of constraints
1394 * in the pg_class entry for the relation.
1397 StoreRelCheck(Relation rel, char *ccname, char *ccbin)
1406 * Convert condition to an expression tree.
1408 expr = stringToNode(ccbin);
1413 ccsrc = deparse_expression(expr,
1414 deparse_context_for(RelationGetRelationName(rel),
1415 RelationGetRelid(rel)),
1419 * Find columns of rel that are used in ccbin
1421 * NB: pull_var_clause is okay here only because we don't allow subselects
1422 * in check constraints; it would fail to examine the contents of
1425 varList = pull_var_clause(expr, false);
1426 keycount = list_length(varList);
1433 attNos = (int16 *) palloc(keycount * sizeof(int16));
1434 foreach(vl, varList)
1436 Var *var = (Var *) lfirst(vl);
1439 for (j = 0; j < i; j++)
1440 if (attNos[j] == var->varattno)
1443 attNos[i++] = var->varattno;
1451 * Create the Check Constraint
1453 CreateConstraintEntry(ccname, /* Constraint Name */
1454 RelationGetNamespace(rel), /* namespace */
1455 CONSTRAINT_CHECK, /* Constraint Type */
1456 false, /* Is Deferrable */
1457 false, /* Is Deferred */
1458 RelationGetRelid(rel), /* relation */
1459 attNos, /* attrs in the constraint */
1460 keycount, /* # attrs in the constraint */
1461 InvalidOid, /* not a domain constraint */
1462 InvalidOid, /* Foreign key fields */
1468 InvalidOid, /* no associated index */
1469 expr, /* Tree form check constraint */
1470 ccbin, /* Binary form check constraint */
1471 ccsrc); /* Source form check constraint */
1477 * Store defaults and constraints passed in via the tuple constraint struct.
1479 * NOTE: only pre-cooked expressions will be passed this way, which is to
1480 * say expressions inherited from an existing relation. Newly parsed
1481 * expressions can be added later, by direct calls to StoreAttrDefault
1482 * and StoreRelCheck (see AddRelationRawConstraints()).
1485 StoreConstraints(Relation rel, TupleDesc tupdesc)
1487 TupleConstr *constr = tupdesc->constr;
1491 return; /* nothing to do */
1494 * Deparsing of constraint expressions will fail unless the just-created
1495 * pg_attribute tuples for this relation are made visible. So, bump the
1496 * command counter. CAUTION: this will cause a relcache entry rebuild.
1498 CommandCounterIncrement();
1500 for (i = 0; i < constr->num_defval; i++)
1501 StoreAttrDefault(rel, constr->defval[i].adnum,
1502 constr->defval[i].adbin);
1504 for (i = 0; i < constr->num_check; i++)
1505 StoreRelCheck(rel, constr->check[i].ccname,
1506 constr->check[i].ccbin);
1508 if (constr->num_check > 0)
1509 SetRelationNumChecks(rel, constr->num_check);
1513 * AddRelationRawConstraints
1515 * Add raw (not-yet-transformed) column default expressions and/or constraint
1516 * check expressions to an existing relation. This is defined to do both
1517 * for efficiency in DefineRelation, but of course you can do just one or
1518 * the other by passing empty lists.
1520 * rel: relation to be modified
1521 * rawColDefaults: list of RawColumnDefault structures
1522 * rawConstraints: list of Constraint nodes
1524 * All entries in rawColDefaults will be processed. Entries in rawConstraints
1525 * will be processed only if they are CONSTR_CHECK type and contain a "raw"
1528 * Returns a list of CookedConstraint nodes that shows the cooked form of
1529 * the default and constraint expressions added to the relation.
1531 * NB: caller should have opened rel with AccessExclusiveLock, and should
1532 * hold that lock till end of transaction. Also, we assume the caller has
1533 * done a CommandCounterIncrement if necessary to make the relation's catalog
1537 AddRelationRawConstraints(Relation rel,
1538 List *rawColDefaults,
1539 List *rawConstraints)
1541 List *cookedConstraints = NIL;
1542 TupleDesc tupleDesc;
1543 TupleConstr *oldconstr;
1551 CookedConstraint *cooked;
1554 * Get info about existing constraints.
1556 tupleDesc = RelationGetDescr(rel);
1557 oldconstr = tupleDesc->constr;
1559 numoldchecks = oldconstr->num_check;
1564 * Create a dummy ParseState and insert the target relation as its sole
1565 * rangetable entry. We need a ParseState for transformExpr.
1567 pstate = make_parsestate(NULL);
1568 rte = addRangeTableEntryForRelation(pstate,
1573 addRTEtoQuery(pstate, rte, true, true, true);
1576 * Process column default expressions.
1578 foreach(cell, rawColDefaults)
1580 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1581 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1583 expr = cookDefault(pstate, colDef->raw_default,
1584 atp->atttypid, atp->atttypmod,
1585 NameStr(atp->attname));
1587 StoreAttrDefault(rel, colDef->attnum, nodeToString(expr));
1589 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1590 cooked->contype = CONSTR_DEFAULT;
1591 cooked->name = NULL;
1592 cooked->attnum = colDef->attnum;
1593 cooked->expr = expr;
1594 cookedConstraints = lappend(cookedConstraints, cooked);
1598 * Process constraint expressions.
1600 numchecks = numoldchecks;
1602 foreach(cell, rawConstraints)
1604 Constraint *cdef = (Constraint *) lfirst(cell);
1607 if (cdef->contype != CONSTR_CHECK || cdef->raw_expr == NULL)
1609 Assert(cdef->cooked_expr == NULL);
1612 * Transform raw parsetree to executable expression.
1614 expr = transformExpr(pstate, cdef->raw_expr);
1617 * Make sure it yields a boolean result.
1619 expr = coerce_to_boolean(pstate, expr, "CHECK");
1622 * Make sure no outside relations are referred to.
1624 if (list_length(pstate->p_rtable) != 1)
1626 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1627 errmsg("only table \"%s\" can be referenced in check constraint",
1628 RelationGetRelationName(rel))));
1631 * No subplans or aggregates, either...
1633 if (pstate->p_hasSubLinks)
1635 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1636 errmsg("cannot use subquery in check constraint")));
1637 if (pstate->p_hasAggs)
1639 (errcode(ERRCODE_GROUPING_ERROR),
1640 errmsg("cannot use aggregate function in check constraint")));
1643 * Check name uniqueness, or generate a name if none was given.
1645 if (cdef->name != NULL)
1649 ccname = cdef->name;
1650 /* Check against pre-existing constraints */
1651 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
1652 RelationGetRelid(rel),
1653 RelationGetNamespace(rel),
1656 (errcode(ERRCODE_DUPLICATE_OBJECT),
1657 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1658 ccname, RelationGetRelationName(rel))));
1659 /* Check against other new constraints */
1660 /* Needed because we don't do CommandCounterIncrement in loop */
1661 foreach(cell2, checknames)
1663 if (strcmp((char *) lfirst(cell2), ccname) == 0)
1665 (errcode(ERRCODE_DUPLICATE_OBJECT),
1666 errmsg("check constraint \"%s\" already exists",
1673 * When generating a name, we want to create "tab_col_check" for a
1674 * column constraint and "tab_check" for a table constraint. We
1675 * no longer have any info about the syntactic positioning of the
1676 * constraint phrase, so we approximate this by seeing whether the
1677 * expression references more than one column. (If the user
1678 * played by the rules, the result is the same...)
1680 * Note: pull_var_clause() doesn't descend into sublinks, but we
1681 * eliminated those above; and anyway this only needs to be an
1682 * approximate answer.
1687 vars = pull_var_clause(expr, false);
1689 /* eliminate duplicates */
1690 vars = list_union(NIL, vars);
1692 if (list_length(vars) == 1)
1693 colname = get_attname(RelationGetRelid(rel),
1694 ((Var *) linitial(vars))->varattno);
1698 ccname = ChooseConstraintName(RelationGetRelationName(rel),
1701 RelationGetNamespace(rel),
1705 /* save name for future checks */
1706 checknames = lappend(checknames, ccname);
1711 StoreRelCheck(rel, ccname, nodeToString(expr));
1715 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1716 cooked->contype = CONSTR_CHECK;
1717 cooked->name = ccname;
1719 cooked->expr = expr;
1720 cookedConstraints = lappend(cookedConstraints, cooked);
1724 * Update the count of constraints in the relation's pg_class tuple. We do
1725 * this even if there was no change, in order to ensure that an SI update
1726 * message is sent out for the pg_class tuple, which will force other
1727 * backends to rebuild their relcache entries for the rel. (This is
1728 * critical if we added defaults but not constraints.)
1730 SetRelationNumChecks(rel, numchecks);
1732 return cookedConstraints;
1736 * Update the count of constraints in the relation's pg_class tuple.
1738 * Caller had better hold exclusive lock on the relation.
1740 * An important side effect is that a SI update message will be sent out for
1741 * the pg_class tuple, which will force other backends to rebuild their
1742 * relcache entries for the rel. Also, this backend will rebuild its
1743 * own relcache entry at the next CommandCounterIncrement.
1746 SetRelationNumChecks(Relation rel, int numchecks)
1750 Form_pg_class relStruct;
1752 relrel = heap_open(RelationRelationId, RowExclusiveLock);
1753 reltup = SearchSysCacheCopy(RELOID,
1754 ObjectIdGetDatum(RelationGetRelid(rel)),
1756 if (!HeapTupleIsValid(reltup))
1757 elog(ERROR, "cache lookup failed for relation %u",
1758 RelationGetRelid(rel));
1759 relStruct = (Form_pg_class) GETSTRUCT(reltup);
1761 if (relStruct->relchecks != numchecks)
1763 relStruct->relchecks = numchecks;
1765 simple_heap_update(relrel, &reltup->t_self, reltup);
1767 /* keep catalog indexes current */
1768 CatalogUpdateIndexes(relrel, reltup);
1772 /* Skip the disk update, but force relcache inval anyway */
1773 CacheInvalidateRelcache(rel);
1776 heap_freetuple(reltup);
1777 heap_close(relrel, RowExclusiveLock);
1781 * Take a raw default and convert it to a cooked format ready for
1784 * Parse state should be set up to recognize any vars that might appear
1785 * in the expression. (Even though we plan to reject vars, it's more
1786 * user-friendly to give the correct error message than "unknown var".)
1788 * If atttypid is not InvalidOid, coerce the expression to the specified
1789 * type (and typmod atttypmod). attname is only needed in this case:
1790 * it is used in the error message, if any.
1793 cookDefault(ParseState *pstate,
1801 Assert(raw_default != NULL);
1804 * Transform raw parsetree to executable expression.
1806 expr = transformExpr(pstate, raw_default);
1809 * Make sure default expr does not refer to any vars.
1811 if (contain_var_clause(expr))
1813 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1814 errmsg("cannot use column references in default expression")));
1817 * It can't return a set either.
1819 if (expression_returns_set(expr))
1821 (errcode(ERRCODE_DATATYPE_MISMATCH),
1822 errmsg("default expression must not return a set")));
1825 * No subplans or aggregates, either...
1827 if (pstate->p_hasSubLinks)
1829 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1830 errmsg("cannot use subquery in default expression")));
1831 if (pstate->p_hasAggs)
1833 (errcode(ERRCODE_GROUPING_ERROR),
1834 errmsg("cannot use aggregate function in default expression")));
1837 * Coerce the expression to the correct type and typmod, if given. This
1838 * should match the parser's processing of non-defaulted expressions ---
1839 * see transformAssignedExpr().
1841 if (OidIsValid(atttypid))
1843 Oid type_id = exprType(expr);
1845 expr = coerce_to_target_type(pstate, expr, type_id,
1846 atttypid, atttypmod,
1847 COERCION_ASSIGNMENT,
1848 COERCE_IMPLICIT_CAST);
1851 (errcode(ERRCODE_DATATYPE_MISMATCH),
1852 errmsg("column \"%s\" is of type %s"
1853 " but default expression is of type %s",
1855 format_type_be(atttypid),
1856 format_type_be(type_id)),
1857 errhint("You will need to rewrite or cast the expression.")));
1865 * Removes all constraints on a relation that match the given name.
1867 * It is the responsibility of the calling function to acquire a suitable
1868 * lock on the relation.
1870 * Returns: The number of constraints removed.
1873 RemoveRelConstraints(Relation rel, const char *constrName,
1874 DropBehavior behavior)
1878 SysScanDesc conscan;
1882 /* Grab an appropriate lock on the pg_constraint relation */
1883 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
1885 /* Use the index to scan only constraints of the target relation */
1886 ScanKeyInit(&key[0],
1887 Anum_pg_constraint_conrelid,
1888 BTEqualStrategyNumber, F_OIDEQ,
1889 ObjectIdGetDatum(RelationGetRelid(rel)));
1891 conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true,
1892 SnapshotNow, 1, key);
1895 * Scan over the result set, removing any matching entries.
1897 while ((contup = systable_getnext(conscan)) != NULL)
1899 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
1901 if (strcmp(NameStr(con->conname), constrName) == 0)
1903 ObjectAddress conobj;
1905 conobj.classId = ConstraintRelationId;
1906 conobj.objectId = HeapTupleGetOid(contup);
1907 conobj.objectSubId = 0;
1909 performDeletion(&conobj, behavior);
1915 /* Clean up after the scan */
1916 systable_endscan(conscan);
1917 heap_close(conrel, RowExclusiveLock);
1924 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
1926 * If attnum is zero, remove all entries for rel; else remove only the one
1930 RemoveStatistics(Oid relid, AttrNumber attnum)
1932 Relation pgstatistic;
1938 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
1940 ScanKeyInit(&key[0],
1941 Anum_pg_statistic_starelid,
1942 BTEqualStrategyNumber, F_OIDEQ,
1943 ObjectIdGetDatum(relid));
1949 ScanKeyInit(&key[1],
1950 Anum_pg_statistic_staattnum,
1951 BTEqualStrategyNumber, F_INT2EQ,
1952 Int16GetDatum(attnum));
1956 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumIndexId, true,
1957 SnapshotNow, nkeys, key);
1959 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1960 simple_heap_delete(pgstatistic, &tuple->t_self);
1962 systable_endscan(scan);
1964 heap_close(pgstatistic, RowExclusiveLock);
1969 * RelationTruncateIndexes - truncate all indexes associated
1970 * with the heap relation to zero tuples.
1972 * The routine will truncate and then reconstruct the indexes on
1973 * the specified relation. Caller must hold exclusive lock on rel.
1976 RelationTruncateIndexes(Relation heapRelation)
1980 /* Ask the relcache to produce a list of the indexes of the rel */
1981 foreach(indlist, RelationGetIndexList(heapRelation))
1983 Oid indexId = lfirst_oid(indlist);
1984 Relation currentIndex;
1985 IndexInfo *indexInfo;
1987 /* Open the index relation; use exclusive lock, just to be sure */
1988 currentIndex = index_open(indexId, AccessExclusiveLock);
1990 /* Fetch info needed for index_build */
1991 indexInfo = BuildIndexInfo(currentIndex);
1993 /* Now truncate the actual file (and discard buffers) */
1994 RelationTruncate(currentIndex, 0);
1996 /* Initialize the index and rebuild */
1997 /* Note: we do not need to re-establish pkey setting */
1998 index_build(heapRelation, currentIndex, indexInfo, false);
2000 /* We're done with this index */
2001 index_close(currentIndex, NoLock);
2008 * This routine deletes all data within all the specified relations.
2010 * This is not transaction-safe! There is another, transaction-safe
2011 * implementation in commands/tablecmds.c. We now use this only for
2012 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2015 heap_truncate(List *relids)
2017 List *relations = NIL;
2020 /* Open relations for processing, and grab exclusive access on each */
2021 foreach(cell, relids)
2023 Oid rid = lfirst_oid(cell);
2027 rel = heap_open(rid, AccessExclusiveLock);
2028 relations = lappend(relations, rel);
2030 /* If there is a toast table, add it to the list too */
2031 toastrelid = rel->rd_rel->reltoastrelid;
2032 if (OidIsValid(toastrelid))
2034 rel = heap_open(toastrelid, AccessExclusiveLock);
2035 relations = lappend(relations, rel);
2039 /* Don't allow truncate on tables that are referenced by foreign keys */
2040 heap_truncate_check_FKs(relations, true);
2043 foreach(cell, relations)
2045 Relation rel = lfirst(cell);
2047 /* Truncate the actual file (and discard buffers) */
2048 RelationTruncate(rel, 0);
2050 /* If this relation has indexes, truncate the indexes too */
2051 RelationTruncateIndexes(rel);
2054 * Close the relation, but keep exclusive lock on it until commit.
2056 heap_close(rel, NoLock);
2061 * heap_truncate_check_FKs
2062 * Check for foreign keys referencing a list of relations that
2063 * are to be truncated, and raise error if there are any
2065 * We disallow such FKs (except self-referential ones) since the whole point
2066 * of TRUNCATE is to not scan the individual rows to be thrown away.
2068 * This is split out so it can be shared by both implementations of truncate.
2069 * Caller should already hold a suitable lock on the relations.
2071 * tempTables is only used to select an appropriate error message.
2074 heap_truncate_check_FKs(List *relations, bool tempTables)
2081 * Build a list of OIDs of the interesting relations.
2083 * If a relation has no triggers, then it can neither have FKs nor be
2084 * referenced by a FK from another table, so we can ignore it.
2086 foreach(cell, relations)
2088 Relation rel = lfirst(cell);
2090 if (rel->rd_rel->reltriggers != 0)
2091 oids = lappend_oid(oids, RelationGetRelid(rel));
2095 * Fast path: if no relation has triggers, none has FKs either.
2101 * Otherwise, must scan pg_constraint. We make one pass with all the
2102 * relations considered; if this finds nothing, then all is well.
2104 dependents = heap_truncate_find_FKs(oids);
2105 if (dependents == NIL)
2109 * Otherwise we repeat the scan once per relation to identify a particular
2110 * pair of relations to complain about. This is pretty slow, but
2111 * performance shouldn't matter much in a failure path. The reason for
2112 * doing things this way is to ensure that the message produced is not
2113 * dependent on chance row locations within pg_constraint.
2117 Oid relid = lfirst_oid(cell);
2120 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2122 foreach(cell2, dependents)
2124 Oid relid2 = lfirst_oid(cell2);
2126 if (!list_member_oid(oids, relid2))
2128 char *relname = get_rel_name(relid);
2129 char *relname2 = get_rel_name(relid2);
2133 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2134 errmsg("unsupported ON COMMIT and foreign key combination"),
2135 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2136 relname2, relname)));
2139 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2140 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2141 errdetail("Table \"%s\" references \"%s\".",
2143 errhint("Truncate table \"%s\" at the same time, "
2144 "or use TRUNCATE ... CASCADE.",
2152 * heap_truncate_find_FKs
2153 * Find relations having foreign keys referencing any of the given rels
2155 * Input and result are both lists of relation OIDs. The result contains
2156 * no duplicates, does *not* include any rels that were already in the input
2157 * list, and is sorted in OID order. (The last property is enforced mainly
2158 * to guarantee consistent behavior in the regression tests; we don't want
2159 * behavior to change depending on chance locations of rows in pg_constraint.)
2161 * Note: caller should already have appropriate lock on all rels mentioned
2162 * in relationIds. Since adding or dropping an FK requires exclusive lock
2163 * on both rels, this ensures that the answer will be stable.
2166 heap_truncate_find_FKs(List *relationIds)
2170 SysScanDesc fkeyScan;
2174 * Must scan pg_constraint. Right now, it is a seqscan because there is
2175 * no available index on confrelid.
2177 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2179 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2180 SnapshotNow, 0, NULL);
2182 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2184 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2186 /* Not a foreign key */
2187 if (con->contype != CONSTRAINT_FOREIGN)
2190 /* Not referencing one of our list of tables */
2191 if (!list_member_oid(relationIds, con->confrelid))
2194 /* Add referencer unless already in input or result list */
2195 if (!list_member_oid(relationIds, con->conrelid))
2196 result = insert_ordered_unique_oid(result, con->conrelid);
2199 systable_endscan(fkeyScan);
2200 heap_close(fkeyRel, AccessShareLock);
2206 * insert_ordered_unique_oid
2207 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2208 * and eliminating duplicates
2210 * Building the ordered list this way is O(N^2), but with a pretty small
2211 * constant, so for the number of entries we expect it will probably be
2212 * faster than trying to apply qsort(). It seems unlikely someone would be
2213 * trying to truncate a table with thousands of dependent tables ...
2216 insert_ordered_unique_oid(List *list, Oid datum)
2220 /* Does the datum belong at the front? */
2221 if (list == NIL || datum < linitial_oid(list))
2222 return lcons_oid(datum, list);
2223 /* Does it match the first entry? */
2224 if (datum == linitial_oid(list))
2225 return list; /* duplicate, so don't insert */
2226 /* No, so find the entry it belongs after */
2227 prev = list_head(list);
2230 ListCell *curr = lnext(prev);
2232 if (curr == NULL || datum < lfirst_oid(curr))
2233 break; /* it belongs after 'prev', before 'curr' */
2235 if (datum == lfirst_oid(curr))
2236 return list; /* duplicate, so don't insert */
2240 /* Insert datum into list after 'prev' */
2241 lappend_cell_oid(list, prev, datum);