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,
109 static void SetRelationNumChecks(Relation rel, int numchecks);
110 static Node *cookConstraint(ParseState *pstate,
111 Node *raw_constraint,
113 static List *insert_ordered_unique_oid(List *list, Oid datum);
116 /* ----------------------------------------------------------------
117 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
119 * these should all be moved to someplace in the lib/catalog
120 * module, if not obliterated first.
121 * ----------------------------------------------------------------
127 * Should the system special case these attributes in the future?
128 * Advantage: consume much less space in the ATTRIBUTE relation.
129 * Disadvantage: special cases will be all over the place.
133 * The initializers below do not include trailing variable length fields,
134 * but that's OK - we're never going to reference anything beyond the
135 * fixed-size portion of the structure anyway.
138 static FormData_pg_attribute a1 = {
139 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
140 SelfItemPointerAttributeNumber, 0, -1, -1,
141 false, 'p', 's', true, false, false, true, 0
144 static FormData_pg_attribute a2 = {
145 0, {"oid"}, OIDOID, 0, sizeof(Oid),
146 ObjectIdAttributeNumber, 0, -1, -1,
147 true, 'p', 'i', true, false, false, true, 0
150 static FormData_pg_attribute a3 = {
151 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
152 MinTransactionIdAttributeNumber, 0, -1, -1,
153 true, 'p', 'i', true, false, false, true, 0
156 static FormData_pg_attribute a4 = {
157 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
158 MinCommandIdAttributeNumber, 0, -1, -1,
159 true, 'p', 'i', true, false, false, true, 0
162 static FormData_pg_attribute a5 = {
163 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
164 MaxTransactionIdAttributeNumber, 0, -1, -1,
165 true, 'p', 'i', true, false, false, true, 0
168 static FormData_pg_attribute a6 = {
169 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
170 MaxCommandIdAttributeNumber, 0, -1, -1,
171 true, 'p', 'i', true, false, false, true, 0
175 * We decided to call this attribute "tableoid" rather than say
176 * "classoid" on the basis that in the future there may be more than one
177 * table of a particular class/type. In any case table is still the word
180 static FormData_pg_attribute a7 = {
181 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
182 TableOidAttributeNumber, 0, -1, -1,
183 true, 'p', 'i', true, false, false, true, 0
186 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
189 * This function returns a Form_pg_attribute pointer for a system attribute.
190 * Note that we elog if the presented attno is invalid, which would only
191 * happen if there's a problem upstream.
194 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
196 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
197 elog(ERROR, "invalid system attribute number %d", attno);
198 if (attno == ObjectIdAttributeNumber && !relhasoids)
199 elog(ERROR, "invalid system attribute number %d", attno);
200 return SysAtt[-attno - 1];
204 * If the given name is a system attribute name, return a Form_pg_attribute
205 * pointer for a prototype definition. If not, return NULL.
208 SystemAttributeByName(const char *attname, bool relhasoids)
212 for (j = 0; j < (int) lengthof(SysAtt); j++)
214 Form_pg_attribute att = SysAtt[j];
216 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
218 if (strcmp(NameStr(att->attname), attname) == 0)
227 /* ----------------------------------------------------------------
228 * XXX END OF UGLY HARD CODED BADNESS XXX
229 * ---------------------------------------------------------------- */
232 /* ----------------------------------------------------------------
233 * heap_create - Create an uncataloged heap relation
235 * Note API change: the caller must now always provide the OID
236 * to use for the relation. The relfilenode may (and, normally,
237 * should) be left unspecified.
239 * rel->rd_rel is initialized by RelationBuildLocalRelation,
240 * and is mostly zeroes at return.
241 * ----------------------------------------------------------------
244 heap_create(const char *relname,
252 bool shared_relation,
253 bool mapped_relation,
254 bool allow_system_table_mods)
259 /* The caller must have provided an OID for the relation. */
260 Assert(OidIsValid(relid));
263 * Don't allow creating relations in pg_catalog directly, even though it
264 * is allowed to move user defined relations there. Semantics with search
265 * paths including pg_catalog are too confusing for now.
267 * But allow creating indexes on relations in pg_catalog even if
268 * allow_system_table_mods = off, upper layers already guarantee it's on a
269 * user defined relation, not a system one.
271 if (!allow_system_table_mods &&
272 ((IsSystemNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
273 IsToastNamespace(relnamespace)) &&
274 IsNormalProcessingMode())
276 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
277 errmsg("permission denied to create \"%s.%s\"",
278 get_namespace_name(relnamespace), relname),
279 errdetail("System catalog modifications are currently disallowed.")));
282 * Decide if we need storage or not, and handle a couple other special
283 * cases for particular relkinds.
288 case RELKIND_COMPOSITE_TYPE:
289 case RELKIND_FOREIGN_TABLE:
290 create_storage = false;
293 * Force reltablespace to zero if the relation has no physical
294 * storage. This is mainly just for cleanliness' sake.
296 reltablespace = InvalidOid;
298 case RELKIND_SEQUENCE:
299 create_storage = true;
302 * Force reltablespace to zero for sequences, since we don't
303 * support moving them around into different tablespaces.
305 reltablespace = InvalidOid;
308 create_storage = true;
313 * Unless otherwise requested, the physical ID (relfilenode) is initially
314 * the same as the logical ID (OID). When the caller did specify a
315 * relfilenode, it already exists; do not attempt to create it.
317 if (OidIsValid(relfilenode))
318 create_storage = false;
323 * Never allow a pg_class entry to explicitly specify the database's
324 * default tablespace in reltablespace; force it to zero instead. This
325 * ensures that if the database is cloned with a different default
326 * tablespace, the pg_class entry will still match where CREATE DATABASE
327 * will put the physically copied relation.
329 * Yes, this is a bit of a hack.
331 if (reltablespace == MyDatabaseTableSpace)
332 reltablespace = InvalidOid;
335 * build the relcache entry.
337 rel = RelationBuildLocalRelation(relname,
349 * Have the storage manager create the relation's disk file, if needed.
351 * We only create the main fork here, other forks will be created on
356 RelationOpenSmgr(rel);
357 RelationCreateStorage(rel->rd_node, relpersistence);
363 /* ----------------------------------------------------------------
364 * heap_create_with_catalog - Create a cataloged relation
366 * this is done in multiple steps:
368 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
369 * descriptor contains a valid set of attribute names and types
371 * 2) pg_class is opened and get_relname_relid()
372 * performs a scan to ensure that no relation with the
373 * same name already exists.
375 * 3) heap_create() is called to create the new relation on disk.
377 * 4) TypeCreate() is called to define a new type corresponding
378 * to the new relation.
380 * 5) AddNewRelationTuple() is called to register the
381 * relation in pg_class.
383 * 6) AddNewAttributeTuples() is called to register the
384 * new relation's schema in pg_attribute.
386 * 7) StoreConstraints is called () - vadim 08/22/97
388 * 8) the relations are closed and the new relation's oid
391 * ----------------------------------------------------------------
394 /* --------------------------------
395 * CheckAttributeNamesTypes
397 * this is used to make certain the tuple descriptor contains a
398 * valid set of attribute names and datatypes. a problem simply
399 * generates ereport(ERROR) which aborts the current transaction.
400 * --------------------------------
403 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
404 bool allow_system_table_mods)
408 int natts = tupdesc->natts;
410 /* Sanity check on column count */
411 if (natts < 0 || natts > MaxHeapAttributeNumber)
413 (errcode(ERRCODE_TOO_MANY_COLUMNS),
414 errmsg("tables can have at most %d columns",
415 MaxHeapAttributeNumber)));
418 * first check for collision with system attribute names
420 * Skip this for a view or type relation, since those don't have system
423 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
425 for (i = 0; i < natts; i++)
427 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
428 tupdesc->tdhasoid) != NULL)
430 (errcode(ERRCODE_DUPLICATE_COLUMN),
431 errmsg("column name \"%s\" conflicts with a system column name",
432 NameStr(tupdesc->attrs[i]->attname))));
437 * next check for repeated attribute names
439 for (i = 1; i < natts; i++)
441 for (j = 0; j < i; j++)
443 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
444 NameStr(tupdesc->attrs[i]->attname)) == 0)
446 (errcode(ERRCODE_DUPLICATE_COLUMN),
447 errmsg("column name \"%s\" specified more than once",
448 NameStr(tupdesc->attrs[j]->attname))));
453 * next check the attribute types
455 for (i = 0; i < natts; i++)
457 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
458 tupdesc->attrs[i]->atttypid,
459 tupdesc->attrs[i]->attcollation,
460 NIL, /* assume we're creating a new rowtype */
461 allow_system_table_mods);
465 /* --------------------------------
468 * Verify that the proposed datatype of an attribute is legal.
469 * This is needed mainly because there are types (and pseudo-types)
470 * in the catalogs that we do not support as elements of real tuples.
471 * We also check some other properties required of a table column.
473 * If the attribute is being proposed for addition to an existing table or
474 * composite type, pass a one-element list of the rowtype OID as
475 * containing_rowtypes. When checking a to-be-created rowtype, it's
476 * sufficient to pass NIL, because there could not be any recursive reference
477 * to a not-yet-existing rowtype.
478 * --------------------------------
481 CheckAttributeType(const char *attname,
482 Oid atttypid, Oid attcollation,
483 List *containing_rowtypes,
484 bool allow_system_table_mods)
486 char att_typtype = get_typtype(atttypid);
489 if (atttypid == UNKNOWNOID)
492 * Warn user, but don't fail, if column to be created has UNKNOWN type
493 * (usually as a result of a 'retrieve into' - jolly)
496 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
497 errmsg("column \"%s\" has type \"unknown\"", attname),
498 errdetail("Proceeding with relation creation anyway.")));
500 else if (att_typtype == TYPTYPE_PSEUDO)
503 * Refuse any attempt to create a pseudo-type column, except for a
504 * special hack for pg_statistic: allow ANYARRAY when modifying system
505 * catalogs (this allows creating pg_statistic and cloning it during
508 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
510 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
511 errmsg("column \"%s\" has pseudo-type %s",
512 attname, format_type_be(atttypid))));
514 else if (att_typtype == TYPTYPE_DOMAIN)
517 * If it's a domain, recurse to check its base type.
519 CheckAttributeType(attname, getBaseType(atttypid), attcollation,
521 allow_system_table_mods);
523 else if (att_typtype == TYPTYPE_COMPOSITE)
526 * For a composite type, recurse into its attributes.
533 * Check for self-containment. Eventually we might be able to allow
534 * this (just return without complaint, if so) but it's not clear how
535 * many other places would require anti-recursion defenses before it
536 * would be safe to allow tables to contain their own rowtype.
538 if (list_member_oid(containing_rowtypes, atttypid))
540 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
541 errmsg("composite type %s cannot be made a member of itself",
542 format_type_be(atttypid))));
544 containing_rowtypes = lcons_oid(atttypid, containing_rowtypes);
546 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
548 tupdesc = RelationGetDescr(relation);
550 for (i = 0; i < tupdesc->natts; i++)
552 Form_pg_attribute attr = tupdesc->attrs[i];
554 if (attr->attisdropped)
556 CheckAttributeType(NameStr(attr->attname),
557 attr->atttypid, attr->attcollation,
559 allow_system_table_mods);
562 relation_close(relation, AccessShareLock);
564 containing_rowtypes = list_delete_first(containing_rowtypes);
566 else if (OidIsValid((att_typelem = get_element_type(atttypid))))
569 * Must recurse into array types, too, in case they are composite.
571 CheckAttributeType(attname, att_typelem, attcollation,
573 allow_system_table_mods);
577 * This might not be strictly invalid per SQL standard, but it is pretty
578 * useless, and it cannot be dumped, so we must disallow it.
580 if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
582 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
583 errmsg("no collation was derived for column \"%s\" with collatable type %s",
584 attname, format_type_be(atttypid)),
585 errhint("Use the COLLATE clause to set the collation explicitly.")));
589 * InsertPgAttributeTuple
590 * Construct and insert a new tuple in pg_attribute.
592 * Caller has already opened and locked pg_attribute. new_attribute is the
593 * attribute to insert (but we ignore attacl and attoptions, which are always
594 * initialized to NULL).
596 * indstate is the index state for CatalogIndexInsert. It can be passed as
597 * NULL, in which case we'll fetch the necessary info. (Don't do this when
598 * inserting multiple attributes, because it's a tad more expensive.)
601 InsertPgAttributeTuple(Relation pg_attribute_rel,
602 Form_pg_attribute new_attribute,
603 CatalogIndexState indstate)
605 Datum values[Natts_pg_attribute];
606 bool nulls[Natts_pg_attribute];
609 /* This is a tad tedious, but way cleaner than what we used to do... */
610 memset(values, 0, sizeof(values));
611 memset(nulls, false, sizeof(nulls));
613 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
614 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
615 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
616 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
617 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
618 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
619 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
620 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
621 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
622 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
623 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
624 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
625 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
626 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
627 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
628 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
629 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
630 values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
632 /* start out with empty permissions and empty options */
633 nulls[Anum_pg_attribute_attacl - 1] = true;
634 nulls[Anum_pg_attribute_attoptions - 1] = true;
635 nulls[Anum_pg_attribute_attfdwoptions - 1] = true;
637 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
639 /* finally insert the new tuple, update the indexes, and clean up */
640 simple_heap_insert(pg_attribute_rel, tup);
642 if (indstate != NULL)
643 CatalogIndexInsert(indstate, tup);
645 CatalogUpdateIndexes(pg_attribute_rel, tup);
650 /* --------------------------------
651 * AddNewAttributeTuples
653 * this registers the new relation's schema by adding
654 * tuples to pg_attribute.
655 * --------------------------------
658 AddNewAttributeTuples(Oid new_rel_oid,
664 Form_pg_attribute attr;
667 CatalogIndexState indstate;
668 int natts = tupdesc->natts;
669 ObjectAddress myself,
673 * open pg_attribute and its indexes.
675 rel = heap_open(AttributeRelationId, RowExclusiveLock);
677 indstate = CatalogOpenIndexes(rel);
680 * First we add the user attributes. This is also a convenient place to
681 * add dependencies on their datatypes and collations.
683 for (i = 0; i < natts; i++)
685 attr = tupdesc->attrs[i];
686 /* Fill in the correct relation OID */
687 attr->attrelid = new_rel_oid;
688 /* Make sure these are OK, too */
689 attr->attstattarget = -1;
690 attr->attcacheoff = -1;
692 InsertPgAttributeTuple(rel, attr, indstate);
694 /* Add dependency info */
695 myself.classId = RelationRelationId;
696 myself.objectId = new_rel_oid;
697 myself.objectSubId = i + 1;
698 referenced.classId = TypeRelationId;
699 referenced.objectId = attr->atttypid;
700 referenced.objectSubId = 0;
701 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
703 /* The default collation is pinned, so don't bother recording it */
704 if (OidIsValid(attr->attcollation) &&
705 attr->attcollation != DEFAULT_COLLATION_OID)
707 referenced.classId = CollationRelationId;
708 referenced.objectId = attr->attcollation;
709 referenced.objectSubId = 0;
710 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
715 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
716 * all for a view or type relation. We don't bother with making datatype
717 * dependencies here, since presumably all these types are pinned.
719 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
721 for (i = 0; i < (int) lengthof(SysAtt); i++)
723 FormData_pg_attribute attStruct;
725 /* skip OID where appropriate */
726 if (!tupdesc->tdhasoid &&
727 SysAtt[i]->attnum == ObjectIdAttributeNumber)
730 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
732 /* Fill in the correct relation OID in the copied tuple */
733 attStruct.attrelid = new_rel_oid;
735 /* Fill in correct inheritance info for the OID column */
736 if (attStruct.attnum == ObjectIdAttributeNumber)
738 attStruct.attislocal = oidislocal;
739 attStruct.attinhcount = oidinhcount;
742 InsertPgAttributeTuple(rel, &attStruct, indstate);
749 CatalogCloseIndexes(indstate);
751 heap_close(rel, RowExclusiveLock);
754 /* --------------------------------
757 * Construct and insert a new tuple in pg_class.
759 * Caller has already opened and locked pg_class.
760 * Tuple data is taken from new_rel_desc->rd_rel, except for the
761 * variable-width fields which are not present in a cached reldesc.
762 * relacl and reloptions are passed in Datum form (to avoid having
763 * to reference the data types in heap.h). Pass (Datum) 0 to set them
765 * --------------------------------
768 InsertPgClassTuple(Relation pg_class_desc,
769 Relation new_rel_desc,
774 Form_pg_class rd_rel = new_rel_desc->rd_rel;
775 Datum values[Natts_pg_class];
776 bool nulls[Natts_pg_class];
779 /* This is a tad tedious, but way cleaner than what we used to do... */
780 memset(values, 0, sizeof(values));
781 memset(nulls, false, sizeof(nulls));
783 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
784 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
785 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
786 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
787 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
788 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
789 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
790 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
791 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
792 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
793 values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
794 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
795 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
796 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
797 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
798 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
799 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
800 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
801 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
802 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
803 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
804 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
805 values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
806 values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
807 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
808 values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
809 values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
810 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
811 values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
812 if (relacl != (Datum) 0)
813 values[Anum_pg_class_relacl - 1] = relacl;
815 nulls[Anum_pg_class_relacl - 1] = true;
816 if (reloptions != (Datum) 0)
817 values[Anum_pg_class_reloptions - 1] = reloptions;
819 nulls[Anum_pg_class_reloptions - 1] = true;
821 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
824 * The new tuple must have the oid already chosen for the rel. Sure would
825 * be embarrassing to do this sort of thing in polite company.
827 HeapTupleSetOid(tup, new_rel_oid);
829 /* finally insert the new tuple, update the indexes, and clean up */
830 simple_heap_insert(pg_class_desc, tup);
832 CatalogUpdateIndexes(pg_class_desc, tup);
837 /* --------------------------------
838 * AddNewRelationTuple
840 * this registers the new relation in the catalogs by
841 * adding a tuple to pg_class.
842 * --------------------------------
845 AddNewRelationTuple(Relation pg_class_desc,
846 Relation new_rel_desc,
855 Form_pg_class new_rel_reltup;
858 * first we update some of the information in our uncataloged relation's
859 * relation descriptor.
861 new_rel_reltup = new_rel_desc->rd_rel;
865 case RELKIND_RELATION:
866 case RELKIND_MATVIEW:
868 case RELKIND_TOASTVALUE:
869 /* The relation is real, but as yet empty */
870 new_rel_reltup->relpages = 0;
871 new_rel_reltup->reltuples = 0;
872 new_rel_reltup->relallvisible = 0;
874 case RELKIND_SEQUENCE:
875 /* Sequences always have a known size */
876 new_rel_reltup->relpages = 1;
877 new_rel_reltup->reltuples = 1;
878 new_rel_reltup->relallvisible = 0;
881 /* Views, etc, have no disk storage */
882 new_rel_reltup->relpages = 0;
883 new_rel_reltup->reltuples = 0;
884 new_rel_reltup->relallvisible = 0;
888 /* Initialize relfrozenxid and relminmxid */
889 if (relkind == RELKIND_RELATION ||
890 relkind == RELKIND_MATVIEW ||
891 relkind == RELKIND_TOASTVALUE)
894 * Initialize to the minimum XID that could put tuples in the table.
895 * We know that no xacts older than RecentXmin are still running, so
898 new_rel_reltup->relfrozenxid = RecentXmin;
901 * Similarly, initialize the minimum Multixact to the first value that
902 * could possibly be stored in tuples in the table. Running
903 * transactions could reuse values from their local cache, so we are
904 * careful to consider all currently running multis.
906 * XXX this could be refined further, but is it worth the hassle?
908 new_rel_reltup->relminmxid = GetOldestMultiXactId();
913 * Other relation types will not contain XIDs, so set relfrozenxid to
914 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
915 * we force its xmin to be FrozenTransactionId always; see
916 * commands/sequence.c.)
918 new_rel_reltup->relfrozenxid = InvalidTransactionId;
919 new_rel_reltup->relminmxid = InvalidMultiXactId;
922 new_rel_reltup->relowner = relowner;
923 new_rel_reltup->reltype = new_type_oid;
924 new_rel_reltup->reloftype = reloftype;
926 new_rel_desc->rd_att->tdtypeid = new_type_oid;
928 /* Now build and insert the tuple */
929 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
934 /* --------------------------------
935 * AddNewRelationType -
937 * define a composite type corresponding to the new relation
938 * --------------------------------
941 AddNewRelationType(const char *typeName,
950 TypeCreate(new_row_type, /* optional predetermined OID */
951 typeName, /* type name */
952 typeNamespace, /* type namespace */
953 new_rel_oid, /* relation oid */
954 new_rel_kind, /* relation kind */
955 ownerid, /* owner's ID */
956 -1, /* internal size (varlena) */
957 TYPTYPE_COMPOSITE, /* type-type (composite) */
958 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
959 false, /* composite types are never preferred */
960 DEFAULT_TYPDELIM, /* default array delimiter */
961 F_RECORD_IN, /* input procedure */
962 F_RECORD_OUT, /* output procedure */
963 F_RECORD_RECV, /* receive procedure */
964 F_RECORD_SEND, /* send procedure */
965 InvalidOid, /* typmodin procedure - none */
966 InvalidOid, /* typmodout procedure - none */
967 InvalidOid, /* analyze procedure - default */
968 InvalidOid, /* array element type - irrelevant */
969 false, /* this is not an array type */
970 new_array_type, /* array type if any */
971 InvalidOid, /* domain base type - irrelevant */
972 NULL, /* default value - none */
973 NULL, /* default binary representation */
974 false, /* passed by reference */
975 'd', /* alignment - must be the largest! */
976 'x', /* fully TOASTable */
978 0, /* array dimensions for typBaseType */
979 false, /* Type NOT NULL */
980 InvalidOid); /* rowtypes never have a collation */
983 /* --------------------------------
984 * heap_create_with_catalog
986 * creates a new cataloged relation. see comments above.
989 * relname: name to give to new rel
990 * relnamespace: OID of namespace it goes in
991 * reltablespace: OID of tablespace it goes in
992 * relid: OID to assign to new rel, or InvalidOid to select a new OID
993 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
994 * reloftypeid: if a typed table, OID of underlying type; else InvalidOid
995 * ownerid: OID of new rel's owner
996 * tupdesc: tuple descriptor (source of column definitions)
997 * cooked_constraints: list of precooked check constraints and defaults
998 * relkind: relkind for new rel
999 * relpersistence: rel's persistence status (permanent, temp, or unlogged)
1000 * shared_relation: TRUE if it's to be a shared relation
1001 * mapped_relation: TRUE if the relation will use the relfilenode map
1002 * oidislocal: TRUE if oid column (if any) should be marked attislocal
1003 * oidinhcount: attinhcount to assign to oid column (if any)
1004 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
1005 * reloptions: reloptions in Datum form, or (Datum) 0 if none
1006 * use_user_acl: TRUE if should look for user-defined default permissions;
1007 * if FALSE, relacl is always set NULL
1008 * allow_system_table_mods: TRUE to allow creation in system namespaces
1009 * is_internal: is this a system-generated catalog?
1011 * Output parameters:
1012 * typaddress: if not null, gets the object address of the new pg_type entry
1014 * Returns the OID of the new relation
1015 * --------------------------------
1018 heap_create_with_catalog(const char *relname,
1026 List *cooked_constraints,
1028 char relpersistence,
1029 bool shared_relation,
1030 bool mapped_relation,
1033 OnCommitAction oncommit,
1036 bool allow_system_table_mods,
1038 ObjectAddress *typaddress)
1040 Relation pg_class_desc;
1041 Relation new_rel_desc;
1046 ObjectAddress new_type_addr;
1047 Oid new_array_oid = InvalidOid;
1049 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1054 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
1056 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
1059 * This would fail later on anyway, if the relation already exists. But
1060 * by catching it here we can emit a nicer error message.
1062 existing_relid = get_relname_relid(relname, relnamespace);
1063 if (existing_relid != InvalidOid)
1065 (errcode(ERRCODE_DUPLICATE_TABLE),
1066 errmsg("relation \"%s\" already exists", relname)));
1069 * Since we are going to create a rowtype as well, also check for
1070 * collision with an existing type name. If there is one and it's an
1071 * autogenerated array, we can rename it out of the way; otherwise we can
1072 * at least give a good error message.
1074 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1075 CStringGetDatum(relname),
1076 ObjectIdGetDatum(relnamespace));
1077 if (OidIsValid(old_type_oid))
1079 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1081 (errcode(ERRCODE_DUPLICATE_OBJECT),
1082 errmsg("type \"%s\" already exists", relname),
1083 errhint("A relation has an associated type of the same name, "
1084 "so you must use a name that doesn't conflict "
1085 "with any existing type.")));
1089 * Shared relations must be in pg_global (last-ditch check)
1091 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1092 elog(ERROR, "shared relations must be placed in pg_global tablespace");
1095 * Allocate an OID for the relation, unless we were told what to use.
1097 * The OID will be the relfilenode as well, so make sure it doesn't
1098 * collide with either pg_class OIDs or existing physical files.
1100 if (!OidIsValid(relid))
1102 /* Use binary-upgrade override for pg_class.oid/relfilenode? */
1103 if (IsBinaryUpgrade &&
1104 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
1105 relkind == RELKIND_VIEW || relkind == RELKIND_MATVIEW ||
1106 relkind == RELKIND_COMPOSITE_TYPE || relkind == RELKIND_FOREIGN_TABLE))
1108 if (!OidIsValid(binary_upgrade_next_heap_pg_class_oid))
1110 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1111 errmsg("pg_class heap OID value not set when in binary upgrade mode")));
1113 relid = binary_upgrade_next_heap_pg_class_oid;
1114 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1116 /* There might be no TOAST table, so we have to test for it. */
1117 else if (IsBinaryUpgrade &&
1118 OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1119 relkind == RELKIND_TOASTVALUE)
1121 relid = binary_upgrade_next_toast_pg_class_oid;
1122 binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1125 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1130 * Determine the relation's initial permissions.
1136 case RELKIND_RELATION:
1138 case RELKIND_MATVIEW:
1139 case RELKIND_FOREIGN_TABLE:
1140 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1143 case RELKIND_SEQUENCE:
1144 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1156 * Create the relcache entry (mostly dummy at this point) and the physical
1157 * disk file. (If we fail further down, it's the smgr's responsibility to
1158 * remove the disk file again.)
1160 new_rel_desc = heap_create(relname,
1170 allow_system_table_mods);
1172 Assert(relid == RelationGetRelid(new_rel_desc));
1175 * Decide whether to create an array type over the relation's rowtype. We
1176 * do not create any array types for system catalogs (ie, those made
1177 * during initdb). We do not create them where the use of a relation as
1178 * such is an implementation detail: toast tables, sequences and indexes.
1180 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1181 relkind == RELKIND_VIEW ||
1182 relkind == RELKIND_MATVIEW ||
1183 relkind == RELKIND_FOREIGN_TABLE ||
1184 relkind == RELKIND_COMPOSITE_TYPE))
1185 new_array_oid = AssignTypeArrayOid();
1188 * Since defining a relation also defines a complex type, we add a new
1189 * system type corresponding to the new relation. The OID of the type can
1190 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1191 * generate a new OID for it.
1193 * NOTE: we could get a unique-index failure here, in case someone else is
1194 * creating the same type name in parallel but hadn't committed yet when
1195 * we checked for a duplicate name above.
1197 new_type_addr = AddNewRelationType(relname,
1204 new_type_oid = new_type_addr.objectId;
1206 *typaddress = new_type_addr;
1209 * Now make the array type if wanted.
1211 if (OidIsValid(new_array_oid))
1215 relarrayname = makeArrayTypeName(relname, relnamespace);
1217 TypeCreate(new_array_oid, /* force the type's OID to this */
1218 relarrayname, /* Array type name */
1219 relnamespace, /* Same namespace as parent */
1220 InvalidOid, /* Not composite, no relationOid */
1221 0, /* relkind, also N/A here */
1222 ownerid, /* owner's ID */
1223 -1, /* Internal size (varlena) */
1224 TYPTYPE_BASE, /* Not composite - typelem is */
1225 TYPCATEGORY_ARRAY, /* type-category (array) */
1226 false, /* array types are never preferred */
1227 DEFAULT_TYPDELIM, /* default array delimiter */
1228 F_ARRAY_IN, /* array input proc */
1229 F_ARRAY_OUT, /* array output proc */
1230 F_ARRAY_RECV, /* array recv (bin) proc */
1231 F_ARRAY_SEND, /* array send (bin) proc */
1232 InvalidOid, /* typmodin procedure - none */
1233 InvalidOid, /* typmodout procedure - none */
1234 F_ARRAY_TYPANALYZE, /* array analyze procedure */
1235 new_type_oid, /* array element type - the rowtype */
1236 true, /* yes, this is an array type */
1237 InvalidOid, /* this has no array type */
1238 InvalidOid, /* domain base type - irrelevant */
1239 NULL, /* default value - none */
1240 NULL, /* default binary representation */
1241 false, /* passed by reference */
1242 'd', /* alignment - must be the largest! */
1243 'x', /* fully TOASTable */
1245 0, /* array dimensions for typBaseType */
1246 false, /* Type NOT NULL */
1247 InvalidOid); /* rowtypes never have a collation */
1249 pfree(relarrayname);
1253 * now create an entry in pg_class for the relation.
1255 * NOTE: we could get a unique-index failure here, in case someone else is
1256 * creating the same relation name in parallel but hadn't committed yet
1257 * when we checked for a duplicate name above.
1259 AddNewRelationTuple(pg_class_desc,
1266 PointerGetDatum(relacl),
1270 * now add tuples to pg_attribute for the attributes in our new relation.
1272 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1273 oidislocal, oidinhcount);
1276 * Make a dependency link to force the relation to be deleted if its
1277 * namespace is. Also make a dependency link to its owner, as well as
1278 * dependencies for any roles mentioned in the default ACL.
1280 * For composite types, these dependencies are tracked for the pg_type
1281 * entry, so we needn't record them here. Likewise, TOAST tables don't
1282 * need a namespace dependency (they live in a pinned namespace) nor an
1283 * owner dependency (they depend indirectly through the parent table), nor
1284 * should they have any ACL entries. The same applies for extension
1287 * If it's a temp table, we do not make it an extension member; this
1288 * prevents the unintuitive result that deletion of the temp table at
1289 * session end would make the whole extension go away.
1291 * Also, skip this in bootstrap mode, since we don't make dependencies
1292 * while bootstrapping.
1294 if (relkind != RELKIND_COMPOSITE_TYPE &&
1295 relkind != RELKIND_TOASTVALUE &&
1296 !IsBootstrapProcessingMode())
1298 ObjectAddress myself,
1301 myself.classId = RelationRelationId;
1302 myself.objectId = relid;
1303 myself.objectSubId = 0;
1304 referenced.classId = NamespaceRelationId;
1305 referenced.objectId = relnamespace;
1306 referenced.objectSubId = 0;
1307 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1309 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1311 if (relpersistence != RELPERSISTENCE_TEMP)
1312 recordDependencyOnCurrentExtension(&myself, false);
1316 referenced.classId = TypeRelationId;
1317 referenced.objectId = reloftypeid;
1318 referenced.objectSubId = 0;
1319 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1327 nnewmembers = aclmembers(relacl, &newmembers);
1328 updateAclDependencies(RelationRelationId, relid, 0,
1331 nnewmembers, newmembers);
1335 /* Post creation hook for new relation */
1336 InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
1339 * Store any supplied constraints and defaults.
1341 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1342 * entry, so the relation must be valid and self-consistent at this point.
1343 * In particular, there are not yet constraints and defaults anywhere.
1345 StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
1348 * If there's a special on-commit action, remember it
1350 if (oncommit != ONCOMMIT_NOOP)
1351 register_on_commit_action(relid, oncommit);
1353 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1355 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW ||
1356 relkind == RELKIND_TOASTVALUE);
1357 heap_create_init_fork(new_rel_desc);
1361 * ok, the relation has been cataloged, so close our relations and return
1362 * the OID of the newly created relation.
1364 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1365 heap_close(pg_class_desc, RowExclusiveLock);
1371 * Set up an init fork for an unlogged table so that it can be correctly
1372 * reinitialized on restart. Since we're going to do an immediate sync, we
1373 * only need to xlog this if archiving or streaming is enabled. And the
1374 * immediate sync is required, because otherwise there's no guarantee that
1375 * this will hit the disk before the next checkpoint moves the redo pointer.
1378 heap_create_init_fork(Relation rel)
1380 RelationOpenSmgr(rel);
1381 smgrcreate(rel->rd_smgr, INIT_FORKNUM, false);
1383 log_smgrcreate(&rel->rd_smgr->smgr_rnode.node, INIT_FORKNUM);
1384 smgrimmedsync(rel->rd_smgr, INIT_FORKNUM);
1388 * RelationRemoveInheritance
1390 * Formerly, this routine checked for child relations and aborted the
1391 * deletion if any were found. Now we rely on the dependency mechanism
1392 * to check for or delete child relations. By the time we get here,
1393 * there are no children and we need only remove any pg_inherits rows
1394 * linking this relation to its parent(s).
1397 RelationRemoveInheritance(Oid relid)
1399 Relation catalogRelation;
1404 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1407 Anum_pg_inherits_inhrelid,
1408 BTEqualStrategyNumber, F_OIDEQ,
1409 ObjectIdGetDatum(relid));
1411 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1414 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1415 simple_heap_delete(catalogRelation, &tuple->t_self);
1417 systable_endscan(scan);
1418 heap_close(catalogRelation, RowExclusiveLock);
1422 * DeleteRelationTuple
1424 * Remove pg_class row for the given relid.
1426 * Note: this is shared by relation deletion and index deletion. It's
1427 * not intended for use anyplace else.
1430 DeleteRelationTuple(Oid relid)
1432 Relation pg_class_desc;
1435 /* Grab an appropriate lock on the pg_class relation */
1436 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1438 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1439 if (!HeapTupleIsValid(tup))
1440 elog(ERROR, "cache lookup failed for relation %u", relid);
1442 /* delete the relation tuple from pg_class, and finish up */
1443 simple_heap_delete(pg_class_desc, &tup->t_self);
1445 ReleaseSysCache(tup);
1447 heap_close(pg_class_desc, RowExclusiveLock);
1451 * DeleteAttributeTuples
1453 * Remove pg_attribute rows for the given relid.
1455 * Note: this is shared by relation deletion and index deletion. It's
1456 * not intended for use anyplace else.
1459 DeleteAttributeTuples(Oid relid)
1466 /* Grab an appropriate lock on the pg_attribute relation */
1467 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1469 /* Use the index to scan only attributes of the target relation */
1470 ScanKeyInit(&key[0],
1471 Anum_pg_attribute_attrelid,
1472 BTEqualStrategyNumber, F_OIDEQ,
1473 ObjectIdGetDatum(relid));
1475 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1478 /* Delete all the matching tuples */
1479 while ((atttup = systable_getnext(scan)) != NULL)
1480 simple_heap_delete(attrel, &atttup->t_self);
1482 /* Clean up after the scan */
1483 systable_endscan(scan);
1484 heap_close(attrel, RowExclusiveLock);
1488 * DeleteSystemAttributeTuples
1490 * Remove pg_attribute rows for system columns of the given relid.
1492 * Note: this is only used when converting a table to a view. Views don't
1493 * have system columns, so we should remove them from pg_attribute.
1496 DeleteSystemAttributeTuples(Oid relid)
1503 /* Grab an appropriate lock on the pg_attribute relation */
1504 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1506 /* Use the index to scan only system attributes of the target relation */
1507 ScanKeyInit(&key[0],
1508 Anum_pg_attribute_attrelid,
1509 BTEqualStrategyNumber, F_OIDEQ,
1510 ObjectIdGetDatum(relid));
1511 ScanKeyInit(&key[1],
1512 Anum_pg_attribute_attnum,
1513 BTLessEqualStrategyNumber, F_INT2LE,
1516 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1519 /* Delete all the matching tuples */
1520 while ((atttup = systable_getnext(scan)) != NULL)
1521 simple_heap_delete(attrel, &atttup->t_self);
1523 /* Clean up after the scan */
1524 systable_endscan(scan);
1525 heap_close(attrel, RowExclusiveLock);
1529 * RemoveAttributeById
1531 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1532 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1533 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1534 * is handled by dependency.c.)
1537 RemoveAttributeById(Oid relid, AttrNumber attnum)
1542 Form_pg_attribute attStruct;
1543 char newattname[NAMEDATALEN];
1546 * Grab an exclusive lock on the target table, which we will NOT release
1547 * until end of transaction. (In the simple case where we are directly
1548 * dropping this column, AlterTableDropColumn already did this ... but
1549 * when cascading from a drop of some other object, we may not have any
1552 rel = relation_open(relid, AccessExclusiveLock);
1554 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1556 tuple = SearchSysCacheCopy2(ATTNUM,
1557 ObjectIdGetDatum(relid),
1558 Int16GetDatum(attnum));
1559 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1560 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1562 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1566 /* System attribute (probably OID) ... just delete the row */
1568 simple_heap_delete(attr_rel, &tuple->t_self);
1572 /* Dropping user attributes is lots harder */
1574 /* Mark the attribute as dropped */
1575 attStruct->attisdropped = true;
1578 * Set the type OID to invalid. A dropped attribute's type link
1579 * cannot be relied on (once the attribute is dropped, the type might
1580 * be too). Fortunately we do not need the type row --- the only
1581 * really essential information is the type's typlen and typalign,
1582 * which are preserved in the attribute's attlen and attalign. We set
1583 * atttypid to zero here as a means of catching code that incorrectly
1584 * expects it to be valid.
1586 attStruct->atttypid = InvalidOid;
1588 /* Remove any NOT NULL constraint the column may have */
1589 attStruct->attnotnull = false;
1591 /* We don't want to keep stats for it anymore */
1592 attStruct->attstattarget = 0;
1595 * Change the column name to something that isn't likely to conflict
1597 snprintf(newattname, sizeof(newattname),
1598 "........pg.dropped.%d........", attnum);
1599 namestrcpy(&(attStruct->attname), newattname);
1601 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1603 /* keep the system catalog indexes current */
1604 CatalogUpdateIndexes(attr_rel, tuple);
1608 * Because updating the pg_attribute row will trigger a relcache flush for
1609 * the target relation, we need not do anything else to notify other
1610 * backends of the change.
1613 heap_close(attr_rel, RowExclusiveLock);
1616 RemoveStatistics(relid, attnum);
1618 relation_close(rel, NoLock);
1624 * If the specified relation/attribute has a default, remove it.
1625 * (If no default, raise error if complain is true, else return quietly.)
1628 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1629 DropBehavior behavior, bool complain, bool internal)
1631 Relation attrdef_rel;
1632 ScanKeyData scankeys[2];
1637 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1639 ScanKeyInit(&scankeys[0],
1640 Anum_pg_attrdef_adrelid,
1641 BTEqualStrategyNumber, F_OIDEQ,
1642 ObjectIdGetDatum(relid));
1643 ScanKeyInit(&scankeys[1],
1644 Anum_pg_attrdef_adnum,
1645 BTEqualStrategyNumber, F_INT2EQ,
1646 Int16GetDatum(attnum));
1648 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1651 /* There should be at most one matching tuple, but we loop anyway */
1652 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1654 ObjectAddress object;
1656 object.classId = AttrDefaultRelationId;
1657 object.objectId = HeapTupleGetOid(tuple);
1658 object.objectSubId = 0;
1660 performDeletion(&object, behavior,
1661 internal ? PERFORM_DELETION_INTERNAL : 0);
1666 systable_endscan(scan);
1667 heap_close(attrdef_rel, RowExclusiveLock);
1669 if (complain && !found)
1670 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1675 * RemoveAttrDefaultById
1677 * Remove a pg_attrdef entry specified by OID. This is the guts of
1678 * attribute-default removal. Note it should be called via performDeletion,
1682 RemoveAttrDefaultById(Oid attrdefId)
1684 Relation attrdef_rel;
1687 ScanKeyData scankeys[1];
1691 AttrNumber myattnum;
1693 /* Grab an appropriate lock on the pg_attrdef relation */
1694 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1696 /* Find the pg_attrdef tuple */
1697 ScanKeyInit(&scankeys[0],
1698 ObjectIdAttributeNumber,
1699 BTEqualStrategyNumber, F_OIDEQ,
1700 ObjectIdGetDatum(attrdefId));
1702 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1705 tuple = systable_getnext(scan);
1706 if (!HeapTupleIsValid(tuple))
1707 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1709 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1710 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1712 /* Get an exclusive lock on the relation owning the attribute */
1713 myrel = relation_open(myrelid, AccessExclusiveLock);
1715 /* Now we can delete the pg_attrdef row */
1716 simple_heap_delete(attrdef_rel, &tuple->t_self);
1718 systable_endscan(scan);
1719 heap_close(attrdef_rel, RowExclusiveLock);
1721 /* Fix the pg_attribute row */
1722 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1724 tuple = SearchSysCacheCopy2(ATTNUM,
1725 ObjectIdGetDatum(myrelid),
1726 Int16GetDatum(myattnum));
1727 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1728 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1731 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1733 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1735 /* keep the system catalog indexes current */
1736 CatalogUpdateIndexes(attr_rel, tuple);
1739 * Our update of the pg_attribute row will force a relcache rebuild, so
1740 * there's nothing else to do here.
1742 heap_close(attr_rel, RowExclusiveLock);
1744 /* Keep lock on attribute's rel until end of xact */
1745 relation_close(myrel, NoLock);
1749 * heap_drop_with_catalog - removes specified relation from catalogs
1751 * Note that this routine is not responsible for dropping objects that are
1752 * linked to the pg_class entry via dependencies (for example, indexes and
1753 * constraints). Those are deleted by the dependency-tracing logic in
1754 * dependency.c before control gets here. In general, therefore, this routine
1755 * should never be called directly; go through performDeletion() instead.
1758 heap_drop_with_catalog(Oid relid)
1763 * Open and lock the relation.
1765 rel = relation_open(relid, AccessExclusiveLock);
1768 * There can no longer be anyone *else* touching the relation, but we
1769 * might still have open queries or cursors, or pending trigger events, in
1772 CheckTableNotInUse(rel, "DROP TABLE");
1775 * This effectively deletes all rows in the table, and may be done in a
1776 * serializable transaction. In that case we must record a rw-conflict in
1777 * to this transaction from each transaction holding a predicate lock on
1780 CheckTableForSerializableConflictIn(rel);
1783 * Delete pg_foreign_table tuple first.
1785 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1790 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1792 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1793 if (!HeapTupleIsValid(tuple))
1794 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1796 simple_heap_delete(rel, &tuple->t_self);
1798 ReleaseSysCache(tuple);
1799 heap_close(rel, RowExclusiveLock);
1803 * Schedule unlinking of the relation's physical files at commit.
1805 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1806 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1807 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1809 RelationDropStorage(rel);
1813 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1814 * until transaction commit. This ensures no one else will try to do
1815 * something with the doomed relation.
1817 relation_close(rel, NoLock);
1820 * Forget any ON COMMIT action for the rel
1822 remove_on_commit_action(relid);
1825 * Flush the relation from the relcache. We want to do this before
1826 * starting to remove catalog entries, just to be certain that no relcache
1827 * entry rebuild will happen partway through. (That should not really
1828 * matter, since we don't do CommandCounterIncrement here, but let's be
1831 RelationForgetRelation(relid);
1834 * remove inheritance information
1836 RelationRemoveInheritance(relid);
1841 RemoveStatistics(relid, 0);
1844 * delete attribute tuples
1846 DeleteAttributeTuples(relid);
1849 * delete relation tuple
1851 DeleteRelationTuple(relid);
1856 * Store a default expression for column attnum of relation rel.
1858 * Returns the OID of the new pg_attrdef tuple.
1861 StoreAttrDefault(Relation rel, AttrNumber attnum,
1862 Node *expr, bool is_internal)
1869 static bool nulls[4] = {false, false, false, false};
1872 Form_pg_attribute attStruct;
1874 ObjectAddress colobject,
1878 * Flatten expression to string form for storage.
1880 adbin = nodeToString(expr);
1883 * Also deparse it to form the mostly-obsolete adsrc field.
1885 adsrc = deparse_expression(expr,
1886 deparse_context_for(RelationGetRelationName(rel),
1887 RelationGetRelid(rel)),
1891 * Make the pg_attrdef entry.
1893 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1894 values[Anum_pg_attrdef_adnum - 1] = attnum;
1895 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1896 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1898 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1900 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1901 attrdefOid = simple_heap_insert(adrel, tuple);
1903 CatalogUpdateIndexes(adrel, tuple);
1905 defobject.classId = AttrDefaultRelationId;
1906 defobject.objectId = attrdefOid;
1907 defobject.objectSubId = 0;
1909 heap_close(adrel, RowExclusiveLock);
1911 /* now can free some of the stuff allocated above */
1912 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1913 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1914 heap_freetuple(tuple);
1919 * Update the pg_attribute entry for the column to show that a default
1922 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1923 atttup = SearchSysCacheCopy2(ATTNUM,
1924 ObjectIdGetDatum(RelationGetRelid(rel)),
1925 Int16GetDatum(attnum));
1926 if (!HeapTupleIsValid(atttup))
1927 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1928 attnum, RelationGetRelid(rel));
1929 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1930 if (!attStruct->atthasdef)
1932 attStruct->atthasdef = true;
1933 simple_heap_update(attrrel, &atttup->t_self, atttup);
1934 /* keep catalog indexes current */
1935 CatalogUpdateIndexes(attrrel, atttup);
1937 heap_close(attrrel, RowExclusiveLock);
1938 heap_freetuple(atttup);
1941 * Make a dependency so that the pg_attrdef entry goes away if the column
1942 * (or whole table) is deleted.
1944 colobject.classId = RelationRelationId;
1945 colobject.objectId = RelationGetRelid(rel);
1946 colobject.objectSubId = attnum;
1948 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1951 * Record dependencies on objects used in the expression, too.
1953 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1956 * Post creation hook for attribute defaults.
1958 * XXX. ALTER TABLE ALTER COLUMN SET/DROP DEFAULT is implemented with a
1959 * couple of deletion/creation of the attribute's default entry, so the
1960 * callee should check existence of an older version of this entry if it
1961 * needs to distinguish.
1963 InvokeObjectPostCreateHookArg(AttrDefaultRelationId,
1964 RelationGetRelid(rel), attnum, is_internal);
1970 * Store a check-constraint expression for the given relation.
1972 * Caller is responsible for updating the count of constraints
1973 * in the pg_class entry for the relation.
1975 * The OID of the new constraint is returned.
1978 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1979 bool is_validated, bool is_local, int inhcount,
1980 bool is_no_inherit, bool is_internal)
1990 * Flatten expression to string form for storage.
1992 ccbin = nodeToString(expr);
1995 * Also deparse it to form the mostly-obsolete consrc field.
1997 ccsrc = deparse_expression(expr,
1998 deparse_context_for(RelationGetRelationName(rel),
1999 RelationGetRelid(rel)),
2003 * Find columns of rel that are used in expr
2005 * NB: pull_var_clause is okay here only because we don't allow subselects
2006 * in check constraints; it would fail to examine the contents of
2009 varList = pull_var_clause(expr, 0);
2010 keycount = list_length(varList);
2017 attNos = (int16 *) palloc(keycount * sizeof(int16));
2018 foreach(vl, varList)
2020 Var *var = (Var *) lfirst(vl);
2023 for (j = 0; j < i; j++)
2024 if (attNos[j] == var->varattno)
2027 attNos[i++] = var->varattno;
2035 * Create the Check Constraint
2038 CreateConstraintEntry(ccname, /* Constraint Name */
2039 RelationGetNamespace(rel), /* namespace */
2040 CONSTRAINT_CHECK, /* Constraint Type */
2041 false, /* Is Deferrable */
2042 false, /* Is Deferred */
2044 RelationGetRelid(rel), /* relation */
2045 attNos, /* attrs in the constraint */
2046 keycount, /* # attrs in the constraint */
2047 InvalidOid, /* not a domain constraint */
2048 InvalidOid, /* no associated index */
2049 InvalidOid, /* Foreign key fields */
2058 NULL, /* not an exclusion constraint */
2059 expr, /* Tree form of check constraint */
2060 ccbin, /* Binary form of check constraint */
2061 ccsrc, /* Source form of check constraint */
2062 is_local, /* conislocal */
2063 inhcount, /* coninhcount */
2064 is_no_inherit, /* connoinherit */
2065 is_internal); /* internally constructed? */
2074 * Store defaults and constraints (passed as a list of CookedConstraint).
2076 * Each CookedConstraint struct is modified to store the new catalog tuple OID.
2078 * NOTE: only pre-cooked expressions will be passed this way, which is to
2079 * say expressions inherited from an existing relation. Newly parsed
2080 * expressions can be added later, by direct calls to StoreAttrDefault
2081 * and StoreRelCheck (see AddRelationNewConstraints()).
2084 StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
2089 if (cooked_constraints == NIL)
2090 return; /* nothing to do */
2093 * Deparsing of constraint expressions will fail unless the just-created
2094 * pg_attribute tuples for this relation are made visible. So, bump the
2095 * command counter. CAUTION: this will cause a relcache entry rebuild.
2097 CommandCounterIncrement();
2099 foreach(lc, cooked_constraints)
2101 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
2103 switch (con->contype)
2105 case CONSTR_DEFAULT:
2106 con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
2111 StoreRelCheck(rel, con->name, con->expr,
2112 !con->skip_validation, con->is_local,
2113 con->inhcount, con->is_no_inherit,
2118 elog(ERROR, "unrecognized constraint type: %d",
2119 (int) con->contype);
2124 SetRelationNumChecks(rel, numchecks);
2128 * AddRelationNewConstraints
2130 * Add new column default expressions and/or constraint check expressions
2131 * to an existing relation. This is defined to do both for efficiency in
2132 * DefineRelation, but of course you can do just one or the other by passing
2135 * rel: relation to be modified
2136 * newColDefaults: list of RawColumnDefault structures
2137 * newConstraints: list of Constraint nodes
2138 * allow_merge: TRUE if check constraints may be merged with existing ones
2139 * is_local: TRUE if definition is local, FALSE if it's inherited
2140 * is_internal: TRUE if result of some internal process, not a user request
2142 * All entries in newColDefaults will be processed. Entries in newConstraints
2143 * will be processed only if they are CONSTR_CHECK type.
2145 * Returns a list of CookedConstraint nodes that shows the cooked form of
2146 * the default and constraint expressions added to the relation.
2148 * NB: caller should have opened rel with AccessExclusiveLock, and should
2149 * hold that lock till end of transaction. Also, we assume the caller has
2150 * done a CommandCounterIncrement if necessary to make the relation's catalog
2154 AddRelationNewConstraints(Relation rel,
2155 List *newColDefaults,
2156 List *newConstraints,
2161 List *cookedConstraints = NIL;
2162 TupleDesc tupleDesc;
2163 TupleConstr *oldconstr;
2171 CookedConstraint *cooked;
2174 * Get info about existing constraints.
2176 tupleDesc = RelationGetDescr(rel);
2177 oldconstr = tupleDesc->constr;
2179 numoldchecks = oldconstr->num_check;
2184 * Create a dummy ParseState and insert the target relation as its sole
2185 * rangetable entry. We need a ParseState for transformExpr.
2187 pstate = make_parsestate(NULL);
2188 rte = addRangeTableEntryForRelation(pstate,
2193 addRTEtoQuery(pstate, rte, true, true, true);
2196 * Process column default expressions.
2198 foreach(cell, newColDefaults)
2200 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
2201 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
2204 expr = cookDefault(pstate, colDef->raw_default,
2205 atp->atttypid, atp->atttypmod,
2206 NameStr(atp->attname));
2209 * If the expression is just a NULL constant, we do not bother to make
2210 * an explicit pg_attrdef entry, since the default behavior is
2213 * Note a nonobvious property of this test: if the column is of a
2214 * domain type, what we'll get is not a bare null Const but a
2215 * CoerceToDomain expr, so we will not discard the default. This is
2216 * critical because the column default needs to be retained to
2217 * override any default that the domain might have.
2220 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2223 defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
2225 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2226 cooked->contype = CONSTR_DEFAULT;
2227 cooked->conoid = defOid;
2228 cooked->name = NULL;
2229 cooked->attnum = colDef->attnum;
2230 cooked->expr = expr;
2231 cooked->skip_validation = false;
2232 cooked->is_local = is_local;
2233 cooked->inhcount = is_local ? 0 : 1;
2234 cooked->is_no_inherit = false;
2235 cookedConstraints = lappend(cookedConstraints, cooked);
2239 * Process constraint expressions.
2241 numchecks = numoldchecks;
2243 foreach(cell, newConstraints)
2245 Constraint *cdef = (Constraint *) lfirst(cell);
2249 if (cdef->contype != CONSTR_CHECK)
2252 if (cdef->raw_expr != NULL)
2254 Assert(cdef->cooked_expr == NULL);
2257 * Transform raw parsetree to executable expression, and verify
2258 * it's valid as a CHECK constraint.
2260 expr = cookConstraint(pstate, cdef->raw_expr,
2261 RelationGetRelationName(rel));
2265 Assert(cdef->cooked_expr != NULL);
2268 * Here, we assume the parser will only pass us valid CHECK
2269 * expressions, so we do no particular checking.
2271 expr = stringToNode(cdef->cooked_expr);
2275 * Check name uniqueness, or generate a name if none was given.
2277 if (cdef->conname != NULL)
2281 ccname = cdef->conname;
2282 /* Check against other new constraints */
2283 /* Needed because we don't do CommandCounterIncrement in loop */
2284 foreach(cell2, checknames)
2286 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2288 (errcode(ERRCODE_DUPLICATE_OBJECT),
2289 errmsg("check constraint \"%s\" already exists",
2293 /* save name for future checks */
2294 checknames = lappend(checknames, ccname);
2297 * Check against pre-existing constraints. If we are allowed to
2298 * merge with an existing constraint, there's no more to do here.
2299 * (We omit the duplicate constraint from the result, which is
2300 * what ATAddCheckConstraint wants.)
2302 if (MergeWithExistingConstraint(rel, ccname, expr,
2303 allow_merge, is_local,
2304 cdef->is_no_inherit))
2310 * When generating a name, we want to create "tab_col_check" for a
2311 * column constraint and "tab_check" for a table constraint. We
2312 * no longer have any info about the syntactic positioning of the
2313 * constraint phrase, so we approximate this by seeing whether the
2314 * expression references more than one column. (If the user
2315 * played by the rules, the result is the same...)
2317 * Note: pull_var_clause() doesn't descend into sublinks, but we
2318 * eliminated those above; and anyway this only needs to be an
2319 * approximate answer.
2324 vars = pull_var_clause(expr, 0);
2326 /* eliminate duplicates */
2327 vars = list_union(NIL, vars);
2329 if (list_length(vars) == 1)
2330 colname = get_attname(RelationGetRelid(rel),
2331 ((Var *) linitial(vars))->varattno);
2335 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2338 RelationGetNamespace(rel),
2341 /* save name for future checks */
2342 checknames = lappend(checknames, ccname);
2349 StoreRelCheck(rel, ccname, expr, cdef->initially_valid, is_local,
2350 is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
2354 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2355 cooked->contype = CONSTR_CHECK;
2356 cooked->conoid = constrOid;
2357 cooked->name = ccname;
2359 cooked->expr = expr;
2360 cooked->skip_validation = cdef->skip_validation;
2361 cooked->is_local = is_local;
2362 cooked->inhcount = is_local ? 0 : 1;
2363 cooked->is_no_inherit = cdef->is_no_inherit;
2364 cookedConstraints = lappend(cookedConstraints, cooked);
2368 * Update the count of constraints in the relation's pg_class tuple. We do
2369 * this even if there was no change, in order to ensure that an SI update
2370 * message is sent out for the pg_class tuple, which will force other
2371 * backends to rebuild their relcache entries for the rel. (This is
2372 * critical if we added defaults but not constraints.)
2374 SetRelationNumChecks(rel, numchecks);
2376 return cookedConstraints;
2380 * Check for a pre-existing check constraint that conflicts with a proposed
2381 * new one, and either adjust its conislocal/coninhcount settings or throw
2384 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2385 * got a so-far-unique name, or throws error if conflict.
2387 * XXX See MergeConstraintsIntoExisting too if you change this code.
2390 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2391 bool allow_merge, bool is_local,
2396 SysScanDesc conscan;
2397 ScanKeyData skey[2];
2400 /* Search for a pg_constraint entry with same name and relation */
2401 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2405 ScanKeyInit(&skey[0],
2406 Anum_pg_constraint_conname,
2407 BTEqualStrategyNumber, F_NAMEEQ,
2408 CStringGetDatum(ccname));
2410 ScanKeyInit(&skey[1],
2411 Anum_pg_constraint_connamespace,
2412 BTEqualStrategyNumber, F_OIDEQ,
2413 ObjectIdGetDatum(RelationGetNamespace(rel)));
2415 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2418 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2420 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2422 if (con->conrelid == RelationGetRelid(rel))
2424 /* Found it. Conflicts if not identical check constraint */
2425 if (con->contype == CONSTRAINT_CHECK)
2430 val = fastgetattr(tup,
2431 Anum_pg_constraint_conbin,
2432 conDesc->rd_att, &isnull);
2434 elog(ERROR, "null conbin for rel %s",
2435 RelationGetRelationName(rel));
2436 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2439 if (!found || !allow_merge)
2441 (errcode(ERRCODE_DUPLICATE_OBJECT),
2442 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2443 ccname, RelationGetRelationName(rel))));
2445 tup = heap_copytuple(tup);
2446 con = (Form_pg_constraint) GETSTRUCT(tup);
2448 /* If the constraint is "no inherit" then cannot merge */
2449 if (con->connoinherit)
2451 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2452 errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
2453 ccname, RelationGetRelationName(rel))));
2456 con->conislocal = true;
2462 con->connoinherit = true;
2464 /* OK to update the tuple */
2466 (errmsg("merging constraint \"%s\" with inherited definition",
2468 simple_heap_update(conDesc, &tup->t_self, tup);
2469 CatalogUpdateIndexes(conDesc, tup);
2474 systable_endscan(conscan);
2475 heap_close(conDesc, RowExclusiveLock);
2481 * Update the count of constraints in the relation's pg_class tuple.
2483 * Caller had better hold exclusive lock on the relation.
2485 * An important side effect is that a SI update message will be sent out for
2486 * the pg_class tuple, which will force other backends to rebuild their
2487 * relcache entries for the rel. Also, this backend will rebuild its
2488 * own relcache entry at the next CommandCounterIncrement.
2491 SetRelationNumChecks(Relation rel, int numchecks)
2495 Form_pg_class relStruct;
2497 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2498 reltup = SearchSysCacheCopy1(RELOID,
2499 ObjectIdGetDatum(RelationGetRelid(rel)));
2500 if (!HeapTupleIsValid(reltup))
2501 elog(ERROR, "cache lookup failed for relation %u",
2502 RelationGetRelid(rel));
2503 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2505 if (relStruct->relchecks != numchecks)
2507 relStruct->relchecks = numchecks;
2509 simple_heap_update(relrel, &reltup->t_self, reltup);
2511 /* keep catalog indexes current */
2512 CatalogUpdateIndexes(relrel, reltup);
2516 /* Skip the disk update, but force relcache inval anyway */
2517 CacheInvalidateRelcache(rel);
2520 heap_freetuple(reltup);
2521 heap_close(relrel, RowExclusiveLock);
2525 * Take a raw default and convert it to a cooked format ready for
2528 * Parse state should be set up to recognize any vars that might appear
2529 * in the expression. (Even though we plan to reject vars, it's more
2530 * user-friendly to give the correct error message than "unknown var".)
2532 * If atttypid is not InvalidOid, coerce the expression to the specified
2533 * type (and typmod atttypmod). attname is only needed in this case:
2534 * it is used in the error message, if any.
2537 cookDefault(ParseState *pstate,
2545 Assert(raw_default != NULL);
2548 * Transform raw parsetree to executable expression.
2550 expr = transformExpr(pstate, raw_default, EXPR_KIND_COLUMN_DEFAULT);
2553 * Make sure default expr does not refer to any vars (we need this check
2554 * since the pstate includes the target table).
2556 if (contain_var_clause(expr))
2558 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2559 errmsg("cannot use column references in default expression")));
2562 * transformExpr() should have already rejected subqueries, aggregates,
2563 * and window functions, based on the EXPR_KIND_ for a default expression.
2565 * It can't return a set either.
2567 if (expression_returns_set(expr))
2569 (errcode(ERRCODE_DATATYPE_MISMATCH),
2570 errmsg("default expression must not return a set")));
2573 * Coerce the expression to the correct type and typmod, if given. This
2574 * should match the parser's processing of non-defaulted expressions ---
2575 * see transformAssignedExpr().
2577 if (OidIsValid(atttypid))
2579 Oid type_id = exprType(expr);
2581 expr = coerce_to_target_type(pstate, expr, type_id,
2582 atttypid, atttypmod,
2583 COERCION_ASSIGNMENT,
2584 COERCE_IMPLICIT_CAST,
2588 (errcode(ERRCODE_DATATYPE_MISMATCH),
2589 errmsg("column \"%s\" is of type %s"
2590 " but default expression is of type %s",
2592 format_type_be(atttypid),
2593 format_type_be(type_id)),
2594 errhint("You will need to rewrite or cast the expression.")));
2598 * Finally, take care of collations in the finished expression.
2600 assign_expr_collations(pstate, expr);
2606 * Take a raw CHECK constraint expression and convert it to a cooked format
2607 * ready for storage.
2609 * Parse state must be set up to recognize any vars that might appear
2610 * in the expression.
2613 cookConstraint(ParseState *pstate,
2614 Node *raw_constraint,
2620 * Transform raw parsetree to executable expression.
2622 expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
2625 * Make sure it yields a boolean result.
2627 expr = coerce_to_boolean(pstate, expr, "CHECK");
2630 * Take care of collations.
2632 assign_expr_collations(pstate, expr);
2635 * Make sure no outside relations are referred to (this is probably dead
2636 * code now that add_missing_from is history).
2638 if (list_length(pstate->p_rtable) != 1)
2640 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2641 errmsg("only table \"%s\" can be referenced in check constraint",
2649 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2651 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2655 RemoveStatistics(Oid relid, AttrNumber attnum)
2657 Relation pgstatistic;
2663 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2665 ScanKeyInit(&key[0],
2666 Anum_pg_statistic_starelid,
2667 BTEqualStrategyNumber, F_OIDEQ,
2668 ObjectIdGetDatum(relid));
2674 ScanKeyInit(&key[1],
2675 Anum_pg_statistic_staattnum,
2676 BTEqualStrategyNumber, F_INT2EQ,
2677 Int16GetDatum(attnum));
2681 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2684 /* we must loop even when attnum != 0, in case of inherited stats */
2685 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2686 simple_heap_delete(pgstatistic, &tuple->t_self);
2688 systable_endscan(scan);
2690 heap_close(pgstatistic, RowExclusiveLock);
2695 * RelationTruncateIndexes - truncate all indexes associated
2696 * with the heap relation to zero tuples.
2698 * The routine will truncate and then reconstruct the indexes on
2699 * the specified relation. Caller must hold exclusive lock on rel.
2702 RelationTruncateIndexes(Relation heapRelation)
2706 /* Ask the relcache to produce a list of the indexes of the rel */
2707 foreach(indlist, RelationGetIndexList(heapRelation))
2709 Oid indexId = lfirst_oid(indlist);
2710 Relation currentIndex;
2711 IndexInfo *indexInfo;
2713 /* Open the index relation; use exclusive lock, just to be sure */
2714 currentIndex = index_open(indexId, AccessExclusiveLock);
2716 /* Fetch info needed for index_build */
2717 indexInfo = BuildIndexInfo(currentIndex);
2720 * Now truncate the actual file (and discard buffers).
2722 RelationTruncate(currentIndex, 0);
2724 /* Initialize the index and rebuild */
2725 /* Note: we do not need to re-establish pkey setting */
2726 index_build(heapRelation, currentIndex, indexInfo, false, true);
2728 /* We're done with this index */
2729 index_close(currentIndex, NoLock);
2736 * This routine deletes all data within all the specified relations.
2738 * This is not transaction-safe! There is another, transaction-safe
2739 * implementation in commands/tablecmds.c. We now use this only for
2740 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2743 heap_truncate(List *relids)
2745 List *relations = NIL;
2748 /* Open relations for processing, and grab exclusive access on each */
2749 foreach(cell, relids)
2751 Oid rid = lfirst_oid(cell);
2754 rel = heap_open(rid, AccessExclusiveLock);
2755 relations = lappend(relations, rel);
2758 /* Don't allow truncate on tables that are referenced by foreign keys */
2759 heap_truncate_check_FKs(relations, true);
2762 foreach(cell, relations)
2764 Relation rel = lfirst(cell);
2766 /* Truncate the relation */
2767 heap_truncate_one_rel(rel);
2769 /* Close the relation, but keep exclusive lock on it until commit */
2770 heap_close(rel, NoLock);
2775 * heap_truncate_one_rel
2777 * This routine deletes all data within the specified relation.
2779 * This is not transaction-safe, because the truncation is done immediately
2780 * and cannot be rolled back later. Caller is responsible for having
2781 * checked permissions etc, and must have obtained AccessExclusiveLock.
2784 heap_truncate_one_rel(Relation rel)
2788 /* Truncate the actual file (and discard buffers) */
2789 RelationTruncate(rel, 0);
2791 /* If the relation has indexes, truncate the indexes too */
2792 RelationTruncateIndexes(rel);
2794 /* If there is a toast table, truncate that too */
2795 toastrelid = rel->rd_rel->reltoastrelid;
2796 if (OidIsValid(toastrelid))
2798 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2800 RelationTruncate(toastrel, 0);
2801 RelationTruncateIndexes(toastrel);
2802 /* keep the lock... */
2803 heap_close(toastrel, NoLock);
2808 * heap_truncate_check_FKs
2809 * Check for foreign keys referencing a list of relations that
2810 * are to be truncated, and raise error if there are any
2812 * We disallow such FKs (except self-referential ones) since the whole point
2813 * of TRUNCATE is to not scan the individual rows to be thrown away.
2815 * This is split out so it can be shared by both implementations of truncate.
2816 * Caller should already hold a suitable lock on the relations.
2818 * tempTables is only used to select an appropriate error message.
2821 heap_truncate_check_FKs(List *relations, bool tempTables)
2828 * Build a list of OIDs of the interesting relations.
2830 * If a relation has no triggers, then it can neither have FKs nor be
2831 * referenced by a FK from another table, so we can ignore it.
2833 foreach(cell, relations)
2835 Relation rel = lfirst(cell);
2837 if (rel->rd_rel->relhastriggers)
2838 oids = lappend_oid(oids, RelationGetRelid(rel));
2842 * Fast path: if no relation has triggers, none has FKs either.
2848 * Otherwise, must scan pg_constraint. We make one pass with all the
2849 * relations considered; if this finds nothing, then all is well.
2851 dependents = heap_truncate_find_FKs(oids);
2852 if (dependents == NIL)
2856 * Otherwise we repeat the scan once per relation to identify a particular
2857 * pair of relations to complain about. This is pretty slow, but
2858 * performance shouldn't matter much in a failure path. The reason for
2859 * doing things this way is to ensure that the message produced is not
2860 * dependent on chance row locations within pg_constraint.
2864 Oid relid = lfirst_oid(cell);
2867 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2869 foreach(cell2, dependents)
2871 Oid relid2 = lfirst_oid(cell2);
2873 if (!list_member_oid(oids, relid2))
2875 char *relname = get_rel_name(relid);
2876 char *relname2 = get_rel_name(relid2);
2880 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2881 errmsg("unsupported ON COMMIT and foreign key combination"),
2882 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2883 relname2, relname)));
2886 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2887 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2888 errdetail("Table \"%s\" references \"%s\".",
2890 errhint("Truncate table \"%s\" at the same time, "
2891 "or use TRUNCATE ... CASCADE.",
2899 * heap_truncate_find_FKs
2900 * Find relations having foreign keys referencing any of the given rels
2902 * Input and result are both lists of relation OIDs. The result contains
2903 * no duplicates, does *not* include any rels that were already in the input
2904 * list, and is sorted in OID order. (The last property is enforced mainly
2905 * to guarantee consistent behavior in the regression tests; we don't want
2906 * behavior to change depending on chance locations of rows in pg_constraint.)
2908 * Note: caller should already have appropriate lock on all rels mentioned
2909 * in relationIds. Since adding or dropping an FK requires exclusive lock
2910 * on both rels, this ensures that the answer will be stable.
2913 heap_truncate_find_FKs(List *relationIds)
2917 SysScanDesc fkeyScan;
2921 * Must scan pg_constraint. Right now, it is a seqscan because there is
2922 * no available index on confrelid.
2924 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2926 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2929 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2931 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2933 /* Not a foreign key */
2934 if (con->contype != CONSTRAINT_FOREIGN)
2937 /* Not referencing one of our list of tables */
2938 if (!list_member_oid(relationIds, con->confrelid))
2941 /* Add referencer unless already in input or result list */
2942 if (!list_member_oid(relationIds, con->conrelid))
2943 result = insert_ordered_unique_oid(result, con->conrelid);
2946 systable_endscan(fkeyScan);
2947 heap_close(fkeyRel, AccessShareLock);
2953 * insert_ordered_unique_oid
2954 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2955 * and eliminating duplicates
2957 * Building the ordered list this way is O(N^2), but with a pretty small
2958 * constant, so for the number of entries we expect it will probably be
2959 * faster than trying to apply qsort(). It seems unlikely someone would be
2960 * trying to truncate a table with thousands of dependent tables ...
2963 insert_ordered_unique_oid(List *list, Oid datum)
2967 /* Does the datum belong at the front? */
2968 if (list == NIL || datum < linitial_oid(list))
2969 return lcons_oid(datum, list);
2970 /* Does it match the first entry? */
2971 if (datum == linitial_oid(list))
2972 return list; /* duplicate, so don't insert */
2973 /* No, so find the entry it belongs after */
2974 prev = list_head(list);
2977 ListCell *curr = lnext(prev);
2979 if (curr == NULL || datum < lfirst_oid(curr))
2980 break; /* it belongs after 'prev', before 'curr' */
2982 if (datum == lfirst_oid(curr))
2983 return list; /* duplicate, so don't insert */
2987 /* Insert datum into list after 'prev' */
2988 lappend_cell_oid(list, prev, datum);