1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2011, 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/genam.h"
33 #include "access/heapam.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/indexing.h"
42 #include "catalog/namespace.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_foreign_table.h"
48 #include "catalog/pg_inherits.h"
49 #include "catalog/pg_namespace.h"
50 #include "catalog/pg_statistic.h"
51 #include "catalog/pg_tablespace.h"
52 #include "catalog/pg_type.h"
53 #include "catalog/pg_type_fn.h"
54 #include "catalog/storage.h"
55 #include "commands/tablecmds.h"
56 #include "commands/typecmds.h"
57 #include "miscadmin.h"
58 #include "nodes/nodeFuncs.h"
59 #include "optimizer/var.h"
60 #include "parser/parse_coerce.h"
61 #include "parser/parse_collate.h"
62 #include "parser/parse_expr.h"
63 #include "parser/parse_relation.h"
64 #include "storage/bufmgr.h"
65 #include "storage/freespace.h"
66 #include "storage/smgr.h"
67 #include "utils/acl.h"
68 #include "utils/builtins.h"
69 #include "utils/fmgroids.h"
70 #include "utils/inval.h"
71 #include "utils/lsyscache.h"
72 #include "utils/relcache.h"
73 #include "utils/snapmgr.h"
74 #include "utils/syscache.h"
75 #include "utils/tqual.h"
78 /* Potentially set by contrib/pg_upgrade_support functions */
79 Oid binary_upgrade_next_heap_pg_class_oid = InvalidOid;
80 Oid binary_upgrade_next_toast_pg_class_oid = InvalidOid;
82 static void AddNewRelationTuple(Relation pg_class_desc,
83 Relation new_rel_desc,
91 static Oid AddNewRelationType(const char *typeName,
98 static void RelationRemoveInheritance(Oid relid);
99 static void StoreRelCheck(Relation rel, char *ccname, Node *expr,
100 bool is_local, int inhcount);
101 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);
104 static void SetRelationNumChecks(Relation rel, int numchecks);
105 static Node *cookConstraint(ParseState *pstate,
106 Node *raw_constraint,
108 static List *insert_ordered_unique_oid(List *list, Oid datum);
111 /* ----------------------------------------------------------------
112 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
114 * these should all be moved to someplace in the lib/catalog
115 * module, if not obliterated first.
116 * ----------------------------------------------------------------
122 * Should the system special case these attributes in the future?
123 * Advantage: consume much less space in the ATTRIBUTE relation.
124 * Disadvantage: special cases will be all over the place.
128 * The initializers below do not include the attoptions or attacl fields,
129 * but that's OK - we're never going to reference anything beyond the
130 * fixed-size portion of the structure anyway.
133 static FormData_pg_attribute a1 = {
134 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
135 SelfItemPointerAttributeNumber, 0, -1, -1,
136 false, 'p', 's', true, false, false, true, 0
139 static FormData_pg_attribute a2 = {
140 0, {"oid"}, OIDOID, 0, sizeof(Oid),
141 ObjectIdAttributeNumber, 0, -1, -1,
142 true, 'p', 'i', true, false, false, true, 0
145 static FormData_pg_attribute a3 = {
146 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
147 MinTransactionIdAttributeNumber, 0, -1, -1,
148 true, 'p', 'i', true, false, false, true, 0
151 static FormData_pg_attribute a4 = {
152 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
153 MinCommandIdAttributeNumber, 0, -1, -1,
154 true, 'p', 'i', true, false, false, true, 0
157 static FormData_pg_attribute a5 = {
158 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
159 MaxTransactionIdAttributeNumber, 0, -1, -1,
160 true, 'p', 'i', true, false, false, true, 0
163 static FormData_pg_attribute a6 = {
164 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
165 MaxCommandIdAttributeNumber, 0, -1, -1,
166 true, 'p', 'i', true, false, false, true, 0
170 * We decided to call this attribute "tableoid" rather than say
171 * "classoid" on the basis that in the future there may be more than one
172 * table of a particular class/type. In any case table is still the word
175 static FormData_pg_attribute a7 = {
176 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
177 TableOidAttributeNumber, 0, -1, -1,
178 true, 'p', 'i', true, false, false, true, 0
181 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
184 * This function returns a Form_pg_attribute pointer for a system attribute.
185 * Note that we elog if the presented attno is invalid, which would only
186 * happen if there's a problem upstream.
189 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
191 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
192 elog(ERROR, "invalid system attribute number %d", attno);
193 if (attno == ObjectIdAttributeNumber && !relhasoids)
194 elog(ERROR, "invalid system attribute number %d", attno);
195 return SysAtt[-attno - 1];
199 * If the given name is a system attribute name, return a Form_pg_attribute
200 * pointer for a prototype definition. If not, return NULL.
203 SystemAttributeByName(const char *attname, bool relhasoids)
207 for (j = 0; j < (int) lengthof(SysAtt); j++)
209 Form_pg_attribute att = SysAtt[j];
211 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
213 if (strcmp(NameStr(att->attname), attname) == 0)
222 /* ----------------------------------------------------------------
223 * XXX END OF UGLY HARD CODED BADNESS XXX
224 * ---------------------------------------------------------------- */
227 /* ----------------------------------------------------------------
228 * heap_create - Create an uncataloged heap relation
230 * Note API change: the caller must now always provide the OID
231 * to use for the relation.
233 * rel->rd_rel is initialized by RelationBuildLocalRelation,
234 * and is mostly zeroes at return.
235 * ----------------------------------------------------------------
238 heap_create(const char *relname,
245 bool shared_relation,
246 bool mapped_relation,
247 bool allow_system_table_mods)
252 /* The caller must have provided an OID for the relation. */
253 Assert(OidIsValid(relid));
258 if (!allow_system_table_mods &&
259 (IsSystemNamespace(relnamespace) || IsToastNamespace(relnamespace)) &&
260 IsNormalProcessingMode())
262 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
263 errmsg("permission denied to create \"%s.%s\"",
264 get_namespace_name(relnamespace), relname),
265 errdetail("System catalog modifications are currently disallowed.")));
268 * Decide if we need storage or not, and handle a couple other special
269 * cases for particular relkinds.
274 case RELKIND_COMPOSITE_TYPE:
275 case RELKIND_FOREIGN_TABLE:
276 create_storage = false;
279 * Force reltablespace to zero if the relation has no physical
280 * storage. This is mainly just for cleanliness' sake.
282 reltablespace = InvalidOid;
284 case RELKIND_SEQUENCE:
285 create_storage = true;
288 * Force reltablespace to zero for sequences, since we don't
289 * support moving them around into different tablespaces.
291 reltablespace = InvalidOid;
294 create_storage = true;
299 * Never allow a pg_class entry to explicitly specify the database's
300 * default tablespace in reltablespace; force it to zero instead. This
301 * ensures that if the database is cloned with a different default
302 * tablespace, the pg_class entry will still match where CREATE DATABASE
303 * will put the physically copied relation.
305 * Yes, this is a bit of a hack.
307 if (reltablespace == MyDatabaseTableSpace)
308 reltablespace = InvalidOid;
311 * build the relcache entry.
313 rel = RelationBuildLocalRelation(relname,
323 * Have the storage manager create the relation's disk file, if needed.
325 * We only create the main fork here, other forks will be created on
330 RelationOpenSmgr(rel);
331 RelationCreateStorage(rel->rd_node, relpersistence);
337 /* ----------------------------------------------------------------
338 * heap_create_with_catalog - Create a cataloged relation
340 * this is done in multiple steps:
342 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
343 * descriptor contains a valid set of attribute names and types
345 * 2) pg_class is opened and get_relname_relid()
346 * performs a scan to ensure that no relation with the
347 * same name already exists.
349 * 3) heap_create() is called to create the new relation on disk.
351 * 4) TypeCreate() is called to define a new type corresponding
352 * to the new relation.
354 * 5) AddNewRelationTuple() is called to register the
355 * relation in pg_class.
357 * 6) AddNewAttributeTuples() is called to register the
358 * new relation's schema in pg_attribute.
360 * 7) StoreConstraints is called () - vadim 08/22/97
362 * 8) the relations are closed and the new relation's oid
365 * ----------------------------------------------------------------
368 /* --------------------------------
369 * CheckAttributeNamesTypes
371 * this is used to make certain the tuple descriptor contains a
372 * valid set of attribute names and datatypes. a problem simply
373 * generates ereport(ERROR) which aborts the current transaction.
374 * --------------------------------
377 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
378 bool allow_system_table_mods)
382 int natts = tupdesc->natts;
384 /* Sanity check on column count */
385 if (natts < 0 || natts > MaxHeapAttributeNumber)
387 (errcode(ERRCODE_TOO_MANY_COLUMNS),
388 errmsg("tables can have at most %d columns",
389 MaxHeapAttributeNumber)));
392 * first check for collision with system attribute names
394 * Skip this for a view or type relation, since those don't have system
397 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
399 for (i = 0; i < natts; i++)
401 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
402 tupdesc->tdhasoid) != NULL)
404 (errcode(ERRCODE_DUPLICATE_COLUMN),
405 errmsg("column name \"%s\" conflicts with a system column name",
406 NameStr(tupdesc->attrs[i]->attname))));
411 * next check for repeated attribute names
413 for (i = 1; i < natts; i++)
415 for (j = 0; j < i; j++)
417 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
418 NameStr(tupdesc->attrs[i]->attname)) == 0)
420 (errcode(ERRCODE_DUPLICATE_COLUMN),
421 errmsg("column name \"%s\" specified more than once",
422 NameStr(tupdesc->attrs[j]->attname))));
427 * next check the attribute types
429 for (i = 0; i < natts; i++)
431 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
432 tupdesc->attrs[i]->atttypid,
433 tupdesc->attrs[i]->attcollation,
434 NIL, /* assume we're creating a new rowtype */
435 allow_system_table_mods);
439 /* --------------------------------
442 * Verify that the proposed datatype of an attribute is legal.
443 * This is needed mainly because there are types (and pseudo-types)
444 * in the catalogs that we do not support as elements of real tuples.
445 * We also check some other properties required of a table column.
447 * If the attribute is being proposed for addition to an existing table or
448 * composite type, pass a one-element list of the rowtype OID as
449 * containing_rowtypes. When checking a to-be-created rowtype, it's
450 * sufficient to pass NIL, because there could not be any recursive reference
451 * to a not-yet-existing rowtype.
452 * --------------------------------
455 CheckAttributeType(const char *attname,
456 Oid atttypid, Oid attcollation,
457 List *containing_rowtypes,
458 bool allow_system_table_mods)
460 char att_typtype = get_typtype(atttypid);
463 if (atttypid == UNKNOWNOID)
466 * Warn user, but don't fail, if column to be created has UNKNOWN type
467 * (usually as a result of a 'retrieve into' - jolly)
470 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
471 errmsg("column \"%s\" has type \"unknown\"", attname),
472 errdetail("Proceeding with relation creation anyway.")));
474 else if (att_typtype == TYPTYPE_PSEUDO)
477 * Refuse any attempt to create a pseudo-type column, except for a
478 * special hack for pg_statistic: allow ANYARRAY when modifying system
479 * catalogs (this allows creating pg_statistic and cloning it during
482 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
484 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
485 errmsg("column \"%s\" has pseudo-type %s",
486 attname, format_type_be(atttypid))));
488 else if (att_typtype == TYPTYPE_COMPOSITE)
491 * For a composite type, recurse into its attributes. You might think
492 * this isn't necessary, but since we allow system catalogs to break
493 * the rule, we have to guard against the case.
500 * Check for self-containment. Eventually we might be able to allow
501 * this (just return without complaint, if so) but it's not clear how
502 * many other places would require anti-recursion defenses before it
503 * would be safe to allow tables to contain their own rowtype.
505 if (list_member_oid(containing_rowtypes, atttypid))
507 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
508 errmsg("composite type %s cannot be made a member of itself",
509 format_type_be(atttypid))));
511 containing_rowtypes = lcons_oid(atttypid, containing_rowtypes);
513 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
515 tupdesc = RelationGetDescr(relation);
517 for (i = 0; i < tupdesc->natts; i++)
519 Form_pg_attribute attr = tupdesc->attrs[i];
521 if (attr->attisdropped)
523 CheckAttributeType(NameStr(attr->attname),
524 attr->atttypid, attr->attcollation,
526 allow_system_table_mods);
529 relation_close(relation, AccessShareLock);
531 containing_rowtypes = list_delete_first(containing_rowtypes);
533 else if (OidIsValid((att_typelem = get_element_type(atttypid))))
536 * Must recurse into array types, too, in case they are composite.
538 CheckAttributeType(attname, att_typelem, attcollation,
540 allow_system_table_mods);
544 * This might not be strictly invalid per SQL standard, but it is pretty
545 * useless, and it cannot be dumped, so we must disallow it.
547 if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
549 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
550 errmsg("no collation was derived for column \"%s\" with collatable type %s",
551 attname, format_type_be(atttypid)),
552 errhint("Use the COLLATE clause to set the collation explicitly.")));
556 * InsertPgAttributeTuple
557 * Construct and insert a new tuple in pg_attribute.
559 * Caller has already opened and locked pg_attribute. new_attribute is the
560 * attribute to insert (but we ignore attacl and attoptions, which are always
561 * initialized to NULL).
563 * indstate is the index state for CatalogIndexInsert. It can be passed as
564 * NULL, in which case we'll fetch the necessary info. (Don't do this when
565 * inserting multiple attributes, because it's a tad more expensive.)
568 InsertPgAttributeTuple(Relation pg_attribute_rel,
569 Form_pg_attribute new_attribute,
570 CatalogIndexState indstate)
572 Datum values[Natts_pg_attribute];
573 bool nulls[Natts_pg_attribute];
576 /* This is a tad tedious, but way cleaner than what we used to do... */
577 memset(values, 0, sizeof(values));
578 memset(nulls, false, sizeof(nulls));
580 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
581 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
582 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
583 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
584 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
585 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
586 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
587 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
588 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
589 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
590 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
591 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
592 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
593 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
594 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
595 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
596 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
597 values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
599 /* start out with empty permissions and empty options */
600 nulls[Anum_pg_attribute_attacl - 1] = true;
601 nulls[Anum_pg_attribute_attoptions - 1] = true;
603 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
605 /* finally insert the new tuple, update the indexes, and clean up */
606 simple_heap_insert(pg_attribute_rel, tup);
608 if (indstate != NULL)
609 CatalogIndexInsert(indstate, tup);
611 CatalogUpdateIndexes(pg_attribute_rel, tup);
616 /* --------------------------------
617 * AddNewAttributeTuples
619 * this registers the new relation's schema by adding
620 * tuples to pg_attribute.
621 * --------------------------------
624 AddNewAttributeTuples(Oid new_rel_oid,
630 Form_pg_attribute attr;
633 CatalogIndexState indstate;
634 int natts = tupdesc->natts;
635 ObjectAddress myself,
639 * open pg_attribute and its indexes.
641 rel = heap_open(AttributeRelationId, RowExclusiveLock);
643 indstate = CatalogOpenIndexes(rel);
646 * First we add the user attributes. This is also a convenient place to
647 * add dependencies on their datatypes and collations.
649 for (i = 0; i < natts; i++)
651 attr = tupdesc->attrs[i];
652 /* Fill in the correct relation OID */
653 attr->attrelid = new_rel_oid;
654 /* Make sure these are OK, too */
655 attr->attstattarget = -1;
656 attr->attcacheoff = -1;
658 InsertPgAttributeTuple(rel, attr, indstate);
660 /* Add dependency info */
661 myself.classId = RelationRelationId;
662 myself.objectId = new_rel_oid;
663 myself.objectSubId = i + 1;
664 referenced.classId = TypeRelationId;
665 referenced.objectId = attr->atttypid;
666 referenced.objectSubId = 0;
667 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
669 /* The default collation is pinned, so don't bother recording it */
670 if (OidIsValid(attr->attcollation) &&
671 attr->attcollation != DEFAULT_COLLATION_OID)
673 referenced.classId = CollationRelationId;
674 referenced.objectId = attr->attcollation;
675 referenced.objectSubId = 0;
676 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
681 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
682 * all for a view or type relation. We don't bother with making datatype
683 * dependencies here, since presumably all these types are pinned.
685 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
687 for (i = 0; i < (int) lengthof(SysAtt); i++)
689 FormData_pg_attribute attStruct;
691 /* skip OID where appropriate */
692 if (!tupdesc->tdhasoid &&
693 SysAtt[i]->attnum == ObjectIdAttributeNumber)
696 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
698 /* Fill in the correct relation OID in the copied tuple */
699 attStruct.attrelid = new_rel_oid;
701 /* Fill in correct inheritance info for the OID column */
702 if (attStruct.attnum == ObjectIdAttributeNumber)
704 attStruct.attislocal = oidislocal;
705 attStruct.attinhcount = oidinhcount;
708 InsertPgAttributeTuple(rel, &attStruct, indstate);
715 CatalogCloseIndexes(indstate);
717 heap_close(rel, RowExclusiveLock);
720 /* --------------------------------
723 * Construct and insert a new tuple in pg_class.
725 * Caller has already opened and locked pg_class.
726 * Tuple data is taken from new_rel_desc->rd_rel, except for the
727 * variable-width fields which are not present in a cached reldesc.
728 * relacl and reloptions are passed in Datum form (to avoid having
729 * to reference the data types in heap.h). Pass (Datum) 0 to set them
731 * --------------------------------
734 InsertPgClassTuple(Relation pg_class_desc,
735 Relation new_rel_desc,
740 Form_pg_class rd_rel = new_rel_desc->rd_rel;
741 Datum values[Natts_pg_class];
742 bool nulls[Natts_pg_class];
745 /* This is a tad tedious, but way cleaner than what we used to do... */
746 memset(values, 0, sizeof(values));
747 memset(nulls, false, sizeof(nulls));
749 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
750 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
751 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
752 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
753 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
754 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
755 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
756 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
757 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
758 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
759 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
760 values[Anum_pg_class_reltoastidxid - 1] = ObjectIdGetDatum(rd_rel->reltoastidxid);
761 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
762 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
763 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
764 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
765 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
766 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
767 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
768 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
769 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
770 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
771 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
772 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
773 if (relacl != (Datum) 0)
774 values[Anum_pg_class_relacl - 1] = relacl;
776 nulls[Anum_pg_class_relacl - 1] = true;
777 if (reloptions != (Datum) 0)
778 values[Anum_pg_class_reloptions - 1] = reloptions;
780 nulls[Anum_pg_class_reloptions - 1] = true;
782 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
785 * The new tuple must have the oid already chosen for the rel. Sure would
786 * be embarrassing to do this sort of thing in polite company.
788 HeapTupleSetOid(tup, new_rel_oid);
790 /* finally insert the new tuple, update the indexes, and clean up */
791 simple_heap_insert(pg_class_desc, tup);
793 CatalogUpdateIndexes(pg_class_desc, tup);
798 /* --------------------------------
799 * AddNewRelationTuple
801 * this registers the new relation in the catalogs by
802 * adding a tuple to pg_class.
803 * --------------------------------
806 AddNewRelationTuple(Relation pg_class_desc,
807 Relation new_rel_desc,
816 Form_pg_class new_rel_reltup;
819 * first we update some of the information in our uncataloged relation's
820 * relation descriptor.
822 new_rel_reltup = new_rel_desc->rd_rel;
826 case RELKIND_RELATION:
828 case RELKIND_TOASTVALUE:
829 /* The relation is real, but as yet empty */
830 new_rel_reltup->relpages = 0;
831 new_rel_reltup->reltuples = 0;
833 case RELKIND_SEQUENCE:
834 /* Sequences always have a known size */
835 new_rel_reltup->relpages = 1;
836 new_rel_reltup->reltuples = 1;
839 /* Views, etc, have no disk storage */
840 new_rel_reltup->relpages = 0;
841 new_rel_reltup->reltuples = 0;
845 /* Initialize relfrozenxid */
846 if (relkind == RELKIND_RELATION ||
847 relkind == RELKIND_TOASTVALUE)
850 * Initialize to the minimum XID that could put tuples in the table.
851 * We know that no xacts older than RecentXmin are still running, so
854 new_rel_reltup->relfrozenxid = RecentXmin;
859 * Other relation types will not contain XIDs, so set relfrozenxid to
860 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
861 * we force its xmin to be FrozenTransactionId always; see
862 * commands/sequence.c.)
864 new_rel_reltup->relfrozenxid = InvalidTransactionId;
867 new_rel_reltup->relowner = relowner;
868 new_rel_reltup->reltype = new_type_oid;
869 new_rel_reltup->reloftype = reloftype;
870 new_rel_reltup->relkind = relkind;
872 new_rel_desc->rd_att->tdtypeid = new_type_oid;
874 /* Now build and insert the tuple */
875 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
880 /* --------------------------------
881 * AddNewRelationType -
883 * define a composite type corresponding to the new relation
884 * --------------------------------
887 AddNewRelationType(const char *typeName,
896 TypeCreate(new_row_type, /* optional predetermined OID */
897 typeName, /* type name */
898 typeNamespace, /* type namespace */
899 new_rel_oid, /* relation oid */
900 new_rel_kind, /* relation kind */
901 ownerid, /* owner's ID */
902 -1, /* internal size (varlena) */
903 TYPTYPE_COMPOSITE, /* type-type (composite) */
904 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
905 false, /* composite types are never preferred */
906 DEFAULT_TYPDELIM, /* default array delimiter */
907 F_RECORD_IN, /* input procedure */
908 F_RECORD_OUT, /* output procedure */
909 F_RECORD_RECV, /* receive procedure */
910 F_RECORD_SEND, /* send procedure */
911 InvalidOid, /* typmodin procedure - none */
912 InvalidOid, /* typmodout procedure - none */
913 InvalidOid, /* analyze procedure - default */
914 InvalidOid, /* array element type - irrelevant */
915 false, /* this is not an array type */
916 new_array_type, /* array type if any */
917 InvalidOid, /* domain base type - irrelevant */
918 NULL, /* default value - none */
919 NULL, /* default binary representation */
920 false, /* passed by reference */
921 'd', /* alignment - must be the largest! */
922 'x', /* fully TOASTable */
924 0, /* array dimensions for typBaseType */
925 false, /* Type NOT NULL */
926 InvalidOid); /* rowtypes never have a collation */
929 /* --------------------------------
930 * heap_create_with_catalog
932 * creates a new cataloged relation. see comments above.
935 * relname: name to give to new rel
936 * relnamespace: OID of namespace it goes in
937 * reltablespace: OID of tablespace it goes in
938 * relid: OID to assign to new rel, or InvalidOid to select a new OID
939 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
940 * ownerid: OID of new rel's owner
941 * tupdesc: tuple descriptor (source of column definitions)
942 * cooked_constraints: list of precooked check constraints and defaults
943 * relkind: relkind for new rel
944 * shared_relation: TRUE if it's to be a shared relation
945 * mapped_relation: TRUE if the relation will use the relfilenode map
946 * oidislocal: TRUE if oid column (if any) should be marked attislocal
947 * oidinhcount: attinhcount to assign to oid column (if any)
948 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
949 * reloptions: reloptions in Datum form, or (Datum) 0 if none
950 * use_user_acl: TRUE if should look for user-defined default permissions;
951 * if FALSE, relacl is always set NULL
952 * allow_system_table_mods: TRUE to allow creation in system namespaces
954 * Returns the OID of the new relation
955 * --------------------------------
958 heap_create_with_catalog(const char *relname,
966 List *cooked_constraints,
969 bool shared_relation,
970 bool mapped_relation,
973 OnCommitAction oncommit,
976 bool allow_system_table_mods)
978 Relation pg_class_desc;
979 Relation new_rel_desc;
984 Oid new_array_oid = InvalidOid;
986 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
991 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
993 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
996 * This would fail later on anyway, if the relation already exists. But
997 * by catching it here we can emit a nicer error message.
999 existing_relid = get_relname_relid(relname, relnamespace);
1000 if (existing_relid != InvalidOid)
1002 (errcode(ERRCODE_DUPLICATE_TABLE),
1003 errmsg("relation \"%s\" already exists", relname)));
1006 * Since we are going to create a rowtype as well, also check for
1007 * collision with an existing type name. If there is one and it's an
1008 * autogenerated array, we can rename it out of the way; otherwise we can
1009 * at least give a good error message.
1011 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1012 CStringGetDatum(relname),
1013 ObjectIdGetDatum(relnamespace));
1014 if (OidIsValid(old_type_oid))
1016 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1018 (errcode(ERRCODE_DUPLICATE_OBJECT),
1019 errmsg("type \"%s\" already exists", relname),
1020 errhint("A relation has an associated type of the same name, "
1021 "so you must use a name that doesn't conflict "
1022 "with any existing type.")));
1026 * Shared relations must be in pg_global (last-ditch check)
1028 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1029 elog(ERROR, "shared relations must be placed in pg_global tablespace");
1032 * Allocate an OID for the relation, unless we were told what to use.
1034 * The OID will be the relfilenode as well, so make sure it doesn't
1035 * collide with either pg_class OIDs or existing physical files.
1037 if (!OidIsValid(relid))
1040 * Use binary-upgrade override for pg_class.oid/relfilenode, if
1043 if (IsBinaryUpgrade &&
1044 OidIsValid(binary_upgrade_next_heap_pg_class_oid) &&
1045 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
1046 relkind == RELKIND_VIEW || relkind == RELKIND_COMPOSITE_TYPE ||
1047 relkind == RELKIND_FOREIGN_TABLE))
1049 relid = binary_upgrade_next_heap_pg_class_oid;
1050 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1052 else if (IsBinaryUpgrade &&
1053 OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1054 relkind == RELKIND_TOASTVALUE)
1056 relid = binary_upgrade_next_toast_pg_class_oid;
1057 binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1060 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1065 * Determine the relation's initial permissions.
1071 case RELKIND_RELATION:
1073 case RELKIND_FOREIGN_TABLE:
1074 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1077 case RELKIND_SEQUENCE:
1078 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1090 * Create the relcache entry (mostly dummy at this point) and the physical
1091 * disk file. (If we fail further down, it's the smgr's responsibility to
1092 * remove the disk file again.)
1094 new_rel_desc = heap_create(relname,
1103 allow_system_table_mods);
1105 Assert(relid == RelationGetRelid(new_rel_desc));
1108 * Decide whether to create an array type over the relation's rowtype. We
1109 * do not create any array types for system catalogs (ie, those made
1110 * during initdb). We create array types for regular relations, views,
1111 * composite types and foreign tables ... but not, eg, for toast tables or
1114 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1115 relkind == RELKIND_VIEW ||
1116 relkind == RELKIND_FOREIGN_TABLE ||
1117 relkind == RELKIND_COMPOSITE_TYPE))
1118 new_array_oid = AssignTypeArrayOid();
1121 * Since defining a relation also defines a complex type, we add a new
1122 * system type corresponding to the new relation. The OID of the type can
1123 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1124 * generate a new OID for it.
1126 * NOTE: we could get a unique-index failure here, in case someone else is
1127 * creating the same type name in parallel but hadn't committed yet when
1128 * we checked for a duplicate name above.
1130 new_type_oid = AddNewRelationType(relname,
1139 * Now make the array type if wanted.
1141 if (OidIsValid(new_array_oid))
1145 relarrayname = makeArrayTypeName(relname, relnamespace);
1147 TypeCreate(new_array_oid, /* force the type's OID to this */
1148 relarrayname, /* Array type name */
1149 relnamespace, /* Same namespace as parent */
1150 InvalidOid, /* Not composite, no relationOid */
1151 0, /* relkind, also N/A here */
1152 ownerid, /* owner's ID */
1153 -1, /* Internal size (varlena) */
1154 TYPTYPE_BASE, /* Not composite - typelem is */
1155 TYPCATEGORY_ARRAY, /* type-category (array) */
1156 false, /* array types are never preferred */
1157 DEFAULT_TYPDELIM, /* default array delimiter */
1158 F_ARRAY_IN, /* array input proc */
1159 F_ARRAY_OUT, /* array output proc */
1160 F_ARRAY_RECV, /* array recv (bin) proc */
1161 F_ARRAY_SEND, /* array send (bin) proc */
1162 InvalidOid, /* typmodin procedure - none */
1163 InvalidOid, /* typmodout procedure - none */
1164 InvalidOid, /* analyze procedure - default */
1165 new_type_oid, /* array element type - the rowtype */
1166 true, /* yes, this is an array type */
1167 InvalidOid, /* this has no array type */
1168 InvalidOid, /* domain base type - irrelevant */
1169 NULL, /* default value - none */
1170 NULL, /* default binary representation */
1171 false, /* passed by reference */
1172 'd', /* alignment - must be the largest! */
1173 'x', /* fully TOASTable */
1175 0, /* array dimensions for typBaseType */
1176 false, /* Type NOT NULL */
1177 InvalidOid); /* rowtypes never have a collation */
1179 pfree(relarrayname);
1183 * now create an entry in pg_class for the relation.
1185 * NOTE: we could get a unique-index failure here, in case someone else is
1186 * creating the same relation name in parallel but hadn't committed yet
1187 * when we checked for a duplicate name above.
1189 AddNewRelationTuple(pg_class_desc,
1196 PointerGetDatum(relacl),
1200 * now add tuples to pg_attribute for the attributes in our new relation.
1202 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1203 oidislocal, oidinhcount);
1206 * Make a dependency link to force the relation to be deleted if its
1207 * namespace is. Also make a dependency link to its owner, as well as
1208 * dependencies for any roles mentioned in the default ACL.
1210 * For composite types, these dependencies are tracked for the pg_type
1211 * entry, so we needn't record them here. Likewise, TOAST tables don't
1212 * need a namespace dependency (they live in a pinned namespace) nor an
1213 * owner dependency (they depend indirectly through the parent table), nor
1214 * should they have any ACL entries. The same applies for extension
1217 * Also, skip this in bootstrap mode, since we don't make dependencies
1218 * while bootstrapping.
1220 if (relkind != RELKIND_COMPOSITE_TYPE &&
1221 relkind != RELKIND_TOASTVALUE &&
1222 !IsBootstrapProcessingMode())
1224 ObjectAddress myself,
1227 myself.classId = RelationRelationId;
1228 myself.objectId = relid;
1229 myself.objectSubId = 0;
1230 referenced.classId = NamespaceRelationId;
1231 referenced.objectId = relnamespace;
1232 referenced.objectSubId = 0;
1233 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1235 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1237 recordDependencyOnCurrentExtension(&myself);
1241 referenced.classId = TypeRelationId;
1242 referenced.objectId = reloftypeid;
1243 referenced.objectSubId = 0;
1244 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1252 nnewmembers = aclmembers(relacl, &newmembers);
1253 updateAclDependencies(RelationRelationId, relid, 0,
1256 nnewmembers, newmembers);
1260 /* Post creation hook for new relation */
1261 InvokeObjectAccessHook(OAT_POST_CREATE, RelationRelationId, relid, 0);
1264 * Store any supplied constraints and defaults.
1266 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1267 * entry, so the relation must be valid and self-consistent at this point.
1268 * In particular, there are not yet constraints and defaults anywhere.
1270 StoreConstraints(new_rel_desc, cooked_constraints);
1273 * If there's a special on-commit action, remember it
1275 if (oncommit != ONCOMMIT_NOOP)
1276 register_on_commit_action(relid, oncommit);
1279 * If this is an unlogged relation, it needs an init fork so that it can
1280 * be correctly reinitialized on restart. Since we're going to do an
1281 * immediate sync, we ony need to xlog this if archiving or streaming is
1282 * enabled. And the immediate sync is required, because otherwise there's
1283 * no guarantee that this will hit the disk before the next checkpoint
1284 * moves the redo pointer.
1286 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1288 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_TOASTVALUE);
1290 smgrcreate(new_rel_desc->rd_smgr, INIT_FORKNUM, false);
1292 log_smgrcreate(&new_rel_desc->rd_smgr->smgr_rnode.node,
1294 smgrimmedsync(new_rel_desc->rd_smgr, INIT_FORKNUM);
1298 * ok, the relation has been cataloged, so close our relations and return
1299 * the OID of the newly created relation.
1301 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1302 heap_close(pg_class_desc, RowExclusiveLock);
1309 * RelationRemoveInheritance
1311 * Formerly, this routine checked for child relations and aborted the
1312 * deletion if any were found. Now we rely on the dependency mechanism
1313 * to check for or delete child relations. By the time we get here,
1314 * there are no children and we need only remove any pg_inherits rows
1315 * linking this relation to its parent(s).
1318 RelationRemoveInheritance(Oid relid)
1320 Relation catalogRelation;
1325 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1328 Anum_pg_inherits_inhrelid,
1329 BTEqualStrategyNumber, F_OIDEQ,
1330 ObjectIdGetDatum(relid));
1332 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1333 SnapshotNow, 1, &key);
1335 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1336 simple_heap_delete(catalogRelation, &tuple->t_self);
1338 systable_endscan(scan);
1339 heap_close(catalogRelation, RowExclusiveLock);
1343 * DeleteRelationTuple
1345 * Remove pg_class row for the given relid.
1347 * Note: this is shared by relation deletion and index deletion. It's
1348 * not intended for use anyplace else.
1351 DeleteRelationTuple(Oid relid)
1353 Relation pg_class_desc;
1356 /* Grab an appropriate lock on the pg_class relation */
1357 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1359 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1360 if (!HeapTupleIsValid(tup))
1361 elog(ERROR, "cache lookup failed for relation %u", relid);
1363 /* delete the relation tuple from pg_class, and finish up */
1364 simple_heap_delete(pg_class_desc, &tup->t_self);
1366 ReleaseSysCache(tup);
1368 heap_close(pg_class_desc, RowExclusiveLock);
1372 * DeleteAttributeTuples
1374 * Remove pg_attribute rows for the given relid.
1376 * Note: this is shared by relation deletion and index deletion. It's
1377 * not intended for use anyplace else.
1380 DeleteAttributeTuples(Oid relid)
1387 /* Grab an appropriate lock on the pg_attribute relation */
1388 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1390 /* Use the index to scan only attributes of the target relation */
1391 ScanKeyInit(&key[0],
1392 Anum_pg_attribute_attrelid,
1393 BTEqualStrategyNumber, F_OIDEQ,
1394 ObjectIdGetDatum(relid));
1396 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1397 SnapshotNow, 1, key);
1399 /* Delete all the matching tuples */
1400 while ((atttup = systable_getnext(scan)) != NULL)
1401 simple_heap_delete(attrel, &atttup->t_self);
1403 /* Clean up after the scan */
1404 systable_endscan(scan);
1405 heap_close(attrel, RowExclusiveLock);
1409 * RemoveAttributeById
1411 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1412 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1413 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1414 * is handled by dependency.c.)
1417 RemoveAttributeById(Oid relid, AttrNumber attnum)
1422 Form_pg_attribute attStruct;
1423 char newattname[NAMEDATALEN];
1426 * Grab an exclusive lock on the target table, which we will NOT release
1427 * until end of transaction. (In the simple case where we are directly
1428 * dropping this column, AlterTableDropColumn already did this ... but
1429 * when cascading from a drop of some other object, we may not have any
1432 rel = relation_open(relid, AccessExclusiveLock);
1434 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1436 tuple = SearchSysCacheCopy2(ATTNUM,
1437 ObjectIdGetDatum(relid),
1438 Int16GetDatum(attnum));
1439 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1440 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1442 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1446 /* System attribute (probably OID) ... just delete the row */
1448 simple_heap_delete(attr_rel, &tuple->t_self);
1452 /* Dropping user attributes is lots harder */
1454 /* Mark the attribute as dropped */
1455 attStruct->attisdropped = true;
1458 * Set the type OID to invalid. A dropped attribute's type link
1459 * cannot be relied on (once the attribute is dropped, the type might
1460 * be too). Fortunately we do not need the type row --- the only
1461 * really essential information is the type's typlen and typalign,
1462 * which are preserved in the attribute's attlen and attalign. We set
1463 * atttypid to zero here as a means of catching code that incorrectly
1464 * expects it to be valid.
1466 attStruct->atttypid = InvalidOid;
1468 /* Remove any NOT NULL constraint the column may have */
1469 attStruct->attnotnull = false;
1471 /* We don't want to keep stats for it anymore */
1472 attStruct->attstattarget = 0;
1475 * Change the column name to something that isn't likely to conflict
1477 snprintf(newattname, sizeof(newattname),
1478 "........pg.dropped.%d........", attnum);
1479 namestrcpy(&(attStruct->attname), newattname);
1481 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1483 /* keep the system catalog indexes current */
1484 CatalogUpdateIndexes(attr_rel, tuple);
1488 * Because updating the pg_attribute row will trigger a relcache flush for
1489 * the target relation, we need not do anything else to notify other
1490 * backends of the change.
1493 heap_close(attr_rel, RowExclusiveLock);
1496 RemoveStatistics(relid, attnum);
1498 relation_close(rel, NoLock);
1504 * If the specified relation/attribute has a default, remove it.
1505 * (If no default, raise error if complain is true, else return quietly.)
1508 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1509 DropBehavior behavior, bool complain)
1511 Relation attrdef_rel;
1512 ScanKeyData scankeys[2];
1517 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1519 ScanKeyInit(&scankeys[0],
1520 Anum_pg_attrdef_adrelid,
1521 BTEqualStrategyNumber, F_OIDEQ,
1522 ObjectIdGetDatum(relid));
1523 ScanKeyInit(&scankeys[1],
1524 Anum_pg_attrdef_adnum,
1525 BTEqualStrategyNumber, F_INT2EQ,
1526 Int16GetDatum(attnum));
1528 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1529 SnapshotNow, 2, scankeys);
1531 /* There should be at most one matching tuple, but we loop anyway */
1532 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1534 ObjectAddress object;
1536 object.classId = AttrDefaultRelationId;
1537 object.objectId = HeapTupleGetOid(tuple);
1538 object.objectSubId = 0;
1540 performDeletion(&object, behavior);
1545 systable_endscan(scan);
1546 heap_close(attrdef_rel, RowExclusiveLock);
1548 if (complain && !found)
1549 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1554 * RemoveAttrDefaultById
1556 * Remove a pg_attrdef entry specified by OID. This is the guts of
1557 * attribute-default removal. Note it should be called via performDeletion,
1561 RemoveAttrDefaultById(Oid attrdefId)
1563 Relation attrdef_rel;
1566 ScanKeyData scankeys[1];
1570 AttrNumber myattnum;
1572 /* Grab an appropriate lock on the pg_attrdef relation */
1573 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1575 /* Find the pg_attrdef tuple */
1576 ScanKeyInit(&scankeys[0],
1577 ObjectIdAttributeNumber,
1578 BTEqualStrategyNumber, F_OIDEQ,
1579 ObjectIdGetDatum(attrdefId));
1581 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1582 SnapshotNow, 1, scankeys);
1584 tuple = systable_getnext(scan);
1585 if (!HeapTupleIsValid(tuple))
1586 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1588 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1589 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1591 /* Get an exclusive lock on the relation owning the attribute */
1592 myrel = relation_open(myrelid, AccessExclusiveLock);
1594 /* Now we can delete the pg_attrdef row */
1595 simple_heap_delete(attrdef_rel, &tuple->t_self);
1597 systable_endscan(scan);
1598 heap_close(attrdef_rel, RowExclusiveLock);
1600 /* Fix the pg_attribute row */
1601 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1603 tuple = SearchSysCacheCopy2(ATTNUM,
1604 ObjectIdGetDatum(myrelid),
1605 Int16GetDatum(myattnum));
1606 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1607 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1610 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1612 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1614 /* keep the system catalog indexes current */
1615 CatalogUpdateIndexes(attr_rel, tuple);
1618 * Our update of the pg_attribute row will force a relcache rebuild, so
1619 * there's nothing else to do here.
1621 heap_close(attr_rel, RowExclusiveLock);
1623 /* Keep lock on attribute's rel until end of xact */
1624 relation_close(myrel, NoLock);
1628 * heap_drop_with_catalog - removes specified relation from catalogs
1630 * Note that this routine is not responsible for dropping objects that are
1631 * linked to the pg_class entry via dependencies (for example, indexes and
1632 * constraints). Those are deleted by the dependency-tracing logic in
1633 * dependency.c before control gets here. In general, therefore, this routine
1634 * should never be called directly; go through performDeletion() instead.
1637 heap_drop_with_catalog(Oid relid)
1642 * Open and lock the relation.
1644 rel = relation_open(relid, AccessExclusiveLock);
1647 * There can no longer be anyone *else* touching the relation, but we
1648 * might still have open queries or cursors, or pending trigger events, in
1651 CheckTableNotInUse(rel, "DROP TABLE");
1654 * Delete pg_foreign_table tuple first.
1656 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1661 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1663 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1664 if (!HeapTupleIsValid(tuple))
1665 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1667 simple_heap_delete(rel, &tuple->t_self);
1669 ReleaseSysCache(tuple);
1670 heap_close(rel, RowExclusiveLock);
1674 * Schedule unlinking of the relation's physical files at commit.
1676 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1677 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1678 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1680 RelationDropStorage(rel);
1684 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1685 * until transaction commit. This ensures no one else will try to do
1686 * something with the doomed relation.
1688 relation_close(rel, NoLock);
1691 * Forget any ON COMMIT action for the rel
1693 remove_on_commit_action(relid);
1696 * Flush the relation from the relcache. We want to do this before
1697 * starting to remove catalog entries, just to be certain that no relcache
1698 * entry rebuild will happen partway through. (That should not really
1699 * matter, since we don't do CommandCounterIncrement here, but let's be
1702 RelationForgetRelation(relid);
1705 * remove inheritance information
1707 RelationRemoveInheritance(relid);
1712 RemoveStatistics(relid, 0);
1715 * delete attribute tuples
1717 DeleteAttributeTuples(relid);
1720 * delete relation tuple
1722 DeleteRelationTuple(relid);
1727 * Store a default expression for column attnum of relation rel.
1730 StoreAttrDefault(Relation rel, AttrNumber attnum, Node *expr)
1737 static bool nulls[4] = {false, false, false, false};
1740 Form_pg_attribute attStruct;
1742 ObjectAddress colobject,
1746 * Flatten expression to string form for storage.
1748 adbin = nodeToString(expr);
1751 * Also deparse it to form the mostly-obsolete adsrc field.
1753 adsrc = deparse_expression(expr,
1754 deparse_context_for(RelationGetRelationName(rel),
1755 RelationGetRelid(rel)),
1759 * Make the pg_attrdef entry.
1761 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1762 values[Anum_pg_attrdef_adnum - 1] = attnum;
1763 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1764 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1766 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1768 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1769 attrdefOid = simple_heap_insert(adrel, tuple);
1771 CatalogUpdateIndexes(adrel, tuple);
1773 defobject.classId = AttrDefaultRelationId;
1774 defobject.objectId = attrdefOid;
1775 defobject.objectSubId = 0;
1777 heap_close(adrel, RowExclusiveLock);
1779 /* now can free some of the stuff allocated above */
1780 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1781 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1782 heap_freetuple(tuple);
1787 * Update the pg_attribute entry for the column to show that a default
1790 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1791 atttup = SearchSysCacheCopy2(ATTNUM,
1792 ObjectIdGetDatum(RelationGetRelid(rel)),
1793 Int16GetDatum(attnum));
1794 if (!HeapTupleIsValid(atttup))
1795 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1796 attnum, RelationGetRelid(rel));
1797 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1798 if (!attStruct->atthasdef)
1800 attStruct->atthasdef = true;
1801 simple_heap_update(attrrel, &atttup->t_self, atttup);
1802 /* keep catalog indexes current */
1803 CatalogUpdateIndexes(attrrel, atttup);
1805 heap_close(attrrel, RowExclusiveLock);
1806 heap_freetuple(atttup);
1809 * Make a dependency so that the pg_attrdef entry goes away if the column
1810 * (or whole table) is deleted.
1812 colobject.classId = RelationRelationId;
1813 colobject.objectId = RelationGetRelid(rel);
1814 colobject.objectSubId = attnum;
1816 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1819 * Record dependencies on objects used in the expression, too.
1821 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1825 * Store a check-constraint expression for the given relation.
1827 * Caller is responsible for updating the count of constraints
1828 * in the pg_class entry for the relation.
1831 StoreRelCheck(Relation rel, char *ccname, Node *expr,
1832 bool is_local, int inhcount)
1841 * Flatten expression to string form for storage.
1843 ccbin = nodeToString(expr);
1846 * Also deparse it to form the mostly-obsolete consrc field.
1848 ccsrc = deparse_expression(expr,
1849 deparse_context_for(RelationGetRelationName(rel),
1850 RelationGetRelid(rel)),
1854 * Find columns of rel that are used in expr
1856 * NB: pull_var_clause is okay here only because we don't allow subselects
1857 * in check constraints; it would fail to examine the contents of
1860 varList = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
1861 keycount = list_length(varList);
1868 attNos = (int16 *) palloc(keycount * sizeof(int16));
1869 foreach(vl, varList)
1871 Var *var = (Var *) lfirst(vl);
1874 for (j = 0; j < i; j++)
1875 if (attNos[j] == var->varattno)
1878 attNos[i++] = var->varattno;
1886 * Create the Check Constraint
1888 CreateConstraintEntry(ccname, /* Constraint Name */
1889 RelationGetNamespace(rel), /* namespace */
1890 CONSTRAINT_CHECK, /* Constraint Type */
1891 false, /* Is Deferrable */
1892 false, /* Is Deferred */
1893 true, /* Is Validated */
1894 RelationGetRelid(rel), /* relation */
1895 attNos, /* attrs in the constraint */
1896 keycount, /* # attrs in the constraint */
1897 InvalidOid, /* not a domain constraint */
1898 InvalidOid, /* no associated index */
1899 InvalidOid, /* Foreign key fields */
1908 NULL, /* not an exclusion constraint */
1909 expr, /* Tree form of check constraint */
1910 ccbin, /* Binary form of check constraint */
1911 ccsrc, /* Source form of check constraint */
1912 is_local, /* conislocal */
1913 inhcount); /* coninhcount */
1920 * Store defaults and constraints (passed as a list of CookedConstraint).
1922 * NOTE: only pre-cooked expressions will be passed this way, which is to
1923 * say expressions inherited from an existing relation. Newly parsed
1924 * expressions can be added later, by direct calls to StoreAttrDefault
1925 * and StoreRelCheck (see AddRelationNewConstraints()).
1928 StoreConstraints(Relation rel, List *cooked_constraints)
1933 if (!cooked_constraints)
1934 return; /* nothing to do */
1937 * Deparsing of constraint expressions will fail unless the just-created
1938 * pg_attribute tuples for this relation are made visible. So, bump the
1939 * command counter. CAUTION: this will cause a relcache entry rebuild.
1941 CommandCounterIncrement();
1943 foreach(lc, cooked_constraints)
1945 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
1947 switch (con->contype)
1949 case CONSTR_DEFAULT:
1950 StoreAttrDefault(rel, con->attnum, con->expr);
1953 StoreRelCheck(rel, con->name, con->expr,
1954 con->is_local, con->inhcount);
1958 elog(ERROR, "unrecognized constraint type: %d",
1959 (int) con->contype);
1964 SetRelationNumChecks(rel, numchecks);
1968 * AddRelationNewConstraints
1970 * Add new column default expressions and/or constraint check expressions
1971 * to an existing relation. This is defined to do both for efficiency in
1972 * DefineRelation, but of course you can do just one or the other by passing
1975 * rel: relation to be modified
1976 * newColDefaults: list of RawColumnDefault structures
1977 * newConstraints: list of Constraint nodes
1978 * allow_merge: TRUE if check constraints may be merged with existing ones
1979 * is_local: TRUE if definition is local, FALSE if it's inherited
1981 * All entries in newColDefaults will be processed. Entries in newConstraints
1982 * will be processed only if they are CONSTR_CHECK type.
1984 * Returns a list of CookedConstraint nodes that shows the cooked form of
1985 * the default and constraint expressions added to the relation.
1987 * NB: caller should have opened rel with AccessExclusiveLock, and should
1988 * hold that lock till end of transaction. Also, we assume the caller has
1989 * done a CommandCounterIncrement if necessary to make the relation's catalog
1993 AddRelationNewConstraints(Relation rel,
1994 List *newColDefaults,
1995 List *newConstraints,
1999 List *cookedConstraints = NIL;
2000 TupleDesc tupleDesc;
2001 TupleConstr *oldconstr;
2009 CookedConstraint *cooked;
2012 * Get info about existing constraints.
2014 tupleDesc = RelationGetDescr(rel);
2015 oldconstr = tupleDesc->constr;
2017 numoldchecks = oldconstr->num_check;
2022 * Create a dummy ParseState and insert the target relation as its sole
2023 * rangetable entry. We need a ParseState for transformExpr.
2025 pstate = make_parsestate(NULL);
2026 rte = addRangeTableEntryForRelation(pstate,
2031 addRTEtoQuery(pstate, rte, true, true, true);
2034 * Process column default expressions.
2036 foreach(cell, newColDefaults)
2038 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
2039 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
2041 expr = cookDefault(pstate, colDef->raw_default,
2042 atp->atttypid, atp->atttypmod,
2043 NameStr(atp->attname));
2046 * If the expression is just a NULL constant, we do not bother to make
2047 * an explicit pg_attrdef entry, since the default behavior is
2050 * Note a nonobvious property of this test: if the column is of a
2051 * domain type, what we'll get is not a bare null Const but a
2052 * CoerceToDomain expr, so we will not discard the default. This is
2053 * critical because the column default needs to be retained to
2054 * override any default that the domain might have.
2057 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2060 StoreAttrDefault(rel, colDef->attnum, expr);
2062 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2063 cooked->contype = CONSTR_DEFAULT;
2064 cooked->name = NULL;
2065 cooked->attnum = colDef->attnum;
2066 cooked->expr = expr;
2067 cooked->is_local = is_local;
2068 cooked->inhcount = is_local ? 0 : 1;
2069 cookedConstraints = lappend(cookedConstraints, cooked);
2073 * Process constraint expressions.
2075 numchecks = numoldchecks;
2077 foreach(cell, newConstraints)
2079 Constraint *cdef = (Constraint *) lfirst(cell);
2082 if (cdef->contype != CONSTR_CHECK)
2085 if (cdef->raw_expr != NULL)
2087 Assert(cdef->cooked_expr == NULL);
2090 * Transform raw parsetree to executable expression, and verify
2091 * it's valid as a CHECK constraint.
2093 expr = cookConstraint(pstate, cdef->raw_expr,
2094 RelationGetRelationName(rel));
2098 Assert(cdef->cooked_expr != NULL);
2101 * Here, we assume the parser will only pass us valid CHECK
2102 * expressions, so we do no particular checking.
2104 expr = stringToNode(cdef->cooked_expr);
2108 * Check name uniqueness, or generate a name if none was given.
2110 if (cdef->conname != NULL)
2114 ccname = cdef->conname;
2115 /* Check against other new constraints */
2116 /* Needed because we don't do CommandCounterIncrement in loop */
2117 foreach(cell2, checknames)
2119 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2121 (errcode(ERRCODE_DUPLICATE_OBJECT),
2122 errmsg("check constraint \"%s\" already exists",
2126 /* save name for future checks */
2127 checknames = lappend(checknames, ccname);
2130 * Check against pre-existing constraints. If we are allowed to
2131 * merge with an existing constraint, there's no more to do here.
2132 * (We omit the duplicate constraint from the result, which is
2133 * what ATAddCheckConstraint wants.)
2135 if (MergeWithExistingConstraint(rel, ccname, expr,
2136 allow_merge, is_local))
2142 * When generating a name, we want to create "tab_col_check" for a
2143 * column constraint and "tab_check" for a table constraint. We
2144 * no longer have any info about the syntactic positioning of the
2145 * constraint phrase, so we approximate this by seeing whether the
2146 * expression references more than one column. (If the user
2147 * played by the rules, the result is the same...)
2149 * Note: pull_var_clause() doesn't descend into sublinks, but we
2150 * eliminated those above; and anyway this only needs to be an
2151 * approximate answer.
2156 vars = pull_var_clause(expr, PVC_REJECT_PLACEHOLDERS);
2158 /* eliminate duplicates */
2159 vars = list_union(NIL, vars);
2161 if (list_length(vars) == 1)
2162 colname = get_attname(RelationGetRelid(rel),
2163 ((Var *) linitial(vars))->varattno);
2167 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2170 RelationGetNamespace(rel),
2173 /* save name for future checks */
2174 checknames = lappend(checknames, ccname);
2180 StoreRelCheck(rel, ccname, expr, is_local, is_local ? 0 : 1);
2184 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2185 cooked->contype = CONSTR_CHECK;
2186 cooked->name = ccname;
2188 cooked->expr = expr;
2189 cooked->is_local = is_local;
2190 cooked->inhcount = is_local ? 0 : 1;
2191 cookedConstraints = lappend(cookedConstraints, cooked);
2195 * Update the count of constraints in the relation's pg_class tuple. We do
2196 * this even if there was no change, in order to ensure that an SI update
2197 * message is sent out for the pg_class tuple, which will force other
2198 * backends to rebuild their relcache entries for the rel. (This is
2199 * critical if we added defaults but not constraints.)
2201 SetRelationNumChecks(rel, numchecks);
2203 return cookedConstraints;
2207 * Check for a pre-existing check constraint that conflicts with a proposed
2208 * new one, and either adjust its conislocal/coninhcount settings or throw
2211 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2212 * got a so-far-unique name, or throws error if conflict.
2215 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2216 bool allow_merge, bool is_local)
2220 SysScanDesc conscan;
2221 ScanKeyData skey[2];
2224 /* Search for a pg_constraint entry with same name and relation */
2225 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2229 ScanKeyInit(&skey[0],
2230 Anum_pg_constraint_conname,
2231 BTEqualStrategyNumber, F_NAMEEQ,
2232 CStringGetDatum(ccname));
2234 ScanKeyInit(&skey[1],
2235 Anum_pg_constraint_connamespace,
2236 BTEqualStrategyNumber, F_OIDEQ,
2237 ObjectIdGetDatum(RelationGetNamespace(rel)));
2239 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2240 SnapshotNow, 2, skey);
2242 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2244 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2246 if (con->conrelid == RelationGetRelid(rel))
2248 /* Found it. Conflicts if not identical check constraint */
2249 if (con->contype == CONSTRAINT_CHECK)
2254 val = fastgetattr(tup,
2255 Anum_pg_constraint_conbin,
2256 conDesc->rd_att, &isnull);
2258 elog(ERROR, "null conbin for rel %s",
2259 RelationGetRelationName(rel));
2260 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2263 if (!found || !allow_merge)
2265 (errcode(ERRCODE_DUPLICATE_OBJECT),
2266 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2267 ccname, RelationGetRelationName(rel))));
2268 /* OK to update the tuple */
2270 (errmsg("merging constraint \"%s\" with inherited definition",
2272 tup = heap_copytuple(tup);
2273 con = (Form_pg_constraint) GETSTRUCT(tup);
2275 con->conislocal = true;
2278 simple_heap_update(conDesc, &tup->t_self, tup);
2279 CatalogUpdateIndexes(conDesc, tup);
2284 systable_endscan(conscan);
2285 heap_close(conDesc, RowExclusiveLock);
2291 * Update the count of constraints in the relation's pg_class tuple.
2293 * Caller had better hold exclusive lock on the relation.
2295 * An important side effect is that a SI update message will be sent out for
2296 * the pg_class tuple, which will force other backends to rebuild their
2297 * relcache entries for the rel. Also, this backend will rebuild its
2298 * own relcache entry at the next CommandCounterIncrement.
2301 SetRelationNumChecks(Relation rel, int numchecks)
2305 Form_pg_class relStruct;
2307 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2308 reltup = SearchSysCacheCopy1(RELOID,
2309 ObjectIdGetDatum(RelationGetRelid(rel)));
2310 if (!HeapTupleIsValid(reltup))
2311 elog(ERROR, "cache lookup failed for relation %u",
2312 RelationGetRelid(rel));
2313 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2315 if (relStruct->relchecks != numchecks)
2317 relStruct->relchecks = numchecks;
2319 simple_heap_update(relrel, &reltup->t_self, reltup);
2321 /* keep catalog indexes current */
2322 CatalogUpdateIndexes(relrel, reltup);
2326 /* Skip the disk update, but force relcache inval anyway */
2327 CacheInvalidateRelcache(rel);
2330 heap_freetuple(reltup);
2331 heap_close(relrel, RowExclusiveLock);
2335 * Take a raw default and convert it to a cooked format ready for
2338 * Parse state should be set up to recognize any vars that might appear
2339 * in the expression. (Even though we plan to reject vars, it's more
2340 * user-friendly to give the correct error message than "unknown var".)
2342 * If atttypid is not InvalidOid, coerce the expression to the specified
2343 * type (and typmod atttypmod). attname is only needed in this case:
2344 * it is used in the error message, if any.
2347 cookDefault(ParseState *pstate,
2355 Assert(raw_default != NULL);
2358 * Transform raw parsetree to executable expression.
2360 expr = transformExpr(pstate, raw_default);
2363 * Make sure default expr does not refer to any vars.
2365 if (contain_var_clause(expr))
2367 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2368 errmsg("cannot use column references in default expression")));
2371 * It can't return a set either.
2373 if (expression_returns_set(expr))
2375 (errcode(ERRCODE_DATATYPE_MISMATCH),
2376 errmsg("default expression must not return a set")));
2379 * No subplans or aggregates, either...
2381 if (pstate->p_hasSubLinks)
2383 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2384 errmsg("cannot use subquery in default expression")));
2385 if (pstate->p_hasAggs)
2387 (errcode(ERRCODE_GROUPING_ERROR),
2388 errmsg("cannot use aggregate function in default expression")));
2389 if (pstate->p_hasWindowFuncs)
2391 (errcode(ERRCODE_WINDOWING_ERROR),
2392 errmsg("cannot use window function in default expression")));
2395 * Coerce the expression to the correct type and typmod, if given. This
2396 * should match the parser's processing of non-defaulted expressions ---
2397 * see transformAssignedExpr().
2399 if (OidIsValid(atttypid))
2401 Oid type_id = exprType(expr);
2403 expr = coerce_to_target_type(pstate, expr, type_id,
2404 atttypid, atttypmod,
2405 COERCION_ASSIGNMENT,
2406 COERCE_IMPLICIT_CAST,
2410 (errcode(ERRCODE_DATATYPE_MISMATCH),
2411 errmsg("column \"%s\" is of type %s"
2412 " but default expression is of type %s",
2414 format_type_be(atttypid),
2415 format_type_be(type_id)),
2416 errhint("You will need to rewrite or cast the expression.")));
2420 * Finally, take care of collations in the finished expression.
2422 assign_expr_collations(pstate, expr);
2428 * Take a raw CHECK constraint expression and convert it to a cooked format
2429 * ready for storage.
2431 * Parse state must be set up to recognize any vars that might appear
2432 * in the expression.
2435 cookConstraint(ParseState *pstate,
2436 Node *raw_constraint,
2442 * Transform raw parsetree to executable expression.
2444 expr = transformExpr(pstate, raw_constraint);
2447 * Make sure it yields a boolean result.
2449 expr = coerce_to_boolean(pstate, expr, "CHECK");
2452 * Take care of collations.
2454 assign_expr_collations(pstate, expr);
2457 * Make sure no outside relations are referred to.
2459 if (list_length(pstate->p_rtable) != 1)
2461 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2462 errmsg("only table \"%s\" can be referenced in check constraint",
2466 * No subplans or aggregates, either...
2468 if (pstate->p_hasSubLinks)
2470 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2471 errmsg("cannot use subquery in check constraint")));
2472 if (pstate->p_hasAggs)
2474 (errcode(ERRCODE_GROUPING_ERROR),
2475 errmsg("cannot use aggregate function in check constraint")));
2476 if (pstate->p_hasWindowFuncs)
2478 (errcode(ERRCODE_WINDOWING_ERROR),
2479 errmsg("cannot use window function in check constraint")));
2486 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2488 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2492 RemoveStatistics(Oid relid, AttrNumber attnum)
2494 Relation pgstatistic;
2500 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2502 ScanKeyInit(&key[0],
2503 Anum_pg_statistic_starelid,
2504 BTEqualStrategyNumber, F_OIDEQ,
2505 ObjectIdGetDatum(relid));
2511 ScanKeyInit(&key[1],
2512 Anum_pg_statistic_staattnum,
2513 BTEqualStrategyNumber, F_INT2EQ,
2514 Int16GetDatum(attnum));
2518 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2519 SnapshotNow, nkeys, key);
2521 /* we must loop even when attnum != 0, in case of inherited stats */
2522 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2523 simple_heap_delete(pgstatistic, &tuple->t_self);
2525 systable_endscan(scan);
2527 heap_close(pgstatistic, RowExclusiveLock);
2532 * RelationTruncateIndexes - truncate all indexes associated
2533 * with the heap relation to zero tuples.
2535 * The routine will truncate and then reconstruct the indexes on
2536 * the specified relation. Caller must hold exclusive lock on rel.
2539 RelationTruncateIndexes(Relation heapRelation)
2543 /* Ask the relcache to produce a list of the indexes of the rel */
2544 foreach(indlist, RelationGetIndexList(heapRelation))
2546 Oid indexId = lfirst_oid(indlist);
2547 Relation currentIndex;
2548 IndexInfo *indexInfo;
2550 /* Open the index relation; use exclusive lock, just to be sure */
2551 currentIndex = index_open(indexId, AccessExclusiveLock);
2553 /* Fetch info needed for index_build */
2554 indexInfo = BuildIndexInfo(currentIndex);
2557 * Now truncate the actual file (and discard buffers).
2559 RelationTruncate(currentIndex, 0);
2561 /* Initialize the index and rebuild */
2562 /* Note: we do not need to re-establish pkey setting */
2563 index_build(heapRelation, currentIndex, indexInfo, false, true);
2565 /* We're done with this index */
2566 index_close(currentIndex, NoLock);
2573 * This routine deletes all data within all the specified relations.
2575 * This is not transaction-safe! There is another, transaction-safe
2576 * implementation in commands/tablecmds.c. We now use this only for
2577 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2580 heap_truncate(List *relids)
2582 List *relations = NIL;
2585 /* Open relations for processing, and grab exclusive access on each */
2586 foreach(cell, relids)
2588 Oid rid = lfirst_oid(cell);
2591 rel = heap_open(rid, AccessExclusiveLock);
2592 relations = lappend(relations, rel);
2595 /* Don't allow truncate on tables that are referenced by foreign keys */
2596 heap_truncate_check_FKs(relations, true);
2599 foreach(cell, relations)
2601 Relation rel = lfirst(cell);
2603 /* Truncate the relation */
2604 heap_truncate_one_rel(rel);
2606 /* Close the relation, but keep exclusive lock on it until commit */
2607 heap_close(rel, NoLock);
2612 * heap_truncate_one_rel
2614 * This routine deletes all data within the specified relation.
2616 * This is not transaction-safe, because the truncation is done immediately
2617 * and cannot be rolled back later. Caller is responsible for having
2618 * checked permissions etc, and must have obtained AccessExclusiveLock.
2621 heap_truncate_one_rel(Relation rel)
2625 /* Truncate the actual file (and discard buffers) */
2626 RelationTruncate(rel, 0);
2628 /* If the relation has indexes, truncate the indexes too */
2629 RelationTruncateIndexes(rel);
2631 /* If there is a toast table, truncate that too */
2632 toastrelid = rel->rd_rel->reltoastrelid;
2633 if (OidIsValid(toastrelid))
2635 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2637 RelationTruncate(toastrel, 0);
2638 RelationTruncateIndexes(toastrel);
2639 /* keep the lock... */
2640 heap_close(toastrel, NoLock);
2645 * heap_truncate_check_FKs
2646 * Check for foreign keys referencing a list of relations that
2647 * are to be truncated, and raise error if there are any
2649 * We disallow such FKs (except self-referential ones) since the whole point
2650 * of TRUNCATE is to not scan the individual rows to be thrown away.
2652 * This is split out so it can be shared by both implementations of truncate.
2653 * Caller should already hold a suitable lock on the relations.
2655 * tempTables is only used to select an appropriate error message.
2658 heap_truncate_check_FKs(List *relations, bool tempTables)
2665 * Build a list of OIDs of the interesting relations.
2667 * If a relation has no triggers, then it can neither have FKs nor be
2668 * referenced by a FK from another table, so we can ignore it.
2670 foreach(cell, relations)
2672 Relation rel = lfirst(cell);
2674 if (rel->rd_rel->relhastriggers)
2675 oids = lappend_oid(oids, RelationGetRelid(rel));
2679 * Fast path: if no relation has triggers, none has FKs either.
2685 * Otherwise, must scan pg_constraint. We make one pass with all the
2686 * relations considered; if this finds nothing, then all is well.
2688 dependents = heap_truncate_find_FKs(oids);
2689 if (dependents == NIL)
2693 * Otherwise we repeat the scan once per relation to identify a particular
2694 * pair of relations to complain about. This is pretty slow, but
2695 * performance shouldn't matter much in a failure path. The reason for
2696 * doing things this way is to ensure that the message produced is not
2697 * dependent on chance row locations within pg_constraint.
2701 Oid relid = lfirst_oid(cell);
2704 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2706 foreach(cell2, dependents)
2708 Oid relid2 = lfirst_oid(cell2);
2710 if (!list_member_oid(oids, relid2))
2712 char *relname = get_rel_name(relid);
2713 char *relname2 = get_rel_name(relid2);
2717 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2718 errmsg("unsupported ON COMMIT and foreign key combination"),
2719 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2720 relname2, relname)));
2723 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2724 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2725 errdetail("Table \"%s\" references \"%s\".",
2727 errhint("Truncate table \"%s\" at the same time, "
2728 "or use TRUNCATE ... CASCADE.",
2736 * heap_truncate_find_FKs
2737 * Find relations having foreign keys referencing any of the given rels
2739 * Input and result are both lists of relation OIDs. The result contains
2740 * no duplicates, does *not* include any rels that were already in the input
2741 * list, and is sorted in OID order. (The last property is enforced mainly
2742 * to guarantee consistent behavior in the regression tests; we don't want
2743 * behavior to change depending on chance locations of rows in pg_constraint.)
2745 * Note: caller should already have appropriate lock on all rels mentioned
2746 * in relationIds. Since adding or dropping an FK requires exclusive lock
2747 * on both rels, this ensures that the answer will be stable.
2750 heap_truncate_find_FKs(List *relationIds)
2754 SysScanDesc fkeyScan;
2758 * Must scan pg_constraint. Right now, it is a seqscan because there is
2759 * no available index on confrelid.
2761 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
2763 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
2764 SnapshotNow, 0, NULL);
2766 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
2768 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
2770 /* Not a foreign key */
2771 if (con->contype != CONSTRAINT_FOREIGN)
2774 /* Not referencing one of our list of tables */
2775 if (!list_member_oid(relationIds, con->confrelid))
2778 /* Add referencer unless already in input or result list */
2779 if (!list_member_oid(relationIds, con->conrelid))
2780 result = insert_ordered_unique_oid(result, con->conrelid);
2783 systable_endscan(fkeyScan);
2784 heap_close(fkeyRel, AccessShareLock);
2790 * insert_ordered_unique_oid
2791 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2792 * and eliminating duplicates
2794 * Building the ordered list this way is O(N^2), but with a pretty small
2795 * constant, so for the number of entries we expect it will probably be
2796 * faster than trying to apply qsort(). It seems unlikely someone would be
2797 * trying to truncate a table with thousands of dependent tables ...
2800 insert_ordered_unique_oid(List *list, Oid datum)
2804 /* Does the datum belong at the front? */
2805 if (list == NIL || datum < linitial_oid(list))
2806 return lcons_oid(datum, list);
2807 /* Does it match the first entry? */
2808 if (datum == linitial_oid(list))
2809 return list; /* duplicate, so don't insert */
2810 /* No, so find the entry it belongs after */
2811 prev = list_head(list);
2814 ListCell *curr = lnext(prev);
2816 if (curr == NULL || datum < lfirst_oid(curr))
2817 break; /* it belongs after 'prev', before 'curr' */
2819 if (datum == lfirst_oid(curr))
2820 return list; /* duplicate, so don't insert */
2824 /* Insert datum into list after 'prev' */
2825 lappend_cell_oid(list, prev, datum);