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.306 2006/07/10 16:20:49 alvherre 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/heapam.h"
33 #include "access/genam.h"
34 #include "catalog/catalog.h"
35 #include "catalog/dependency.h"
36 #include "catalog/heap.h"
37 #include "catalog/index.h"
38 #include "catalog/indexing.h"
39 #include "catalog/pg_attrdef.h"
40 #include "catalog/pg_constraint.h"
41 #include "catalog/pg_inherits.h"
42 #include "catalog/pg_namespace.h"
43 #include "catalog/pg_statistic.h"
44 #include "catalog/pg_type.h"
45 #include "commands/tablecmds.h"
46 #include "commands/trigger.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "optimizer/clauses.h"
50 #include "optimizer/planmain.h"
51 #include "optimizer/var.h"
52 #include "parser/parse_coerce.h"
53 #include "parser/parse_expr.h"
54 #include "parser/parse_relation.h"
55 #include "rewrite/rewriteRemove.h"
56 #include "storage/smgr.h"
57 #include "utils/builtins.h"
58 #include "utils/fmgroids.h"
59 #include "utils/inval.h"
60 #include "utils/lsyscache.h"
61 #include "utils/relcache.h"
62 #include "utils/syscache.h"
65 static void AddNewRelationTuple(Relation pg_class_desc,
66 Relation new_rel_desc,
67 Oid new_rel_oid, Oid new_type_oid,
71 static Oid AddNewRelationType(const char *typeName,
75 static void RelationRemoveInheritance(Oid relid);
76 static void StoreRelCheck(Relation rel, char *ccname, char *ccbin);
77 static void StoreConstraints(Relation rel, TupleDesc tupdesc);
78 static void SetRelationNumChecks(Relation rel, int numchecks);
79 static List *insert_ordered_unique_oid(List *list, Oid datum);
82 /* ----------------------------------------------------------------
83 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
85 * these should all be moved to someplace in the lib/catalog
86 * module, if not obliterated first.
87 * ----------------------------------------------------------------
93 * Should the system special case these attributes in the future?
94 * Advantage: consume much less space in the ATTRIBUTE relation.
95 * Disadvantage: special cases will be all over the place.
98 static FormData_pg_attribute a1 = {
99 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
100 SelfItemPointerAttributeNumber, 0, -1, -1,
101 false, 'p', 's', true, false, false, true, 0
104 static FormData_pg_attribute a2 = {
105 0, {"oid"}, OIDOID, 0, sizeof(Oid),
106 ObjectIdAttributeNumber, 0, -1, -1,
107 true, 'p', 'i', true, false, false, true, 0
110 static FormData_pg_attribute a3 = {
111 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
112 MinTransactionIdAttributeNumber, 0, -1, -1,
113 true, 'p', 'i', true, false, false, true, 0
116 static FormData_pg_attribute a4 = {
117 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
118 MinCommandIdAttributeNumber, 0, -1, -1,
119 true, 'p', 'i', true, false, false, true, 0
122 static FormData_pg_attribute a5 = {
123 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
124 MaxTransactionIdAttributeNumber, 0, -1, -1,
125 true, 'p', 'i', true, false, false, true, 0
128 static FormData_pg_attribute a6 = {
129 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
130 MaxCommandIdAttributeNumber, 0, -1, -1,
131 true, 'p', 'i', true, false, false, true, 0
135 * We decided to call this attribute "tableoid" rather than say
136 * "classoid" on the basis that in the future there may be more than one
137 * table of a particular class/type. In any case table is still the word
140 static FormData_pg_attribute a7 = {
141 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
142 TableOidAttributeNumber, 0, -1, -1,
143 true, 'p', 'i', true, false, false, true, 0
146 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
149 * This function returns a Form_pg_attribute pointer for a system attribute.
150 * Note that we elog if the presented attno is invalid, which would only
151 * happen if there's a problem upstream.
154 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
156 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
157 elog(ERROR, "invalid system attribute number %d", attno);
158 if (attno == ObjectIdAttributeNumber && !relhasoids)
159 elog(ERROR, "invalid system attribute number %d", attno);
160 return SysAtt[-attno - 1];
164 * If the given name is a system attribute name, return a Form_pg_attribute
165 * pointer for a prototype definition. If not, return NULL.
168 SystemAttributeByName(const char *attname, bool relhasoids)
172 for (j = 0; j < (int) lengthof(SysAtt); j++)
174 Form_pg_attribute att = SysAtt[j];
176 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
178 if (strcmp(NameStr(att->attname), attname) == 0)
187 /* ----------------------------------------------------------------
188 * XXX END OF UGLY HARD CODED BADNESS XXX
189 * ---------------------------------------------------------------- */
192 /* ----------------------------------------------------------------
193 * heap_create - Create an uncataloged heap relation
195 * Note API change: the caller must now always provide the OID
196 * to use for the relation.
198 * rel->rd_rel is initialized by RelationBuildLocalRelation,
199 * and is mostly zeroes at return.
200 * ----------------------------------------------------------------
203 heap_create(const char *relname,
209 bool shared_relation,
210 bool allow_system_table_mods)
215 /* The caller must have provided an OID for the relation. */
216 Assert(OidIsValid(relid));
221 if (!allow_system_table_mods &&
222 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
223 IsNormalProcessingMode())
225 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
226 errmsg("permission denied to create \"%s.%s\"",
227 get_namespace_name(relnamespace), relname),
228 errdetail("System catalog modifications are currently disallowed.")));
231 * Decide if we need storage or not, and handle a couple other special
232 * cases for particular relkinds.
237 case RELKIND_COMPOSITE_TYPE:
238 create_storage = false;
241 * Force reltablespace to zero if the relation has no physical
242 * storage. This is mainly just for cleanliness' sake.
244 reltablespace = InvalidOid;
246 case RELKIND_SEQUENCE:
247 create_storage = true;
250 * Force reltablespace to zero for sequences, since we don't
251 * support moving them around into different tablespaces.
253 reltablespace = InvalidOid;
256 create_storage = true;
261 * Never allow a pg_class entry to explicitly specify the database's
262 * default tablespace in reltablespace; force it to zero instead. This
263 * ensures that if the database is cloned with a different default
264 * tablespace, the pg_class entry will still match where CREATE DATABASE
265 * will put the physically copied relation.
267 * Yes, this is a bit of a hack.
269 if (reltablespace == MyDatabaseTableSpace)
270 reltablespace = InvalidOid;
273 * build the relcache entry.
275 rel = RelationBuildLocalRelation(relname,
283 * have the storage manager create the relation's disk file, if needed.
287 Assert(rel->rd_smgr == NULL);
288 RelationOpenSmgr(rel);
289 smgrcreate(rel->rd_smgr, rel->rd_istemp, false);
295 /* ----------------------------------------------------------------
296 * heap_create_with_catalog - Create a cataloged relation
298 * this is done in multiple steps:
300 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
301 * descriptor contains a valid set of attribute names and types
303 * 2) pg_class is opened and get_relname_relid()
304 * performs a scan to ensure that no relation with the
305 * same name already exists.
307 * 3) heap_create() is called to create the new relation on disk.
309 * 4) TypeCreate() is called to define a new type corresponding
310 * to the new relation.
312 * 5) AddNewRelationTuple() is called to register the
313 * relation in pg_class.
315 * 6) AddNewAttributeTuples() is called to register the
316 * new relation's schema in pg_attribute.
318 * 7) StoreConstraints is called () - vadim 08/22/97
320 * 8) the relations are closed and the new relation's oid
323 * ----------------------------------------------------------------
326 /* --------------------------------
327 * CheckAttributeNamesTypes
329 * this is used to make certain the tuple descriptor contains a
330 * valid set of attribute names and datatypes. a problem simply
331 * generates ereport(ERROR) which aborts the current transaction.
332 * --------------------------------
335 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind)
339 int natts = tupdesc->natts;
341 /* Sanity check on column count */
342 if (natts < 0 || natts > MaxHeapAttributeNumber)
344 (errcode(ERRCODE_TOO_MANY_COLUMNS),
345 errmsg("tables can have at most %d columns",
346 MaxHeapAttributeNumber)));
349 * first check for collision with system attribute names
351 * Skip this for a view or type relation, since those don't have system
354 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
356 for (i = 0; i < natts; i++)
358 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
359 tupdesc->tdhasoid) != NULL)
361 (errcode(ERRCODE_DUPLICATE_COLUMN),
362 errmsg("column name \"%s\" conflicts with a system column name",
363 NameStr(tupdesc->attrs[i]->attname))));
368 * next check for repeated attribute names
370 for (i = 1; i < natts; i++)
372 for (j = 0; j < i; j++)
374 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
375 NameStr(tupdesc->attrs[i]->attname)) == 0)
377 (errcode(ERRCODE_DUPLICATE_COLUMN),
378 errmsg("column name \"%s\" is duplicated",
379 NameStr(tupdesc->attrs[j]->attname))));
384 * next check the attribute types
386 for (i = 0; i < natts; i++)
388 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
389 tupdesc->attrs[i]->atttypid);
393 /* --------------------------------
396 * Verify that the proposed datatype of an attribute is legal.
397 * This is needed because there are types (and pseudo-types)
398 * in the catalogs that we do not support as elements of real tuples.
399 * --------------------------------
402 CheckAttributeType(const char *attname, Oid atttypid)
404 char att_typtype = get_typtype(atttypid);
407 * Warn user, but don't fail, if column to be created has UNKNOWN type
408 * (usually as a result of a 'retrieve into' - jolly)
410 * Refuse any attempt to create a pseudo-type column.
412 if (atttypid == UNKNOWNOID)
414 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
415 errmsg("column \"%s\" has type \"unknown\"", attname),
416 errdetail("Proceeding with relation creation anyway.")));
417 else if (att_typtype == 'p')
419 /* Special hack for pg_statistic: allow ANYARRAY during initdb */
420 if (atttypid != ANYARRAYOID || IsUnderPostmaster)
422 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
423 errmsg("column \"%s\" has pseudo-type %s",
424 attname, format_type_be(atttypid))));
428 /* --------------------------------
429 * AddNewAttributeTuples
431 * this registers the new relation's schema by adding
432 * tuples to pg_attribute.
433 * --------------------------------
436 AddNewAttributeTuples(Oid new_rel_oid,
442 const Form_pg_attribute *dpp;
446 CatalogIndexState indstate;
447 int natts = tupdesc->natts;
448 ObjectAddress myself,
452 * open pg_attribute and its indexes.
454 rel = heap_open(AttributeRelationId, RowExclusiveLock);
456 indstate = CatalogOpenIndexes(rel);
459 * First we add the user attributes. This is also a convenient place to
460 * add dependencies on their datatypes.
462 dpp = tupdesc->attrs;
463 for (i = 0; i < natts; i++)
465 /* Fill in the correct relation OID */
466 (*dpp)->attrelid = new_rel_oid;
467 /* Make sure these are OK, too */
468 (*dpp)->attstattarget = -1;
469 (*dpp)->attcacheoff = -1;
471 tup = heap_addheader(Natts_pg_attribute,
473 ATTRIBUTE_TUPLE_SIZE,
476 simple_heap_insert(rel, tup);
478 CatalogIndexInsert(indstate, tup);
482 myself.classId = RelationRelationId;
483 myself.objectId = new_rel_oid;
484 myself.objectSubId = i + 1;
485 referenced.classId = TypeRelationId;
486 referenced.objectId = (*dpp)->atttypid;
487 referenced.objectSubId = 0;
488 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
494 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
495 * all for a view or type relation. We don't bother with making datatype
496 * dependencies here, since presumably all these types are pinned.
498 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
501 for (i = 0; i < -1 - FirstLowInvalidHeapAttributeNumber; i++)
503 if (tupdesc->tdhasoid ||
504 (*dpp)->attnum != ObjectIdAttributeNumber)
506 Form_pg_attribute attStruct;
508 tup = heap_addheader(Natts_pg_attribute,
510 ATTRIBUTE_TUPLE_SIZE,
512 attStruct = (Form_pg_attribute) GETSTRUCT(tup);
514 /* Fill in the correct relation OID in the copied tuple */
515 attStruct->attrelid = new_rel_oid;
517 /* Fill in correct inheritance info for the OID column */
518 if (attStruct->attnum == ObjectIdAttributeNumber)
520 attStruct->attislocal = oidislocal;
521 attStruct->attinhcount = oidinhcount;
525 * Unneeded since they should be OK in the constant data
528 /* attStruct->attstattarget = 0; */
529 /* attStruct->attcacheoff = -1; */
531 simple_heap_insert(rel, tup);
533 CatalogIndexInsert(indstate, tup);
544 CatalogCloseIndexes(indstate);
546 heap_close(rel, RowExclusiveLock);
549 /* --------------------------------
552 * Construct and insert a new tuple in pg_class.
554 * Caller has already opened and locked pg_class.
555 * Tuple data is taken from new_rel_desc->rd_rel, except for the
556 * variable-width fields which are not present in a cached reldesc.
557 * We always initialize relacl to NULL (i.e., default permissions),
558 * and reloptions is set to the passed-in text array (if any).
559 * --------------------------------
562 InsertPgClassTuple(Relation pg_class_desc,
563 Relation new_rel_desc,
567 Form_pg_class rd_rel = new_rel_desc->rd_rel;
568 Datum values[Natts_pg_class];
569 char nulls[Natts_pg_class];
572 /* This is a tad tedious, but way cleaner than what we used to do... */
573 memset(values, 0, sizeof(values));
574 memset(nulls, ' ', sizeof(nulls));
576 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
577 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
578 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
579 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
580 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
581 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
582 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
583 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
584 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
585 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
586 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
587 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
588 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
589 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
590 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
591 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
592 values[Anum_pg_class_reltriggers - 1] = Int16GetDatum(rd_rel->reltriggers);
593 values[Anum_pg_class_relukeys - 1] = Int16GetDatum(rd_rel->relukeys);
594 values[Anum_pg_class_relfkeys - 1] = Int16GetDatum(rd_rel->relfkeys);
595 values[Anum_pg_class_relrefs - 1] = Int16GetDatum(rd_rel->relrefs);
596 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
597 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
598 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
599 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
600 values[Anum_pg_class_relminxid - 1] = TransactionIdGetDatum(rd_rel->relminxid);
601 values[Anum_pg_class_relvacuumxid - 1] = TransactionIdGetDatum(rd_rel->relvacuumxid);
602 /* start out with empty permissions */
603 nulls[Anum_pg_class_relacl - 1] = 'n';
604 if (reloptions != (Datum) 0)
605 values[Anum_pg_class_reloptions - 1] = reloptions;
607 nulls[Anum_pg_class_reloptions - 1] = 'n';
609 tup = heap_formtuple(RelationGetDescr(pg_class_desc), values, nulls);
612 * The new tuple must have the oid already chosen for the rel. Sure
613 * would be embarrassing to do this sort of thing in polite company.
615 HeapTupleSetOid(tup, new_rel_oid);
617 /* finally insert the new tuple, update the indexes, and clean up */
618 simple_heap_insert(pg_class_desc, tup);
620 CatalogUpdateIndexes(pg_class_desc, tup);
625 /* --------------------------------
626 * AddNewRelationTuple
628 * this registers the new relation in the catalogs by
629 * adding a tuple to pg_class.
630 * --------------------------------
633 AddNewRelationTuple(Relation pg_class_desc,
634 Relation new_rel_desc,
641 Form_pg_class new_rel_reltup;
644 * first we update some of the information in our uncataloged relation's
645 * relation descriptor.
647 new_rel_reltup = new_rel_desc->rd_rel;
649 /* Initialize relminxid and relvacuumxid */
650 if (relkind == RELKIND_RELATION ||
651 relkind == RELKIND_TOASTVALUE)
654 * Only real tables have Xids stored in them; initialize our known
655 * value to the minimum Xid that could put tuples in the new table.
657 if (!IsBootstrapProcessingMode())
659 new_rel_reltup->relminxid = RecentXmin;
660 new_rel_reltup->relvacuumxid = RecentXmin;
664 new_rel_reltup->relminxid = FirstNormalTransactionId;
665 new_rel_reltup->relvacuumxid = FirstNormalTransactionId;
671 * Other relations will not have Xids in them, so set the initial value
672 * to InvalidTransactionId.
674 new_rel_reltup->relminxid = InvalidTransactionId;
675 new_rel_reltup->relvacuumxid = InvalidTransactionId;
680 case RELKIND_RELATION:
682 case RELKIND_TOASTVALUE:
683 /* The relation is real, but as yet empty */
684 new_rel_reltup->relpages = 0;
685 new_rel_reltup->reltuples = 0;
687 case RELKIND_SEQUENCE:
688 /* Sequences always have a known size */
689 new_rel_reltup->relpages = 1;
690 new_rel_reltup->reltuples = 1;
693 /* Views, etc, have no disk storage */
694 new_rel_reltup->relpages = 0;
695 new_rel_reltup->reltuples = 0;
699 new_rel_reltup->relowner = relowner;
700 new_rel_reltup->reltype = new_type_oid;
701 new_rel_reltup->relkind = relkind;
703 new_rel_desc->rd_att->tdtypeid = new_type_oid;
705 /* Now build and insert the tuple */
706 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid, reloptions);
710 /* --------------------------------
711 * AddNewRelationType -
713 * define a composite type corresponding to the new relation
714 * --------------------------------
717 AddNewRelationType(const char *typeName,
723 TypeCreate(typeName, /* type name */
724 typeNamespace, /* type namespace */
725 new_rel_oid, /* relation oid */
726 new_rel_kind, /* relation kind */
727 -1, /* internal size (varlena) */
728 'c', /* type-type (complex) */
729 ',', /* default array delimiter */
730 F_RECORD_IN, /* input procedure */
731 F_RECORD_OUT, /* output procedure */
732 F_RECORD_RECV, /* receive procedure */
733 F_RECORD_SEND, /* send procedure */
734 InvalidOid, /* analyze procedure - default */
735 InvalidOid, /* array element type - irrelevant */
736 InvalidOid, /* domain base type - irrelevant */
737 NULL, /* default value - none */
738 NULL, /* default binary representation */
739 false, /* passed by reference */
740 'd', /* alignment - must be the largest! */
741 'x', /* fully TOASTable */
743 0, /* array dimensions for typBaseType */
744 false); /* Type NOT NULL */
747 /* --------------------------------
748 * heap_create_with_catalog
750 * creates a new cataloged relation. see comments above.
751 * --------------------------------
754 heap_create_with_catalog(const char *relname,
761 bool shared_relation,
764 OnCommitAction oncommit,
766 bool allow_system_table_mods)
768 Relation pg_class_desc;
769 Relation new_rel_desc;
772 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
777 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
779 CheckAttributeNamesTypes(tupdesc, relkind);
781 if (get_relname_relid(relname, relnamespace))
783 (errcode(ERRCODE_DUPLICATE_TABLE),
784 errmsg("relation \"%s\" already exists", relname)));
787 * Allocate an OID for the relation, unless we were told what to use.
789 * The OID will be the relfilenode as well, so make sure it doesn't
790 * collide with either pg_class OIDs or existing physical files.
792 if (!OidIsValid(relid))
793 relid = GetNewRelFileNode(reltablespace, shared_relation,
797 * Create the relcache entry (mostly dummy at this point) and the physical
798 * disk file. (If we fail further down, it's the smgr's responsibility to
799 * remove the disk file again.)
801 new_rel_desc = heap_create(relname,
808 allow_system_table_mods);
810 Assert(relid == RelationGetRelid(new_rel_desc));
813 * since defining a relation also defines a complex type, we add a new
814 * system type corresponding to the new relation.
816 * NOTE: we could get a unique-index failure here, in case the same name
817 * has already been used for a type.
819 new_type_oid = AddNewRelationType(relname,
825 * now create an entry in pg_class for the relation.
827 * NOTE: we could get a unique-index failure here, in case someone else is
828 * creating the same relation name in parallel but hadn't committed yet
829 * when we checked for a duplicate name above.
831 AddNewRelationTuple(pg_class_desc,
840 * now add tuples to pg_attribute for the attributes in our new relation.
842 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
843 oidislocal, oidinhcount);
846 * make a dependency link to force the relation to be deleted if its
847 * namespace is. Skip this in bootstrap mode, since we don't make
848 * dependencies while bootstrapping.
850 * Also make a dependency link to its owner.
852 if (!IsBootstrapProcessingMode())
854 ObjectAddress myself,
857 myself.classId = RelationRelationId;
858 myself.objectId = relid;
859 myself.objectSubId = 0;
860 referenced.classId = NamespaceRelationId;
861 referenced.objectId = relnamespace;
862 referenced.objectSubId = 0;
863 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
866 * For composite types, the dependency on owner is tracked for the
867 * pg_type entry, so don't record it here. All other relkinds need
868 * their ownership tracked.
870 if (relkind != RELKIND_COMPOSITE_TYPE)
871 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
875 * store constraints and defaults passed in the tupdesc, if any.
877 * NB: this may do a CommandCounterIncrement and rebuild the relcache
878 * entry, so the relation must be valid and self-consistent at this point.
879 * In particular, there are not yet constraints and defaults anywhere.
881 StoreConstraints(new_rel_desc, tupdesc);
884 * If there's a special on-commit action, remember it
886 if (oncommit != ONCOMMIT_NOOP)
887 register_on_commit_action(relid, oncommit);
890 * ok, the relation has been cataloged, so close our relations and return
891 * the OID of the newly created relation.
893 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
894 heap_close(pg_class_desc, RowExclusiveLock);
901 * RelationRemoveInheritance
903 * Formerly, this routine checked for child relations and aborted the
904 * deletion if any were found. Now we rely on the dependency mechanism
905 * to check for or delete child relations. By the time we get here,
906 * there are no children and we need only remove any pg_inherits rows
907 * linking this relation to its parent(s).
910 RelationRemoveInheritance(Oid relid)
912 Relation catalogRelation;
917 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
920 Anum_pg_inherits_inhrelid,
921 BTEqualStrategyNumber, F_OIDEQ,
922 ObjectIdGetDatum(relid));
924 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
925 SnapshotNow, 1, &key);
927 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
928 simple_heap_delete(catalogRelation, &tuple->t_self);
930 systable_endscan(scan);
931 heap_close(catalogRelation, RowExclusiveLock);
935 * DeleteRelationTuple
937 * Remove pg_class row for the given relid.
939 * Note: this is shared by relation deletion and index deletion. It's
940 * not intended for use anyplace else.
943 DeleteRelationTuple(Oid relid)
945 Relation pg_class_desc;
948 /* Grab an appropriate lock on the pg_class relation */
949 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
951 tup = SearchSysCache(RELOID,
952 ObjectIdGetDatum(relid),
954 if (!HeapTupleIsValid(tup))
955 elog(ERROR, "cache lookup failed for relation %u", relid);
957 /* delete the relation tuple from pg_class, and finish up */
958 simple_heap_delete(pg_class_desc, &tup->t_self);
960 ReleaseSysCache(tup);
962 heap_close(pg_class_desc, RowExclusiveLock);
966 * DeleteAttributeTuples
968 * Remove pg_attribute rows for the given relid.
970 * Note: this is shared by relation deletion and index deletion. It's
971 * not intended for use anyplace else.
974 DeleteAttributeTuples(Oid relid)
981 /* Grab an appropriate lock on the pg_attribute relation */
982 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
984 /* Use the index to scan only attributes of the target relation */
986 Anum_pg_attribute_attrelid,
987 BTEqualStrategyNumber, F_OIDEQ,
988 ObjectIdGetDatum(relid));
990 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
991 SnapshotNow, 1, key);
993 /* Delete all the matching tuples */
994 while ((atttup = systable_getnext(scan)) != NULL)
995 simple_heap_delete(attrel, &atttup->t_self);
997 /* Clean up after the scan */
998 systable_endscan(scan);
999 heap_close(attrel, RowExclusiveLock);
1003 * RemoveAttributeById
1005 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1006 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1007 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1008 * is handled by dependency.c.)
1011 RemoveAttributeById(Oid relid, AttrNumber attnum)
1016 Form_pg_attribute attStruct;
1017 char newattname[NAMEDATALEN];
1020 * Grab an exclusive lock on the target table, which we will NOT release
1021 * until end of transaction. (In the simple case where we are directly
1022 * dropping this column, AlterTableDropColumn already did this ... but
1023 * when cascading from a drop of some other object, we may not have any
1026 rel = relation_open(relid, AccessExclusiveLock);
1028 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1030 tuple = SearchSysCacheCopy(ATTNUM,
1031 ObjectIdGetDatum(relid),
1032 Int16GetDatum(attnum),
1034 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1035 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1037 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1041 /* System attribute (probably OID) ... just delete the row */
1043 simple_heap_delete(attr_rel, &tuple->t_self);
1047 /* Dropping user attributes is lots harder */
1049 /* Mark the attribute as dropped */
1050 attStruct->attisdropped = true;
1053 * Set the type OID to invalid. A dropped attribute's type link
1054 * cannot be relied on (once the attribute is dropped, the type might
1055 * be too). Fortunately we do not need the type row --- the only
1056 * really essential information is the type's typlen and typalign,
1057 * which are preserved in the attribute's attlen and attalign. We set
1058 * atttypid to zero here as a means of catching code that incorrectly
1059 * expects it to be valid.
1061 attStruct->atttypid = InvalidOid;
1063 /* Remove any NOT NULL constraint the column may have */
1064 attStruct->attnotnull = false;
1066 /* We don't want to keep stats for it anymore */
1067 attStruct->attstattarget = 0;
1070 * Change the column name to something that isn't likely to conflict
1072 snprintf(newattname, sizeof(newattname),
1073 "........pg.dropped.%d........", attnum);
1074 namestrcpy(&(attStruct->attname), newattname);
1076 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1078 /* keep the system catalog indexes current */
1079 CatalogUpdateIndexes(attr_rel, tuple);
1083 * Because updating the pg_attribute row will trigger a relcache flush for
1084 * the target relation, we need not do anything else to notify other
1085 * backends of the change.
1088 heap_close(attr_rel, RowExclusiveLock);
1091 RemoveStatistics(relid, attnum);
1093 relation_close(rel, NoLock);
1099 * If the specified relation/attribute has a default, remove it.
1100 * (If no default, raise error if complain is true, else return quietly.)
1103 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1104 DropBehavior behavior, bool complain)
1106 Relation attrdef_rel;
1107 ScanKeyData scankeys[2];
1112 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1114 ScanKeyInit(&scankeys[0],
1115 Anum_pg_attrdef_adrelid,
1116 BTEqualStrategyNumber, F_OIDEQ,
1117 ObjectIdGetDatum(relid));
1118 ScanKeyInit(&scankeys[1],
1119 Anum_pg_attrdef_adnum,
1120 BTEqualStrategyNumber, F_INT2EQ,
1121 Int16GetDatum(attnum));
1123 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1124 SnapshotNow, 2, scankeys);
1126 /* There should be at most one matching tuple, but we loop anyway */
1127 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1129 ObjectAddress object;
1131 object.classId = AttrDefaultRelationId;
1132 object.objectId = HeapTupleGetOid(tuple);
1133 object.objectSubId = 0;
1135 performDeletion(&object, behavior);
1140 systable_endscan(scan);
1141 heap_close(attrdef_rel, RowExclusiveLock);
1143 if (complain && !found)
1144 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1149 * RemoveAttrDefaultById
1151 * Remove a pg_attrdef entry specified by OID. This is the guts of
1152 * attribute-default removal. Note it should be called via performDeletion,
1156 RemoveAttrDefaultById(Oid attrdefId)
1158 Relation attrdef_rel;
1161 ScanKeyData scankeys[1];
1165 AttrNumber myattnum;
1167 /* Grab an appropriate lock on the pg_attrdef relation */
1168 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1170 /* Find the pg_attrdef tuple */
1171 ScanKeyInit(&scankeys[0],
1172 ObjectIdAttributeNumber,
1173 BTEqualStrategyNumber, F_OIDEQ,
1174 ObjectIdGetDatum(attrdefId));
1176 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1177 SnapshotNow, 1, scankeys);
1179 tuple = systable_getnext(scan);
1180 if (!HeapTupleIsValid(tuple))
1181 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1183 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1184 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1186 /* Get an exclusive lock on the relation owning the attribute */
1187 myrel = relation_open(myrelid, AccessExclusiveLock);
1189 /* Now we can delete the pg_attrdef row */
1190 simple_heap_delete(attrdef_rel, &tuple->t_self);
1192 systable_endscan(scan);
1193 heap_close(attrdef_rel, RowExclusiveLock);
1195 /* Fix the pg_attribute row */
1196 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1198 tuple = SearchSysCacheCopy(ATTNUM,
1199 ObjectIdGetDatum(myrelid),
1200 Int16GetDatum(myattnum),
1202 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1203 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1206 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1208 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1210 /* keep the system catalog indexes current */
1211 CatalogUpdateIndexes(attr_rel, tuple);
1214 * Our update of the pg_attribute row will force a relcache rebuild, so
1215 * there's nothing else to do here.
1217 heap_close(attr_rel, RowExclusiveLock);
1219 /* Keep lock on attribute's rel until end of xact */
1220 relation_close(myrel, NoLock);
1224 * heap_drop_with_catalog - removes specified relation from catalogs
1226 * Note that this routine is not responsible for dropping objects that are
1227 * linked to the pg_class entry via dependencies (for example, indexes and
1228 * constraints). Those are deleted by the dependency-tracing logic in
1229 * dependency.c before control gets here. In general, therefore, this routine
1230 * should never be called directly; go through performDeletion() instead.
1233 heap_drop_with_catalog(Oid relid)
1238 * Open and lock the relation.
1240 rel = relation_open(relid, AccessExclusiveLock);
1243 * Schedule unlinking of the relation's physical file at commit.
1245 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1246 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
1248 RelationOpenSmgr(rel);
1249 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
1253 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1254 * until transaction commit. This ensures no one else will try to do
1255 * something with the doomed relation.
1257 relation_close(rel, NoLock);
1260 * Forget any ON COMMIT action for the rel
1262 remove_on_commit_action(relid);
1265 * Flush the relation from the relcache. We want to do this before
1266 * starting to remove catalog entries, just to be certain that no relcache
1267 * entry rebuild will happen partway through. (That should not really
1268 * matter, since we don't do CommandCounterIncrement here, but let's be
1271 RelationForgetRelation(relid);
1274 * remove inheritance information
1276 RelationRemoveInheritance(relid);
1281 RemoveStatistics(relid, 0);
1284 * delete attribute tuples
1286 DeleteAttributeTuples(relid);
1289 * delete relation tuple
1291 DeleteRelationTuple(relid);
1296 * Store a default expression for column attnum of relation rel.
1297 * The expression must be presented as a nodeToString() string.
1300 StoreAttrDefault(Relation rel, AttrNumber attnum, char *adbin)
1307 static char nulls[4] = {' ', ' ', ' ', ' '};
1310 Form_pg_attribute attStruct;
1312 ObjectAddress colobject,
1316 * Need to construct source equivalent of given node-string.
1318 expr = stringToNode(adbin);
1323 adsrc = deparse_expression(expr,
1324 deparse_context_for(RelationGetRelationName(rel),
1325 RelationGetRelid(rel)),
1329 * Make the pg_attrdef entry.
1331 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1332 values[Anum_pg_attrdef_adnum - 1] = attnum;
1333 values[Anum_pg_attrdef_adbin - 1] = DirectFunctionCall1(textin,
1334 CStringGetDatum(adbin));
1335 values[Anum_pg_attrdef_adsrc - 1] = DirectFunctionCall1(textin,
1336 CStringGetDatum(adsrc));
1338 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1340 tuple = heap_formtuple(adrel->rd_att, values, nulls);
1341 attrdefOid = simple_heap_insert(adrel, tuple);
1343 CatalogUpdateIndexes(adrel, tuple);
1345 defobject.classId = AttrDefaultRelationId;
1346 defobject.objectId = attrdefOid;
1347 defobject.objectSubId = 0;
1349 heap_close(adrel, RowExclusiveLock);
1351 /* now can free some of the stuff allocated above */
1352 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1353 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1354 heap_freetuple(tuple);
1358 * Update the pg_attribute entry for the column to show that a default
1361 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1362 atttup = SearchSysCacheCopy(ATTNUM,
1363 ObjectIdGetDatum(RelationGetRelid(rel)),
1364 Int16GetDatum(attnum),
1366 if (!HeapTupleIsValid(atttup))
1367 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1368 attnum, RelationGetRelid(rel));
1369 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1370 if (!attStruct->atthasdef)
1372 attStruct->atthasdef = true;
1373 simple_heap_update(attrrel, &atttup->t_self, atttup);
1374 /* keep catalog indexes current */
1375 CatalogUpdateIndexes(attrrel, atttup);
1377 heap_close(attrrel, RowExclusiveLock);
1378 heap_freetuple(atttup);
1381 * Make a dependency so that the pg_attrdef entry goes away if the column
1382 * (or whole table) is deleted.
1384 colobject.classId = RelationRelationId;
1385 colobject.objectId = RelationGetRelid(rel);
1386 colobject.objectSubId = attnum;
1388 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1391 * Record dependencies on objects used in the expression, too.
1393 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1397 * Store a check-constraint expression for the given relation.
1398 * The expression must be presented as a nodeToString() string.
1400 * Caller is responsible for updating the count of constraints
1401 * in the pg_class entry for the relation.
1404 StoreRelCheck(Relation rel, char *ccname, char *ccbin)
1413 * Convert condition to an expression tree.
1415 expr = stringToNode(ccbin);
1420 ccsrc = deparse_expression(expr,
1421 deparse_context_for(RelationGetRelationName(rel),
1422 RelationGetRelid(rel)),
1426 * Find columns of rel that are used in ccbin
1428 * NB: pull_var_clause is okay here only because we don't allow subselects
1429 * in check constraints; it would fail to examine the contents of
1432 varList = pull_var_clause(expr, false);
1433 keycount = list_length(varList);
1440 attNos = (int16 *) palloc(keycount * sizeof(int16));
1441 foreach(vl, varList)
1443 Var *var = (Var *) lfirst(vl);
1446 for (j = 0; j < i; j++)
1447 if (attNos[j] == var->varattno)
1450 attNos[i++] = var->varattno;
1458 * Create the Check Constraint
1460 CreateConstraintEntry(ccname, /* Constraint Name */
1461 RelationGetNamespace(rel), /* namespace */
1462 CONSTRAINT_CHECK, /* Constraint Type */
1463 false, /* Is Deferrable */
1464 false, /* Is Deferred */
1465 RelationGetRelid(rel), /* relation */
1466 attNos, /* attrs in the constraint */
1467 keycount, /* # attrs in the constraint */
1468 InvalidOid, /* not a domain constraint */
1469 InvalidOid, /* Foreign key fields */
1475 InvalidOid, /* no associated index */
1476 expr, /* Tree form check constraint */
1477 ccbin, /* Binary form check constraint */
1478 ccsrc); /* Source form check constraint */
1484 * Store defaults and constraints passed in via the tuple constraint struct.
1486 * NOTE: only pre-cooked expressions will be passed this way, which is to
1487 * say expressions inherited from an existing relation. Newly parsed
1488 * expressions can be added later, by direct calls to StoreAttrDefault
1489 * and StoreRelCheck (see AddRelationRawConstraints()).
1492 StoreConstraints(Relation rel, TupleDesc tupdesc)
1494 TupleConstr *constr = tupdesc->constr;
1498 return; /* nothing to do */
1501 * Deparsing of constraint expressions will fail unless the just-created
1502 * pg_attribute tuples for this relation are made visible. So, bump the
1503 * command counter. CAUTION: this will cause a relcache entry rebuild.
1505 CommandCounterIncrement();
1507 for (i = 0; i < constr->num_defval; i++)
1508 StoreAttrDefault(rel, constr->defval[i].adnum,
1509 constr->defval[i].adbin);
1511 for (i = 0; i < constr->num_check; i++)
1512 StoreRelCheck(rel, constr->check[i].ccname,
1513 constr->check[i].ccbin);
1515 if (constr->num_check > 0)
1516 SetRelationNumChecks(rel, constr->num_check);
1520 * AddRelationRawConstraints
1522 * Add raw (not-yet-transformed) column default expressions and/or constraint
1523 * check expressions to an existing relation. This is defined to do both
1524 * for efficiency in DefineRelation, but of course you can do just one or
1525 * the other by passing empty lists.
1527 * rel: relation to be modified
1528 * rawColDefaults: list of RawColumnDefault structures
1529 * rawConstraints: list of Constraint nodes
1531 * All entries in rawColDefaults will be processed. Entries in rawConstraints
1532 * will be processed only if they are CONSTR_CHECK type and contain a "raw"
1535 * Returns a list of CookedConstraint nodes that shows the cooked form of
1536 * the default and constraint expressions added to the relation.
1538 * NB: caller should have opened rel with AccessExclusiveLock, and should
1539 * hold that lock till end of transaction. Also, we assume the caller has
1540 * done a CommandCounterIncrement if necessary to make the relation's catalog
1544 AddRelationRawConstraints(Relation rel,
1545 List *rawColDefaults,
1546 List *rawConstraints)
1548 List *cookedConstraints = NIL;
1549 TupleDesc tupleDesc;
1550 TupleConstr *oldconstr;
1558 CookedConstraint *cooked;
1561 * Get info about existing constraints.
1563 tupleDesc = RelationGetDescr(rel);
1564 oldconstr = tupleDesc->constr;
1566 numoldchecks = oldconstr->num_check;
1571 * Create a dummy ParseState and insert the target relation as its sole
1572 * rangetable entry. We need a ParseState for transformExpr.
1574 pstate = make_parsestate(NULL);
1575 rte = addRangeTableEntryForRelation(pstate,
1580 addRTEtoQuery(pstate, rte, true, true, true);
1583 * Process column default expressions.
1585 foreach(cell, rawColDefaults)
1587 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
1588 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
1590 expr = cookDefault(pstate, colDef->raw_default,
1591 atp->atttypid, atp->atttypmod,
1592 NameStr(atp->attname));
1594 StoreAttrDefault(rel, colDef->attnum, nodeToString(expr));
1596 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1597 cooked->contype = CONSTR_DEFAULT;
1598 cooked->name = NULL;
1599 cooked->attnum = colDef->attnum;
1600 cooked->expr = expr;
1601 cookedConstraints = lappend(cookedConstraints, cooked);
1605 * Process constraint expressions.
1607 numchecks = numoldchecks;
1609 foreach(cell, rawConstraints)
1611 Constraint *cdef = (Constraint *) lfirst(cell);
1614 if (cdef->contype != CONSTR_CHECK || cdef->raw_expr == NULL)
1616 Assert(cdef->cooked_expr == NULL);
1619 * Transform raw parsetree to executable expression.
1621 expr = transformExpr(pstate, cdef->raw_expr);
1624 * Make sure it yields a boolean result.
1626 expr = coerce_to_boolean(pstate, expr, "CHECK");
1629 * Make sure no outside relations are referred to.
1631 if (list_length(pstate->p_rtable) != 1)
1633 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1634 errmsg("only table \"%s\" can be referenced in check constraint",
1635 RelationGetRelationName(rel))));
1638 * No subplans or aggregates, either...
1640 if (pstate->p_hasSubLinks)
1642 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1643 errmsg("cannot use subquery in check constraint")));
1644 if (pstate->p_hasAggs)
1646 (errcode(ERRCODE_GROUPING_ERROR),
1647 errmsg("cannot use aggregate function in check constraint")));
1650 * Check name uniqueness, or generate a name if none was given.
1652 if (cdef->name != NULL)
1656 ccname = cdef->name;
1657 /* Check against pre-existing constraints */
1658 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
1659 RelationGetRelid(rel),
1660 RelationGetNamespace(rel),
1663 (errcode(ERRCODE_DUPLICATE_OBJECT),
1664 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1665 ccname, RelationGetRelationName(rel))));
1666 /* Check against other new constraints */
1667 /* Needed because we don't do CommandCounterIncrement in loop */
1668 foreach(cell2, checknames)
1670 if (strcmp((char *) lfirst(cell2), ccname) == 0)
1672 (errcode(ERRCODE_DUPLICATE_OBJECT),
1673 errmsg("check constraint \"%s\" already exists",
1680 * When generating a name, we want to create "tab_col_check" for a
1681 * column constraint and "tab_check" for a table constraint. We
1682 * no longer have any info about the syntactic positioning of the
1683 * constraint phrase, so we approximate this by seeing whether the
1684 * expression references more than one column. (If the user
1685 * played by the rules, the result is the same...)
1687 * Note: pull_var_clause() doesn't descend into sublinks, but we
1688 * eliminated those above; and anyway this only needs to be an
1689 * approximate answer.
1694 vars = pull_var_clause(expr, false);
1696 /* eliminate duplicates */
1697 vars = list_union(NIL, vars);
1699 if (list_length(vars) == 1)
1700 colname = get_attname(RelationGetRelid(rel),
1701 ((Var *) linitial(vars))->varattno);
1705 ccname = ChooseConstraintName(RelationGetRelationName(rel),
1708 RelationGetNamespace(rel),
1712 /* save name for future checks */
1713 checknames = lappend(checknames, ccname);
1718 StoreRelCheck(rel, ccname, nodeToString(expr));
1722 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1723 cooked->contype = CONSTR_CHECK;
1724 cooked->name = ccname;
1726 cooked->expr = expr;
1727 cookedConstraints = lappend(cookedConstraints, cooked);
1731 * Update the count of constraints in the relation's pg_class tuple. We do
1732 * this even if there was no change, in order to ensure that an SI update
1733 * message is sent out for the pg_class tuple, which will force other
1734 * backends to rebuild their relcache entries for the rel. (This is
1735 * critical if we added defaults but not constraints.)
1737 SetRelationNumChecks(rel, numchecks);
1739 return cookedConstraints;
1743 * Update the count of constraints in the relation's pg_class tuple.
1745 * Caller had better hold exclusive lock on the relation.
1747 * An important side effect is that a SI update message will be sent out for
1748 * the pg_class tuple, which will force other backends to rebuild their
1749 * relcache entries for the rel. Also, this backend will rebuild its
1750 * own relcache entry at the next CommandCounterIncrement.
1753 SetRelationNumChecks(Relation rel, int numchecks)
1757 Form_pg_class relStruct;
1759 relrel = heap_open(RelationRelationId, RowExclusiveLock);
1760 reltup = SearchSysCacheCopy(RELOID,
1761 ObjectIdGetDatum(RelationGetRelid(rel)),
1763 if (!HeapTupleIsValid(reltup))
1764 elog(ERROR, "cache lookup failed for relation %u",
1765 RelationGetRelid(rel));
1766 relStruct = (Form_pg_class) GETSTRUCT(reltup);
1768 if (relStruct->relchecks != numchecks)
1770 relStruct->relchecks = numchecks;
1772 simple_heap_update(relrel, &reltup->t_self, reltup);
1774 /* keep catalog indexes current */
1775 CatalogUpdateIndexes(relrel, reltup);
1779 /* Skip the disk update, but force relcache inval anyway */
1780 CacheInvalidateRelcache(rel);
1783 heap_freetuple(reltup);
1784 heap_close(relrel, RowExclusiveLock);
1788 * Take a raw default and convert it to a cooked format ready for
1791 * Parse state should be set up to recognize any vars that might appear
1792 * in the expression. (Even though we plan to reject vars, it's more
1793 * user-friendly to give the correct error message than "unknown var".)
1795 * If atttypid is not InvalidOid, coerce the expression to the specified
1796 * type (and typmod atttypmod). attname is only needed in this case:
1797 * it is used in the error message, if any.
1800 cookDefault(ParseState *pstate,
1808 Assert(raw_default != NULL);
1811 * Transform raw parsetree to executable expression.
1813 expr = transformExpr(pstate, raw_default);
1816 * Make sure default expr does not refer to any vars.
1818 if (contain_var_clause(expr))
1820 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1821 errmsg("cannot use column references in default expression")));
1824 * It can't return a set either.
1826 if (expression_returns_set(expr))
1828 (errcode(ERRCODE_DATATYPE_MISMATCH),
1829 errmsg("default expression must not return a set")));
1832 * No subplans or aggregates, either...
1834 if (pstate->p_hasSubLinks)
1836 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1837 errmsg("cannot use subquery in default expression")));
1838 if (pstate->p_hasAggs)
1840 (errcode(ERRCODE_GROUPING_ERROR),
1841 errmsg("cannot use aggregate function in default expression")));
1844 * Coerce the expression to the correct type and typmod, if given. This
1845 * should match the parser's processing of non-defaulted expressions ---
1846 * see updateTargetListEntry().
1848 if (OidIsValid(atttypid))
1850 Oid type_id = exprType(expr);
1852 expr = coerce_to_target_type(pstate, expr, type_id,
1853 atttypid, atttypmod,
1854 COERCION_ASSIGNMENT,
1855 COERCE_IMPLICIT_CAST);
1858 (errcode(ERRCODE_DATATYPE_MISMATCH),
1859 errmsg("column \"%s\" is of type %s"
1860 " but default expression is of type %s",
1862 format_type_be(atttypid),
1863 format_type_be(type_id)),
1864 errhint("You will need to rewrite or cast the expression.")));
1872 * Removes all constraints on a relation that match the given name.
1874 * It is the responsibility of the calling function to acquire a suitable
1875 * lock on the relation.
1877 * Returns: The number of constraints removed.
1880 RemoveRelConstraints(Relation rel, const char *constrName,
1881 DropBehavior behavior)
1885 SysScanDesc conscan;
1889 /* Grab an appropriate lock on the pg_constraint relation */
1890 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
1892 /* Use the index to scan only constraints of the target relation */
1893 ScanKeyInit(&key[0],
1894 Anum_pg_constraint_conrelid,
1895 BTEqualStrategyNumber, F_OIDEQ,
1896 ObjectIdGetDatum(RelationGetRelid(rel)));
1898 conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true,
1899 SnapshotNow, 1, key);
1902 * Scan over the result set, removing any matching entries.
1904 while ((contup = systable_getnext(conscan)) != NULL)
1906 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
1908 if (strcmp(NameStr(con->conname), constrName) == 0)
1910 ObjectAddress conobj;
1912 conobj.classId = ConstraintRelationId;
1913 conobj.objectId = HeapTupleGetOid(contup);
1914 conobj.objectSubId = 0;
1916 performDeletion(&conobj, behavior);
1922 /* Clean up after the scan */
1923 systable_endscan(conscan);
1924 heap_close(conrel, RowExclusiveLock);
1931 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
1933 * If attnum is zero, remove all entries for rel; else remove only the one
1937 RemoveStatistics(Oid relid, AttrNumber attnum)
1939 Relation pgstatistic;
1945 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
1947 ScanKeyInit(&key[0],
1948 Anum_pg_statistic_starelid,
1949 BTEqualStrategyNumber, F_OIDEQ,
1950 ObjectIdGetDatum(relid));
1956 ScanKeyInit(&key[1],
1957 Anum_pg_statistic_staattnum,
1958 BTEqualStrategyNumber, F_INT2EQ,
1959 Int16GetDatum(attnum));
1963 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumIndexId, true,
1964 SnapshotNow, nkeys, key);
1966 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1967 simple_heap_delete(pgstatistic, &tuple->t_self);
1969 systable_endscan(scan);
1971 heap_close(pgstatistic, RowExclusiveLock);
1976 * RelationTruncateIndexes - truncate all
1977 * indexes associated with the heap relation to zero tuples.
1979 * The routine will truncate and then reconstruct the indexes on
1980 * the relation specified by the heapId parameter.
1983 RelationTruncateIndexes(Oid heapId)
1985 Relation heapRelation;
1989 * Open the heap rel. We need grab no lock because we assume
1990 * heap_truncate is holding an exclusive lock on the heap rel.
1992 heapRelation = heap_open(heapId, NoLock);
1994 /* Ask the relcache to produce a list of the indexes of the rel */
1995 foreach(indlist, RelationGetIndexList(heapRelation))
1997 Oid indexId = lfirst_oid(indlist);
1998 Relation currentIndex;
1999 IndexInfo *indexInfo;
2001 /* Open the index relation */
2002 currentIndex = index_open(indexId);
2004 /* Obtain exclusive lock on it, just to be sure */
2005 LockRelation(currentIndex, AccessExclusiveLock);
2007 /* Fetch info needed for index_build */
2008 indexInfo = BuildIndexInfo(currentIndex);
2010 /* Now truncate the actual file (and discard buffers) */
2011 RelationTruncate(currentIndex, 0);
2013 /* Initialize the index and rebuild */
2014 /* Note: we do not need to re-establish pkey or toast settings */
2015 index_build(heapRelation, currentIndex, indexInfo, false, false);
2017 /* We're done with this index */
2018 index_close(currentIndex);
2021 /* And now done with the heap; but keep lock until commit */
2022 heap_close(heapRelation, NoLock);
2028 * This routine deletes all data within all the specified relations.
2030 * This is not transaction-safe! There is another, transaction-safe
2031 * implementation in commands/tablecmds.c. We now use this only for
2032 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2035 heap_truncate(List *relids)
2037 List *relations = NIL;
2040 /* Open relations for processing, and grab exclusive access on each */
2041 foreach(cell, relids)
2043 Oid rid = lfirst_oid(cell);
2047 rel = heap_open(rid, AccessExclusiveLock);
2048 relations = lappend(relations, rel);
2050 /* If there is a toast table, add it to the list too */
2051 toastrelid = rel->rd_rel->reltoastrelid;
2052 if (OidIsValid(toastrelid))
2054 rel = heap_open(toastrelid, AccessExclusiveLock);
2055 relations = lappend(relations, rel);
2059 /* Don't allow truncate on tables that are referenced by foreign keys */
2060 heap_truncate_check_FKs(relations, true);
2063 foreach(cell, relations)
2065 Relation rel = lfirst(cell);
2067 /* Truncate the actual file (and discard buffers) */
2068 RelationTruncate(rel, 0);
2070 /* If this relation has indexes, truncate the indexes too */
2071 RelationTruncateIndexes(RelationGetRelid(rel));
2074 * Close the relation, but keep exclusive lock on it until commit.
2076 heap_close(rel, NoLock);
2081 * heap_truncate_check_FKs
2082 * Check for foreign keys referencing a list of relations that
2083 * are to be truncated, and raise error if there are any
2085 * We disallow such FKs (except self-referential ones) since the whole point
2086 * of TRUNCATE is to not scan the individual rows to be thrown away.
2088 * This is split out so it can be shared by both implementations of truncate.
2089 * Caller should already hold a suitable lock on the relations.
2091 * tempTables is only used to select an appropriate error message.
2094 heap_truncate_check_FKs(List *relations, bool tempTables)
2101 * Build a list of OIDs of the interesting relations.
2103 * If a relation has no triggers, then it can neither have FKs nor be
2104 * referenced by a FK from another table, so we can ignore it.
2106 foreach(cell, relations)
2108 Relation rel = lfirst(cell);
2110 if (rel->rd_rel->reltriggers != 0)
2111 oids = lappend_oid(oids, RelationGetRelid(rel));
2115 * Fast path: if no relation has triggers, none has FKs either.
2121 * Otherwise, must scan pg_constraint. We make one pass with all the
2122 * relations considered; if this finds nothing, then all is well.
2124 dependents = heap_truncate_find_FKs(oids);
2125 if (dependents == NIL)
2129 * Otherwise we repeat the scan once per relation to identify a particular
2130 * pair of relations to complain about. This is pretty slow, but
2131 * performance shouldn't matter much in a failure path. The reason for
2132 * doing things this way is to ensure that the message produced is not
2133 * dependent on chance row locations within pg_constraint.
2137 Oid relid = lfirst_oid(cell);
2140 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2142 foreach(cell2, dependents)
2144 Oid relid2 = lfirst_oid(cell2);
2146 if (!list_member_oid(oids, relid2))
2148 char *relname = get_rel_name(relid);
2149 char *relname2 = get_rel_name(relid2);
2153 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2154 errmsg("unsupported ON COMMIT and foreign key combination"),
2155 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2156 relname2, relname)));
2159 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2160 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2161 errdetail("Table \"%s\" references \"%s\".",
2163 errhint("Truncate table \"%s\" at the same time, "
2164 "or use TRUNCATE ... CASCADE.",
2172 * heap_truncate_find_FKs
2173 * Find relations having foreign keys referencing any of the given rels
2175 * Input and result are both lists of relation OIDs. The result contains
2176 * no duplicates, does *not* include any rels that were already in the input
2177 * list, and is sorted in OID order. (The last property is enforced mainly
2178 * to guarantee consistent behavior in the regression tests; we don't want
2179 * behavior to change depending on chance locations of rows in pg_constraint.)
2181 * Note: caller should already have appropriate lock on all rels mentioned
2182 * in relationIds. Since adding or dropping an FK requires exclusive lock
2183 * on both rels, this ensures that the answer will be stable.
2186 heap_truncate_find_FKs(List *relationIds)
2190 SysScanDesc fkeyScan;
2194 * Must scan pg_constraint. Right now, it is a seqscan because
2195 * there is no available index on confrelid.
2197 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2199 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2200 SnapshotNow, 0, NULL);
2202 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2204 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2206 /* Not a foreign key */
2207 if (con->contype != CONSTRAINT_FOREIGN)
2210 /* Not referencing one of our list of tables */
2211 if (!list_member_oid(relationIds, con->confrelid))
2214 /* Add referencer unless already in input or result list */
2215 if (!list_member_oid(relationIds, con->conrelid))
2216 result = insert_ordered_unique_oid(result, con->conrelid);
2219 systable_endscan(fkeyScan);
2220 heap_close(fkeyRel, AccessShareLock);
2226 * insert_ordered_unique_oid
2227 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2228 * and eliminating duplicates
2230 * Building the ordered list this way is O(N^2), but with a pretty small
2231 * constant, so for the number of entries we expect it will probably be
2232 * faster than trying to apply qsort(). It seems unlikely someone would be
2233 * trying to truncate a table with thousands of dependent tables ...
2236 insert_ordered_unique_oid(List *list, Oid datum)
2240 /* Does the datum belong at the front? */
2241 if (list == NIL || datum < linitial_oid(list))
2242 return lcons_oid(datum, list);
2243 /* Does it match the first entry? */
2244 if (datum == linitial_oid(list))
2245 return list; /* duplicate, so don't insert */
2246 /* No, so find the entry it belongs after */
2247 prev = list_head(list);
2250 ListCell *curr = lnext(prev);
2252 if (curr == NULL || datum < lfirst_oid(curr))
2253 break; /* it belongs after 'prev', before 'curr' */
2255 if (datum == lfirst_oid(curr))
2256 return list; /* duplicate, so don't insert */
2260 /* Insert datum into list after 'prev' */
2261 lappend_cell_oid(list, prev, datum);