1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/catalog/heap.c
15 * heap_create() - Create an uncataloged heap relation
16 * heap_create_with_catalog() - Create a cataloged relation
17 * heap_drop_with_catalog() - Removes named relation from catalogs
20 * this code taken from access/heap/create.c, which contains
21 * the old heap_create_with_catalog, amcreate, and amdestroy.
22 * those routines will soon call these routines using the function
24 * just like the poorly named "NewXXX" routines do. The
25 * "New" routines are all going to die soon, once and for all!
28 *-------------------------------------------------------------------------
32 #include "access/htup_details.h"
33 #include "access/multixact.h"
34 #include "access/sysattr.h"
35 #include "access/transam.h"
36 #include "access/xact.h"
37 #include "access/xlog.h"
38 #include "catalog/binary_upgrade.h"
39 #include "catalog/catalog.h"
40 #include "catalog/dependency.h"
41 #include "catalog/heap.h"
42 #include "catalog/index.h"
43 #include "catalog/objectaccess.h"
44 #include "catalog/pg_attrdef.h"
45 #include "catalog/pg_collation.h"
46 #include "catalog/pg_constraint.h"
47 #include "catalog/pg_constraint_fn.h"
48 #include "catalog/pg_foreign_table.h"
49 #include "catalog/pg_inherits.h"
50 #include "catalog/pg_namespace.h"
51 #include "catalog/pg_statistic.h"
52 #include "catalog/pg_tablespace.h"
53 #include "catalog/pg_type.h"
54 #include "catalog/pg_type_fn.h"
55 #include "catalog/storage.h"
56 #include "catalog/storage_xlog.h"
57 #include "commands/tablecmds.h"
58 #include "commands/typecmds.h"
59 #include "miscadmin.h"
60 #include "nodes/nodeFuncs.h"
61 #include "optimizer/var.h"
62 #include "parser/parse_coerce.h"
63 #include "parser/parse_collate.h"
64 #include "parser/parse_expr.h"
65 #include "parser/parse_relation.h"
66 #include "storage/predicate.h"
67 #include "storage/smgr.h"
68 #include "utils/acl.h"
69 #include "utils/builtins.h"
70 #include "utils/fmgroids.h"
71 #include "utils/inval.h"
72 #include "utils/lsyscache.h"
73 #include "utils/rel.h"
74 #include "utils/ruleutils.h"
75 #include "utils/snapmgr.h"
76 #include "utils/syscache.h"
77 #include "utils/tqual.h"
80 /* Potentially set by pg_upgrade_support functions */
81 Oid binary_upgrade_next_heap_pg_class_oid = InvalidOid;
82 Oid binary_upgrade_next_toast_pg_class_oid = InvalidOid;
84 static void AddNewRelationTuple(Relation pg_class_desc,
85 Relation new_rel_desc,
93 static ObjectAddress AddNewRelationType(const char *typeName,
100 static void RelationRemoveInheritance(Oid relid);
101 static Oid StoreRelCheck(Relation rel, char *ccname, Node *expr,
102 bool is_validated, bool is_local, int inhcount,
103 bool is_no_inherit, bool is_internal);
104 static void StoreConstraints(Relation rel, List *cooked_constraints,
106 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
107 bool allow_merge, bool is_local,
108 bool is_initially_valid,
110 static void SetRelationNumChecks(Relation rel, int numchecks);
111 static Node *cookConstraint(ParseState *pstate,
112 Node *raw_constraint,
114 static List *insert_ordered_unique_oid(List *list, Oid datum);
117 /* ----------------------------------------------------------------
118 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
120 * these should all be moved to someplace in the lib/catalog
121 * module, if not obliterated first.
122 * ----------------------------------------------------------------
128 * Should the system special case these attributes in the future?
129 * Advantage: consume much less space in the ATTRIBUTE relation.
130 * Disadvantage: special cases will be all over the place.
134 * The initializers below do not include trailing variable length fields,
135 * but that's OK - we're never going to reference anything beyond the
136 * fixed-size portion of the structure anyway.
139 static FormData_pg_attribute a1 = {
140 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
141 SelfItemPointerAttributeNumber, 0, -1, -1,
142 false, 'p', 's', true, false, false, true, 0
145 static FormData_pg_attribute a2 = {
146 0, {"oid"}, OIDOID, 0, sizeof(Oid),
147 ObjectIdAttributeNumber, 0, -1, -1,
148 true, 'p', 'i', true, false, false, true, 0
151 static FormData_pg_attribute a3 = {
152 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
153 MinTransactionIdAttributeNumber, 0, -1, -1,
154 true, 'p', 'i', true, false, false, true, 0
157 static FormData_pg_attribute a4 = {
158 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
159 MinCommandIdAttributeNumber, 0, -1, -1,
160 true, 'p', 'i', true, false, false, true, 0
163 static FormData_pg_attribute a5 = {
164 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
165 MaxTransactionIdAttributeNumber, 0, -1, -1,
166 true, 'p', 'i', true, false, false, true, 0
169 static FormData_pg_attribute a6 = {
170 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
171 MaxCommandIdAttributeNumber, 0, -1, -1,
172 true, 'p', 'i', true, false, false, true, 0
176 * We decided to call this attribute "tableoid" rather than say
177 * "classoid" on the basis that in the future there may be more than one
178 * table of a particular class/type. In any case table is still the word
181 static FormData_pg_attribute a7 = {
182 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
183 TableOidAttributeNumber, 0, -1, -1,
184 true, 'p', 'i', true, false, false, true, 0
187 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
190 * This function returns a Form_pg_attribute pointer for a system attribute.
191 * Note that we elog if the presented attno is invalid, which would only
192 * happen if there's a problem upstream.
195 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
197 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
198 elog(ERROR, "invalid system attribute number %d", attno);
199 if (attno == ObjectIdAttributeNumber && !relhasoids)
200 elog(ERROR, "invalid system attribute number %d", attno);
201 return SysAtt[-attno - 1];
205 * If the given name is a system attribute name, return a Form_pg_attribute
206 * pointer for a prototype definition. If not, return NULL.
209 SystemAttributeByName(const char *attname, bool relhasoids)
213 for (j = 0; j < (int) lengthof(SysAtt); j++)
215 Form_pg_attribute att = SysAtt[j];
217 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
219 if (strcmp(NameStr(att->attname), attname) == 0)
228 /* ----------------------------------------------------------------
229 * XXX END OF UGLY HARD CODED BADNESS XXX
230 * ---------------------------------------------------------------- */
233 /* ----------------------------------------------------------------
234 * heap_create - Create an uncataloged heap relation
236 * Note API change: the caller must now always provide the OID
237 * to use for the relation. The relfilenode may (and, normally,
238 * should) be left unspecified.
240 * rel->rd_rel is initialized by RelationBuildLocalRelation,
241 * and is mostly zeroes at return.
242 * ----------------------------------------------------------------
245 heap_create(const char *relname,
253 bool shared_relation,
254 bool mapped_relation,
255 bool allow_system_table_mods)
260 /* The caller must have provided an OID for the relation. */
261 Assert(OidIsValid(relid));
264 * Don't allow creating relations in pg_catalog directly, even though it
265 * is allowed to move user defined relations there. Semantics with search
266 * paths including pg_catalog are too confusing for now.
268 * But allow creating indexes on relations in pg_catalog even if
269 * allow_system_table_mods = off, upper layers already guarantee it's on a
270 * user defined relation, not a system one.
272 if (!allow_system_table_mods &&
273 ((IsSystemNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
274 IsToastNamespace(relnamespace)) &&
275 IsNormalProcessingMode())
277 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
278 errmsg("permission denied to create \"%s.%s\"",
279 get_namespace_name(relnamespace), relname),
280 errdetail("System catalog modifications are currently disallowed.")));
283 * Decide if we need storage or not, and handle a couple other special
284 * cases for particular relkinds.
289 case RELKIND_COMPOSITE_TYPE:
290 case RELKIND_FOREIGN_TABLE:
291 create_storage = false;
294 * Force reltablespace to zero if the relation has no physical
295 * storage. This is mainly just for cleanliness' sake.
297 reltablespace = InvalidOid;
299 case RELKIND_SEQUENCE:
300 create_storage = true;
303 * Force reltablespace to zero for sequences, since we don't
304 * support moving them around into different tablespaces.
306 reltablespace = InvalidOid;
309 create_storage = true;
314 * Unless otherwise requested, the physical ID (relfilenode) is initially
315 * the same as the logical ID (OID). When the caller did specify a
316 * relfilenode, it already exists; do not attempt to create it.
318 if (OidIsValid(relfilenode))
319 create_storage = false;
324 * Never allow a pg_class entry to explicitly specify the database's
325 * default tablespace in reltablespace; force it to zero instead. This
326 * ensures that if the database is cloned with a different default
327 * tablespace, the pg_class entry will still match where CREATE DATABASE
328 * will put the physically copied relation.
330 * Yes, this is a bit of a hack.
332 if (reltablespace == MyDatabaseTableSpace)
333 reltablespace = InvalidOid;
336 * build the relcache entry.
338 rel = RelationBuildLocalRelation(relname,
350 * Have the storage manager create the relation's disk file, if needed.
352 * We only create the main fork here, other forks will be created on
357 RelationOpenSmgr(rel);
358 RelationCreateStorage(rel->rd_node, relpersistence);
364 /* ----------------------------------------------------------------
365 * heap_create_with_catalog - Create a cataloged relation
367 * this is done in multiple steps:
369 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
370 * descriptor contains a valid set of attribute names and types
372 * 2) pg_class is opened and get_relname_relid()
373 * performs a scan to ensure that no relation with the
374 * same name already exists.
376 * 3) heap_create() is called to create the new relation on disk.
378 * 4) TypeCreate() is called to define a new type corresponding
379 * to the new relation.
381 * 5) AddNewRelationTuple() is called to register the
382 * relation in pg_class.
384 * 6) AddNewAttributeTuples() is called to register the
385 * new relation's schema in pg_attribute.
387 * 7) StoreConstraints is called () - vadim 08/22/97
389 * 8) the relations are closed and the new relation's oid
392 * ----------------------------------------------------------------
395 /* --------------------------------
396 * CheckAttributeNamesTypes
398 * this is used to make certain the tuple descriptor contains a
399 * valid set of attribute names and datatypes. a problem simply
400 * generates ereport(ERROR) which aborts the current transaction.
401 * --------------------------------
404 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
405 bool allow_system_table_mods)
409 int natts = tupdesc->natts;
411 /* Sanity check on column count */
412 if (natts < 0 || natts > MaxHeapAttributeNumber)
414 (errcode(ERRCODE_TOO_MANY_COLUMNS),
415 errmsg("tables can have at most %d columns",
416 MaxHeapAttributeNumber)));
419 * first check for collision with system attribute names
421 * Skip this for a view or type relation, since those don't have system
424 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
426 for (i = 0; i < natts; i++)
428 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
429 tupdesc->tdhasoid) != NULL)
431 (errcode(ERRCODE_DUPLICATE_COLUMN),
432 errmsg("column name \"%s\" conflicts with a system column name",
433 NameStr(tupdesc->attrs[i]->attname))));
438 * next check for repeated attribute names
440 for (i = 1; i < natts; i++)
442 for (j = 0; j < i; j++)
444 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
445 NameStr(tupdesc->attrs[i]->attname)) == 0)
447 (errcode(ERRCODE_DUPLICATE_COLUMN),
448 errmsg("column name \"%s\" specified more than once",
449 NameStr(tupdesc->attrs[j]->attname))));
454 * next check the attribute types
456 for (i = 0; i < natts; i++)
458 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
459 tupdesc->attrs[i]->atttypid,
460 tupdesc->attrs[i]->attcollation,
461 NIL, /* assume we're creating a new rowtype */
462 allow_system_table_mods);
466 /* --------------------------------
469 * Verify that the proposed datatype of an attribute is legal.
470 * This is needed mainly because there are types (and pseudo-types)
471 * in the catalogs that we do not support as elements of real tuples.
472 * We also check some other properties required of a table column.
474 * If the attribute is being proposed for addition to an existing table or
475 * composite type, pass a one-element list of the rowtype OID as
476 * containing_rowtypes. When checking a to-be-created rowtype, it's
477 * sufficient to pass NIL, because there could not be any recursive reference
478 * to a not-yet-existing rowtype.
479 * --------------------------------
482 CheckAttributeType(const char *attname,
483 Oid atttypid, Oid attcollation,
484 List *containing_rowtypes,
485 bool allow_system_table_mods)
487 char att_typtype = get_typtype(atttypid);
490 if (atttypid == UNKNOWNOID)
493 * Warn user, but don't fail, if column to be created has UNKNOWN type
494 * (usually as a result of a 'retrieve into' - jolly)
497 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
498 errmsg("column \"%s\" has type \"unknown\"", attname),
499 errdetail("Proceeding with relation creation anyway.")));
501 else if (att_typtype == TYPTYPE_PSEUDO)
504 * Refuse any attempt to create a pseudo-type column, except for a
505 * special hack for pg_statistic: allow ANYARRAY when modifying system
506 * catalogs (this allows creating pg_statistic and cloning it during
509 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
511 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
512 errmsg("column \"%s\" has pseudo-type %s",
513 attname, format_type_be(atttypid))));
515 else if (att_typtype == TYPTYPE_DOMAIN)
518 * If it's a domain, recurse to check its base type.
520 CheckAttributeType(attname, getBaseType(atttypid), attcollation,
522 allow_system_table_mods);
524 else if (att_typtype == TYPTYPE_COMPOSITE)
527 * For a composite type, recurse into its attributes.
534 * Check for self-containment. Eventually we might be able to allow
535 * this (just return without complaint, if so) but it's not clear how
536 * many other places would require anti-recursion defenses before it
537 * would be safe to allow tables to contain their own rowtype.
539 if (list_member_oid(containing_rowtypes, atttypid))
541 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
542 errmsg("composite type %s cannot be made a member of itself",
543 format_type_be(atttypid))));
545 containing_rowtypes = lcons_oid(atttypid, containing_rowtypes);
547 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
549 tupdesc = RelationGetDescr(relation);
551 for (i = 0; i < tupdesc->natts; i++)
553 Form_pg_attribute attr = tupdesc->attrs[i];
555 if (attr->attisdropped)
557 CheckAttributeType(NameStr(attr->attname),
558 attr->atttypid, attr->attcollation,
560 allow_system_table_mods);
563 relation_close(relation, AccessShareLock);
565 containing_rowtypes = list_delete_first(containing_rowtypes);
567 else if (OidIsValid((att_typelem = get_element_type(atttypid))))
570 * Must recurse into array types, too, in case they are composite.
572 CheckAttributeType(attname, att_typelem, attcollation,
574 allow_system_table_mods);
578 * This might not be strictly invalid per SQL standard, but it is pretty
579 * useless, and it cannot be dumped, so we must disallow it.
581 if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
583 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
584 errmsg("no collation was derived for column \"%s\" with collatable type %s",
585 attname, format_type_be(atttypid)),
586 errhint("Use the COLLATE clause to set the collation explicitly.")));
590 * InsertPgAttributeTuple
591 * Construct and insert a new tuple in pg_attribute.
593 * Caller has already opened and locked pg_attribute. new_attribute is the
594 * attribute to insert (but we ignore attacl and attoptions, which are always
595 * initialized to NULL).
597 * indstate is the index state for CatalogIndexInsert. It can be passed as
598 * NULL, in which case we'll fetch the necessary info. (Don't do this when
599 * inserting multiple attributes, because it's a tad more expensive.)
602 InsertPgAttributeTuple(Relation pg_attribute_rel,
603 Form_pg_attribute new_attribute,
604 CatalogIndexState indstate)
606 Datum values[Natts_pg_attribute];
607 bool nulls[Natts_pg_attribute];
610 /* This is a tad tedious, but way cleaner than what we used to do... */
611 memset(values, 0, sizeof(values));
612 memset(nulls, false, sizeof(nulls));
614 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
615 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
616 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
617 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
618 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
619 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
620 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
621 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
622 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
623 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
624 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
625 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
626 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
627 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
628 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
629 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
630 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
631 values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
633 /* start out with empty permissions and empty options */
634 nulls[Anum_pg_attribute_attacl - 1] = true;
635 nulls[Anum_pg_attribute_attoptions - 1] = true;
636 nulls[Anum_pg_attribute_attfdwoptions - 1] = true;
638 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
640 /* finally insert the new tuple, update the indexes, and clean up */
641 simple_heap_insert(pg_attribute_rel, tup);
643 if (indstate != NULL)
644 CatalogIndexInsert(indstate, tup);
646 CatalogUpdateIndexes(pg_attribute_rel, tup);
651 /* --------------------------------
652 * AddNewAttributeTuples
654 * this registers the new relation's schema by adding
655 * tuples to pg_attribute.
656 * --------------------------------
659 AddNewAttributeTuples(Oid new_rel_oid,
665 Form_pg_attribute attr;
668 CatalogIndexState indstate;
669 int natts = tupdesc->natts;
670 ObjectAddress myself,
674 * open pg_attribute and its indexes.
676 rel = heap_open(AttributeRelationId, RowExclusiveLock);
678 indstate = CatalogOpenIndexes(rel);
681 * First we add the user attributes. This is also a convenient place to
682 * add dependencies on their datatypes and collations.
684 for (i = 0; i < natts; i++)
686 attr = tupdesc->attrs[i];
687 /* Fill in the correct relation OID */
688 attr->attrelid = new_rel_oid;
689 /* Make sure these are OK, too */
690 attr->attstattarget = -1;
691 attr->attcacheoff = -1;
693 InsertPgAttributeTuple(rel, attr, indstate);
695 /* Add dependency info */
696 myself.classId = RelationRelationId;
697 myself.objectId = new_rel_oid;
698 myself.objectSubId = i + 1;
699 referenced.classId = TypeRelationId;
700 referenced.objectId = attr->atttypid;
701 referenced.objectSubId = 0;
702 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
704 /* The default collation is pinned, so don't bother recording it */
705 if (OidIsValid(attr->attcollation) &&
706 attr->attcollation != DEFAULT_COLLATION_OID)
708 referenced.classId = CollationRelationId;
709 referenced.objectId = attr->attcollation;
710 referenced.objectSubId = 0;
711 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
716 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
717 * all for a view or type relation. We don't bother with making datatype
718 * dependencies here, since presumably all these types are pinned.
720 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
722 for (i = 0; i < (int) lengthof(SysAtt); i++)
724 FormData_pg_attribute attStruct;
726 /* skip OID where appropriate */
727 if (!tupdesc->tdhasoid &&
728 SysAtt[i]->attnum == ObjectIdAttributeNumber)
731 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
733 /* Fill in the correct relation OID in the copied tuple */
734 attStruct.attrelid = new_rel_oid;
736 /* Fill in correct inheritance info for the OID column */
737 if (attStruct.attnum == ObjectIdAttributeNumber)
739 attStruct.attislocal = oidislocal;
740 attStruct.attinhcount = oidinhcount;
743 InsertPgAttributeTuple(rel, &attStruct, indstate);
750 CatalogCloseIndexes(indstate);
752 heap_close(rel, RowExclusiveLock);
755 /* --------------------------------
758 * Construct and insert a new tuple in pg_class.
760 * Caller has already opened and locked pg_class.
761 * Tuple data is taken from new_rel_desc->rd_rel, except for the
762 * variable-width fields which are not present in a cached reldesc.
763 * relacl and reloptions are passed in Datum form (to avoid having
764 * to reference the data types in heap.h). Pass (Datum) 0 to set them
766 * --------------------------------
769 InsertPgClassTuple(Relation pg_class_desc,
770 Relation new_rel_desc,
775 Form_pg_class rd_rel = new_rel_desc->rd_rel;
776 Datum values[Natts_pg_class];
777 bool nulls[Natts_pg_class];
780 /* This is a tad tedious, but way cleaner than what we used to do... */
781 memset(values, 0, sizeof(values));
782 memset(nulls, false, sizeof(nulls));
784 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
785 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
786 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
787 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
788 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
789 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
790 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
791 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
792 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
793 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
794 values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
795 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
796 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
797 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
798 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
799 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
800 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
801 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
802 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
803 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
804 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
805 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
806 values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
807 values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
808 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
809 values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
810 values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
811 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
812 values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
813 if (relacl != (Datum) 0)
814 values[Anum_pg_class_relacl - 1] = relacl;
816 nulls[Anum_pg_class_relacl - 1] = true;
817 if (reloptions != (Datum) 0)
818 values[Anum_pg_class_reloptions - 1] = reloptions;
820 nulls[Anum_pg_class_reloptions - 1] = true;
822 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
825 * The new tuple must have the oid already chosen for the rel. Sure would
826 * be embarrassing to do this sort of thing in polite company.
828 HeapTupleSetOid(tup, new_rel_oid);
830 /* finally insert the new tuple, update the indexes, and clean up */
831 simple_heap_insert(pg_class_desc, tup);
833 CatalogUpdateIndexes(pg_class_desc, tup);
838 /* --------------------------------
839 * AddNewRelationTuple
841 * this registers the new relation in the catalogs by
842 * adding a tuple to pg_class.
843 * --------------------------------
846 AddNewRelationTuple(Relation pg_class_desc,
847 Relation new_rel_desc,
856 Form_pg_class new_rel_reltup;
859 * first we update some of the information in our uncataloged relation's
860 * relation descriptor.
862 new_rel_reltup = new_rel_desc->rd_rel;
866 case RELKIND_RELATION:
867 case RELKIND_MATVIEW:
869 case RELKIND_TOASTVALUE:
870 /* The relation is real, but as yet empty */
871 new_rel_reltup->relpages = 0;
872 new_rel_reltup->reltuples = 0;
873 new_rel_reltup->relallvisible = 0;
875 case RELKIND_SEQUENCE:
876 /* Sequences always have a known size */
877 new_rel_reltup->relpages = 1;
878 new_rel_reltup->reltuples = 1;
879 new_rel_reltup->relallvisible = 0;
882 /* Views, etc, have no disk storage */
883 new_rel_reltup->relpages = 0;
884 new_rel_reltup->reltuples = 0;
885 new_rel_reltup->relallvisible = 0;
889 /* Initialize relfrozenxid and relminmxid */
890 if (relkind == RELKIND_RELATION ||
891 relkind == RELKIND_MATVIEW ||
892 relkind == RELKIND_TOASTVALUE)
895 * Initialize to the minimum XID that could put tuples in the table.
896 * We know that no xacts older than RecentXmin are still running, so
899 new_rel_reltup->relfrozenxid = RecentXmin;
902 * Similarly, initialize the minimum Multixact to the first value that
903 * could possibly be stored in tuples in the table. Running
904 * transactions could reuse values from their local cache, so we are
905 * careful to consider all currently running multis.
907 * XXX this could be refined further, but is it worth the hassle?
909 new_rel_reltup->relminmxid = GetOldestMultiXactId();
914 * Other relation types will not contain XIDs, so set relfrozenxid to
915 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
916 * we force its xmin to be FrozenTransactionId always; see
917 * commands/sequence.c.)
919 new_rel_reltup->relfrozenxid = InvalidTransactionId;
920 new_rel_reltup->relminmxid = InvalidMultiXactId;
923 new_rel_reltup->relowner = relowner;
924 new_rel_reltup->reltype = new_type_oid;
925 new_rel_reltup->reloftype = reloftype;
927 new_rel_desc->rd_att->tdtypeid = new_type_oid;
929 /* Now build and insert the tuple */
930 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
935 /* --------------------------------
936 * AddNewRelationType -
938 * define a composite type corresponding to the new relation
939 * --------------------------------
942 AddNewRelationType(const char *typeName,
951 TypeCreate(new_row_type, /* optional predetermined OID */
952 typeName, /* type name */
953 typeNamespace, /* type namespace */
954 new_rel_oid, /* relation oid */
955 new_rel_kind, /* relation kind */
956 ownerid, /* owner's ID */
957 -1, /* internal size (varlena) */
958 TYPTYPE_COMPOSITE, /* type-type (composite) */
959 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
960 false, /* composite types are never preferred */
961 DEFAULT_TYPDELIM, /* default array delimiter */
962 F_RECORD_IN, /* input procedure */
963 F_RECORD_OUT, /* output procedure */
964 F_RECORD_RECV, /* receive procedure */
965 F_RECORD_SEND, /* send procedure */
966 InvalidOid, /* typmodin procedure - none */
967 InvalidOid, /* typmodout procedure - none */
968 InvalidOid, /* analyze procedure - default */
969 InvalidOid, /* array element type - irrelevant */
970 false, /* this is not an array type */
971 new_array_type, /* array type if any */
972 InvalidOid, /* domain base type - irrelevant */
973 NULL, /* default value - none */
974 NULL, /* default binary representation */
975 false, /* passed by reference */
976 'd', /* alignment - must be the largest! */
977 'x', /* fully TOASTable */
979 0, /* array dimensions for typBaseType */
980 false, /* Type NOT NULL */
981 InvalidOid); /* rowtypes never have a collation */
984 /* --------------------------------
985 * heap_create_with_catalog
987 * creates a new cataloged relation. see comments above.
990 * relname: name to give to new rel
991 * relnamespace: OID of namespace it goes in
992 * reltablespace: OID of tablespace it goes in
993 * relid: OID to assign to new rel, or InvalidOid to select a new OID
994 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
995 * reloftypeid: if a typed table, OID of underlying type; else InvalidOid
996 * ownerid: OID of new rel's owner
997 * tupdesc: tuple descriptor (source of column definitions)
998 * cooked_constraints: list of precooked check constraints and defaults
999 * relkind: relkind for new rel
1000 * relpersistence: rel's persistence status (permanent, temp, or unlogged)
1001 * shared_relation: TRUE if it's to be a shared relation
1002 * mapped_relation: TRUE if the relation will use the relfilenode map
1003 * oidislocal: TRUE if oid column (if any) should be marked attislocal
1004 * oidinhcount: attinhcount to assign to oid column (if any)
1005 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
1006 * reloptions: reloptions in Datum form, or (Datum) 0 if none
1007 * use_user_acl: TRUE if should look for user-defined default permissions;
1008 * if FALSE, relacl is always set NULL
1009 * allow_system_table_mods: TRUE to allow creation in system namespaces
1010 * is_internal: is this a system-generated catalog?
1012 * Output parameters:
1013 * typaddress: if not null, gets the object address of the new pg_type entry
1015 * Returns the OID of the new relation
1016 * --------------------------------
1019 heap_create_with_catalog(const char *relname,
1027 List *cooked_constraints,
1029 char relpersistence,
1030 bool shared_relation,
1031 bool mapped_relation,
1034 OnCommitAction oncommit,
1037 bool allow_system_table_mods,
1039 ObjectAddress *typaddress)
1041 Relation pg_class_desc;
1042 Relation new_rel_desc;
1047 ObjectAddress new_type_addr;
1048 Oid new_array_oid = InvalidOid;
1050 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1055 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
1057 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
1060 * This would fail later on anyway, if the relation already exists. But
1061 * by catching it here we can emit a nicer error message.
1063 existing_relid = get_relname_relid(relname, relnamespace);
1064 if (existing_relid != InvalidOid)
1066 (errcode(ERRCODE_DUPLICATE_TABLE),
1067 errmsg("relation \"%s\" already exists", relname)));
1070 * Since we are going to create a rowtype as well, also check for
1071 * collision with an existing type name. If there is one and it's an
1072 * autogenerated array, we can rename it out of the way; otherwise we can
1073 * at least give a good error message.
1075 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1076 CStringGetDatum(relname),
1077 ObjectIdGetDatum(relnamespace));
1078 if (OidIsValid(old_type_oid))
1080 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1082 (errcode(ERRCODE_DUPLICATE_OBJECT),
1083 errmsg("type \"%s\" already exists", relname),
1084 errhint("A relation has an associated type of the same name, "
1085 "so you must use a name that doesn't conflict "
1086 "with any existing type.")));
1090 * Shared relations must be in pg_global (last-ditch check)
1092 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1093 elog(ERROR, "shared relations must be placed in pg_global tablespace");
1096 * Allocate an OID for the relation, unless we were told what to use.
1098 * The OID will be the relfilenode as well, so make sure it doesn't
1099 * collide with either pg_class OIDs or existing physical files.
1101 if (!OidIsValid(relid))
1103 /* Use binary-upgrade override for pg_class.oid/relfilenode? */
1104 if (IsBinaryUpgrade &&
1105 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
1106 relkind == RELKIND_VIEW || relkind == RELKIND_MATVIEW ||
1107 relkind == RELKIND_COMPOSITE_TYPE || relkind == RELKIND_FOREIGN_TABLE))
1109 if (!OidIsValid(binary_upgrade_next_heap_pg_class_oid))
1111 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1112 errmsg("pg_class heap OID value not set when in binary upgrade mode")));
1114 relid = binary_upgrade_next_heap_pg_class_oid;
1115 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1117 /* There might be no TOAST table, so we have to test for it. */
1118 else if (IsBinaryUpgrade &&
1119 OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1120 relkind == RELKIND_TOASTVALUE)
1122 relid = binary_upgrade_next_toast_pg_class_oid;
1123 binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1126 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1131 * Determine the relation's initial permissions.
1137 case RELKIND_RELATION:
1139 case RELKIND_MATVIEW:
1140 case RELKIND_FOREIGN_TABLE:
1141 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1144 case RELKIND_SEQUENCE:
1145 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1157 * Create the relcache entry (mostly dummy at this point) and the physical
1158 * disk file. (If we fail further down, it's the smgr's responsibility to
1159 * remove the disk file again.)
1161 new_rel_desc = heap_create(relname,
1171 allow_system_table_mods);
1173 Assert(relid == RelationGetRelid(new_rel_desc));
1176 * Decide whether to create an array type over the relation's rowtype. We
1177 * do not create any array types for system catalogs (ie, those made
1178 * during initdb). We do not create them where the use of a relation as
1179 * such is an implementation detail: toast tables, sequences and indexes.
1181 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1182 relkind == RELKIND_VIEW ||
1183 relkind == RELKIND_MATVIEW ||
1184 relkind == RELKIND_FOREIGN_TABLE ||
1185 relkind == RELKIND_COMPOSITE_TYPE))
1186 new_array_oid = AssignTypeArrayOid();
1189 * Since defining a relation also defines a complex type, we add a new
1190 * system type corresponding to the new relation. The OID of the type can
1191 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1192 * generate a new OID for it.
1194 * NOTE: we could get a unique-index failure here, in case someone else is
1195 * creating the same type name in parallel but hadn't committed yet when
1196 * we checked for a duplicate name above.
1198 new_type_addr = AddNewRelationType(relname,
1205 new_type_oid = new_type_addr.objectId;
1207 *typaddress = new_type_addr;
1210 * Now make the array type if wanted.
1212 if (OidIsValid(new_array_oid))
1216 relarrayname = makeArrayTypeName(relname, relnamespace);
1218 TypeCreate(new_array_oid, /* force the type's OID to this */
1219 relarrayname, /* Array type name */
1220 relnamespace, /* Same namespace as parent */
1221 InvalidOid, /* Not composite, no relationOid */
1222 0, /* relkind, also N/A here */
1223 ownerid, /* owner's ID */
1224 -1, /* Internal size (varlena) */
1225 TYPTYPE_BASE, /* Not composite - typelem is */
1226 TYPCATEGORY_ARRAY, /* type-category (array) */
1227 false, /* array types are never preferred */
1228 DEFAULT_TYPDELIM, /* default array delimiter */
1229 F_ARRAY_IN, /* array input proc */
1230 F_ARRAY_OUT, /* array output proc */
1231 F_ARRAY_RECV, /* array recv (bin) proc */
1232 F_ARRAY_SEND, /* array send (bin) proc */
1233 InvalidOid, /* typmodin procedure - none */
1234 InvalidOid, /* typmodout procedure - none */
1235 F_ARRAY_TYPANALYZE, /* array analyze procedure */
1236 new_type_oid, /* array element type - the rowtype */
1237 true, /* yes, this is an array type */
1238 InvalidOid, /* this has no array type */
1239 InvalidOid, /* domain base type - irrelevant */
1240 NULL, /* default value - none */
1241 NULL, /* default binary representation */
1242 false, /* passed by reference */
1243 'd', /* alignment - must be the largest! */
1244 'x', /* fully TOASTable */
1246 0, /* array dimensions for typBaseType */
1247 false, /* Type NOT NULL */
1248 InvalidOid); /* rowtypes never have a collation */
1250 pfree(relarrayname);
1254 * now create an entry in pg_class for the relation.
1256 * NOTE: we could get a unique-index failure here, in case someone else is
1257 * creating the same relation name in parallel but hadn't committed yet
1258 * when we checked for a duplicate name above.
1260 AddNewRelationTuple(pg_class_desc,
1267 PointerGetDatum(relacl),
1271 * now add tuples to pg_attribute for the attributes in our new relation.
1273 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1274 oidislocal, oidinhcount);
1277 * Make a dependency link to force the relation to be deleted if its
1278 * namespace is. Also make a dependency link to its owner, as well as
1279 * dependencies for any roles mentioned in the default ACL.
1281 * For composite types, these dependencies are tracked for the pg_type
1282 * entry, so we needn't record them here. Likewise, TOAST tables don't
1283 * need a namespace dependency (they live in a pinned namespace) nor an
1284 * owner dependency (they depend indirectly through the parent table), nor
1285 * should they have any ACL entries. The same applies for extension
1288 * Also, skip this in bootstrap mode, since we don't make dependencies
1289 * while bootstrapping.
1291 if (relkind != RELKIND_COMPOSITE_TYPE &&
1292 relkind != RELKIND_TOASTVALUE &&
1293 !IsBootstrapProcessingMode())
1295 ObjectAddress myself,
1298 myself.classId = RelationRelationId;
1299 myself.objectId = relid;
1300 myself.objectSubId = 0;
1301 referenced.classId = NamespaceRelationId;
1302 referenced.objectId = relnamespace;
1303 referenced.objectSubId = 0;
1304 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1306 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1308 recordDependencyOnCurrentExtension(&myself, false);
1312 referenced.classId = TypeRelationId;
1313 referenced.objectId = reloftypeid;
1314 referenced.objectSubId = 0;
1315 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1323 nnewmembers = aclmembers(relacl, &newmembers);
1324 updateAclDependencies(RelationRelationId, relid, 0,
1327 nnewmembers, newmembers);
1331 /* Post creation hook for new relation */
1332 InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
1335 * Store any supplied constraints and defaults.
1337 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1338 * entry, so the relation must be valid and self-consistent at this point.
1339 * In particular, there are not yet constraints and defaults anywhere.
1341 StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
1344 * If there's a special on-commit action, remember it
1346 if (oncommit != ONCOMMIT_NOOP)
1347 register_on_commit_action(relid, oncommit);
1349 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1351 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW ||
1352 relkind == RELKIND_TOASTVALUE);
1353 heap_create_init_fork(new_rel_desc);
1357 * ok, the relation has been cataloged, so close our relations and return
1358 * the OID of the newly created relation.
1360 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1361 heap_close(pg_class_desc, RowExclusiveLock);
1367 * Set up an init fork for an unlogged table so that it can be correctly
1368 * reinitialized on restart. Since we're going to do an immediate sync, we
1369 * only need to xlog this if archiving or streaming is enabled. And the
1370 * immediate sync is required, because otherwise there's no guarantee that
1371 * this will hit the disk before the next checkpoint moves the redo pointer.
1374 heap_create_init_fork(Relation rel)
1376 RelationOpenSmgr(rel);
1377 smgrcreate(rel->rd_smgr, INIT_FORKNUM, false);
1379 log_smgrcreate(&rel->rd_smgr->smgr_rnode.node, INIT_FORKNUM);
1380 smgrimmedsync(rel->rd_smgr, INIT_FORKNUM);
1384 * RelationRemoveInheritance
1386 * Formerly, this routine checked for child relations and aborted the
1387 * deletion if any were found. Now we rely on the dependency mechanism
1388 * to check for or delete child relations. By the time we get here,
1389 * there are no children and we need only remove any pg_inherits rows
1390 * linking this relation to its parent(s).
1393 RelationRemoveInheritance(Oid relid)
1395 Relation catalogRelation;
1400 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1403 Anum_pg_inherits_inhrelid,
1404 BTEqualStrategyNumber, F_OIDEQ,
1405 ObjectIdGetDatum(relid));
1407 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1410 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1411 simple_heap_delete(catalogRelation, &tuple->t_self);
1413 systable_endscan(scan);
1414 heap_close(catalogRelation, RowExclusiveLock);
1418 * DeleteRelationTuple
1420 * Remove pg_class row for the given relid.
1422 * Note: this is shared by relation deletion and index deletion. It's
1423 * not intended for use anyplace else.
1426 DeleteRelationTuple(Oid relid)
1428 Relation pg_class_desc;
1431 /* Grab an appropriate lock on the pg_class relation */
1432 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1434 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1435 if (!HeapTupleIsValid(tup))
1436 elog(ERROR, "cache lookup failed for relation %u", relid);
1438 /* delete the relation tuple from pg_class, and finish up */
1439 simple_heap_delete(pg_class_desc, &tup->t_self);
1441 ReleaseSysCache(tup);
1443 heap_close(pg_class_desc, RowExclusiveLock);
1447 * DeleteAttributeTuples
1449 * Remove pg_attribute rows for the given relid.
1451 * Note: this is shared by relation deletion and index deletion. It's
1452 * not intended for use anyplace else.
1455 DeleteAttributeTuples(Oid relid)
1462 /* Grab an appropriate lock on the pg_attribute relation */
1463 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1465 /* Use the index to scan only attributes of the target relation */
1466 ScanKeyInit(&key[0],
1467 Anum_pg_attribute_attrelid,
1468 BTEqualStrategyNumber, F_OIDEQ,
1469 ObjectIdGetDatum(relid));
1471 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1474 /* Delete all the matching tuples */
1475 while ((atttup = systable_getnext(scan)) != NULL)
1476 simple_heap_delete(attrel, &atttup->t_self);
1478 /* Clean up after the scan */
1479 systable_endscan(scan);
1480 heap_close(attrel, RowExclusiveLock);
1484 * DeleteSystemAttributeTuples
1486 * Remove pg_attribute rows for system columns of the given relid.
1488 * Note: this is only used when converting a table to a view. Views don't
1489 * have system columns, so we should remove them from pg_attribute.
1492 DeleteSystemAttributeTuples(Oid relid)
1499 /* Grab an appropriate lock on the pg_attribute relation */
1500 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1502 /* Use the index to scan only system attributes of the target relation */
1503 ScanKeyInit(&key[0],
1504 Anum_pg_attribute_attrelid,
1505 BTEqualStrategyNumber, F_OIDEQ,
1506 ObjectIdGetDatum(relid));
1507 ScanKeyInit(&key[1],
1508 Anum_pg_attribute_attnum,
1509 BTLessEqualStrategyNumber, F_INT2LE,
1512 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1515 /* Delete all the matching tuples */
1516 while ((atttup = systable_getnext(scan)) != NULL)
1517 simple_heap_delete(attrel, &atttup->t_self);
1519 /* Clean up after the scan */
1520 systable_endscan(scan);
1521 heap_close(attrel, RowExclusiveLock);
1525 * RemoveAttributeById
1527 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1528 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1529 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1530 * is handled by dependency.c.)
1533 RemoveAttributeById(Oid relid, AttrNumber attnum)
1538 Form_pg_attribute attStruct;
1539 char newattname[NAMEDATALEN];
1542 * Grab an exclusive lock on the target table, which we will NOT release
1543 * until end of transaction. (In the simple case where we are directly
1544 * dropping this column, AlterTableDropColumn already did this ... but
1545 * when cascading from a drop of some other object, we may not have any
1548 rel = relation_open(relid, AccessExclusiveLock);
1550 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1552 tuple = SearchSysCacheCopy2(ATTNUM,
1553 ObjectIdGetDatum(relid),
1554 Int16GetDatum(attnum));
1555 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1556 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1558 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1562 /* System attribute (probably OID) ... just delete the row */
1564 simple_heap_delete(attr_rel, &tuple->t_self);
1568 /* Dropping user attributes is lots harder */
1570 /* Mark the attribute as dropped */
1571 attStruct->attisdropped = true;
1574 * Set the type OID to invalid. A dropped attribute's type link
1575 * cannot be relied on (once the attribute is dropped, the type might
1576 * be too). Fortunately we do not need the type row --- the only
1577 * really essential information is the type's typlen and typalign,
1578 * which are preserved in the attribute's attlen and attalign. We set
1579 * atttypid to zero here as a means of catching code that incorrectly
1580 * expects it to be valid.
1582 attStruct->atttypid = InvalidOid;
1584 /* Remove any NOT NULL constraint the column may have */
1585 attStruct->attnotnull = false;
1587 /* We don't want to keep stats for it anymore */
1588 attStruct->attstattarget = 0;
1591 * Change the column name to something that isn't likely to conflict
1593 snprintf(newattname, sizeof(newattname),
1594 "........pg.dropped.%d........", attnum);
1595 namestrcpy(&(attStruct->attname), newattname);
1597 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1599 /* keep the system catalog indexes current */
1600 CatalogUpdateIndexes(attr_rel, tuple);
1604 * Because updating the pg_attribute row will trigger a relcache flush for
1605 * the target relation, we need not do anything else to notify other
1606 * backends of the change.
1609 heap_close(attr_rel, RowExclusiveLock);
1612 RemoveStatistics(relid, attnum);
1614 relation_close(rel, NoLock);
1620 * If the specified relation/attribute has a default, remove it.
1621 * (If no default, raise error if complain is true, else return quietly.)
1624 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1625 DropBehavior behavior, bool complain, bool internal)
1627 Relation attrdef_rel;
1628 ScanKeyData scankeys[2];
1633 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1635 ScanKeyInit(&scankeys[0],
1636 Anum_pg_attrdef_adrelid,
1637 BTEqualStrategyNumber, F_OIDEQ,
1638 ObjectIdGetDatum(relid));
1639 ScanKeyInit(&scankeys[1],
1640 Anum_pg_attrdef_adnum,
1641 BTEqualStrategyNumber, F_INT2EQ,
1642 Int16GetDatum(attnum));
1644 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1647 /* There should be at most one matching tuple, but we loop anyway */
1648 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1650 ObjectAddress object;
1652 object.classId = AttrDefaultRelationId;
1653 object.objectId = HeapTupleGetOid(tuple);
1654 object.objectSubId = 0;
1656 performDeletion(&object, behavior,
1657 internal ? PERFORM_DELETION_INTERNAL : 0);
1662 systable_endscan(scan);
1663 heap_close(attrdef_rel, RowExclusiveLock);
1665 if (complain && !found)
1666 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1671 * RemoveAttrDefaultById
1673 * Remove a pg_attrdef entry specified by OID. This is the guts of
1674 * attribute-default removal. Note it should be called via performDeletion,
1678 RemoveAttrDefaultById(Oid attrdefId)
1680 Relation attrdef_rel;
1683 ScanKeyData scankeys[1];
1687 AttrNumber myattnum;
1689 /* Grab an appropriate lock on the pg_attrdef relation */
1690 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1692 /* Find the pg_attrdef tuple */
1693 ScanKeyInit(&scankeys[0],
1694 ObjectIdAttributeNumber,
1695 BTEqualStrategyNumber, F_OIDEQ,
1696 ObjectIdGetDatum(attrdefId));
1698 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1701 tuple = systable_getnext(scan);
1702 if (!HeapTupleIsValid(tuple))
1703 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1705 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1706 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1708 /* Get an exclusive lock on the relation owning the attribute */
1709 myrel = relation_open(myrelid, AccessExclusiveLock);
1711 /* Now we can delete the pg_attrdef row */
1712 simple_heap_delete(attrdef_rel, &tuple->t_self);
1714 systable_endscan(scan);
1715 heap_close(attrdef_rel, RowExclusiveLock);
1717 /* Fix the pg_attribute row */
1718 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1720 tuple = SearchSysCacheCopy2(ATTNUM,
1721 ObjectIdGetDatum(myrelid),
1722 Int16GetDatum(myattnum));
1723 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1724 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1727 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1729 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1731 /* keep the system catalog indexes current */
1732 CatalogUpdateIndexes(attr_rel, tuple);
1735 * Our update of the pg_attribute row will force a relcache rebuild, so
1736 * there's nothing else to do here.
1738 heap_close(attr_rel, RowExclusiveLock);
1740 /* Keep lock on attribute's rel until end of xact */
1741 relation_close(myrel, NoLock);
1745 * heap_drop_with_catalog - removes specified relation from catalogs
1747 * Note that this routine is not responsible for dropping objects that are
1748 * linked to the pg_class entry via dependencies (for example, indexes and
1749 * constraints). Those are deleted by the dependency-tracing logic in
1750 * dependency.c before control gets here. In general, therefore, this routine
1751 * should never be called directly; go through performDeletion() instead.
1754 heap_drop_with_catalog(Oid relid)
1759 * Open and lock the relation.
1761 rel = relation_open(relid, AccessExclusiveLock);
1764 * There can no longer be anyone *else* touching the relation, but we
1765 * might still have open queries or cursors, or pending trigger events, in
1768 CheckTableNotInUse(rel, "DROP TABLE");
1771 * This effectively deletes all rows in the table, and may be done in a
1772 * serializable transaction. In that case we must record a rw-conflict in
1773 * to this transaction from each transaction holding a predicate lock on
1776 CheckTableForSerializableConflictIn(rel);
1779 * Delete pg_foreign_table tuple first.
1781 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1786 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1788 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1789 if (!HeapTupleIsValid(tuple))
1790 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1792 simple_heap_delete(rel, &tuple->t_self);
1794 ReleaseSysCache(tuple);
1795 heap_close(rel, RowExclusiveLock);
1799 * Schedule unlinking of the relation's physical files at commit.
1801 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1802 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1803 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1805 RelationDropStorage(rel);
1809 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1810 * until transaction commit. This ensures no one else will try to do
1811 * something with the doomed relation.
1813 relation_close(rel, NoLock);
1816 * Forget any ON COMMIT action for the rel
1818 remove_on_commit_action(relid);
1821 * Flush the relation from the relcache. We want to do this before
1822 * starting to remove catalog entries, just to be certain that no relcache
1823 * entry rebuild will happen partway through. (That should not really
1824 * matter, since we don't do CommandCounterIncrement here, but let's be
1827 RelationForgetRelation(relid);
1830 * remove inheritance information
1832 RelationRemoveInheritance(relid);
1837 RemoveStatistics(relid, 0);
1840 * delete attribute tuples
1842 DeleteAttributeTuples(relid);
1845 * delete relation tuple
1847 DeleteRelationTuple(relid);
1852 * Store a default expression for column attnum of relation rel.
1854 * Returns the OID of the new pg_attrdef tuple.
1857 StoreAttrDefault(Relation rel, AttrNumber attnum,
1858 Node *expr, bool is_internal)
1865 static bool nulls[4] = {false, false, false, false};
1868 Form_pg_attribute attStruct;
1870 ObjectAddress colobject,
1874 * Flatten expression to string form for storage.
1876 adbin = nodeToString(expr);
1879 * Also deparse it to form the mostly-obsolete adsrc field.
1881 adsrc = deparse_expression(expr,
1882 deparse_context_for(RelationGetRelationName(rel),
1883 RelationGetRelid(rel)),
1887 * Make the pg_attrdef entry.
1889 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1890 values[Anum_pg_attrdef_adnum - 1] = attnum;
1891 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1892 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1894 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1896 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1897 attrdefOid = simple_heap_insert(adrel, tuple);
1899 CatalogUpdateIndexes(adrel, tuple);
1901 defobject.classId = AttrDefaultRelationId;
1902 defobject.objectId = attrdefOid;
1903 defobject.objectSubId = 0;
1905 heap_close(adrel, RowExclusiveLock);
1907 /* now can free some of the stuff allocated above */
1908 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1909 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1910 heap_freetuple(tuple);
1915 * Update the pg_attribute entry for the column to show that a default
1918 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1919 atttup = SearchSysCacheCopy2(ATTNUM,
1920 ObjectIdGetDatum(RelationGetRelid(rel)),
1921 Int16GetDatum(attnum));
1922 if (!HeapTupleIsValid(atttup))
1923 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1924 attnum, RelationGetRelid(rel));
1925 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1926 if (!attStruct->atthasdef)
1928 attStruct->atthasdef = true;
1929 simple_heap_update(attrrel, &atttup->t_self, atttup);
1930 /* keep catalog indexes current */
1931 CatalogUpdateIndexes(attrrel, atttup);
1933 heap_close(attrrel, RowExclusiveLock);
1934 heap_freetuple(atttup);
1937 * Make a dependency so that the pg_attrdef entry goes away if the column
1938 * (or whole table) is deleted.
1940 colobject.classId = RelationRelationId;
1941 colobject.objectId = RelationGetRelid(rel);
1942 colobject.objectSubId = attnum;
1944 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1947 * Record dependencies on objects used in the expression, too.
1949 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1952 * Post creation hook for attribute defaults.
1954 * XXX. ALTER TABLE ALTER COLUMN SET/DROP DEFAULT is implemented with a
1955 * couple of deletion/creation of the attribute's default entry, so the
1956 * callee should check existence of an older version of this entry if it
1957 * needs to distinguish.
1959 InvokeObjectPostCreateHookArg(AttrDefaultRelationId,
1960 RelationGetRelid(rel), attnum, is_internal);
1966 * Store a check-constraint expression for the given relation.
1968 * Caller is responsible for updating the count of constraints
1969 * in the pg_class entry for the relation.
1971 * The OID of the new constraint is returned.
1974 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1975 bool is_validated, bool is_local, int inhcount,
1976 bool is_no_inherit, bool is_internal)
1986 * Flatten expression to string form for storage.
1988 ccbin = nodeToString(expr);
1991 * Also deparse it to form the mostly-obsolete consrc field.
1993 ccsrc = deparse_expression(expr,
1994 deparse_context_for(RelationGetRelationName(rel),
1995 RelationGetRelid(rel)),
1999 * Find columns of rel that are used in expr
2001 * NB: pull_var_clause is okay here only because we don't allow subselects
2002 * in check constraints; it would fail to examine the contents of
2005 varList = pull_var_clause(expr, 0);
2006 keycount = list_length(varList);
2013 attNos = (int16 *) palloc(keycount * sizeof(int16));
2014 foreach(vl, varList)
2016 Var *var = (Var *) lfirst(vl);
2019 for (j = 0; j < i; j++)
2020 if (attNos[j] == var->varattno)
2023 attNos[i++] = var->varattno;
2031 * Create the Check Constraint
2034 CreateConstraintEntry(ccname, /* Constraint Name */
2035 RelationGetNamespace(rel), /* namespace */
2036 CONSTRAINT_CHECK, /* Constraint Type */
2037 false, /* Is Deferrable */
2038 false, /* Is Deferred */
2040 RelationGetRelid(rel), /* relation */
2041 attNos, /* attrs in the constraint */
2042 keycount, /* # attrs in the constraint */
2043 InvalidOid, /* not a domain constraint */
2044 InvalidOid, /* no associated index */
2045 InvalidOid, /* Foreign key fields */
2054 NULL, /* not an exclusion constraint */
2055 expr, /* Tree form of check constraint */
2056 ccbin, /* Binary form of check constraint */
2057 ccsrc, /* Source form of check constraint */
2058 is_local, /* conislocal */
2059 inhcount, /* coninhcount */
2060 is_no_inherit, /* connoinherit */
2061 is_internal); /* internally constructed? */
2070 * Store defaults and constraints (passed as a list of CookedConstraint).
2072 * Each CookedConstraint struct is modified to store the new catalog tuple OID.
2074 * NOTE: only pre-cooked expressions will be passed this way, which is to
2075 * say expressions inherited from an existing relation. Newly parsed
2076 * expressions can be added later, by direct calls to StoreAttrDefault
2077 * and StoreRelCheck (see AddRelationNewConstraints()).
2080 StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
2085 if (cooked_constraints == NIL)
2086 return; /* nothing to do */
2089 * Deparsing of constraint expressions will fail unless the just-created
2090 * pg_attribute tuples for this relation are made visible. So, bump the
2091 * command counter. CAUTION: this will cause a relcache entry rebuild.
2093 CommandCounterIncrement();
2095 foreach(lc, cooked_constraints)
2097 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
2099 switch (con->contype)
2101 case CONSTR_DEFAULT:
2102 con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
2107 StoreRelCheck(rel, con->name, con->expr,
2108 !con->skip_validation, con->is_local,
2109 con->inhcount, con->is_no_inherit,
2114 elog(ERROR, "unrecognized constraint type: %d",
2115 (int) con->contype);
2120 SetRelationNumChecks(rel, numchecks);
2124 * AddRelationNewConstraints
2126 * Add new column default expressions and/or constraint check expressions
2127 * to an existing relation. This is defined to do both for efficiency in
2128 * DefineRelation, but of course you can do just one or the other by passing
2131 * rel: relation to be modified
2132 * newColDefaults: list of RawColumnDefault structures
2133 * newConstraints: list of Constraint nodes
2134 * allow_merge: TRUE if check constraints may be merged with existing ones
2135 * is_local: TRUE if definition is local, FALSE if it's inherited
2136 * is_internal: TRUE if result of some internal process, not a user request
2138 * All entries in newColDefaults will be processed. Entries in newConstraints
2139 * will be processed only if they are CONSTR_CHECK type.
2141 * Returns a list of CookedConstraint nodes that shows the cooked form of
2142 * the default and constraint expressions added to the relation.
2144 * NB: caller should have opened rel with AccessExclusiveLock, and should
2145 * hold that lock till end of transaction. Also, we assume the caller has
2146 * done a CommandCounterIncrement if necessary to make the relation's catalog
2150 AddRelationNewConstraints(Relation rel,
2151 List *newColDefaults,
2152 List *newConstraints,
2157 List *cookedConstraints = NIL;
2158 TupleDesc tupleDesc;
2159 TupleConstr *oldconstr;
2167 CookedConstraint *cooked;
2170 * Get info about existing constraints.
2172 tupleDesc = RelationGetDescr(rel);
2173 oldconstr = tupleDesc->constr;
2175 numoldchecks = oldconstr->num_check;
2180 * Create a dummy ParseState and insert the target relation as its sole
2181 * rangetable entry. We need a ParseState for transformExpr.
2183 pstate = make_parsestate(NULL);
2184 rte = addRangeTableEntryForRelation(pstate,
2189 addRTEtoQuery(pstate, rte, true, true, true);
2192 * Process column default expressions.
2194 foreach(cell, newColDefaults)
2196 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
2197 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
2200 expr = cookDefault(pstate, colDef->raw_default,
2201 atp->atttypid, atp->atttypmod,
2202 NameStr(atp->attname));
2205 * If the expression is just a NULL constant, we do not bother to make
2206 * an explicit pg_attrdef entry, since the default behavior is
2209 * Note a nonobvious property of this test: if the column is of a
2210 * domain type, what we'll get is not a bare null Const but a
2211 * CoerceToDomain expr, so we will not discard the default. This is
2212 * critical because the column default needs to be retained to
2213 * override any default that the domain might have.
2216 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2219 defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
2221 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2222 cooked->contype = CONSTR_DEFAULT;
2223 cooked->conoid = defOid;
2224 cooked->name = NULL;
2225 cooked->attnum = colDef->attnum;
2226 cooked->expr = expr;
2227 cooked->skip_validation = false;
2228 cooked->is_local = is_local;
2229 cooked->inhcount = is_local ? 0 : 1;
2230 cooked->is_no_inherit = false;
2231 cookedConstraints = lappend(cookedConstraints, cooked);
2235 * Process constraint expressions.
2237 numchecks = numoldchecks;
2239 foreach(cell, newConstraints)
2241 Constraint *cdef = (Constraint *) lfirst(cell);
2245 if (cdef->contype != CONSTR_CHECK)
2248 if (cdef->raw_expr != NULL)
2250 Assert(cdef->cooked_expr == NULL);
2253 * Transform raw parsetree to executable expression, and verify
2254 * it's valid as a CHECK constraint.
2256 expr = cookConstraint(pstate, cdef->raw_expr,
2257 RelationGetRelationName(rel));
2261 Assert(cdef->cooked_expr != NULL);
2264 * Here, we assume the parser will only pass us valid CHECK
2265 * expressions, so we do no particular checking.
2267 expr = stringToNode(cdef->cooked_expr);
2271 * Check name uniqueness, or generate a name if none was given.
2273 if (cdef->conname != NULL)
2277 ccname = cdef->conname;
2278 /* Check against other new constraints */
2279 /* Needed because we don't do CommandCounterIncrement in loop */
2280 foreach(cell2, checknames)
2282 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2284 (errcode(ERRCODE_DUPLICATE_OBJECT),
2285 errmsg("check constraint \"%s\" already exists",
2289 /* save name for future checks */
2290 checknames = lappend(checknames, ccname);
2293 * Check against pre-existing constraints. If we are allowed to
2294 * merge with an existing constraint, there's no more to do here.
2295 * (We omit the duplicate constraint from the result, which is
2296 * what ATAddCheckConstraint wants.)
2298 if (MergeWithExistingConstraint(rel, ccname, expr,
2299 allow_merge, is_local,
2300 cdef->initially_valid,
2301 cdef->is_no_inherit))
2307 * When generating a name, we want to create "tab_col_check" for a
2308 * column constraint and "tab_check" for a table constraint. We
2309 * no longer have any info about the syntactic positioning of the
2310 * constraint phrase, so we approximate this by seeing whether the
2311 * expression references more than one column. (If the user
2312 * played by the rules, the result is the same...)
2314 * Note: pull_var_clause() doesn't descend into sublinks, but we
2315 * eliminated those above; and anyway this only needs to be an
2316 * approximate answer.
2321 vars = pull_var_clause(expr, 0);
2323 /* eliminate duplicates */
2324 vars = list_union(NIL, vars);
2326 if (list_length(vars) == 1)
2327 colname = get_attname(RelationGetRelid(rel),
2328 ((Var *) linitial(vars))->varattno);
2332 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2335 RelationGetNamespace(rel),
2338 /* save name for future checks */
2339 checknames = lappend(checknames, ccname);
2346 StoreRelCheck(rel, ccname, expr, cdef->initially_valid, is_local,
2347 is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
2351 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2352 cooked->contype = CONSTR_CHECK;
2353 cooked->conoid = constrOid;
2354 cooked->name = ccname;
2356 cooked->expr = expr;
2357 cooked->skip_validation = cdef->skip_validation;
2358 cooked->is_local = is_local;
2359 cooked->inhcount = is_local ? 0 : 1;
2360 cooked->is_no_inherit = cdef->is_no_inherit;
2361 cookedConstraints = lappend(cookedConstraints, cooked);
2365 * Update the count of constraints in the relation's pg_class tuple. We do
2366 * this even if there was no change, in order to ensure that an SI update
2367 * message is sent out for the pg_class tuple, which will force other
2368 * backends to rebuild their relcache entries for the rel. (This is
2369 * critical if we added defaults but not constraints.)
2371 SetRelationNumChecks(rel, numchecks);
2373 return cookedConstraints;
2377 * Check for a pre-existing check constraint that conflicts with a proposed
2378 * new one, and either adjust its conislocal/coninhcount settings or throw
2381 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2382 * got a so-far-unique name, or throws error if conflict.
2384 * XXX See MergeConstraintsIntoExisting too if you change this code.
2387 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2388 bool allow_merge, bool is_local,
2389 bool is_initially_valid,
2394 SysScanDesc conscan;
2395 ScanKeyData skey[2];
2398 /* Search for a pg_constraint entry with same name and relation */
2399 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2403 ScanKeyInit(&skey[0],
2404 Anum_pg_constraint_conname,
2405 BTEqualStrategyNumber, F_NAMEEQ,
2406 CStringGetDatum(ccname));
2408 ScanKeyInit(&skey[1],
2409 Anum_pg_constraint_connamespace,
2410 BTEqualStrategyNumber, F_OIDEQ,
2411 ObjectIdGetDatum(RelationGetNamespace(rel)));
2413 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2416 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2418 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2420 if (con->conrelid == RelationGetRelid(rel))
2422 /* Found it. Conflicts if not identical check constraint */
2423 if (con->contype == CONSTRAINT_CHECK)
2428 val = fastgetattr(tup,
2429 Anum_pg_constraint_conbin,
2430 conDesc->rd_att, &isnull);
2432 elog(ERROR, "null conbin for rel %s",
2433 RelationGetRelationName(rel));
2434 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2439 * If the existing constraint is purely inherited (no local
2440 * definition) then interpret addition of a local constraint as a
2441 * legal merge. This allows ALTER ADD CONSTRAINT on parent and
2442 * child tables to be given in either order with same end state.
2444 if (is_local && !con->conislocal)
2447 if (!found || !allow_merge)
2449 (errcode(ERRCODE_DUPLICATE_OBJECT),
2450 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2451 ccname, RelationGetRelationName(rel))));
2453 /* If the child constraint is "no inherit" then cannot merge */
2454 if (con->connoinherit)
2456 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2457 errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
2458 ccname, RelationGetRelationName(rel))));
2461 * Must not change an existing inherited constraint to "no
2462 * inherit" status. That's because inherited constraints should
2463 * be able to propagate to lower-level children.
2465 if (con->coninhcount > 0 && is_no_inherit)
2467 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2468 errmsg("constraint \"%s\" conflicts with inherited constraint on relation \"%s\"",
2469 ccname, RelationGetRelationName(rel))));
2472 * If the child constraint is "not valid" then cannot merge with a
2473 * valid parent constraint
2475 if (is_initially_valid && !con->convalidated)
2477 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2478 errmsg("constraint \"%s\" conflicts with NOT VALID constraint on relation \"%s\"",
2479 ccname, RelationGetRelationName(rel))));
2481 /* OK to update the tuple */
2483 (errmsg("merging constraint \"%s\" with inherited definition",
2486 tup = heap_copytuple(tup);
2487 con = (Form_pg_constraint) GETSTRUCT(tup);
2490 con->conislocal = true;
2496 con->connoinherit = true;
2498 simple_heap_update(conDesc, &tup->t_self, tup);
2499 CatalogUpdateIndexes(conDesc, tup);
2504 systable_endscan(conscan);
2505 heap_close(conDesc, RowExclusiveLock);
2511 * Update the count of constraints in the relation's pg_class tuple.
2513 * Caller had better hold exclusive lock on the relation.
2515 * An important side effect is that a SI update message will be sent out for
2516 * the pg_class tuple, which will force other backends to rebuild their
2517 * relcache entries for the rel. Also, this backend will rebuild its
2518 * own relcache entry at the next CommandCounterIncrement.
2521 SetRelationNumChecks(Relation rel, int numchecks)
2525 Form_pg_class relStruct;
2527 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2528 reltup = SearchSysCacheCopy1(RELOID,
2529 ObjectIdGetDatum(RelationGetRelid(rel)));
2530 if (!HeapTupleIsValid(reltup))
2531 elog(ERROR, "cache lookup failed for relation %u",
2532 RelationGetRelid(rel));
2533 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2535 if (relStruct->relchecks != numchecks)
2537 relStruct->relchecks = numchecks;
2539 simple_heap_update(relrel, &reltup->t_self, reltup);
2541 /* keep catalog indexes current */
2542 CatalogUpdateIndexes(relrel, reltup);
2546 /* Skip the disk update, but force relcache inval anyway */
2547 CacheInvalidateRelcache(rel);
2550 heap_freetuple(reltup);
2551 heap_close(relrel, RowExclusiveLock);
2555 * Take a raw default and convert it to a cooked format ready for
2558 * Parse state should be set up to recognize any vars that might appear
2559 * in the expression. (Even though we plan to reject vars, it's more
2560 * user-friendly to give the correct error message than "unknown var".)
2562 * If atttypid is not InvalidOid, coerce the expression to the specified
2563 * type (and typmod atttypmod). attname is only needed in this case:
2564 * it is used in the error message, if any.
2567 cookDefault(ParseState *pstate,
2575 Assert(raw_default != NULL);
2578 * Transform raw parsetree to executable expression.
2580 expr = transformExpr(pstate, raw_default, EXPR_KIND_COLUMN_DEFAULT);
2583 * Make sure default expr does not refer to any vars (we need this check
2584 * since the pstate includes the target table).
2586 if (contain_var_clause(expr))
2588 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2589 errmsg("cannot use column references in default expression")));
2592 * transformExpr() should have already rejected subqueries, aggregates,
2593 * window functions, and SRFs, based on the EXPR_KIND_ for a default
2598 * Coerce the expression to the correct type and typmod, if given. This
2599 * should match the parser's processing of non-defaulted expressions ---
2600 * see transformAssignedExpr().
2602 if (OidIsValid(atttypid))
2604 Oid type_id = exprType(expr);
2606 expr = coerce_to_target_type(pstate, expr, type_id,
2607 atttypid, atttypmod,
2608 COERCION_ASSIGNMENT,
2609 COERCE_IMPLICIT_CAST,
2613 (errcode(ERRCODE_DATATYPE_MISMATCH),
2614 errmsg("column \"%s\" is of type %s"
2615 " but default expression is of type %s",
2617 format_type_be(atttypid),
2618 format_type_be(type_id)),
2619 errhint("You will need to rewrite or cast the expression.")));
2623 * Finally, take care of collations in the finished expression.
2625 assign_expr_collations(pstate, expr);
2631 * Take a raw CHECK constraint expression and convert it to a cooked format
2632 * ready for storage.
2634 * Parse state must be set up to recognize any vars that might appear
2635 * in the expression.
2638 cookConstraint(ParseState *pstate,
2639 Node *raw_constraint,
2645 * Transform raw parsetree to executable expression.
2647 expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
2650 * Make sure it yields a boolean result.
2652 expr = coerce_to_boolean(pstate, expr, "CHECK");
2655 * Take care of collations.
2657 assign_expr_collations(pstate, expr);
2660 * Make sure no outside relations are referred to (this is probably dead
2661 * code now that add_missing_from is history).
2663 if (list_length(pstate->p_rtable) != 1)
2665 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2666 errmsg("only table \"%s\" can be referenced in check constraint",
2674 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2676 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2680 RemoveStatistics(Oid relid, AttrNumber attnum)
2682 Relation pgstatistic;
2688 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2690 ScanKeyInit(&key[0],
2691 Anum_pg_statistic_starelid,
2692 BTEqualStrategyNumber, F_OIDEQ,
2693 ObjectIdGetDatum(relid));
2699 ScanKeyInit(&key[1],
2700 Anum_pg_statistic_staattnum,
2701 BTEqualStrategyNumber, F_INT2EQ,
2702 Int16GetDatum(attnum));
2706 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2709 /* we must loop even when attnum != 0, in case of inherited stats */
2710 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2711 simple_heap_delete(pgstatistic, &tuple->t_self);
2713 systable_endscan(scan);
2715 heap_close(pgstatistic, RowExclusiveLock);
2720 * RelationTruncateIndexes - truncate all indexes associated
2721 * with the heap relation to zero tuples.
2723 * The routine will truncate and then reconstruct the indexes on
2724 * the specified relation. Caller must hold exclusive lock on rel.
2727 RelationTruncateIndexes(Relation heapRelation)
2731 /* Ask the relcache to produce a list of the indexes of the rel */
2732 foreach(indlist, RelationGetIndexList(heapRelation))
2734 Oid indexId = lfirst_oid(indlist);
2735 Relation currentIndex;
2736 IndexInfo *indexInfo;
2738 /* Open the index relation; use exclusive lock, just to be sure */
2739 currentIndex = index_open(indexId, AccessExclusiveLock);
2741 /* Fetch info needed for index_build */
2742 indexInfo = BuildIndexInfo(currentIndex);
2745 * Now truncate the actual file (and discard buffers).
2747 RelationTruncate(currentIndex, 0);
2749 /* Initialize the index and rebuild */
2750 /* Note: we do not need to re-establish pkey setting */
2751 index_build(heapRelation, currentIndex, indexInfo, false, true);
2753 /* We're done with this index */
2754 index_close(currentIndex, NoLock);
2761 * This routine deletes all data within all the specified relations.
2763 * This is not transaction-safe! There is another, transaction-safe
2764 * implementation in commands/tablecmds.c. We now use this only for
2765 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2768 heap_truncate(List *relids)
2770 List *relations = NIL;
2773 /* Open relations for processing, and grab exclusive access on each */
2774 foreach(cell, relids)
2776 Oid rid = lfirst_oid(cell);
2779 rel = heap_open(rid, AccessExclusiveLock);
2780 relations = lappend(relations, rel);
2783 /* Don't allow truncate on tables that are referenced by foreign keys */
2784 heap_truncate_check_FKs(relations, true);
2787 foreach(cell, relations)
2789 Relation rel = lfirst(cell);
2791 /* Truncate the relation */
2792 heap_truncate_one_rel(rel);
2794 /* Close the relation, but keep exclusive lock on it until commit */
2795 heap_close(rel, NoLock);
2800 * heap_truncate_one_rel
2802 * This routine deletes all data within the specified relation.
2804 * This is not transaction-safe, because the truncation is done immediately
2805 * and cannot be rolled back later. Caller is responsible for having
2806 * checked permissions etc, and must have obtained AccessExclusiveLock.
2809 heap_truncate_one_rel(Relation rel)
2813 /* Truncate the actual file (and discard buffers) */
2814 RelationTruncate(rel, 0);
2816 /* If the relation has indexes, truncate the indexes too */
2817 RelationTruncateIndexes(rel);
2819 /* If there is a toast table, truncate that too */
2820 toastrelid = rel->rd_rel->reltoastrelid;
2821 if (OidIsValid(toastrelid))
2823 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2825 RelationTruncate(toastrel, 0);
2826 RelationTruncateIndexes(toastrel);
2827 /* keep the lock... */
2828 heap_close(toastrel, NoLock);
2833 * heap_truncate_check_FKs
2834 * Check for foreign keys referencing a list of relations that
2835 * are to be truncated, and raise error if there are any
2837 * We disallow such FKs (except self-referential ones) since the whole point
2838 * of TRUNCATE is to not scan the individual rows to be thrown away.
2840 * This is split out so it can be shared by both implementations of truncate.
2841 * Caller should already hold a suitable lock on the relations.
2843 * tempTables is only used to select an appropriate error message.
2846 heap_truncate_check_FKs(List *relations, bool tempTables)
2853 * Build a list of OIDs of the interesting relations.
2855 * If a relation has no triggers, then it can neither have FKs nor be
2856 * referenced by a FK from another table, so we can ignore it.
2858 foreach(cell, relations)
2860 Relation rel = lfirst(cell);
2862 if (rel->rd_rel->relhastriggers)
2863 oids = lappend_oid(oids, RelationGetRelid(rel));
2867 * Fast path: if no relation has triggers, none has FKs either.
2873 * Otherwise, must scan pg_constraint. We make one pass with all the
2874 * relations considered; if this finds nothing, then all is well.
2876 dependents = heap_truncate_find_FKs(oids);
2877 if (dependents == NIL)
2881 * Otherwise we repeat the scan once per relation to identify a particular
2882 * pair of relations to complain about. This is pretty slow, but
2883 * performance shouldn't matter much in a failure path. The reason for
2884 * doing things this way is to ensure that the message produced is not
2885 * dependent on chance row locations within pg_constraint.
2889 Oid relid = lfirst_oid(cell);
2892 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2894 foreach(cell2, dependents)
2896 Oid relid2 = lfirst_oid(cell2);
2898 if (!list_member_oid(oids, relid2))
2900 char *relname = get_rel_name(relid);
2901 char *relname2 = get_rel_name(relid2);
2905 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2906 errmsg("unsupported ON COMMIT and foreign key combination"),
2907 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2908 relname2, relname)));
2911 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2912 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2913 errdetail("Table \"%s\" references \"%s\".",
2915 errhint("Truncate table \"%s\" at the same time, "
2916 "or use TRUNCATE ... CASCADE.",
2924 * heap_truncate_find_FKs
2925 * Find relations having foreign keys referencing any of the given rels
2927 * Input and result are both lists of relation OIDs. The result contains
2928 * no duplicates, does *not* include any rels that were already in the input
2929 * list, and is sorted in OID order. (The last property is enforced mainly
2930 * to guarantee consistent behavior in the regression tests; we don't want
2931 * behavior to change depending on chance locations of rows in pg_constraint.)
2933 * Note: caller should already have appropriate lock on all rels mentioned
2934 * in relationIds. Since adding or dropping an FK requires exclusive lock
2935 * on both rels, this ensures that the answer will be stable.
2938 heap_truncate_find_FKs(List *relationIds)
2942 SysScanDesc fkeyScan;
2946 * Must scan pg_constraint. Right now, it is a seqscan because there is
2947 * no available index on confrelid.
2949 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2951 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2954 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2956 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2958 /* Not a foreign key */
2959 if (con->contype != CONSTRAINT_FOREIGN)
2962 /* Not referencing one of our list of tables */
2963 if (!list_member_oid(relationIds, con->confrelid))
2966 /* Add referencer unless already in input or result list */
2967 if (!list_member_oid(relationIds, con->conrelid))
2968 result = insert_ordered_unique_oid(result, con->conrelid);
2971 systable_endscan(fkeyScan);
2972 heap_close(fkeyRel, AccessShareLock);
2978 * insert_ordered_unique_oid
2979 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2980 * and eliminating duplicates
2982 * Building the ordered list this way is O(N^2), but with a pretty small
2983 * constant, so for the number of entries we expect it will probably be
2984 * faster than trying to apply qsort(). It seems unlikely someone would be
2985 * trying to truncate a table with thousands of dependent tables ...
2988 insert_ordered_unique_oid(List *list, Oid datum)
2992 /* Does the datum belong at the front? */
2993 if (list == NIL || datum < linitial_oid(list))
2994 return lcons_oid(datum, list);
2995 /* Does it match the first entry? */
2996 if (datum == linitial_oid(list))
2997 return list; /* duplicate, so don't insert */
2998 /* No, so find the entry it belongs after */
2999 prev = list_head(list);
3002 ListCell *curr = lnext(prev);
3004 if (curr == NULL || datum < lfirst_oid(curr))
3005 break; /* it belongs after 'prev', before 'curr' */
3007 if (datum == lfirst_oid(curr))
3008 return list; /* duplicate, so don't insert */
3012 /* Insert datum into list after 'prev' */
3013 lappend_cell_oid(list, prev, datum);