1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2013, 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 "catalog/catalog.h"
38 #include "catalog/dependency.h"
39 #include "catalog/heap.h"
40 #include "catalog/index.h"
41 #include "catalog/objectaccess.h"
42 #include "catalog/pg_attrdef.h"
43 #include "catalog/pg_collation.h"
44 #include "catalog/pg_constraint.h"
45 #include "catalog/pg_foreign_table.h"
46 #include "catalog/pg_inherits.h"
47 #include "catalog/pg_namespace.h"
48 #include "catalog/pg_statistic.h"
49 #include "catalog/pg_tablespace.h"
50 #include "catalog/pg_type.h"
51 #include "catalog/pg_type_fn.h"
52 #include "catalog/storage.h"
53 #include "catalog/storage_xlog.h"
54 #include "commands/tablecmds.h"
55 #include "commands/typecmds.h"
56 #include "miscadmin.h"
57 #include "nodes/nodeFuncs.h"
58 #include "optimizer/var.h"
59 #include "parser/parse_coerce.h"
60 #include "parser/parse_collate.h"
61 #include "parser/parse_expr.h"
62 #include "parser/parse_relation.h"
63 #include "storage/predicate.h"
64 #include "storage/smgr.h"
65 #include "utils/acl.h"
66 #include "utils/builtins.h"
67 #include "utils/fmgroids.h"
68 #include "utils/inval.h"
69 #include "utils/lsyscache.h"
70 #include "utils/rel.h"
71 #include "utils/snapmgr.h"
72 #include "utils/syscache.h"
73 #include "utils/tqual.h"
76 /* Potentially set by contrib/pg_upgrade_support functions */
77 Oid binary_upgrade_next_heap_pg_class_oid = InvalidOid;
78 Oid binary_upgrade_next_toast_pg_class_oid = InvalidOid;
80 static void AddNewRelationTuple(Relation pg_class_desc,
81 Relation new_rel_desc,
89 static Oid AddNewRelationType(const char *typeName,
96 static void RelationRemoveInheritance(Oid relid);
97 static void StoreRelCheck(Relation rel, char *ccname, Node *expr,
98 bool is_validated, bool is_local, int inhcount,
99 bool is_no_inherit, bool is_internal);
100 static void StoreConstraints(Relation rel, List *cooked_constraints,
102 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
103 bool allow_merge, bool is_local,
105 static void SetRelationNumChecks(Relation rel, int numchecks);
106 static Node *cookConstraint(ParseState *pstate,
107 Node *raw_constraint,
109 static List *insert_ordered_unique_oid(List *list, Oid datum);
112 /* ----------------------------------------------------------------
113 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
115 * these should all be moved to someplace in the lib/catalog
116 * module, if not obliterated first.
117 * ----------------------------------------------------------------
123 * Should the system special case these attributes in the future?
124 * Advantage: consume much less space in the ATTRIBUTE relation.
125 * Disadvantage: special cases will be all over the place.
129 * The initializers below do not include trailing variable length fields,
130 * but that's OK - we're never going to reference anything beyond the
131 * fixed-size portion of the structure anyway.
134 static FormData_pg_attribute a1 = {
135 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
136 SelfItemPointerAttributeNumber, 0, -1, -1,
137 false, 'p', 's', true, false, false, true, 0
140 static FormData_pg_attribute a2 = {
141 0, {"oid"}, OIDOID, 0, sizeof(Oid),
142 ObjectIdAttributeNumber, 0, -1, -1,
143 true, 'p', 'i', true, false, false, true, 0
146 static FormData_pg_attribute a3 = {
147 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
148 MinTransactionIdAttributeNumber, 0, -1, -1,
149 true, 'p', 'i', true, false, false, true, 0
152 static FormData_pg_attribute a4 = {
153 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
154 MinCommandIdAttributeNumber, 0, -1, -1,
155 true, 'p', 'i', true, false, false, true, 0
158 static FormData_pg_attribute a5 = {
159 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
160 MaxTransactionIdAttributeNumber, 0, -1, -1,
161 true, 'p', 'i', true, false, false, true, 0
164 static FormData_pg_attribute a6 = {
165 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
166 MaxCommandIdAttributeNumber, 0, -1, -1,
167 true, 'p', 'i', true, false, false, true, 0
171 * We decided to call this attribute "tableoid" rather than say
172 * "classoid" on the basis that in the future there may be more than one
173 * table of a particular class/type. In any case table is still the word
176 static FormData_pg_attribute a7 = {
177 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
178 TableOidAttributeNumber, 0, -1, -1,
179 true, 'p', 'i', true, false, false, true, 0
182 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
185 * This function returns a Form_pg_attribute pointer for a system attribute.
186 * Note that we elog if the presented attno is invalid, which would only
187 * happen if there's a problem upstream.
190 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
192 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
193 elog(ERROR, "invalid system attribute number %d", attno);
194 if (attno == ObjectIdAttributeNumber && !relhasoids)
195 elog(ERROR, "invalid system attribute number %d", attno);
196 return SysAtt[-attno - 1];
200 * If the given name is a system attribute name, return a Form_pg_attribute
201 * pointer for a prototype definition. If not, return NULL.
204 SystemAttributeByName(const char *attname, bool relhasoids)
208 for (j = 0; j < (int) lengthof(SysAtt); j++)
210 Form_pg_attribute att = SysAtt[j];
212 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
214 if (strcmp(NameStr(att->attname), attname) == 0)
223 /* ----------------------------------------------------------------
224 * XXX END OF UGLY HARD CODED BADNESS XXX
225 * ---------------------------------------------------------------- */
228 /* ----------------------------------------------------------------
229 * heap_create - Create an uncataloged heap relation
231 * Note API change: the caller must now always provide the OID
232 * to use for the relation. The relfilenode may (and, normally,
233 * should) be left unspecified.
235 * rel->rd_rel is initialized by RelationBuildLocalRelation,
236 * and is mostly zeroes at return.
237 * ----------------------------------------------------------------
240 heap_create(const char *relname,
248 bool shared_relation,
249 bool mapped_relation,
250 bool allow_system_table_mods)
255 /* The caller must have provided an OID for the relation. */
256 Assert(OidIsValid(relid));
259 * Don't allow creating relations in pg_catalog directly, even though it
260 * is allowed to move user defined relations there. Semantics with search
261 * paths including pg_catalog are too confusing for now.
263 * But allow creating indexes on relations in pg_catalog even if
264 * allow_system_table_mods = off, upper layers already guarantee it's on a
265 * user defined relation, not a system one.
267 if (!allow_system_table_mods &&
268 ((IsSystemNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
269 IsToastNamespace(relnamespace)) &&
270 IsNormalProcessingMode())
272 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
273 errmsg("permission denied to create \"%s.%s\"",
274 get_namespace_name(relnamespace), relname),
275 errdetail("System catalog modifications are currently disallowed.")));
278 * Decide if we need storage or not, and handle a couple other special
279 * cases for particular relkinds.
284 case RELKIND_COMPOSITE_TYPE:
285 case RELKIND_FOREIGN_TABLE:
286 create_storage = false;
289 * Force reltablespace to zero if the relation has no physical
290 * storage. This is mainly just for cleanliness' sake.
292 reltablespace = InvalidOid;
294 case RELKIND_SEQUENCE:
295 create_storage = true;
298 * Force reltablespace to zero for sequences, since we don't
299 * support moving them around into different tablespaces.
301 reltablespace = InvalidOid;
304 create_storage = true;
309 * Unless otherwise requested, the physical ID (relfilenode) is initially
310 * the same as the logical ID (OID). When the caller did specify a
311 * relfilenode, it already exists; do not attempt to create it.
313 if (OidIsValid(relfilenode))
314 create_storage = false;
319 * Never allow a pg_class entry to explicitly specify the database's
320 * default tablespace in reltablespace; force it to zero instead. This
321 * ensures that if the database is cloned with a different default
322 * tablespace, the pg_class entry will still match where CREATE DATABASE
323 * will put the physically copied relation.
325 * Yes, this is a bit of a hack.
327 if (reltablespace == MyDatabaseTableSpace)
328 reltablespace = InvalidOid;
331 * build the relcache entry.
333 rel = RelationBuildLocalRelation(relname,
345 * Have the storage manager create the relation's disk file, if needed.
347 * We only create the main fork here, other forks will be created on
352 RelationOpenSmgr(rel);
353 RelationCreateStorage(rel->rd_node, relpersistence);
359 /* ----------------------------------------------------------------
360 * heap_create_with_catalog - Create a cataloged relation
362 * this is done in multiple steps:
364 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
365 * descriptor contains a valid set of attribute names and types
367 * 2) pg_class is opened and get_relname_relid()
368 * performs a scan to ensure that no relation with the
369 * same name already exists.
371 * 3) heap_create() is called to create the new relation on disk.
373 * 4) TypeCreate() is called to define a new type corresponding
374 * to the new relation.
376 * 5) AddNewRelationTuple() is called to register the
377 * relation in pg_class.
379 * 6) AddNewAttributeTuples() is called to register the
380 * new relation's schema in pg_attribute.
382 * 7) StoreConstraints is called () - vadim 08/22/97
384 * 8) the relations are closed and the new relation's oid
387 * ----------------------------------------------------------------
390 /* --------------------------------
391 * CheckAttributeNamesTypes
393 * this is used to make certain the tuple descriptor contains a
394 * valid set of attribute names and datatypes. a problem simply
395 * generates ereport(ERROR) which aborts the current transaction.
396 * --------------------------------
399 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
400 bool allow_system_table_mods)
404 int natts = tupdesc->natts;
406 /* Sanity check on column count */
407 if (natts < 0 || natts > MaxHeapAttributeNumber)
409 (errcode(ERRCODE_TOO_MANY_COLUMNS),
410 errmsg("tables can have at most %d columns",
411 MaxHeapAttributeNumber)));
414 * first check for collision with system attribute names
416 * Skip this for a view or type relation, since those don't have system
419 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
421 for (i = 0; i < natts; i++)
423 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
424 tupdesc->tdhasoid) != NULL)
426 (errcode(ERRCODE_DUPLICATE_COLUMN),
427 errmsg("column name \"%s\" conflicts with a system column name",
428 NameStr(tupdesc->attrs[i]->attname))));
433 * next check for repeated attribute names
435 for (i = 1; i < natts; i++)
437 for (j = 0; j < i; j++)
439 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
440 NameStr(tupdesc->attrs[i]->attname)) == 0)
442 (errcode(ERRCODE_DUPLICATE_COLUMN),
443 errmsg("column name \"%s\" specified more than once",
444 NameStr(tupdesc->attrs[j]->attname))));
449 * next check the attribute types
451 for (i = 0; i < natts; i++)
453 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
454 tupdesc->attrs[i]->atttypid,
455 tupdesc->attrs[i]->attcollation,
456 NIL, /* assume we're creating a new rowtype */
457 allow_system_table_mods);
461 /* --------------------------------
464 * Verify that the proposed datatype of an attribute is legal.
465 * This is needed mainly because there are types (and pseudo-types)
466 * in the catalogs that we do not support as elements of real tuples.
467 * We also check some other properties required of a table column.
469 * If the attribute is being proposed for addition to an existing table or
470 * composite type, pass a one-element list of the rowtype OID as
471 * containing_rowtypes. When checking a to-be-created rowtype, it's
472 * sufficient to pass NIL, because there could not be any recursive reference
473 * to a not-yet-existing rowtype.
474 * --------------------------------
477 CheckAttributeType(const char *attname,
478 Oid atttypid, Oid attcollation,
479 List *containing_rowtypes,
480 bool allow_system_table_mods)
482 char att_typtype = get_typtype(atttypid);
485 if (atttypid == UNKNOWNOID)
488 * Warn user, but don't fail, if column to be created has UNKNOWN type
489 * (usually as a result of a 'retrieve into' - jolly)
492 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
493 errmsg("column \"%s\" has type \"unknown\"", attname),
494 errdetail("Proceeding with relation creation anyway.")));
496 else if (att_typtype == TYPTYPE_PSEUDO)
499 * Refuse any attempt to create a pseudo-type column, except for a
500 * special hack for pg_statistic: allow ANYARRAY when modifying system
501 * catalogs (this allows creating pg_statistic and cloning it during
504 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
506 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
507 errmsg("column \"%s\" has pseudo-type %s",
508 attname, format_type_be(atttypid))));
510 else if (att_typtype == TYPTYPE_DOMAIN)
513 * If it's a domain, recurse to check its base type.
515 CheckAttributeType(attname, getBaseType(atttypid), attcollation,
517 allow_system_table_mods);
519 else if (att_typtype == TYPTYPE_COMPOSITE)
522 * For a composite type, recurse into its attributes.
529 * Check for self-containment. Eventually we might be able to allow
530 * this (just return without complaint, if so) but it's not clear how
531 * many other places would require anti-recursion defenses before it
532 * would be safe to allow tables to contain their own rowtype.
534 if (list_member_oid(containing_rowtypes, atttypid))
536 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
537 errmsg("composite type %s cannot be made a member of itself",
538 format_type_be(atttypid))));
540 containing_rowtypes = lcons_oid(atttypid, containing_rowtypes);
542 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
544 tupdesc = RelationGetDescr(relation);
546 for (i = 0; i < tupdesc->natts; i++)
548 Form_pg_attribute attr = tupdesc->attrs[i];
550 if (attr->attisdropped)
552 CheckAttributeType(NameStr(attr->attname),
553 attr->atttypid, attr->attcollation,
555 allow_system_table_mods);
558 relation_close(relation, AccessShareLock);
560 containing_rowtypes = list_delete_first(containing_rowtypes);
562 else if (OidIsValid((att_typelem = get_element_type(atttypid))))
565 * Must recurse into array types, too, in case they are composite.
567 CheckAttributeType(attname, att_typelem, attcollation,
569 allow_system_table_mods);
573 * This might not be strictly invalid per SQL standard, but it is pretty
574 * useless, and it cannot be dumped, so we must disallow it.
576 if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
578 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
579 errmsg("no collation was derived for column \"%s\" with collatable type %s",
580 attname, format_type_be(atttypid)),
581 errhint("Use the COLLATE clause to set the collation explicitly.")));
585 * InsertPgAttributeTuple
586 * Construct and insert a new tuple in pg_attribute.
588 * Caller has already opened and locked pg_attribute. new_attribute is the
589 * attribute to insert (but we ignore attacl and attoptions, which are always
590 * initialized to NULL).
592 * indstate is the index state for CatalogIndexInsert. It can be passed as
593 * NULL, in which case we'll fetch the necessary info. (Don't do this when
594 * inserting multiple attributes, because it's a tad more expensive.)
597 InsertPgAttributeTuple(Relation pg_attribute_rel,
598 Form_pg_attribute new_attribute,
599 CatalogIndexState indstate)
601 Datum values[Natts_pg_attribute];
602 bool nulls[Natts_pg_attribute];
605 /* This is a tad tedious, but way cleaner than what we used to do... */
606 memset(values, 0, sizeof(values));
607 memset(nulls, false, sizeof(nulls));
609 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
610 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
611 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
612 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
613 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
614 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
615 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
616 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
617 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
618 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
619 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
620 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
621 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
622 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
623 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
624 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
625 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
626 values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
628 /* start out with empty permissions and empty options */
629 nulls[Anum_pg_attribute_attacl - 1] = true;
630 nulls[Anum_pg_attribute_attoptions - 1] = true;
631 nulls[Anum_pg_attribute_attfdwoptions - 1] = true;
633 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
635 /* finally insert the new tuple, update the indexes, and clean up */
636 simple_heap_insert(pg_attribute_rel, tup);
638 if (indstate != NULL)
639 CatalogIndexInsert(indstate, tup);
641 CatalogUpdateIndexes(pg_attribute_rel, tup);
646 /* --------------------------------
647 * AddNewAttributeTuples
649 * this registers the new relation's schema by adding
650 * tuples to pg_attribute.
651 * --------------------------------
654 AddNewAttributeTuples(Oid new_rel_oid,
660 Form_pg_attribute attr;
663 CatalogIndexState indstate;
664 int natts = tupdesc->natts;
665 ObjectAddress myself,
669 * open pg_attribute and its indexes.
671 rel = heap_open(AttributeRelationId, RowExclusiveLock);
673 indstate = CatalogOpenIndexes(rel);
676 * First we add the user attributes. This is also a convenient place to
677 * add dependencies on their datatypes and collations.
679 for (i = 0; i < natts; i++)
681 attr = tupdesc->attrs[i];
682 /* Fill in the correct relation OID */
683 attr->attrelid = new_rel_oid;
684 /* Make sure these are OK, too */
685 attr->attstattarget = -1;
686 attr->attcacheoff = -1;
688 InsertPgAttributeTuple(rel, attr, indstate);
690 /* Add dependency info */
691 myself.classId = RelationRelationId;
692 myself.objectId = new_rel_oid;
693 myself.objectSubId = i + 1;
694 referenced.classId = TypeRelationId;
695 referenced.objectId = attr->atttypid;
696 referenced.objectSubId = 0;
697 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
699 /* The default collation is pinned, so don't bother recording it */
700 if (OidIsValid(attr->attcollation) &&
701 attr->attcollation != DEFAULT_COLLATION_OID)
703 referenced.classId = CollationRelationId;
704 referenced.objectId = attr->attcollation;
705 referenced.objectSubId = 0;
706 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
711 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
712 * all for a view or type relation. We don't bother with making datatype
713 * dependencies here, since presumably all these types are pinned.
715 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
717 for (i = 0; i < (int) lengthof(SysAtt); i++)
719 FormData_pg_attribute attStruct;
721 /* skip OID where appropriate */
722 if (!tupdesc->tdhasoid &&
723 SysAtt[i]->attnum == ObjectIdAttributeNumber)
726 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
728 /* Fill in the correct relation OID in the copied tuple */
729 attStruct.attrelid = new_rel_oid;
731 /* Fill in correct inheritance info for the OID column */
732 if (attStruct.attnum == ObjectIdAttributeNumber)
734 attStruct.attislocal = oidislocal;
735 attStruct.attinhcount = oidinhcount;
738 InsertPgAttributeTuple(rel, &attStruct, indstate);
745 CatalogCloseIndexes(indstate);
747 heap_close(rel, RowExclusiveLock);
750 /* --------------------------------
753 * Construct and insert a new tuple in pg_class.
755 * Caller has already opened and locked pg_class.
756 * Tuple data is taken from new_rel_desc->rd_rel, except for the
757 * variable-width fields which are not present in a cached reldesc.
758 * relacl and reloptions are passed in Datum form (to avoid having
759 * to reference the data types in heap.h). Pass (Datum) 0 to set them
761 * --------------------------------
764 InsertPgClassTuple(Relation pg_class_desc,
765 Relation new_rel_desc,
770 Form_pg_class rd_rel = new_rel_desc->rd_rel;
771 Datum values[Natts_pg_class];
772 bool nulls[Natts_pg_class];
775 /* This is a tad tedious, but way cleaner than what we used to do... */
776 memset(values, 0, sizeof(values));
777 memset(nulls, false, sizeof(nulls));
779 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
780 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
781 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
782 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
783 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
784 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
785 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
786 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
787 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
788 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
789 values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
790 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
791 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
792 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
793 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
794 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
795 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
796 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
797 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
798 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
799 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
800 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
801 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
802 values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
803 values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
804 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
805 values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
806 if (relacl != (Datum) 0)
807 values[Anum_pg_class_relacl - 1] = relacl;
809 nulls[Anum_pg_class_relacl - 1] = true;
810 if (reloptions != (Datum) 0)
811 values[Anum_pg_class_reloptions - 1] = reloptions;
813 nulls[Anum_pg_class_reloptions - 1] = true;
815 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
818 * The new tuple must have the oid already chosen for the rel. Sure would
819 * be embarrassing to do this sort of thing in polite company.
821 HeapTupleSetOid(tup, new_rel_oid);
823 /* finally insert the new tuple, update the indexes, and clean up */
824 simple_heap_insert(pg_class_desc, tup);
826 CatalogUpdateIndexes(pg_class_desc, tup);
831 /* --------------------------------
832 * AddNewRelationTuple
834 * this registers the new relation in the catalogs by
835 * adding a tuple to pg_class.
836 * --------------------------------
839 AddNewRelationTuple(Relation pg_class_desc,
840 Relation new_rel_desc,
849 Form_pg_class new_rel_reltup;
852 * first we update some of the information in our uncataloged relation's
853 * relation descriptor.
855 new_rel_reltup = new_rel_desc->rd_rel;
859 case RELKIND_RELATION:
860 case RELKIND_MATVIEW:
862 case RELKIND_TOASTVALUE:
863 /* The relation is real, but as yet empty */
864 new_rel_reltup->relpages = 0;
865 new_rel_reltup->reltuples = 0;
866 new_rel_reltup->relallvisible = 0;
868 case RELKIND_SEQUENCE:
869 /* Sequences always have a known size */
870 new_rel_reltup->relpages = 1;
871 new_rel_reltup->reltuples = 1;
872 new_rel_reltup->relallvisible = 0;
875 /* Views, etc, have no disk storage */
876 new_rel_reltup->relpages = 0;
877 new_rel_reltup->reltuples = 0;
878 new_rel_reltup->relallvisible = 0;
882 /* Initialize relfrozenxid and relminmxid */
883 if (relkind == RELKIND_RELATION ||
884 relkind == RELKIND_MATVIEW ||
885 relkind == RELKIND_TOASTVALUE)
888 * Initialize to the minimum XID that could put tuples in the table.
889 * We know that no xacts older than RecentXmin are still running, so
892 new_rel_reltup->relfrozenxid = RecentXmin;
895 * Similarly, initialize the minimum Multixact to the first value that
896 * could possibly be stored in tuples in the table. Running
897 * transactions could reuse values from their local cache, so we are
898 * careful to consider all currently running multis.
900 * XXX this could be refined further, but is it worth the hassle?
902 new_rel_reltup->relminmxid = GetOldestMultiXactId();
907 * Other relation types will not contain XIDs, so set relfrozenxid to
908 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
909 * we force its xmin to be FrozenTransactionId always; see
910 * commands/sequence.c.)
912 new_rel_reltup->relfrozenxid = InvalidTransactionId;
913 new_rel_reltup->relfrozenxid = InvalidMultiXactId;
916 new_rel_reltup->relowner = relowner;
917 new_rel_reltup->reltype = new_type_oid;
918 new_rel_reltup->reloftype = reloftype;
920 new_rel_desc->rd_att->tdtypeid = new_type_oid;
922 /* Now build and insert the tuple */
923 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
928 /* --------------------------------
929 * AddNewRelationType -
931 * define a composite type corresponding to the new relation
932 * --------------------------------
935 AddNewRelationType(const char *typeName,
944 TypeCreate(new_row_type, /* optional predetermined OID */
945 typeName, /* type name */
946 typeNamespace, /* type namespace */
947 new_rel_oid, /* relation oid */
948 new_rel_kind, /* relation kind */
949 ownerid, /* owner's ID */
950 -1, /* internal size (varlena) */
951 TYPTYPE_COMPOSITE, /* type-type (composite) */
952 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
953 false, /* composite types are never preferred */
954 DEFAULT_TYPDELIM, /* default array delimiter */
955 F_RECORD_IN, /* input procedure */
956 F_RECORD_OUT, /* output procedure */
957 F_RECORD_RECV, /* receive procedure */
958 F_RECORD_SEND, /* send procedure */
959 InvalidOid, /* typmodin procedure - none */
960 InvalidOid, /* typmodout procedure - none */
961 InvalidOid, /* analyze procedure - default */
962 InvalidOid, /* array element type - irrelevant */
963 false, /* this is not an array type */
964 new_array_type, /* array type if any */
965 InvalidOid, /* domain base type - irrelevant */
966 NULL, /* default value - none */
967 NULL, /* default binary representation */
968 false, /* passed by reference */
969 'd', /* alignment - must be the largest! */
970 'x', /* fully TOASTable */
972 0, /* array dimensions for typBaseType */
973 false, /* Type NOT NULL */
974 InvalidOid); /* rowtypes never have a collation */
977 /* --------------------------------
978 * heap_create_with_catalog
980 * creates a new cataloged relation. see comments above.
983 * relname: name to give to new rel
984 * relnamespace: OID of namespace it goes in
985 * reltablespace: OID of tablespace it goes in
986 * relid: OID to assign to new rel, or InvalidOid to select a new OID
987 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
988 * reloftypeid: if a typed table, OID of underlying type; else InvalidOid
989 * ownerid: OID of new rel's owner
990 * tupdesc: tuple descriptor (source of column definitions)
991 * cooked_constraints: list of precooked check constraints and defaults
992 * relkind: relkind for new rel
993 * relpersistence: rel's persistence status (permanent, temp, or unlogged)
994 * shared_relation: TRUE if it's to be a shared relation
995 * mapped_relation: TRUE if the relation will use the relfilenode map
996 * oidislocal: TRUE if oid column (if any) should be marked attislocal
997 * oidinhcount: attinhcount to assign to oid column (if any)
998 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
999 * reloptions: reloptions in Datum form, or (Datum) 0 if none
1000 * use_user_acl: TRUE if should look for user-defined default permissions;
1001 * if FALSE, relacl is always set NULL
1002 * allow_system_table_mods: TRUE to allow creation in system namespaces
1004 * Returns the OID of the new relation
1005 * --------------------------------
1008 heap_create_with_catalog(const char *relname,
1016 List *cooked_constraints,
1018 char relpersistence,
1019 bool shared_relation,
1020 bool mapped_relation,
1023 OnCommitAction oncommit,
1026 bool allow_system_table_mods,
1029 Relation pg_class_desc;
1030 Relation new_rel_desc;
1035 Oid new_array_oid = InvalidOid;
1037 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1042 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
1044 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
1047 * This would fail later on anyway, if the relation already exists. But
1048 * by catching it here we can emit a nicer error message.
1050 existing_relid = get_relname_relid(relname, relnamespace);
1051 if (existing_relid != InvalidOid)
1053 (errcode(ERRCODE_DUPLICATE_TABLE),
1054 errmsg("relation \"%s\" already exists", relname)));
1057 * Since we are going to create a rowtype as well, also check for
1058 * collision with an existing type name. If there is one and it's an
1059 * autogenerated array, we can rename it out of the way; otherwise we can
1060 * at least give a good error message.
1062 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1063 CStringGetDatum(relname),
1064 ObjectIdGetDatum(relnamespace));
1065 if (OidIsValid(old_type_oid))
1067 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1069 (errcode(ERRCODE_DUPLICATE_OBJECT),
1070 errmsg("type \"%s\" already exists", relname),
1071 errhint("A relation has an associated type of the same name, "
1072 "so you must use a name that doesn't conflict "
1073 "with any existing type.")));
1077 * Shared relations must be in pg_global (last-ditch check)
1079 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1080 elog(ERROR, "shared relations must be placed in pg_global tablespace");
1083 * Allocate an OID for the relation, unless we were told what to use.
1085 * The OID will be the relfilenode as well, so make sure it doesn't
1086 * collide with either pg_class OIDs or existing physical files.
1088 if (!OidIsValid(relid))
1091 * Use binary-upgrade override for pg_class.oid/relfilenode, if
1094 if (IsBinaryUpgrade &&
1095 OidIsValid(binary_upgrade_next_heap_pg_class_oid) &&
1096 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
1097 relkind == RELKIND_VIEW || relkind == RELKIND_MATVIEW ||
1098 relkind == RELKIND_COMPOSITE_TYPE || relkind == RELKIND_FOREIGN_TABLE))
1100 relid = binary_upgrade_next_heap_pg_class_oid;
1101 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1103 else if (IsBinaryUpgrade &&
1104 OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1105 relkind == RELKIND_TOASTVALUE)
1107 relid = binary_upgrade_next_toast_pg_class_oid;
1108 binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1111 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1116 * Determine the relation's initial permissions.
1122 case RELKIND_RELATION:
1124 case RELKIND_MATVIEW:
1125 case RELKIND_FOREIGN_TABLE:
1126 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1129 case RELKIND_SEQUENCE:
1130 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1142 * Create the relcache entry (mostly dummy at this point) and the physical
1143 * disk file. (If we fail further down, it's the smgr's responsibility to
1144 * remove the disk file again.)
1146 new_rel_desc = heap_create(relname,
1156 allow_system_table_mods);
1158 Assert(relid == RelationGetRelid(new_rel_desc));
1161 * Decide whether to create an array type over the relation's rowtype. We
1162 * do not create any array types for system catalogs (ie, those made
1163 * during initdb). We do not create them where the use of a relation as
1164 * such is an implementation detail: toast tables, sequences and indexes.
1166 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1167 relkind == RELKIND_VIEW ||
1168 relkind == RELKIND_MATVIEW ||
1169 relkind == RELKIND_FOREIGN_TABLE ||
1170 relkind == RELKIND_COMPOSITE_TYPE))
1171 new_array_oid = AssignTypeArrayOid();
1174 * Since defining a relation also defines a complex type, we add a new
1175 * system type corresponding to the new relation. The OID of the type can
1176 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1177 * generate a new OID for it.
1179 * NOTE: we could get a unique-index failure here, in case someone else is
1180 * creating the same type name in parallel but hadn't committed yet when
1181 * we checked for a duplicate name above.
1183 new_type_oid = AddNewRelationType(relname,
1192 * Now make the array type if wanted.
1194 if (OidIsValid(new_array_oid))
1198 relarrayname = makeArrayTypeName(relname, relnamespace);
1200 TypeCreate(new_array_oid, /* force the type's OID to this */
1201 relarrayname, /* Array type name */
1202 relnamespace, /* Same namespace as parent */
1203 InvalidOid, /* Not composite, no relationOid */
1204 0, /* relkind, also N/A here */
1205 ownerid, /* owner's ID */
1206 -1, /* Internal size (varlena) */
1207 TYPTYPE_BASE, /* Not composite - typelem is */
1208 TYPCATEGORY_ARRAY, /* type-category (array) */
1209 false, /* array types are never preferred */
1210 DEFAULT_TYPDELIM, /* default array delimiter */
1211 F_ARRAY_IN, /* array input proc */
1212 F_ARRAY_OUT, /* array output proc */
1213 F_ARRAY_RECV, /* array recv (bin) proc */
1214 F_ARRAY_SEND, /* array send (bin) proc */
1215 InvalidOid, /* typmodin procedure - none */
1216 InvalidOid, /* typmodout procedure - none */
1217 F_ARRAY_TYPANALYZE, /* array analyze procedure */
1218 new_type_oid, /* array element type - the rowtype */
1219 true, /* yes, this is an array type */
1220 InvalidOid, /* this has no array type */
1221 InvalidOid, /* domain base type - irrelevant */
1222 NULL, /* default value - none */
1223 NULL, /* default binary representation */
1224 false, /* passed by reference */
1225 'd', /* alignment - must be the largest! */
1226 'x', /* fully TOASTable */
1228 0, /* array dimensions for typBaseType */
1229 false, /* Type NOT NULL */
1230 InvalidOid); /* rowtypes never have a collation */
1232 pfree(relarrayname);
1236 * now create an entry in pg_class for the relation.
1238 * NOTE: we could get a unique-index failure here, in case someone else is
1239 * creating the same relation name in parallel but hadn't committed yet
1240 * when we checked for a duplicate name above.
1242 AddNewRelationTuple(pg_class_desc,
1249 PointerGetDatum(relacl),
1253 * now add tuples to pg_attribute for the attributes in our new relation.
1255 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1256 oidislocal, oidinhcount);
1259 * Make a dependency link to force the relation to be deleted if its
1260 * namespace is. Also make a dependency link to its owner, as well as
1261 * dependencies for any roles mentioned in the default ACL.
1263 * For composite types, these dependencies are tracked for the pg_type
1264 * entry, so we needn't record them here. Likewise, TOAST tables don't
1265 * need a namespace dependency (they live in a pinned namespace) nor an
1266 * owner dependency (they depend indirectly through the parent table), nor
1267 * should they have any ACL entries. The same applies for extension
1270 * If it's a temp table, we do not make it an extension member; this
1271 * prevents the unintuitive result that deletion of the temp table at
1272 * session end would make the whole extension go away.
1274 * Also, skip this in bootstrap mode, since we don't make dependencies
1275 * while bootstrapping.
1277 if (relkind != RELKIND_COMPOSITE_TYPE &&
1278 relkind != RELKIND_TOASTVALUE &&
1279 !IsBootstrapProcessingMode())
1281 ObjectAddress myself,
1284 myself.classId = RelationRelationId;
1285 myself.objectId = relid;
1286 myself.objectSubId = 0;
1287 referenced.classId = NamespaceRelationId;
1288 referenced.objectId = relnamespace;
1289 referenced.objectSubId = 0;
1290 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1292 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1294 if (relpersistence != RELPERSISTENCE_TEMP)
1295 recordDependencyOnCurrentExtension(&myself, false);
1299 referenced.classId = TypeRelationId;
1300 referenced.objectId = reloftypeid;
1301 referenced.objectSubId = 0;
1302 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1310 nnewmembers = aclmembers(relacl, &newmembers);
1311 updateAclDependencies(RelationRelationId, relid, 0,
1314 nnewmembers, newmembers);
1318 /* Post creation hook for new relation */
1319 InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
1322 * Store any supplied constraints and defaults.
1324 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1325 * entry, so the relation must be valid and self-consistent at this point.
1326 * In particular, there are not yet constraints and defaults anywhere.
1328 StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
1331 * If there's a special on-commit action, remember it
1333 if (oncommit != ONCOMMIT_NOOP)
1334 register_on_commit_action(relid, oncommit);
1336 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1338 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW ||
1339 relkind == RELKIND_TOASTVALUE);
1340 heap_create_init_fork(new_rel_desc);
1344 * ok, the relation has been cataloged, so close our relations and return
1345 * the OID of the newly created relation.
1347 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1348 heap_close(pg_class_desc, RowExclusiveLock);
1354 * Set up an init fork for an unlogged table so that it can be correctly
1355 * reinitialized on restart. Since we're going to do an immediate sync, we
1356 * only need to xlog this if archiving or streaming is enabled. And the
1357 * immediate sync is required, because otherwise there's no guarantee that
1358 * this will hit the disk before the next checkpoint moves the redo pointer.
1361 heap_create_init_fork(Relation rel)
1363 RelationOpenSmgr(rel);
1364 smgrcreate(rel->rd_smgr, INIT_FORKNUM, false);
1366 log_smgrcreate(&rel->rd_smgr->smgr_rnode.node, INIT_FORKNUM);
1367 smgrimmedsync(rel->rd_smgr, INIT_FORKNUM);
1371 * RelationRemoveInheritance
1373 * Formerly, this routine checked for child relations and aborted the
1374 * deletion if any were found. Now we rely on the dependency mechanism
1375 * to check for or delete child relations. By the time we get here,
1376 * there are no children and we need only remove any pg_inherits rows
1377 * linking this relation to its parent(s).
1380 RelationRemoveInheritance(Oid relid)
1382 Relation catalogRelation;
1387 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1390 Anum_pg_inherits_inhrelid,
1391 BTEqualStrategyNumber, F_OIDEQ,
1392 ObjectIdGetDatum(relid));
1394 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1397 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1398 simple_heap_delete(catalogRelation, &tuple->t_self);
1400 systable_endscan(scan);
1401 heap_close(catalogRelation, RowExclusiveLock);
1405 * DeleteRelationTuple
1407 * Remove pg_class row for the given relid.
1409 * Note: this is shared by relation deletion and index deletion. It's
1410 * not intended for use anyplace else.
1413 DeleteRelationTuple(Oid relid)
1415 Relation pg_class_desc;
1418 /* Grab an appropriate lock on the pg_class relation */
1419 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1421 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1422 if (!HeapTupleIsValid(tup))
1423 elog(ERROR, "cache lookup failed for relation %u", relid);
1425 /* delete the relation tuple from pg_class, and finish up */
1426 simple_heap_delete(pg_class_desc, &tup->t_self);
1428 ReleaseSysCache(tup);
1430 heap_close(pg_class_desc, RowExclusiveLock);
1434 * DeleteAttributeTuples
1436 * Remove pg_attribute rows for the given relid.
1438 * Note: this is shared by relation deletion and index deletion. It's
1439 * not intended for use anyplace else.
1442 DeleteAttributeTuples(Oid relid)
1449 /* Grab an appropriate lock on the pg_attribute relation */
1450 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1452 /* Use the index to scan only attributes of the target relation */
1453 ScanKeyInit(&key[0],
1454 Anum_pg_attribute_attrelid,
1455 BTEqualStrategyNumber, F_OIDEQ,
1456 ObjectIdGetDatum(relid));
1458 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1461 /* Delete all the matching tuples */
1462 while ((atttup = systable_getnext(scan)) != NULL)
1463 simple_heap_delete(attrel, &atttup->t_self);
1465 /* Clean up after the scan */
1466 systable_endscan(scan);
1467 heap_close(attrel, RowExclusiveLock);
1471 * DeleteSystemAttributeTuples
1473 * Remove pg_attribute rows for system columns of the given relid.
1475 * Note: this is only used when converting a table to a view. Views don't
1476 * have system columns, so we should remove them from pg_attribute.
1479 DeleteSystemAttributeTuples(Oid relid)
1486 /* Grab an appropriate lock on the pg_attribute relation */
1487 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1489 /* Use the index to scan only system attributes of the target relation */
1490 ScanKeyInit(&key[0],
1491 Anum_pg_attribute_attrelid,
1492 BTEqualStrategyNumber, F_OIDEQ,
1493 ObjectIdGetDatum(relid));
1494 ScanKeyInit(&key[1],
1495 Anum_pg_attribute_attnum,
1496 BTLessEqualStrategyNumber, F_INT2LE,
1499 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1502 /* Delete all the matching tuples */
1503 while ((atttup = systable_getnext(scan)) != NULL)
1504 simple_heap_delete(attrel, &atttup->t_self);
1506 /* Clean up after the scan */
1507 systable_endscan(scan);
1508 heap_close(attrel, RowExclusiveLock);
1512 * RemoveAttributeById
1514 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1515 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1516 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1517 * is handled by dependency.c.)
1520 RemoveAttributeById(Oid relid, AttrNumber attnum)
1525 Form_pg_attribute attStruct;
1526 char newattname[NAMEDATALEN];
1529 * Grab an exclusive lock on the target table, which we will NOT release
1530 * until end of transaction. (In the simple case where we are directly
1531 * dropping this column, AlterTableDropColumn already did this ... but
1532 * when cascading from a drop of some other object, we may not have any
1535 rel = relation_open(relid, AccessExclusiveLock);
1537 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1539 tuple = SearchSysCacheCopy2(ATTNUM,
1540 ObjectIdGetDatum(relid),
1541 Int16GetDatum(attnum));
1542 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1543 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1545 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1549 /* System attribute (probably OID) ... just delete the row */
1551 simple_heap_delete(attr_rel, &tuple->t_self);
1555 /* Dropping user attributes is lots harder */
1557 /* Mark the attribute as dropped */
1558 attStruct->attisdropped = true;
1561 * Set the type OID to invalid. A dropped attribute's type link
1562 * cannot be relied on (once the attribute is dropped, the type might
1563 * be too). Fortunately we do not need the type row --- the only
1564 * really essential information is the type's typlen and typalign,
1565 * which are preserved in the attribute's attlen and attalign. We set
1566 * atttypid to zero here as a means of catching code that incorrectly
1567 * expects it to be valid.
1569 attStruct->atttypid = InvalidOid;
1571 /* Remove any NOT NULL constraint the column may have */
1572 attStruct->attnotnull = false;
1574 /* We don't want to keep stats for it anymore */
1575 attStruct->attstattarget = 0;
1578 * Change the column name to something that isn't likely to conflict
1580 snprintf(newattname, sizeof(newattname),
1581 "........pg.dropped.%d........", attnum);
1582 namestrcpy(&(attStruct->attname), newattname);
1584 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1586 /* keep the system catalog indexes current */
1587 CatalogUpdateIndexes(attr_rel, tuple);
1591 * Because updating the pg_attribute row will trigger a relcache flush for
1592 * the target relation, we need not do anything else to notify other
1593 * backends of the change.
1596 heap_close(attr_rel, RowExclusiveLock);
1599 RemoveStatistics(relid, attnum);
1601 relation_close(rel, NoLock);
1607 * If the specified relation/attribute has a default, remove it.
1608 * (If no default, raise error if complain is true, else return quietly.)
1611 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1612 DropBehavior behavior, bool complain, bool internal)
1614 Relation attrdef_rel;
1615 ScanKeyData scankeys[2];
1620 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1622 ScanKeyInit(&scankeys[0],
1623 Anum_pg_attrdef_adrelid,
1624 BTEqualStrategyNumber, F_OIDEQ,
1625 ObjectIdGetDatum(relid));
1626 ScanKeyInit(&scankeys[1],
1627 Anum_pg_attrdef_adnum,
1628 BTEqualStrategyNumber, F_INT2EQ,
1629 Int16GetDatum(attnum));
1631 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1634 /* There should be at most one matching tuple, but we loop anyway */
1635 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1637 ObjectAddress object;
1639 object.classId = AttrDefaultRelationId;
1640 object.objectId = HeapTupleGetOid(tuple);
1641 object.objectSubId = 0;
1643 performDeletion(&object, behavior,
1644 internal ? PERFORM_DELETION_INTERNAL : 0);
1649 systable_endscan(scan);
1650 heap_close(attrdef_rel, RowExclusiveLock);
1652 if (complain && !found)
1653 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1658 * RemoveAttrDefaultById
1660 * Remove a pg_attrdef entry specified by OID. This is the guts of
1661 * attribute-default removal. Note it should be called via performDeletion,
1665 RemoveAttrDefaultById(Oid attrdefId)
1667 Relation attrdef_rel;
1670 ScanKeyData scankeys[1];
1674 AttrNumber myattnum;
1676 /* Grab an appropriate lock on the pg_attrdef relation */
1677 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1679 /* Find the pg_attrdef tuple */
1680 ScanKeyInit(&scankeys[0],
1681 ObjectIdAttributeNumber,
1682 BTEqualStrategyNumber, F_OIDEQ,
1683 ObjectIdGetDatum(attrdefId));
1685 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1688 tuple = systable_getnext(scan);
1689 if (!HeapTupleIsValid(tuple))
1690 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1692 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1693 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1695 /* Get an exclusive lock on the relation owning the attribute */
1696 myrel = relation_open(myrelid, AccessExclusiveLock);
1698 /* Now we can delete the pg_attrdef row */
1699 simple_heap_delete(attrdef_rel, &tuple->t_self);
1701 systable_endscan(scan);
1702 heap_close(attrdef_rel, RowExclusiveLock);
1704 /* Fix the pg_attribute row */
1705 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1707 tuple = SearchSysCacheCopy2(ATTNUM,
1708 ObjectIdGetDatum(myrelid),
1709 Int16GetDatum(myattnum));
1710 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1711 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1714 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1716 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1718 /* keep the system catalog indexes current */
1719 CatalogUpdateIndexes(attr_rel, tuple);
1722 * Our update of the pg_attribute row will force a relcache rebuild, so
1723 * there's nothing else to do here.
1725 heap_close(attr_rel, RowExclusiveLock);
1727 /* Keep lock on attribute's rel until end of xact */
1728 relation_close(myrel, NoLock);
1732 * heap_drop_with_catalog - removes specified relation from catalogs
1734 * Note that this routine is not responsible for dropping objects that are
1735 * linked to the pg_class entry via dependencies (for example, indexes and
1736 * constraints). Those are deleted by the dependency-tracing logic in
1737 * dependency.c before control gets here. In general, therefore, this routine
1738 * should never be called directly; go through performDeletion() instead.
1741 heap_drop_with_catalog(Oid relid)
1746 * Open and lock the relation.
1748 rel = relation_open(relid, AccessExclusiveLock);
1751 * There can no longer be anyone *else* touching the relation, but we
1752 * might still have open queries or cursors, or pending trigger events, in
1755 CheckTableNotInUse(rel, "DROP TABLE");
1758 * This effectively deletes all rows in the table, and may be done in a
1759 * serializable transaction. In that case we must record a rw-conflict in
1760 * to this transaction from each transaction holding a predicate lock on
1763 CheckTableForSerializableConflictIn(rel);
1766 * Delete pg_foreign_table tuple first.
1768 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1773 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1775 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1776 if (!HeapTupleIsValid(tuple))
1777 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1779 simple_heap_delete(rel, &tuple->t_self);
1781 ReleaseSysCache(tuple);
1782 heap_close(rel, RowExclusiveLock);
1786 * Schedule unlinking of the relation's physical files at commit.
1788 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1789 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1790 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1792 RelationDropStorage(rel);
1796 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1797 * until transaction commit. This ensures no one else will try to do
1798 * something with the doomed relation.
1800 relation_close(rel, NoLock);
1803 * Forget any ON COMMIT action for the rel
1805 remove_on_commit_action(relid);
1808 * Flush the relation from the relcache. We want to do this before
1809 * starting to remove catalog entries, just to be certain that no relcache
1810 * entry rebuild will happen partway through. (That should not really
1811 * matter, since we don't do CommandCounterIncrement here, but let's be
1814 RelationForgetRelation(relid);
1817 * remove inheritance information
1819 RelationRemoveInheritance(relid);
1824 RemoveStatistics(relid, 0);
1827 * delete attribute tuples
1829 DeleteAttributeTuples(relid);
1832 * delete relation tuple
1834 DeleteRelationTuple(relid);
1839 * Store a default expression for column attnum of relation rel.
1842 StoreAttrDefault(Relation rel, AttrNumber attnum,
1843 Node *expr, bool is_internal)
1850 static bool nulls[4] = {false, false, false, false};
1853 Form_pg_attribute attStruct;
1855 ObjectAddress colobject,
1859 * Flatten expression to string form for storage.
1861 adbin = nodeToString(expr);
1864 * Also deparse it to form the mostly-obsolete adsrc field.
1866 adsrc = deparse_expression(expr,
1867 deparse_context_for(RelationGetRelationName(rel),
1868 RelationGetRelid(rel)),
1872 * Make the pg_attrdef entry.
1874 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1875 values[Anum_pg_attrdef_adnum - 1] = attnum;
1876 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1877 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1879 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1881 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1882 attrdefOid = simple_heap_insert(adrel, tuple);
1884 CatalogUpdateIndexes(adrel, tuple);
1886 defobject.classId = AttrDefaultRelationId;
1887 defobject.objectId = attrdefOid;
1888 defobject.objectSubId = 0;
1890 heap_close(adrel, RowExclusiveLock);
1892 /* now can free some of the stuff allocated above */
1893 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1894 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1895 heap_freetuple(tuple);
1900 * Update the pg_attribute entry for the column to show that a default
1903 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1904 atttup = SearchSysCacheCopy2(ATTNUM,
1905 ObjectIdGetDatum(RelationGetRelid(rel)),
1906 Int16GetDatum(attnum));
1907 if (!HeapTupleIsValid(atttup))
1908 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1909 attnum, RelationGetRelid(rel));
1910 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1911 if (!attStruct->atthasdef)
1913 attStruct->atthasdef = true;
1914 simple_heap_update(attrrel, &atttup->t_self, atttup);
1915 /* keep catalog indexes current */
1916 CatalogUpdateIndexes(attrrel, atttup);
1918 heap_close(attrrel, RowExclusiveLock);
1919 heap_freetuple(atttup);
1922 * Make a dependency so that the pg_attrdef entry goes away if the column
1923 * (or whole table) is deleted.
1925 colobject.classId = RelationRelationId;
1926 colobject.objectId = RelationGetRelid(rel);
1927 colobject.objectSubId = attnum;
1929 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1932 * Record dependencies on objects used in the expression, too.
1934 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1937 * Post creation hook for attribute defaults.
1939 * XXX. ALTER TABLE ALTER COLUMN SET/DROP DEFAULT is implemented with a
1940 * couple of deletion/creation of the attribute's default entry, so the
1941 * callee should check existence of an older version of this entry if it
1942 * needs to distinguish.
1944 InvokeObjectPostCreateHookArg(AttrDefaultRelationId,
1945 RelationGetRelid(rel), attnum, is_internal);
1949 * Store a check-constraint expression for the given relation.
1951 * Caller is responsible for updating the count of constraints
1952 * in the pg_class entry for the relation.
1955 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1956 bool is_validated, bool is_local, int inhcount,
1957 bool is_no_inherit, bool is_internal)
1966 * Flatten expression to string form for storage.
1968 ccbin = nodeToString(expr);
1971 * Also deparse it to form the mostly-obsolete consrc field.
1973 ccsrc = deparse_expression(expr,
1974 deparse_context_for(RelationGetRelationName(rel),
1975 RelationGetRelid(rel)),
1979 * Find columns of rel that are used in expr
1981 * NB: pull_var_clause is okay here only because we don't allow subselects
1982 * in check constraints; it would fail to examine the contents of
1985 varList = pull_var_clause(expr,
1986 PVC_REJECT_AGGREGATES,
1987 PVC_REJECT_PLACEHOLDERS);
1988 keycount = list_length(varList);
1995 attNos = (int16 *) palloc(keycount * sizeof(int16));
1996 foreach(vl, varList)
1998 Var *var = (Var *) lfirst(vl);
2001 for (j = 0; j < i; j++)
2002 if (attNos[j] == var->varattno)
2005 attNos[i++] = var->varattno;
2013 * Create the Check Constraint
2015 CreateConstraintEntry(ccname, /* Constraint Name */
2016 RelationGetNamespace(rel), /* namespace */
2017 CONSTRAINT_CHECK, /* Constraint Type */
2018 false, /* Is Deferrable */
2019 false, /* Is Deferred */
2021 RelationGetRelid(rel), /* relation */
2022 attNos, /* attrs in the constraint */
2023 keycount, /* # attrs in the constraint */
2024 InvalidOid, /* not a domain constraint */
2025 InvalidOid, /* no associated index */
2026 InvalidOid, /* Foreign key fields */
2035 NULL, /* not an exclusion constraint */
2036 expr, /* Tree form of check constraint */
2037 ccbin, /* Binary form of check constraint */
2038 ccsrc, /* Source form of check constraint */
2039 is_local, /* conislocal */
2040 inhcount, /* coninhcount */
2041 is_no_inherit, /* connoinherit */
2042 is_internal); /* internally constructed? */
2049 * Store defaults and constraints (passed as a list of CookedConstraint).
2051 * NOTE: only pre-cooked expressions will be passed this way, which is to
2052 * say expressions inherited from an existing relation. Newly parsed
2053 * expressions can be added later, by direct calls to StoreAttrDefault
2054 * and StoreRelCheck (see AddRelationNewConstraints()).
2057 StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
2062 if (!cooked_constraints)
2063 return; /* nothing to do */
2066 * Deparsing of constraint expressions will fail unless the just-created
2067 * pg_attribute tuples for this relation are made visible. So, bump the
2068 * command counter. CAUTION: this will cause a relcache entry rebuild.
2070 CommandCounterIncrement();
2072 foreach(lc, cooked_constraints)
2074 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
2076 switch (con->contype)
2078 case CONSTR_DEFAULT:
2079 StoreAttrDefault(rel, con->attnum, con->expr, is_internal);
2082 StoreRelCheck(rel, con->name, con->expr, !con->skip_validation,
2083 con->is_local, con->inhcount,
2084 con->is_no_inherit, is_internal);
2088 elog(ERROR, "unrecognized constraint type: %d",
2089 (int) con->contype);
2094 SetRelationNumChecks(rel, numchecks);
2098 * AddRelationNewConstraints
2100 * Add new column default expressions and/or constraint check expressions
2101 * to an existing relation. This is defined to do both for efficiency in
2102 * DefineRelation, but of course you can do just one or the other by passing
2105 * rel: relation to be modified
2106 * newColDefaults: list of RawColumnDefault structures
2107 * newConstraints: list of Constraint nodes
2108 * allow_merge: TRUE if check constraints may be merged with existing ones
2109 * is_local: TRUE if definition is local, FALSE if it's inherited
2110 * is_internal: TRUE if result of some internal process, not a user request
2112 * All entries in newColDefaults will be processed. Entries in newConstraints
2113 * will be processed only if they are CONSTR_CHECK type.
2115 * Returns a list of CookedConstraint nodes that shows the cooked form of
2116 * the default and constraint expressions added to the relation.
2118 * NB: caller should have opened rel with AccessExclusiveLock, and should
2119 * hold that lock till end of transaction. Also, we assume the caller has
2120 * done a CommandCounterIncrement if necessary to make the relation's catalog
2124 AddRelationNewConstraints(Relation rel,
2125 List *newColDefaults,
2126 List *newConstraints,
2131 List *cookedConstraints = NIL;
2132 TupleDesc tupleDesc;
2133 TupleConstr *oldconstr;
2141 CookedConstraint *cooked;
2144 * Get info about existing constraints.
2146 tupleDesc = RelationGetDescr(rel);
2147 oldconstr = tupleDesc->constr;
2149 numoldchecks = oldconstr->num_check;
2154 * Create a dummy ParseState and insert the target relation as its sole
2155 * rangetable entry. We need a ParseState for transformExpr.
2157 pstate = make_parsestate(NULL);
2158 rte = addRangeTableEntryForRelation(pstate,
2163 addRTEtoQuery(pstate, rte, true, true, true);
2166 * Process column default expressions.
2168 foreach(cell, newColDefaults)
2170 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
2171 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
2173 expr = cookDefault(pstate, colDef->raw_default,
2174 atp->atttypid, atp->atttypmod,
2175 NameStr(atp->attname));
2178 * If the expression is just a NULL constant, we do not bother to make
2179 * an explicit pg_attrdef entry, since the default behavior is
2182 * Note a nonobvious property of this test: if the column is of a
2183 * domain type, what we'll get is not a bare null Const but a
2184 * CoerceToDomain expr, so we will not discard the default. This is
2185 * critical because the column default needs to be retained to
2186 * override any default that the domain might have.
2189 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2192 StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
2194 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2195 cooked->contype = CONSTR_DEFAULT;
2196 cooked->name = NULL;
2197 cooked->attnum = colDef->attnum;
2198 cooked->expr = expr;
2199 cooked->skip_validation = false;
2200 cooked->is_local = is_local;
2201 cooked->inhcount = is_local ? 0 : 1;
2202 cooked->is_no_inherit = false;
2203 cookedConstraints = lappend(cookedConstraints, cooked);
2207 * Process constraint expressions.
2209 numchecks = numoldchecks;
2211 foreach(cell, newConstraints)
2213 Constraint *cdef = (Constraint *) lfirst(cell);
2216 if (cdef->contype != CONSTR_CHECK)
2219 if (cdef->raw_expr != NULL)
2221 Assert(cdef->cooked_expr == NULL);
2224 * Transform raw parsetree to executable expression, and verify
2225 * it's valid as a CHECK constraint.
2227 expr = cookConstraint(pstate, cdef->raw_expr,
2228 RelationGetRelationName(rel));
2232 Assert(cdef->cooked_expr != NULL);
2235 * Here, we assume the parser will only pass us valid CHECK
2236 * expressions, so we do no particular checking.
2238 expr = stringToNode(cdef->cooked_expr);
2242 * Check name uniqueness, or generate a name if none was given.
2244 if (cdef->conname != NULL)
2248 ccname = cdef->conname;
2249 /* Check against other new constraints */
2250 /* Needed because we don't do CommandCounterIncrement in loop */
2251 foreach(cell2, checknames)
2253 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2255 (errcode(ERRCODE_DUPLICATE_OBJECT),
2256 errmsg("check constraint \"%s\" already exists",
2260 /* save name for future checks */
2261 checknames = lappend(checknames, ccname);
2264 * Check against pre-existing constraints. If we are allowed to
2265 * merge with an existing constraint, there's no more to do here.
2266 * (We omit the duplicate constraint from the result, which is
2267 * what ATAddCheckConstraint wants.)
2269 if (MergeWithExistingConstraint(rel, ccname, expr,
2270 allow_merge, is_local,
2271 cdef->is_no_inherit))
2277 * When generating a name, we want to create "tab_col_check" for a
2278 * column constraint and "tab_check" for a table constraint. We
2279 * no longer have any info about the syntactic positioning of the
2280 * constraint phrase, so we approximate this by seeing whether the
2281 * expression references more than one column. (If the user
2282 * played by the rules, the result is the same...)
2284 * Note: pull_var_clause() doesn't descend into sublinks, but we
2285 * eliminated those above; and anyway this only needs to be an
2286 * approximate answer.
2291 vars = pull_var_clause(expr,
2292 PVC_REJECT_AGGREGATES,
2293 PVC_REJECT_PLACEHOLDERS);
2295 /* eliminate duplicates */
2296 vars = list_union(NIL, vars);
2298 if (list_length(vars) == 1)
2299 colname = get_attname(RelationGetRelid(rel),
2300 ((Var *) linitial(vars))->varattno);
2304 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2307 RelationGetNamespace(rel),
2310 /* save name for future checks */
2311 checknames = lappend(checknames, ccname);
2317 StoreRelCheck(rel, ccname, expr, !cdef->skip_validation, is_local,
2318 is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
2322 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2323 cooked->contype = CONSTR_CHECK;
2324 cooked->name = ccname;
2326 cooked->expr = expr;
2327 cooked->skip_validation = cdef->skip_validation;
2328 cooked->is_local = is_local;
2329 cooked->inhcount = is_local ? 0 : 1;
2330 cooked->is_no_inherit = cdef->is_no_inherit;
2331 cookedConstraints = lappend(cookedConstraints, cooked);
2335 * Update the count of constraints in the relation's pg_class tuple. We do
2336 * this even if there was no change, in order to ensure that an SI update
2337 * message is sent out for the pg_class tuple, which will force other
2338 * backends to rebuild their relcache entries for the rel. (This is
2339 * critical if we added defaults but not constraints.)
2341 SetRelationNumChecks(rel, numchecks);
2343 return cookedConstraints;
2347 * Check for a pre-existing check constraint that conflicts with a proposed
2348 * new one, and either adjust its conislocal/coninhcount settings or throw
2351 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2352 * got a so-far-unique name, or throws error if conflict.
2354 * XXX See MergeConstraintsIntoExisting too if you change this code.
2357 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2358 bool allow_merge, bool is_local,
2363 SysScanDesc conscan;
2364 ScanKeyData skey[2];
2367 /* Search for a pg_constraint entry with same name and relation */
2368 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2372 ScanKeyInit(&skey[0],
2373 Anum_pg_constraint_conname,
2374 BTEqualStrategyNumber, F_NAMEEQ,
2375 CStringGetDatum(ccname));
2377 ScanKeyInit(&skey[1],
2378 Anum_pg_constraint_connamespace,
2379 BTEqualStrategyNumber, F_OIDEQ,
2380 ObjectIdGetDatum(RelationGetNamespace(rel)));
2382 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2385 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2387 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2389 if (con->conrelid == RelationGetRelid(rel))
2391 /* Found it. Conflicts if not identical check constraint */
2392 if (con->contype == CONSTRAINT_CHECK)
2397 val = fastgetattr(tup,
2398 Anum_pg_constraint_conbin,
2399 conDesc->rd_att, &isnull);
2401 elog(ERROR, "null conbin for rel %s",
2402 RelationGetRelationName(rel));
2403 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2406 if (!found || !allow_merge)
2408 (errcode(ERRCODE_DUPLICATE_OBJECT),
2409 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2410 ccname, RelationGetRelationName(rel))));
2412 tup = heap_copytuple(tup);
2413 con = (Form_pg_constraint) GETSTRUCT(tup);
2415 /* If the constraint is "no inherit" then cannot merge */
2416 if (con->connoinherit)
2418 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2419 errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
2420 ccname, RelationGetRelationName(rel))));
2423 con->conislocal = true;
2429 con->connoinherit = true;
2431 /* OK to update the tuple */
2433 (errmsg("merging constraint \"%s\" with inherited definition",
2435 simple_heap_update(conDesc, &tup->t_self, tup);
2436 CatalogUpdateIndexes(conDesc, tup);
2441 systable_endscan(conscan);
2442 heap_close(conDesc, RowExclusiveLock);
2448 * Update the count of constraints in the relation's pg_class tuple.
2450 * Caller had better hold exclusive lock on the relation.
2452 * An important side effect is that a SI update message will be sent out for
2453 * the pg_class tuple, which will force other backends to rebuild their
2454 * relcache entries for the rel. Also, this backend will rebuild its
2455 * own relcache entry at the next CommandCounterIncrement.
2458 SetRelationNumChecks(Relation rel, int numchecks)
2462 Form_pg_class relStruct;
2464 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2465 reltup = SearchSysCacheCopy1(RELOID,
2466 ObjectIdGetDatum(RelationGetRelid(rel)));
2467 if (!HeapTupleIsValid(reltup))
2468 elog(ERROR, "cache lookup failed for relation %u",
2469 RelationGetRelid(rel));
2470 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2472 if (relStruct->relchecks != numchecks)
2474 relStruct->relchecks = numchecks;
2476 simple_heap_update(relrel, &reltup->t_self, reltup);
2478 /* keep catalog indexes current */
2479 CatalogUpdateIndexes(relrel, reltup);
2483 /* Skip the disk update, but force relcache inval anyway */
2484 CacheInvalidateRelcache(rel);
2487 heap_freetuple(reltup);
2488 heap_close(relrel, RowExclusiveLock);
2492 * Take a raw default and convert it to a cooked format ready for
2495 * Parse state should be set up to recognize any vars that might appear
2496 * in the expression. (Even though we plan to reject vars, it's more
2497 * user-friendly to give the correct error message than "unknown var".)
2499 * If atttypid is not InvalidOid, coerce the expression to the specified
2500 * type (and typmod atttypmod). attname is only needed in this case:
2501 * it is used in the error message, if any.
2504 cookDefault(ParseState *pstate,
2512 Assert(raw_default != NULL);
2515 * Transform raw parsetree to executable expression.
2517 expr = transformExpr(pstate, raw_default, EXPR_KIND_COLUMN_DEFAULT);
2520 * Make sure default expr does not refer to any vars (we need this check
2521 * since the pstate includes the target table).
2523 if (contain_var_clause(expr))
2525 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2526 errmsg("cannot use column references in default expression")));
2529 * transformExpr() should have already rejected subqueries, aggregates,
2530 * and window functions, based on the EXPR_KIND_ for a default expression.
2532 * It can't return a set either.
2534 if (expression_returns_set(expr))
2536 (errcode(ERRCODE_DATATYPE_MISMATCH),
2537 errmsg("default expression must not return a set")));
2540 * Coerce the expression to the correct type and typmod, if given. This
2541 * should match the parser's processing of non-defaulted expressions ---
2542 * see transformAssignedExpr().
2544 if (OidIsValid(atttypid))
2546 Oid type_id = exprType(expr);
2548 expr = coerce_to_target_type(pstate, expr, type_id,
2549 atttypid, atttypmod,
2550 COERCION_ASSIGNMENT,
2551 COERCE_IMPLICIT_CAST,
2555 (errcode(ERRCODE_DATATYPE_MISMATCH),
2556 errmsg("column \"%s\" is of type %s"
2557 " but default expression is of type %s",
2559 format_type_be(atttypid),
2560 format_type_be(type_id)),
2561 errhint("You will need to rewrite or cast the expression.")));
2565 * Finally, take care of collations in the finished expression.
2567 assign_expr_collations(pstate, expr);
2573 * Take a raw CHECK constraint expression and convert it to a cooked format
2574 * ready for storage.
2576 * Parse state must be set up to recognize any vars that might appear
2577 * in the expression.
2580 cookConstraint(ParseState *pstate,
2581 Node *raw_constraint,
2587 * Transform raw parsetree to executable expression.
2589 expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
2592 * Make sure it yields a boolean result.
2594 expr = coerce_to_boolean(pstate, expr, "CHECK");
2597 * Take care of collations.
2599 assign_expr_collations(pstate, expr);
2602 * Make sure no outside relations are referred to (this is probably dead
2603 * code now that add_missing_from is history).
2605 if (list_length(pstate->p_rtable) != 1)
2607 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2608 errmsg("only table \"%s\" can be referenced in check constraint",
2616 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2618 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2622 RemoveStatistics(Oid relid, AttrNumber attnum)
2624 Relation pgstatistic;
2630 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2632 ScanKeyInit(&key[0],
2633 Anum_pg_statistic_starelid,
2634 BTEqualStrategyNumber, F_OIDEQ,
2635 ObjectIdGetDatum(relid));
2641 ScanKeyInit(&key[1],
2642 Anum_pg_statistic_staattnum,
2643 BTEqualStrategyNumber, F_INT2EQ,
2644 Int16GetDatum(attnum));
2648 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2651 /* we must loop even when attnum != 0, in case of inherited stats */
2652 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2653 simple_heap_delete(pgstatistic, &tuple->t_self);
2655 systable_endscan(scan);
2657 heap_close(pgstatistic, RowExclusiveLock);
2662 * RelationTruncateIndexes - truncate all indexes associated
2663 * with the heap relation to zero tuples.
2665 * The routine will truncate and then reconstruct the indexes on
2666 * the specified relation. Caller must hold exclusive lock on rel.
2669 RelationTruncateIndexes(Relation heapRelation)
2673 /* Ask the relcache to produce a list of the indexes of the rel */
2674 foreach(indlist, RelationGetIndexList(heapRelation))
2676 Oid indexId = lfirst_oid(indlist);
2677 Relation currentIndex;
2678 IndexInfo *indexInfo;
2680 /* Open the index relation; use exclusive lock, just to be sure */
2681 currentIndex = index_open(indexId, AccessExclusiveLock);
2683 /* Fetch info needed for index_build */
2684 indexInfo = BuildIndexInfo(currentIndex);
2687 * Now truncate the actual file (and discard buffers).
2689 RelationTruncate(currentIndex, 0);
2691 /* Initialize the index and rebuild */
2692 /* Note: we do not need to re-establish pkey setting */
2693 index_build(heapRelation, currentIndex, indexInfo, false, true);
2695 /* We're done with this index */
2696 index_close(currentIndex, NoLock);
2703 * This routine deletes all data within all the specified relations.
2705 * This is not transaction-safe! There is another, transaction-safe
2706 * implementation in commands/tablecmds.c. We now use this only for
2707 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2710 heap_truncate(List *relids)
2712 List *relations = NIL;
2715 /* Open relations for processing, and grab exclusive access on each */
2716 foreach(cell, relids)
2718 Oid rid = lfirst_oid(cell);
2721 rel = heap_open(rid, AccessExclusiveLock);
2722 relations = lappend(relations, rel);
2725 /* Don't allow truncate on tables that are referenced by foreign keys */
2726 heap_truncate_check_FKs(relations, true);
2729 foreach(cell, relations)
2731 Relation rel = lfirst(cell);
2733 /* Truncate the relation */
2734 heap_truncate_one_rel(rel);
2736 /* Close the relation, but keep exclusive lock on it until commit */
2737 heap_close(rel, NoLock);
2742 * heap_truncate_one_rel
2744 * This routine deletes all data within the specified relation.
2746 * This is not transaction-safe, because the truncation is done immediately
2747 * and cannot be rolled back later. Caller is responsible for having
2748 * checked permissions etc, and must have obtained AccessExclusiveLock.
2751 heap_truncate_one_rel(Relation rel)
2755 /* Truncate the actual file (and discard buffers) */
2756 RelationTruncate(rel, 0);
2758 /* If the relation has indexes, truncate the indexes too */
2759 RelationTruncateIndexes(rel);
2761 /* If there is a toast table, truncate that too */
2762 toastrelid = rel->rd_rel->reltoastrelid;
2763 if (OidIsValid(toastrelid))
2765 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2767 RelationTruncate(toastrel, 0);
2768 RelationTruncateIndexes(toastrel);
2769 /* keep the lock... */
2770 heap_close(toastrel, NoLock);
2775 * heap_truncate_check_FKs
2776 * Check for foreign keys referencing a list of relations that
2777 * are to be truncated, and raise error if there are any
2779 * We disallow such FKs (except self-referential ones) since the whole point
2780 * of TRUNCATE is to not scan the individual rows to be thrown away.
2782 * This is split out so it can be shared by both implementations of truncate.
2783 * Caller should already hold a suitable lock on the relations.
2785 * tempTables is only used to select an appropriate error message.
2788 heap_truncate_check_FKs(List *relations, bool tempTables)
2795 * Build a list of OIDs of the interesting relations.
2797 * If a relation has no triggers, then it can neither have FKs nor be
2798 * referenced by a FK from another table, so we can ignore it.
2800 foreach(cell, relations)
2802 Relation rel = lfirst(cell);
2804 if (rel->rd_rel->relhastriggers)
2805 oids = lappend_oid(oids, RelationGetRelid(rel));
2809 * Fast path: if no relation has triggers, none has FKs either.
2815 * Otherwise, must scan pg_constraint. We make one pass with all the
2816 * relations considered; if this finds nothing, then all is well.
2818 dependents = heap_truncate_find_FKs(oids);
2819 if (dependents == NIL)
2823 * Otherwise we repeat the scan once per relation to identify a particular
2824 * pair of relations to complain about. This is pretty slow, but
2825 * performance shouldn't matter much in a failure path. The reason for
2826 * doing things this way is to ensure that the message produced is not
2827 * dependent on chance row locations within pg_constraint.
2831 Oid relid = lfirst_oid(cell);
2834 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2836 foreach(cell2, dependents)
2838 Oid relid2 = lfirst_oid(cell2);
2840 if (!list_member_oid(oids, relid2))
2842 char *relname = get_rel_name(relid);
2843 char *relname2 = get_rel_name(relid2);
2847 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2848 errmsg("unsupported ON COMMIT and foreign key combination"),
2849 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2850 relname2, relname)));
2853 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2854 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2855 errdetail("Table \"%s\" references \"%s\".",
2857 errhint("Truncate table \"%s\" at the same time, "
2858 "or use TRUNCATE ... CASCADE.",
2866 * heap_truncate_find_FKs
2867 * Find relations having foreign keys referencing any of the given rels
2869 * Input and result are both lists of relation OIDs. The result contains
2870 * no duplicates, does *not* include any rels that were already in the input
2871 * list, and is sorted in OID order. (The last property is enforced mainly
2872 * to guarantee consistent behavior in the regression tests; we don't want
2873 * behavior to change depending on chance locations of rows in pg_constraint.)
2875 * Note: caller should already have appropriate lock on all rels mentioned
2876 * in relationIds. Since adding or dropping an FK requires exclusive lock
2877 * on both rels, this ensures that the answer will be stable.
2880 heap_truncate_find_FKs(List *relationIds)
2884 SysScanDesc fkeyScan;
2888 * Must scan pg_constraint. Right now, it is a seqscan because there is
2889 * no available index on confrelid.
2891 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2893 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2896 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2898 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2900 /* Not a foreign key */
2901 if (con->contype != CONSTRAINT_FOREIGN)
2904 /* Not referencing one of our list of tables */
2905 if (!list_member_oid(relationIds, con->confrelid))
2908 /* Add referencer unless already in input or result list */
2909 if (!list_member_oid(relationIds, con->conrelid))
2910 result = insert_ordered_unique_oid(result, con->conrelid);
2913 systable_endscan(fkeyScan);
2914 heap_close(fkeyRel, AccessShareLock);
2920 * insert_ordered_unique_oid
2921 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2922 * and eliminating duplicates
2924 * Building the ordered list this way is O(N^2), but with a pretty small
2925 * constant, so for the number of entries we expect it will probably be
2926 * faster than trying to apply qsort(). It seems unlikely someone would be
2927 * trying to truncate a table with thousands of dependent tables ...
2930 insert_ordered_unique_oid(List *list, Oid datum)
2934 /* Does the datum belong at the front? */
2935 if (list == NIL || datum < linitial_oid(list))
2936 return lcons_oid(datum, list);
2937 /* Does it match the first entry? */
2938 if (datum == linitial_oid(list))
2939 return list; /* duplicate, so don't insert */
2940 /* No, so find the entry it belongs after */
2941 prev = list_head(list);
2944 ListCell *curr = lnext(prev);
2946 if (curr == NULL || datum < lfirst_oid(curr))
2947 break; /* it belongs after 'prev', before 'curr' */
2949 if (datum == lfirst_oid(curr))
2950 return list; /* duplicate, so don't insert */
2954 /* Insert datum into list after 'prev' */
2955 lappend_cell_oid(list, prev, datum);