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/partition.h"
45 #include "catalog/pg_attrdef.h"
46 #include "catalog/pg_collation.h"
47 #include "catalog/pg_constraint.h"
48 #include "catalog/pg_constraint_fn.h"
49 #include "catalog/pg_foreign_table.h"
50 #include "catalog/pg_inherits.h"
51 #include "catalog/pg_namespace.h"
52 #include "catalog/pg_opclass.h"
53 #include "catalog/pg_partitioned_table.h"
54 #include "catalog/pg_statistic.h"
55 #include "catalog/pg_tablespace.h"
56 #include "catalog/pg_type.h"
57 #include "catalog/pg_type_fn.h"
58 #include "catalog/storage.h"
59 #include "catalog/storage_xlog.h"
60 #include "commands/tablecmds.h"
61 #include "commands/typecmds.h"
62 #include "miscadmin.h"
63 #include "nodes/nodeFuncs.h"
64 #include "optimizer/var.h"
65 #include "parser/parse_coerce.h"
66 #include "parser/parse_collate.h"
67 #include "parser/parse_expr.h"
68 #include "parser/parse_relation.h"
69 #include "storage/predicate.h"
70 #include "storage/smgr.h"
71 #include "utils/acl.h"
72 #include "utils/builtins.h"
73 #include "utils/fmgroids.h"
74 #include "utils/inval.h"
75 #include "utils/lsyscache.h"
76 #include "utils/rel.h"
77 #include "utils/ruleutils.h"
78 #include "utils/snapmgr.h"
79 #include "utils/syscache.h"
80 #include "utils/tqual.h"
83 /* Potentially set by pg_upgrade_support functions */
84 Oid binary_upgrade_next_heap_pg_class_oid = InvalidOid;
85 Oid binary_upgrade_next_toast_pg_class_oid = InvalidOid;
87 static void AddNewRelationTuple(Relation pg_class_desc,
88 Relation new_rel_desc,
96 static ObjectAddress AddNewRelationType(const char *typeName,
103 static void RelationRemoveInheritance(Oid relid);
104 static Oid StoreRelCheck(Relation rel, char *ccname, Node *expr,
105 bool is_validated, bool is_local, int inhcount,
106 bool is_no_inherit, bool is_internal);
107 static void StoreConstraints(Relation rel, List *cooked_constraints,
109 static bool MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
110 bool allow_merge, bool is_local,
111 bool is_initially_valid,
113 static void SetRelationNumChecks(Relation rel, int numchecks);
114 static Node *cookConstraint(ParseState *pstate,
115 Node *raw_constraint,
117 static List *insert_ordered_unique_oid(List *list, Oid datum);
120 /* ----------------------------------------------------------------
121 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
123 * these should all be moved to someplace in the lib/catalog
124 * module, if not obliterated first.
125 * ----------------------------------------------------------------
131 * Should the system special case these attributes in the future?
132 * Advantage: consume much less space in the ATTRIBUTE relation.
133 * Disadvantage: special cases will be all over the place.
137 * The initializers below do not include trailing variable length fields,
138 * but that's OK - we're never going to reference anything beyond the
139 * fixed-size portion of the structure anyway.
142 static FormData_pg_attribute a1 = {
143 0, {"ctid"}, TIDOID, 0, sizeof(ItemPointerData),
144 SelfItemPointerAttributeNumber, 0, -1, -1,
145 false, 'p', 's', true, false, false, true, 0
148 static FormData_pg_attribute a2 = {
149 0, {"oid"}, OIDOID, 0, sizeof(Oid),
150 ObjectIdAttributeNumber, 0, -1, -1,
151 true, 'p', 'i', true, false, false, true, 0
154 static FormData_pg_attribute a3 = {
155 0, {"xmin"}, XIDOID, 0, sizeof(TransactionId),
156 MinTransactionIdAttributeNumber, 0, -1, -1,
157 true, 'p', 'i', true, false, false, true, 0
160 static FormData_pg_attribute a4 = {
161 0, {"cmin"}, CIDOID, 0, sizeof(CommandId),
162 MinCommandIdAttributeNumber, 0, -1, -1,
163 true, 'p', 'i', true, false, false, true, 0
166 static FormData_pg_attribute a5 = {
167 0, {"xmax"}, XIDOID, 0, sizeof(TransactionId),
168 MaxTransactionIdAttributeNumber, 0, -1, -1,
169 true, 'p', 'i', true, false, false, true, 0
172 static FormData_pg_attribute a6 = {
173 0, {"cmax"}, CIDOID, 0, sizeof(CommandId),
174 MaxCommandIdAttributeNumber, 0, -1, -1,
175 true, 'p', 'i', true, false, false, true, 0
179 * We decided to call this attribute "tableoid" rather than say
180 * "classoid" on the basis that in the future there may be more than one
181 * table of a particular class/type. In any case table is still the word
184 static FormData_pg_attribute a7 = {
185 0, {"tableoid"}, OIDOID, 0, sizeof(Oid),
186 TableOidAttributeNumber, 0, -1, -1,
187 true, 'p', 'i', true, false, false, true, 0
190 static const Form_pg_attribute SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6, &a7};
193 * This function returns a Form_pg_attribute pointer for a system attribute.
194 * Note that we elog if the presented attno is invalid, which would only
195 * happen if there's a problem upstream.
198 SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
200 if (attno >= 0 || attno < -(int) lengthof(SysAtt))
201 elog(ERROR, "invalid system attribute number %d", attno);
202 if (attno == ObjectIdAttributeNumber && !relhasoids)
203 elog(ERROR, "invalid system attribute number %d", attno);
204 return SysAtt[-attno - 1];
208 * If the given name is a system attribute name, return a Form_pg_attribute
209 * pointer for a prototype definition. If not, return NULL.
212 SystemAttributeByName(const char *attname, bool relhasoids)
216 for (j = 0; j < (int) lengthof(SysAtt); j++)
218 Form_pg_attribute att = SysAtt[j];
220 if (relhasoids || att->attnum != ObjectIdAttributeNumber)
222 if (strcmp(NameStr(att->attname), attname) == 0)
231 /* ----------------------------------------------------------------
232 * XXX END OF UGLY HARD CODED BADNESS XXX
233 * ---------------------------------------------------------------- */
236 /* ----------------------------------------------------------------
237 * heap_create - Create an uncataloged heap relation
239 * Note API change: the caller must now always provide the OID
240 * to use for the relation. The relfilenode may (and, normally,
241 * should) be left unspecified.
243 * rel->rd_rel is initialized by RelationBuildLocalRelation,
244 * and is mostly zeroes at return.
245 * ----------------------------------------------------------------
248 heap_create(const char *relname,
256 bool shared_relation,
257 bool mapped_relation,
258 bool allow_system_table_mods)
263 /* The caller must have provided an OID for the relation. */
264 Assert(OidIsValid(relid));
267 * Don't allow creating relations in pg_catalog directly, even though it
268 * is allowed to move user defined relations there. Semantics with search
269 * paths including pg_catalog are too confusing for now.
271 * But allow creating indexes on relations in pg_catalog even if
272 * allow_system_table_mods = off, upper layers already guarantee it's on a
273 * user defined relation, not a system one.
275 if (!allow_system_table_mods &&
276 ((IsSystemNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
277 IsToastNamespace(relnamespace)) &&
278 IsNormalProcessingMode())
280 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
281 errmsg("permission denied to create \"%s.%s\"",
282 get_namespace_name(relnamespace), relname),
283 errdetail("System catalog modifications are currently disallowed.")));
286 * Decide if we need storage or not, and handle a couple other special
287 * cases for particular relkinds.
292 case RELKIND_COMPOSITE_TYPE:
293 case RELKIND_FOREIGN_TABLE:
294 create_storage = false;
297 * Force reltablespace to zero if the relation has no physical
298 * storage. This is mainly just for cleanliness' sake.
300 reltablespace = InvalidOid;
302 case RELKIND_SEQUENCE:
303 create_storage = true;
306 * Force reltablespace to zero for sequences, since we don't
307 * support moving them around into different tablespaces.
309 reltablespace = InvalidOid;
312 create_storage = true;
317 * Unless otherwise requested, the physical ID (relfilenode) is initially
318 * the same as the logical ID (OID). When the caller did specify a
319 * relfilenode, it already exists; do not attempt to create it.
321 if (OidIsValid(relfilenode))
322 create_storage = false;
327 * Never allow a pg_class entry to explicitly specify the database's
328 * default tablespace in reltablespace; force it to zero instead. This
329 * ensures that if the database is cloned with a different default
330 * tablespace, the pg_class entry will still match where CREATE DATABASE
331 * will put the physically copied relation.
333 * Yes, this is a bit of a hack.
335 if (reltablespace == MyDatabaseTableSpace)
336 reltablespace = InvalidOid;
339 * build the relcache entry.
341 rel = RelationBuildLocalRelation(relname,
353 * Have the storage manager create the relation's disk file, if needed.
355 * We only create the main fork here, other forks will be created on
360 RelationOpenSmgr(rel);
361 RelationCreateStorage(rel->rd_node, relpersistence);
367 /* ----------------------------------------------------------------
368 * heap_create_with_catalog - Create a cataloged relation
370 * this is done in multiple steps:
372 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
373 * descriptor contains a valid set of attribute names and types
375 * 2) pg_class is opened and get_relname_relid()
376 * performs a scan to ensure that no relation with the
377 * same name already exists.
379 * 3) heap_create() is called to create the new relation on disk.
381 * 4) TypeCreate() is called to define a new type corresponding
382 * to the new relation.
384 * 5) AddNewRelationTuple() is called to register the
385 * relation in pg_class.
387 * 6) AddNewAttributeTuples() is called to register the
388 * new relation's schema in pg_attribute.
390 * 7) StoreConstraints is called () - vadim 08/22/97
392 * 8) the relations are closed and the new relation's oid
395 * ----------------------------------------------------------------
398 /* --------------------------------
399 * CheckAttributeNamesTypes
401 * this is used to make certain the tuple descriptor contains a
402 * valid set of attribute names and datatypes. a problem simply
403 * generates ereport(ERROR) which aborts the current transaction.
404 * --------------------------------
407 CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
408 bool allow_system_table_mods)
412 int natts = tupdesc->natts;
414 /* Sanity check on column count */
415 if (natts < 0 || natts > MaxHeapAttributeNumber)
417 (errcode(ERRCODE_TOO_MANY_COLUMNS),
418 errmsg("tables can have at most %d columns",
419 MaxHeapAttributeNumber)));
422 * first check for collision with system attribute names
424 * Skip this for a view or type relation, since those don't have system
427 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
429 for (i = 0; i < natts; i++)
431 if (SystemAttributeByName(NameStr(tupdesc->attrs[i]->attname),
432 tupdesc->tdhasoid) != NULL)
434 (errcode(ERRCODE_DUPLICATE_COLUMN),
435 errmsg("column name \"%s\" conflicts with a system column name",
436 NameStr(tupdesc->attrs[i]->attname))));
441 * next check for repeated attribute names
443 for (i = 1; i < natts; i++)
445 for (j = 0; j < i; j++)
447 if (strcmp(NameStr(tupdesc->attrs[j]->attname),
448 NameStr(tupdesc->attrs[i]->attname)) == 0)
450 (errcode(ERRCODE_DUPLICATE_COLUMN),
451 errmsg("column name \"%s\" specified more than once",
452 NameStr(tupdesc->attrs[j]->attname))));
457 * next check the attribute types
459 for (i = 0; i < natts; i++)
461 CheckAttributeType(NameStr(tupdesc->attrs[i]->attname),
462 tupdesc->attrs[i]->atttypid,
463 tupdesc->attrs[i]->attcollation,
464 NIL, /* assume we're creating a new rowtype */
465 allow_system_table_mods);
469 /* --------------------------------
472 * Verify that the proposed datatype of an attribute is legal.
473 * This is needed mainly because there are types (and pseudo-types)
474 * in the catalogs that we do not support as elements of real tuples.
475 * We also check some other properties required of a table column.
477 * If the attribute is being proposed for addition to an existing table or
478 * composite type, pass a one-element list of the rowtype OID as
479 * containing_rowtypes. When checking a to-be-created rowtype, it's
480 * sufficient to pass NIL, because there could not be any recursive reference
481 * to a not-yet-existing rowtype.
482 * --------------------------------
485 CheckAttributeType(const char *attname,
486 Oid atttypid, Oid attcollation,
487 List *containing_rowtypes,
488 bool allow_system_table_mods)
490 char att_typtype = get_typtype(atttypid);
493 if (atttypid == UNKNOWNOID)
496 * Warn user, but don't fail, if column to be created has UNKNOWN type
497 * (usually as a result of a 'retrieve into' - jolly)
500 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
501 errmsg("column \"%s\" has type \"unknown\"", attname),
502 errdetail("Proceeding with relation creation anyway.")));
504 else if (att_typtype == TYPTYPE_PSEUDO)
507 * Refuse any attempt to create a pseudo-type column, except for a
508 * special hack for pg_statistic: allow ANYARRAY when modifying system
509 * catalogs (this allows creating pg_statistic and cloning it during
512 if (atttypid != ANYARRAYOID || !allow_system_table_mods)
514 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
515 errmsg("column \"%s\" has pseudo-type %s",
516 attname, format_type_be(atttypid))));
518 else if (att_typtype == TYPTYPE_DOMAIN)
521 * If it's a domain, recurse to check its base type.
523 CheckAttributeType(attname, getBaseType(atttypid), attcollation,
525 allow_system_table_mods);
527 else if (att_typtype == TYPTYPE_COMPOSITE)
530 * For a composite type, recurse into its attributes.
537 * Check for self-containment. Eventually we might be able to allow
538 * this (just return without complaint, if so) but it's not clear how
539 * many other places would require anti-recursion defenses before it
540 * would be safe to allow tables to contain their own rowtype.
542 if (list_member_oid(containing_rowtypes, atttypid))
544 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
545 errmsg("composite type %s cannot be made a member of itself",
546 format_type_be(atttypid))));
548 containing_rowtypes = lcons_oid(atttypid, containing_rowtypes);
550 relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
552 tupdesc = RelationGetDescr(relation);
554 for (i = 0; i < tupdesc->natts; i++)
556 Form_pg_attribute attr = tupdesc->attrs[i];
558 if (attr->attisdropped)
560 CheckAttributeType(NameStr(attr->attname),
561 attr->atttypid, attr->attcollation,
563 allow_system_table_mods);
566 relation_close(relation, AccessShareLock);
568 containing_rowtypes = list_delete_first(containing_rowtypes);
570 else if (OidIsValid((att_typelem = get_element_type(atttypid))))
573 * Must recurse into array types, too, in case they are composite.
575 CheckAttributeType(attname, att_typelem, attcollation,
577 allow_system_table_mods);
581 * This might not be strictly invalid per SQL standard, but it is pretty
582 * useless, and it cannot be dumped, so we must disallow it.
584 if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
586 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
587 errmsg("no collation was derived for column \"%s\" with collatable type %s",
588 attname, format_type_be(atttypid)),
589 errhint("Use the COLLATE clause to set the collation explicitly.")));
593 * InsertPgAttributeTuple
594 * Construct and insert a new tuple in pg_attribute.
596 * Caller has already opened and locked pg_attribute. new_attribute is the
597 * attribute to insert (but we ignore attacl and attoptions, which are always
598 * initialized to NULL).
600 * indstate is the index state for CatalogIndexInsert. It can be passed as
601 * NULL, in which case we'll fetch the necessary info. (Don't do this when
602 * inserting multiple attributes, because it's a tad more expensive.)
605 InsertPgAttributeTuple(Relation pg_attribute_rel,
606 Form_pg_attribute new_attribute,
607 CatalogIndexState indstate)
609 Datum values[Natts_pg_attribute];
610 bool nulls[Natts_pg_attribute];
613 /* This is a tad tedious, but way cleaner than what we used to do... */
614 memset(values, 0, sizeof(values));
615 memset(nulls, false, sizeof(nulls));
617 values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_attribute->attrelid);
618 values[Anum_pg_attribute_attname - 1] = NameGetDatum(&new_attribute->attname);
619 values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(new_attribute->atttypid);
620 values[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(new_attribute->attstattarget);
621 values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(new_attribute->attlen);
622 values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(new_attribute->attnum);
623 values[Anum_pg_attribute_attndims - 1] = Int32GetDatum(new_attribute->attndims);
624 values[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(new_attribute->attcacheoff);
625 values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(new_attribute->atttypmod);
626 values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(new_attribute->attbyval);
627 values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(new_attribute->attstorage);
628 values[Anum_pg_attribute_attalign - 1] = CharGetDatum(new_attribute->attalign);
629 values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(new_attribute->attnotnull);
630 values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(new_attribute->atthasdef);
631 values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(new_attribute->attisdropped);
632 values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(new_attribute->attislocal);
633 values[Anum_pg_attribute_attinhcount - 1] = Int32GetDatum(new_attribute->attinhcount);
634 values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(new_attribute->attcollation);
636 /* start out with empty permissions and empty options */
637 nulls[Anum_pg_attribute_attacl - 1] = true;
638 nulls[Anum_pg_attribute_attoptions - 1] = true;
639 nulls[Anum_pg_attribute_attfdwoptions - 1] = true;
641 tup = heap_form_tuple(RelationGetDescr(pg_attribute_rel), values, nulls);
643 /* finally insert the new tuple, update the indexes, and clean up */
644 simple_heap_insert(pg_attribute_rel, tup);
646 if (indstate != NULL)
647 CatalogIndexInsert(indstate, tup);
649 CatalogUpdateIndexes(pg_attribute_rel, tup);
654 /* --------------------------------
655 * AddNewAttributeTuples
657 * this registers the new relation's schema by adding
658 * tuples to pg_attribute.
659 * --------------------------------
662 AddNewAttributeTuples(Oid new_rel_oid,
668 Form_pg_attribute attr;
671 CatalogIndexState indstate;
672 int natts = tupdesc->natts;
673 ObjectAddress myself,
677 * open pg_attribute and its indexes.
679 rel = heap_open(AttributeRelationId, RowExclusiveLock);
681 indstate = CatalogOpenIndexes(rel);
684 * First we add the user attributes. This is also a convenient place to
685 * add dependencies on their datatypes and collations.
687 for (i = 0; i < natts; i++)
689 attr = tupdesc->attrs[i];
690 /* Fill in the correct relation OID */
691 attr->attrelid = new_rel_oid;
692 /* Make sure these are OK, too */
693 attr->attstattarget = -1;
694 attr->attcacheoff = -1;
696 InsertPgAttributeTuple(rel, attr, indstate);
698 /* Add dependency info */
699 myself.classId = RelationRelationId;
700 myself.objectId = new_rel_oid;
701 myself.objectSubId = i + 1;
702 referenced.classId = TypeRelationId;
703 referenced.objectId = attr->atttypid;
704 referenced.objectSubId = 0;
705 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
707 /* The default collation is pinned, so don't bother recording it */
708 if (OidIsValid(attr->attcollation) &&
709 attr->attcollation != DEFAULT_COLLATION_OID)
711 referenced.classId = CollationRelationId;
712 referenced.objectId = attr->attcollation;
713 referenced.objectSubId = 0;
714 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
719 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
720 * all for a view or type relation. We don't bother with making datatype
721 * dependencies here, since presumably all these types are pinned.
723 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
725 for (i = 0; i < (int) lengthof(SysAtt); i++)
727 FormData_pg_attribute attStruct;
729 /* skip OID where appropriate */
730 if (!tupdesc->tdhasoid &&
731 SysAtt[i]->attnum == ObjectIdAttributeNumber)
734 memcpy(&attStruct, (char *) SysAtt[i], sizeof(FormData_pg_attribute));
736 /* Fill in the correct relation OID in the copied tuple */
737 attStruct.attrelid = new_rel_oid;
739 /* Fill in correct inheritance info for the OID column */
740 if (attStruct.attnum == ObjectIdAttributeNumber)
742 attStruct.attislocal = oidislocal;
743 attStruct.attinhcount = oidinhcount;
746 InsertPgAttributeTuple(rel, &attStruct, indstate);
753 CatalogCloseIndexes(indstate);
755 heap_close(rel, RowExclusiveLock);
758 /* --------------------------------
761 * Construct and insert a new tuple in pg_class.
763 * Caller has already opened and locked pg_class.
764 * Tuple data is taken from new_rel_desc->rd_rel, except for the
765 * variable-width fields which are not present in a cached reldesc.
766 * relacl and reloptions are passed in Datum form (to avoid having
767 * to reference the data types in heap.h). Pass (Datum) 0 to set them
769 * --------------------------------
772 InsertPgClassTuple(Relation pg_class_desc,
773 Relation new_rel_desc,
778 Form_pg_class rd_rel = new_rel_desc->rd_rel;
779 Datum values[Natts_pg_class];
780 bool nulls[Natts_pg_class];
783 /* This is a tad tedious, but way cleaner than what we used to do... */
784 memset(values, 0, sizeof(values));
785 memset(nulls, false, sizeof(nulls));
787 values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
788 values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
789 values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
790 values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
791 values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
792 values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
793 values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
794 values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
795 values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
796 values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
797 values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
798 values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
799 values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
800 values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
801 values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
802 values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
803 values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
804 values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
805 values[Anum_pg_class_relhasoids - 1] = BoolGetDatum(rd_rel->relhasoids);
806 values[Anum_pg_class_relhaspkey - 1] = BoolGetDatum(rd_rel->relhaspkey);
807 values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
808 values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
809 values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
810 values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
811 values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
812 values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
813 values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
814 values[Anum_pg_class_relispartition - 1] = BoolGetDatum(rd_rel->relispartition);
815 values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
816 values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
817 if (relacl != (Datum) 0)
818 values[Anum_pg_class_relacl - 1] = relacl;
820 nulls[Anum_pg_class_relacl - 1] = true;
821 if (reloptions != (Datum) 0)
822 values[Anum_pg_class_reloptions - 1] = reloptions;
824 nulls[Anum_pg_class_reloptions - 1] = true;
826 /* relpartbound is set by updating this tuple, if necessary */
827 nulls[Anum_pg_class_relpartbound - 1] = true;
829 tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
832 * The new tuple must have the oid already chosen for the rel. Sure would
833 * be embarrassing to do this sort of thing in polite company.
835 HeapTupleSetOid(tup, new_rel_oid);
837 /* finally insert the new tuple, update the indexes, and clean up */
838 simple_heap_insert(pg_class_desc, tup);
840 CatalogUpdateIndexes(pg_class_desc, tup);
845 /* --------------------------------
846 * AddNewRelationTuple
848 * this registers the new relation in the catalogs by
849 * adding a tuple to pg_class.
850 * --------------------------------
853 AddNewRelationTuple(Relation pg_class_desc,
854 Relation new_rel_desc,
863 Form_pg_class new_rel_reltup;
866 * first we update some of the information in our uncataloged relation's
867 * relation descriptor.
869 new_rel_reltup = new_rel_desc->rd_rel;
873 case RELKIND_RELATION:
874 case RELKIND_MATVIEW:
876 case RELKIND_TOASTVALUE:
877 /* The relation is real, but as yet empty */
878 new_rel_reltup->relpages = 0;
879 new_rel_reltup->reltuples = 0;
880 new_rel_reltup->relallvisible = 0;
882 case RELKIND_SEQUENCE:
883 /* Sequences always have a known size */
884 new_rel_reltup->relpages = 1;
885 new_rel_reltup->reltuples = 1;
886 new_rel_reltup->relallvisible = 0;
889 /* Views, etc, have no disk storage */
890 new_rel_reltup->relpages = 0;
891 new_rel_reltup->reltuples = 0;
892 new_rel_reltup->relallvisible = 0;
896 /* Initialize relfrozenxid and relminmxid */
897 if (relkind == RELKIND_RELATION ||
898 relkind == RELKIND_MATVIEW ||
899 relkind == RELKIND_TOASTVALUE)
902 * Initialize to the minimum XID that could put tuples in the table.
903 * We know that no xacts older than RecentXmin are still running, so
906 new_rel_reltup->relfrozenxid = RecentXmin;
909 * Similarly, initialize the minimum Multixact to the first value that
910 * could possibly be stored in tuples in the table. Running
911 * transactions could reuse values from their local cache, so we are
912 * careful to consider all currently running multis.
914 * XXX this could be refined further, but is it worth the hassle?
916 new_rel_reltup->relminmxid = GetOldestMultiXactId();
921 * Other relation types will not contain XIDs, so set relfrozenxid to
922 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
923 * we force its xmin to be FrozenTransactionId always; see
924 * commands/sequence.c.)
926 new_rel_reltup->relfrozenxid = InvalidTransactionId;
927 new_rel_reltup->relminmxid = InvalidMultiXactId;
930 new_rel_reltup->relowner = relowner;
931 new_rel_reltup->reltype = new_type_oid;
932 new_rel_reltup->reloftype = reloftype;
934 /* relispartition is always set by updating this tuple later */
935 new_rel_reltup->relispartition = false;
937 new_rel_desc->rd_att->tdtypeid = new_type_oid;
939 /* Now build and insert the tuple */
940 InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
945 /* --------------------------------
946 * AddNewRelationType -
948 * define a composite type corresponding to the new relation
949 * --------------------------------
952 AddNewRelationType(const char *typeName,
961 TypeCreate(new_row_type, /* optional predetermined OID */
962 typeName, /* type name */
963 typeNamespace, /* type namespace */
964 new_rel_oid, /* relation oid */
965 new_rel_kind, /* relation kind */
966 ownerid, /* owner's ID */
967 -1, /* internal size (varlena) */
968 TYPTYPE_COMPOSITE, /* type-type (composite) */
969 TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
970 false, /* composite types are never preferred */
971 DEFAULT_TYPDELIM, /* default array delimiter */
972 F_RECORD_IN, /* input procedure */
973 F_RECORD_OUT, /* output procedure */
974 F_RECORD_RECV, /* receive procedure */
975 F_RECORD_SEND, /* send procedure */
976 InvalidOid, /* typmodin procedure - none */
977 InvalidOid, /* typmodout procedure - none */
978 InvalidOid, /* analyze procedure - default */
979 InvalidOid, /* array element type - irrelevant */
980 false, /* this is not an array type */
981 new_array_type, /* array type if any */
982 InvalidOid, /* domain base type - irrelevant */
983 NULL, /* default value - none */
984 NULL, /* default binary representation */
985 false, /* passed by reference */
986 'd', /* alignment - must be the largest! */
987 'x', /* fully TOASTable */
989 0, /* array dimensions for typBaseType */
990 false, /* Type NOT NULL */
991 InvalidOid); /* rowtypes never have a collation */
994 /* --------------------------------
995 * heap_create_with_catalog
997 * creates a new cataloged relation. see comments above.
1000 * relname: name to give to new rel
1001 * relnamespace: OID of namespace it goes in
1002 * reltablespace: OID of tablespace it goes in
1003 * relid: OID to assign to new rel, or InvalidOid to select a new OID
1004 * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
1005 * reloftypeid: if a typed table, OID of underlying type; else InvalidOid
1006 * ownerid: OID of new rel's owner
1007 * tupdesc: tuple descriptor (source of column definitions)
1008 * cooked_constraints: list of precooked check constraints and defaults
1009 * relkind: relkind for new rel
1010 * relpersistence: rel's persistence status (permanent, temp, or unlogged)
1011 * shared_relation: TRUE if it's to be a shared relation
1012 * mapped_relation: TRUE if the relation will use the relfilenode map
1013 * oidislocal: TRUE if oid column (if any) should be marked attislocal
1014 * oidinhcount: attinhcount to assign to oid column (if any)
1015 * oncommit: ON COMMIT marking (only relevant if it's a temp table)
1016 * reloptions: reloptions in Datum form, or (Datum) 0 if none
1017 * use_user_acl: TRUE if should look for user-defined default permissions;
1018 * if FALSE, relacl is always set NULL
1019 * allow_system_table_mods: TRUE to allow creation in system namespaces
1020 * is_internal: is this a system-generated catalog?
1022 * Output parameters:
1023 * typaddress: if not null, gets the object address of the new pg_type entry
1025 * Returns the OID of the new relation
1026 * --------------------------------
1029 heap_create_with_catalog(const char *relname,
1037 List *cooked_constraints,
1039 char relpersistence,
1040 bool shared_relation,
1041 bool mapped_relation,
1044 OnCommitAction oncommit,
1047 bool allow_system_table_mods,
1049 ObjectAddress *typaddress)
1051 Relation pg_class_desc;
1052 Relation new_rel_desc;
1057 ObjectAddress new_type_addr;
1058 Oid new_array_oid = InvalidOid;
1060 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1065 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
1067 CheckAttributeNamesTypes(tupdesc, relkind, allow_system_table_mods);
1070 * This would fail later on anyway, if the relation already exists. But
1071 * by catching it here we can emit a nicer error message.
1073 existing_relid = get_relname_relid(relname, relnamespace);
1074 if (existing_relid != InvalidOid)
1076 (errcode(ERRCODE_DUPLICATE_TABLE),
1077 errmsg("relation \"%s\" already exists", relname)));
1080 * Since we are going to create a rowtype as well, also check for
1081 * collision with an existing type name. If there is one and it's an
1082 * autogenerated array, we can rename it out of the way; otherwise we can
1083 * at least give a good error message.
1085 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1086 CStringGetDatum(relname),
1087 ObjectIdGetDatum(relnamespace));
1088 if (OidIsValid(old_type_oid))
1090 if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1092 (errcode(ERRCODE_DUPLICATE_OBJECT),
1093 errmsg("type \"%s\" already exists", relname),
1094 errhint("A relation has an associated type of the same name, "
1095 "so you must use a name that doesn't conflict "
1096 "with any existing type.")));
1100 * Shared relations must be in pg_global (last-ditch check)
1102 if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1103 elog(ERROR, "shared relations must be placed in pg_global tablespace");
1106 * Allocate an OID for the relation, unless we were told what to use.
1108 * The OID will be the relfilenode as well, so make sure it doesn't
1109 * collide with either pg_class OIDs or existing physical files.
1111 if (!OidIsValid(relid))
1113 /* Use binary-upgrade override for pg_class.oid/relfilenode? */
1114 if (IsBinaryUpgrade &&
1115 (relkind == RELKIND_RELATION || relkind == RELKIND_SEQUENCE ||
1116 relkind == RELKIND_VIEW || relkind == RELKIND_MATVIEW ||
1117 relkind == RELKIND_COMPOSITE_TYPE || relkind == RELKIND_FOREIGN_TABLE ||
1118 relkind == RELKIND_PARTITIONED_TABLE))
1120 if (!OidIsValid(binary_upgrade_next_heap_pg_class_oid))
1122 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1123 errmsg("pg_class heap OID value not set when in binary upgrade mode")));
1125 relid = binary_upgrade_next_heap_pg_class_oid;
1126 binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1128 /* There might be no TOAST table, so we have to test for it. */
1129 else if (IsBinaryUpgrade &&
1130 OidIsValid(binary_upgrade_next_toast_pg_class_oid) &&
1131 relkind == RELKIND_TOASTVALUE)
1133 relid = binary_upgrade_next_toast_pg_class_oid;
1134 binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1137 relid = GetNewRelFileNode(reltablespace, pg_class_desc,
1142 * Determine the relation's initial permissions.
1148 case RELKIND_RELATION:
1150 case RELKIND_MATVIEW:
1151 case RELKIND_FOREIGN_TABLE:
1152 case RELKIND_PARTITIONED_TABLE:
1153 relacl = get_user_default_acl(ACL_OBJECT_RELATION, ownerid,
1156 case RELKIND_SEQUENCE:
1157 relacl = get_user_default_acl(ACL_OBJECT_SEQUENCE, ownerid,
1169 * Create the relcache entry (mostly dummy at this point) and the physical
1170 * disk file. (If we fail further down, it's the smgr's responsibility to
1171 * remove the disk file again.)
1173 new_rel_desc = heap_create(relname,
1183 allow_system_table_mods);
1185 Assert(relid == RelationGetRelid(new_rel_desc));
1188 * Decide whether to create an array type over the relation's rowtype. We
1189 * do not create any array types for system catalogs (ie, those made
1190 * during initdb). We do not create them where the use of a relation as
1191 * such is an implementation detail: toast tables, sequences and indexes.
1193 if (IsUnderPostmaster && (relkind == RELKIND_RELATION ||
1194 relkind == RELKIND_VIEW ||
1195 relkind == RELKIND_MATVIEW ||
1196 relkind == RELKIND_FOREIGN_TABLE ||
1197 relkind == RELKIND_COMPOSITE_TYPE ||
1198 relkind == RELKIND_PARTITIONED_TABLE))
1199 new_array_oid = AssignTypeArrayOid();
1202 * Since defining a relation also defines a complex type, we add a new
1203 * system type corresponding to the new relation. The OID of the type can
1204 * be preselected by the caller, but if reltypeid is InvalidOid, we'll
1205 * generate a new OID for it.
1207 * NOTE: we could get a unique-index failure here, in case someone else is
1208 * creating the same type name in parallel but hadn't committed yet when
1209 * we checked for a duplicate name above.
1211 new_type_addr = AddNewRelationType(relname,
1218 new_type_oid = new_type_addr.objectId;
1220 *typaddress = new_type_addr;
1223 * Now make the array type if wanted.
1225 if (OidIsValid(new_array_oid))
1229 relarrayname = makeArrayTypeName(relname, relnamespace);
1231 TypeCreate(new_array_oid, /* force the type's OID to this */
1232 relarrayname, /* Array type name */
1233 relnamespace, /* Same namespace as parent */
1234 InvalidOid, /* Not composite, no relationOid */
1235 0, /* relkind, also N/A here */
1236 ownerid, /* owner's ID */
1237 -1, /* Internal size (varlena) */
1238 TYPTYPE_BASE, /* Not composite - typelem is */
1239 TYPCATEGORY_ARRAY, /* type-category (array) */
1240 false, /* array types are never preferred */
1241 DEFAULT_TYPDELIM, /* default array delimiter */
1242 F_ARRAY_IN, /* array input proc */
1243 F_ARRAY_OUT, /* array output proc */
1244 F_ARRAY_RECV, /* array recv (bin) proc */
1245 F_ARRAY_SEND, /* array send (bin) proc */
1246 InvalidOid, /* typmodin procedure - none */
1247 InvalidOid, /* typmodout procedure - none */
1248 F_ARRAY_TYPANALYZE, /* array analyze procedure */
1249 new_type_oid, /* array element type - the rowtype */
1250 true, /* yes, this is an array type */
1251 InvalidOid, /* this has no array type */
1252 InvalidOid, /* domain base type - irrelevant */
1253 NULL, /* default value - none */
1254 NULL, /* default binary representation */
1255 false, /* passed by reference */
1256 'd', /* alignment - must be the largest! */
1257 'x', /* fully TOASTable */
1259 0, /* array dimensions for typBaseType */
1260 false, /* Type NOT NULL */
1261 InvalidOid); /* rowtypes never have a collation */
1263 pfree(relarrayname);
1267 * now create an entry in pg_class for the relation.
1269 * NOTE: we could get a unique-index failure here, in case someone else is
1270 * creating the same relation name in parallel but hadn't committed yet
1271 * when we checked for a duplicate name above.
1273 AddNewRelationTuple(pg_class_desc,
1280 PointerGetDatum(relacl),
1284 * now add tuples to pg_attribute for the attributes in our new relation.
1286 AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind,
1287 oidislocal, oidinhcount);
1290 * Make a dependency link to force the relation to be deleted if its
1291 * namespace is. Also make a dependency link to its owner, as well as
1292 * dependencies for any roles mentioned in the default ACL.
1294 * For composite types, these dependencies are tracked for the pg_type
1295 * entry, so we needn't record them here. Likewise, TOAST tables don't
1296 * need a namespace dependency (they live in a pinned namespace) nor an
1297 * owner dependency (they depend indirectly through the parent table), nor
1298 * should they have any ACL entries. The same applies for extension
1301 * Also, skip this in bootstrap mode, since we don't make dependencies
1302 * while bootstrapping.
1304 if (relkind != RELKIND_COMPOSITE_TYPE &&
1305 relkind != RELKIND_TOASTVALUE &&
1306 !IsBootstrapProcessingMode())
1308 ObjectAddress myself,
1311 myself.classId = RelationRelationId;
1312 myself.objectId = relid;
1313 myself.objectSubId = 0;
1314 referenced.classId = NamespaceRelationId;
1315 referenced.objectId = relnamespace;
1316 referenced.objectSubId = 0;
1317 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1319 recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1321 recordDependencyOnCurrentExtension(&myself, false);
1325 referenced.classId = TypeRelationId;
1326 referenced.objectId = reloftypeid;
1327 referenced.objectSubId = 0;
1328 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1336 nnewmembers = aclmembers(relacl, &newmembers);
1337 updateAclDependencies(RelationRelationId, relid, 0,
1340 nnewmembers, newmembers);
1344 /* Post creation hook for new relation */
1345 InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
1348 * Store any supplied constraints and defaults.
1350 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1351 * entry, so the relation must be valid and self-consistent at this point.
1352 * In particular, there are not yet constraints and defaults anywhere.
1354 StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
1357 * If there's a special on-commit action, remember it
1359 if (oncommit != ONCOMMIT_NOOP)
1360 register_on_commit_action(relid, oncommit);
1362 if (relpersistence == RELPERSISTENCE_UNLOGGED)
1364 Assert(relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW ||
1365 relkind == RELKIND_TOASTVALUE ||
1366 relkind == RELKIND_PARTITIONED_TABLE);
1368 heap_create_init_fork(new_rel_desc);
1372 * ok, the relation has been cataloged, so close our relations and return
1373 * the OID of the newly created relation.
1375 heap_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1376 heap_close(pg_class_desc, RowExclusiveLock);
1382 * Set up an init fork for an unlogged table so that it can be correctly
1383 * reinitialized on restart. An immediate sync is required even if the
1384 * page has been logged, because the write did not go through
1385 * shared_buffers and therefore a concurrent checkpoint may have moved
1386 * the redo pointer past our xlog record. Recovery may as well remove it
1387 * while replaying, for example, XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE
1388 * record. Therefore, logging is necessary even if wal_level=minimal.
1391 heap_create_init_fork(Relation rel)
1393 RelationOpenSmgr(rel);
1394 smgrcreate(rel->rd_smgr, INIT_FORKNUM, false);
1395 log_smgrcreate(&rel->rd_smgr->smgr_rnode.node, INIT_FORKNUM);
1396 smgrimmedsync(rel->rd_smgr, INIT_FORKNUM);
1400 * RelationRemoveInheritance
1402 * Formerly, this routine checked for child relations and aborted the
1403 * deletion if any were found. Now we rely on the dependency mechanism
1404 * to check for or delete child relations. By the time we get here,
1405 * there are no children and we need only remove any pg_inherits rows
1406 * linking this relation to its parent(s).
1409 RelationRemoveInheritance(Oid relid)
1411 Relation catalogRelation;
1416 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
1419 Anum_pg_inherits_inhrelid,
1420 BTEqualStrategyNumber, F_OIDEQ,
1421 ObjectIdGetDatum(relid));
1423 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1426 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1427 simple_heap_delete(catalogRelation, &tuple->t_self);
1429 systable_endscan(scan);
1430 heap_close(catalogRelation, RowExclusiveLock);
1434 * DeleteRelationTuple
1436 * Remove pg_class row for the given relid.
1438 * Note: this is shared by relation deletion and index deletion. It's
1439 * not intended for use anyplace else.
1442 DeleteRelationTuple(Oid relid)
1444 Relation pg_class_desc;
1447 /* Grab an appropriate lock on the pg_class relation */
1448 pg_class_desc = heap_open(RelationRelationId, RowExclusiveLock);
1450 tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1451 if (!HeapTupleIsValid(tup))
1452 elog(ERROR, "cache lookup failed for relation %u", relid);
1454 /* delete the relation tuple from pg_class, and finish up */
1455 simple_heap_delete(pg_class_desc, &tup->t_self);
1457 ReleaseSysCache(tup);
1459 heap_close(pg_class_desc, RowExclusiveLock);
1463 * DeleteAttributeTuples
1465 * Remove pg_attribute rows for the given relid.
1467 * Note: this is shared by relation deletion and index deletion. It's
1468 * not intended for use anyplace else.
1471 DeleteAttributeTuples(Oid relid)
1478 /* Grab an appropriate lock on the pg_attribute relation */
1479 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1481 /* Use the index to scan only attributes of the target relation */
1482 ScanKeyInit(&key[0],
1483 Anum_pg_attribute_attrelid,
1484 BTEqualStrategyNumber, F_OIDEQ,
1485 ObjectIdGetDatum(relid));
1487 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1490 /* Delete all the matching tuples */
1491 while ((atttup = systable_getnext(scan)) != NULL)
1492 simple_heap_delete(attrel, &atttup->t_self);
1494 /* Clean up after the scan */
1495 systable_endscan(scan);
1496 heap_close(attrel, RowExclusiveLock);
1500 * DeleteSystemAttributeTuples
1502 * Remove pg_attribute rows for system columns of the given relid.
1504 * Note: this is only used when converting a table to a view. Views don't
1505 * have system columns, so we should remove them from pg_attribute.
1508 DeleteSystemAttributeTuples(Oid relid)
1515 /* Grab an appropriate lock on the pg_attribute relation */
1516 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
1518 /* Use the index to scan only system attributes of the target relation */
1519 ScanKeyInit(&key[0],
1520 Anum_pg_attribute_attrelid,
1521 BTEqualStrategyNumber, F_OIDEQ,
1522 ObjectIdGetDatum(relid));
1523 ScanKeyInit(&key[1],
1524 Anum_pg_attribute_attnum,
1525 BTLessEqualStrategyNumber, F_INT2LE,
1528 scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1531 /* Delete all the matching tuples */
1532 while ((atttup = systable_getnext(scan)) != NULL)
1533 simple_heap_delete(attrel, &atttup->t_self);
1535 /* Clean up after the scan */
1536 systable_endscan(scan);
1537 heap_close(attrel, RowExclusiveLock);
1541 * RemoveAttributeById
1543 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1544 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1545 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1546 * is handled by dependency.c.)
1549 RemoveAttributeById(Oid relid, AttrNumber attnum)
1554 Form_pg_attribute attStruct;
1555 char newattname[NAMEDATALEN];
1558 * Grab an exclusive lock on the target table, which we will NOT release
1559 * until end of transaction. (In the simple case where we are directly
1560 * dropping this column, AlterTableDropColumn already did this ... but
1561 * when cascading from a drop of some other object, we may not have any
1564 rel = relation_open(relid, AccessExclusiveLock);
1566 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1568 tuple = SearchSysCacheCopy2(ATTNUM,
1569 ObjectIdGetDatum(relid),
1570 Int16GetDatum(attnum));
1571 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1572 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1574 attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1578 /* System attribute (probably OID) ... just delete the row */
1580 simple_heap_delete(attr_rel, &tuple->t_self);
1584 /* Dropping user attributes is lots harder */
1586 /* Mark the attribute as dropped */
1587 attStruct->attisdropped = true;
1590 * Set the type OID to invalid. A dropped attribute's type link
1591 * cannot be relied on (once the attribute is dropped, the type might
1592 * be too). Fortunately we do not need the type row --- the only
1593 * really essential information is the type's typlen and typalign,
1594 * which are preserved in the attribute's attlen and attalign. We set
1595 * atttypid to zero here as a means of catching code that incorrectly
1596 * expects it to be valid.
1598 attStruct->atttypid = InvalidOid;
1600 /* Remove any NOT NULL constraint the column may have */
1601 attStruct->attnotnull = false;
1603 /* We don't want to keep stats for it anymore */
1604 attStruct->attstattarget = 0;
1607 * Change the column name to something that isn't likely to conflict
1609 snprintf(newattname, sizeof(newattname),
1610 "........pg.dropped.%d........", attnum);
1611 namestrcpy(&(attStruct->attname), newattname);
1613 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1615 /* keep the system catalog indexes current */
1616 CatalogUpdateIndexes(attr_rel, tuple);
1620 * Because updating the pg_attribute row will trigger a relcache flush for
1621 * the target relation, we need not do anything else to notify other
1622 * backends of the change.
1625 heap_close(attr_rel, RowExclusiveLock);
1628 RemoveStatistics(relid, attnum);
1630 relation_close(rel, NoLock);
1636 * If the specified relation/attribute has a default, remove it.
1637 * (If no default, raise error if complain is true, else return quietly.)
1640 RemoveAttrDefault(Oid relid, AttrNumber attnum,
1641 DropBehavior behavior, bool complain, bool internal)
1643 Relation attrdef_rel;
1644 ScanKeyData scankeys[2];
1649 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1651 ScanKeyInit(&scankeys[0],
1652 Anum_pg_attrdef_adrelid,
1653 BTEqualStrategyNumber, F_OIDEQ,
1654 ObjectIdGetDatum(relid));
1655 ScanKeyInit(&scankeys[1],
1656 Anum_pg_attrdef_adnum,
1657 BTEqualStrategyNumber, F_INT2EQ,
1658 Int16GetDatum(attnum));
1660 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
1663 /* There should be at most one matching tuple, but we loop anyway */
1664 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1666 ObjectAddress object;
1668 object.classId = AttrDefaultRelationId;
1669 object.objectId = HeapTupleGetOid(tuple);
1670 object.objectSubId = 0;
1672 performDeletion(&object, behavior,
1673 internal ? PERFORM_DELETION_INTERNAL : 0);
1678 systable_endscan(scan);
1679 heap_close(attrdef_rel, RowExclusiveLock);
1681 if (complain && !found)
1682 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
1687 * RemoveAttrDefaultById
1689 * Remove a pg_attrdef entry specified by OID. This is the guts of
1690 * attribute-default removal. Note it should be called via performDeletion,
1694 RemoveAttrDefaultById(Oid attrdefId)
1696 Relation attrdef_rel;
1699 ScanKeyData scankeys[1];
1703 AttrNumber myattnum;
1705 /* Grab an appropriate lock on the pg_attrdef relation */
1706 attrdef_rel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1708 /* Find the pg_attrdef tuple */
1709 ScanKeyInit(&scankeys[0],
1710 ObjectIdAttributeNumber,
1711 BTEqualStrategyNumber, F_OIDEQ,
1712 ObjectIdGetDatum(attrdefId));
1714 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
1717 tuple = systable_getnext(scan);
1718 if (!HeapTupleIsValid(tuple))
1719 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
1721 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
1722 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
1724 /* Get an exclusive lock on the relation owning the attribute */
1725 myrel = relation_open(myrelid, AccessExclusiveLock);
1727 /* Now we can delete the pg_attrdef row */
1728 simple_heap_delete(attrdef_rel, &tuple->t_self);
1730 systable_endscan(scan);
1731 heap_close(attrdef_rel, RowExclusiveLock);
1733 /* Fix the pg_attribute row */
1734 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
1736 tuple = SearchSysCacheCopy2(ATTNUM,
1737 ObjectIdGetDatum(myrelid),
1738 Int16GetDatum(myattnum));
1739 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1740 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1743 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
1745 simple_heap_update(attr_rel, &tuple->t_self, tuple);
1747 /* keep the system catalog indexes current */
1748 CatalogUpdateIndexes(attr_rel, tuple);
1751 * Our update of the pg_attribute row will force a relcache rebuild, so
1752 * there's nothing else to do here.
1754 heap_close(attr_rel, RowExclusiveLock);
1756 /* Keep lock on attribute's rel until end of xact */
1757 relation_close(myrel, NoLock);
1761 * heap_drop_with_catalog - removes specified relation from catalogs
1763 * Note that this routine is not responsible for dropping objects that are
1764 * linked to the pg_class entry via dependencies (for example, indexes and
1765 * constraints). Those are deleted by the dependency-tracing logic in
1766 * dependency.c before control gets here. In general, therefore, this routine
1767 * should never be called directly; go through performDeletion() instead.
1770 heap_drop_with_catalog(Oid relid)
1774 Relation parent = NULL;
1777 * Open and lock the relation.
1779 rel = relation_open(relid, AccessExclusiveLock);
1782 * If the relation is a partition, we must grab exclusive lock on its
1783 * parent because we need to update its partition descriptor. We must
1784 * take a table lock strong enough to prevent all queries on the parent
1785 * from proceeding until we commit and send out a shared-cache-inval
1786 * notice that will make them update their partition descriptor.
1787 * Sometimes, doing this is cycles spent uselessly, especially if the
1788 * parent will be dropped as part of the same command anyway.
1790 if (rel->rd_rel->relispartition)
1792 parentOid = get_partition_parent(relid);
1793 parent = heap_open(parentOid, AccessExclusiveLock);
1797 * There can no longer be anyone *else* touching the relation, but we
1798 * might still have open queries or cursors, or pending trigger events, in
1801 CheckTableNotInUse(rel, "DROP TABLE");
1804 * This effectively deletes all rows in the table, and may be done in a
1805 * serializable transaction. In that case we must record a rw-conflict in
1806 * to this transaction from each transaction holding a predicate lock on
1809 CheckTableForSerializableConflictIn(rel);
1812 * Delete pg_foreign_table tuple first.
1814 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1819 rel = heap_open(ForeignTableRelationId, RowExclusiveLock);
1821 tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1822 if (!HeapTupleIsValid(tuple))
1823 elog(ERROR, "cache lookup failed for foreign table %u", relid);
1825 simple_heap_delete(rel, &tuple->t_self);
1827 ReleaseSysCache(tuple);
1828 heap_close(rel, RowExclusiveLock);
1832 * If a partitioned table, delete the pg_partitioned_table tuple.
1834 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1835 RemovePartitionKeyByRelId(relid);
1838 * Schedule unlinking of the relation's physical files at commit.
1840 if (rel->rd_rel->relkind != RELKIND_VIEW &&
1841 rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1842 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1844 RelationDropStorage(rel);
1848 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1849 * until transaction commit. This ensures no one else will try to do
1850 * something with the doomed relation.
1852 relation_close(rel, NoLock);
1855 * Forget any ON COMMIT action for the rel
1857 remove_on_commit_action(relid);
1860 * Flush the relation from the relcache. We want to do this before
1861 * starting to remove catalog entries, just to be certain that no relcache
1862 * entry rebuild will happen partway through. (That should not really
1863 * matter, since we don't do CommandCounterIncrement here, but let's be
1866 RelationForgetRelation(relid);
1869 * remove inheritance information
1871 RelationRemoveInheritance(relid);
1876 RemoveStatistics(relid, 0);
1879 * delete attribute tuples
1881 DeleteAttributeTuples(relid);
1884 * delete relation tuple
1886 DeleteRelationTuple(relid);
1890 CacheInvalidateRelcache(parent);
1891 heap_close(parent, NoLock); /* keep the lock */
1897 * Store a default expression for column attnum of relation rel.
1899 * Returns the OID of the new pg_attrdef tuple.
1902 StoreAttrDefault(Relation rel, AttrNumber attnum,
1903 Node *expr, bool is_internal)
1910 static bool nulls[4] = {false, false, false, false};
1913 Form_pg_attribute attStruct;
1915 ObjectAddress colobject,
1919 * Flatten expression to string form for storage.
1921 adbin = nodeToString(expr);
1924 * Also deparse it to form the mostly-obsolete adsrc field.
1926 adsrc = deparse_expression(expr,
1927 deparse_context_for(RelationGetRelationName(rel),
1928 RelationGetRelid(rel)),
1932 * Make the pg_attrdef entry.
1934 values[Anum_pg_attrdef_adrelid - 1] = RelationGetRelid(rel);
1935 values[Anum_pg_attrdef_adnum - 1] = attnum;
1936 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
1937 values[Anum_pg_attrdef_adsrc - 1] = CStringGetTextDatum(adsrc);
1939 adrel = heap_open(AttrDefaultRelationId, RowExclusiveLock);
1941 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
1942 attrdefOid = simple_heap_insert(adrel, tuple);
1944 CatalogUpdateIndexes(adrel, tuple);
1946 defobject.classId = AttrDefaultRelationId;
1947 defobject.objectId = attrdefOid;
1948 defobject.objectSubId = 0;
1950 heap_close(adrel, RowExclusiveLock);
1952 /* now can free some of the stuff allocated above */
1953 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
1954 pfree(DatumGetPointer(values[Anum_pg_attrdef_adsrc - 1]));
1955 heap_freetuple(tuple);
1960 * Update the pg_attribute entry for the column to show that a default
1963 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
1964 atttup = SearchSysCacheCopy2(ATTNUM,
1965 ObjectIdGetDatum(RelationGetRelid(rel)),
1966 Int16GetDatum(attnum));
1967 if (!HeapTupleIsValid(atttup))
1968 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1969 attnum, RelationGetRelid(rel));
1970 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
1971 if (!attStruct->atthasdef)
1973 attStruct->atthasdef = true;
1974 simple_heap_update(attrrel, &atttup->t_self, atttup);
1975 /* keep catalog indexes current */
1976 CatalogUpdateIndexes(attrrel, atttup);
1978 heap_close(attrrel, RowExclusiveLock);
1979 heap_freetuple(atttup);
1982 * Make a dependency so that the pg_attrdef entry goes away if the column
1983 * (or whole table) is deleted.
1985 colobject.classId = RelationRelationId;
1986 colobject.objectId = RelationGetRelid(rel);
1987 colobject.objectSubId = attnum;
1989 recordDependencyOn(&defobject, &colobject, DEPENDENCY_AUTO);
1992 * Record dependencies on objects used in the expression, too.
1994 recordDependencyOnExpr(&defobject, expr, NIL, DEPENDENCY_NORMAL);
1997 * Post creation hook for attribute defaults.
1999 * XXX. ALTER TABLE ALTER COLUMN SET/DROP DEFAULT is implemented with a
2000 * couple of deletion/creation of the attribute's default entry, so the
2001 * callee should check existence of an older version of this entry if it
2002 * needs to distinguish.
2004 InvokeObjectPostCreateHookArg(AttrDefaultRelationId,
2005 RelationGetRelid(rel), attnum, is_internal);
2011 * Store a check-constraint expression for the given relation.
2013 * Caller is responsible for updating the count of constraints
2014 * in the pg_class entry for the relation.
2016 * The OID of the new constraint is returned.
2019 StoreRelCheck(Relation rel, char *ccname, Node *expr,
2020 bool is_validated, bool is_local, int inhcount,
2021 bool is_no_inherit, bool is_internal)
2031 * Flatten expression to string form for storage.
2033 ccbin = nodeToString(expr);
2036 * Also deparse it to form the mostly-obsolete consrc field.
2038 ccsrc = deparse_expression(expr,
2039 deparse_context_for(RelationGetRelationName(rel),
2040 RelationGetRelid(rel)),
2044 * Find columns of rel that are used in expr
2046 * NB: pull_var_clause is okay here only because we don't allow subselects
2047 * in check constraints; it would fail to examine the contents of
2050 varList = pull_var_clause(expr, 0);
2051 keycount = list_length(varList);
2058 attNos = (int16 *) palloc(keycount * sizeof(int16));
2059 foreach(vl, varList)
2061 Var *var = (Var *) lfirst(vl);
2064 for (j = 0; j < i; j++)
2065 if (attNos[j] == var->varattno)
2068 attNos[i++] = var->varattno;
2076 * Partitioned tables do not contain any rows themselves, so a NO INHERIT
2077 * constraint makes no sense.
2079 if (is_no_inherit &&
2080 rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2082 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2083 errmsg("cannot add NO INHERIT constraint to partitioned table \"%s\"",
2084 RelationGetRelationName(rel))));
2087 * Create the Check Constraint
2090 CreateConstraintEntry(ccname, /* Constraint Name */
2091 RelationGetNamespace(rel), /* namespace */
2092 CONSTRAINT_CHECK, /* Constraint Type */
2093 false, /* Is Deferrable */
2094 false, /* Is Deferred */
2096 RelationGetRelid(rel), /* relation */
2097 attNos, /* attrs in the constraint */
2098 keycount, /* # attrs in the constraint */
2099 InvalidOid, /* not a domain constraint */
2100 InvalidOid, /* no associated index */
2101 InvalidOid, /* Foreign key fields */
2110 NULL, /* not an exclusion constraint */
2111 expr, /* Tree form of check constraint */
2112 ccbin, /* Binary form of check constraint */
2113 ccsrc, /* Source form of check constraint */
2114 is_local, /* conislocal */
2115 inhcount, /* coninhcount */
2116 is_no_inherit, /* connoinherit */
2117 is_internal); /* internally constructed? */
2126 * Store defaults and constraints (passed as a list of CookedConstraint).
2128 * Each CookedConstraint struct is modified to store the new catalog tuple OID.
2130 * NOTE: only pre-cooked expressions will be passed this way, which is to
2131 * say expressions inherited from an existing relation. Newly parsed
2132 * expressions can be added later, by direct calls to StoreAttrDefault
2133 * and StoreRelCheck (see AddRelationNewConstraints()).
2136 StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
2141 if (cooked_constraints == NIL)
2142 return; /* nothing to do */
2145 * Deparsing of constraint expressions will fail unless the just-created
2146 * pg_attribute tuples for this relation are made visible. So, bump the
2147 * command counter. CAUTION: this will cause a relcache entry rebuild.
2149 CommandCounterIncrement();
2151 foreach(lc, cooked_constraints)
2153 CookedConstraint *con = (CookedConstraint *) lfirst(lc);
2155 switch (con->contype)
2157 case CONSTR_DEFAULT:
2158 con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
2163 StoreRelCheck(rel, con->name, con->expr,
2164 !con->skip_validation, con->is_local,
2165 con->inhcount, con->is_no_inherit,
2170 elog(ERROR, "unrecognized constraint type: %d",
2171 (int) con->contype);
2176 SetRelationNumChecks(rel, numchecks);
2180 * AddRelationNewConstraints
2182 * Add new column default expressions and/or constraint check expressions
2183 * to an existing relation. This is defined to do both for efficiency in
2184 * DefineRelation, but of course you can do just one or the other by passing
2187 * rel: relation to be modified
2188 * newColDefaults: list of RawColumnDefault structures
2189 * newConstraints: list of Constraint nodes
2190 * allow_merge: TRUE if check constraints may be merged with existing ones
2191 * is_local: TRUE if definition is local, FALSE if it's inherited
2192 * is_internal: TRUE if result of some internal process, not a user request
2194 * All entries in newColDefaults will be processed. Entries in newConstraints
2195 * will be processed only if they are CONSTR_CHECK type.
2197 * Returns a list of CookedConstraint nodes that shows the cooked form of
2198 * the default and constraint expressions added to the relation.
2200 * NB: caller should have opened rel with AccessExclusiveLock, and should
2201 * hold that lock till end of transaction. Also, we assume the caller has
2202 * done a CommandCounterIncrement if necessary to make the relation's catalog
2206 AddRelationNewConstraints(Relation rel,
2207 List *newColDefaults,
2208 List *newConstraints,
2213 List *cookedConstraints = NIL;
2214 TupleDesc tupleDesc;
2215 TupleConstr *oldconstr;
2223 CookedConstraint *cooked;
2226 * Get info about existing constraints.
2228 tupleDesc = RelationGetDescr(rel);
2229 oldconstr = tupleDesc->constr;
2231 numoldchecks = oldconstr->num_check;
2236 * Create a dummy ParseState and insert the target relation as its sole
2237 * rangetable entry. We need a ParseState for transformExpr.
2239 pstate = make_parsestate(NULL);
2240 rte = addRangeTableEntryForRelation(pstate,
2245 addRTEtoQuery(pstate, rte, true, true, true);
2248 * Process column default expressions.
2250 foreach(cell, newColDefaults)
2252 RawColumnDefault *colDef = (RawColumnDefault *) lfirst(cell);
2253 Form_pg_attribute atp = rel->rd_att->attrs[colDef->attnum - 1];
2256 expr = cookDefault(pstate, colDef->raw_default,
2257 atp->atttypid, atp->atttypmod,
2258 NameStr(atp->attname));
2261 * If the expression is just a NULL constant, we do not bother to make
2262 * an explicit pg_attrdef entry, since the default behavior is
2265 * Note a nonobvious property of this test: if the column is of a
2266 * domain type, what we'll get is not a bare null Const but a
2267 * CoerceToDomain expr, so we will not discard the default. This is
2268 * critical because the column default needs to be retained to
2269 * override any default that the domain might have.
2272 (IsA(expr, Const) &&((Const *) expr)->constisnull))
2275 defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
2277 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2278 cooked->contype = CONSTR_DEFAULT;
2279 cooked->conoid = defOid;
2280 cooked->name = NULL;
2281 cooked->attnum = colDef->attnum;
2282 cooked->expr = expr;
2283 cooked->skip_validation = false;
2284 cooked->is_local = is_local;
2285 cooked->inhcount = is_local ? 0 : 1;
2286 cooked->is_no_inherit = false;
2287 cookedConstraints = lappend(cookedConstraints, cooked);
2291 * Process constraint expressions.
2293 numchecks = numoldchecks;
2295 foreach(cell, newConstraints)
2297 Constraint *cdef = (Constraint *) lfirst(cell);
2301 if (cdef->contype != CONSTR_CHECK)
2304 if (cdef->raw_expr != NULL)
2306 Assert(cdef->cooked_expr == NULL);
2309 * Transform raw parsetree to executable expression, and verify
2310 * it's valid as a CHECK constraint.
2312 expr = cookConstraint(pstate, cdef->raw_expr,
2313 RelationGetRelationName(rel));
2317 Assert(cdef->cooked_expr != NULL);
2320 * Here, we assume the parser will only pass us valid CHECK
2321 * expressions, so we do no particular checking.
2323 expr = stringToNode(cdef->cooked_expr);
2327 * Check name uniqueness, or generate a name if none was given.
2329 if (cdef->conname != NULL)
2333 ccname = cdef->conname;
2334 /* Check against other new constraints */
2335 /* Needed because we don't do CommandCounterIncrement in loop */
2336 foreach(cell2, checknames)
2338 if (strcmp((char *) lfirst(cell2), ccname) == 0)
2340 (errcode(ERRCODE_DUPLICATE_OBJECT),
2341 errmsg("check constraint \"%s\" already exists",
2345 /* save name for future checks */
2346 checknames = lappend(checknames, ccname);
2349 * Check against pre-existing constraints. If we are allowed to
2350 * merge with an existing constraint, there's no more to do here.
2351 * (We omit the duplicate constraint from the result, which is
2352 * what ATAddCheckConstraint wants.)
2354 if (MergeWithExistingConstraint(rel, ccname, expr,
2355 allow_merge, is_local,
2356 cdef->initially_valid,
2357 cdef->is_no_inherit))
2363 * When generating a name, we want to create "tab_col_check" for a
2364 * column constraint and "tab_check" for a table constraint. We
2365 * no longer have any info about the syntactic positioning of the
2366 * constraint phrase, so we approximate this by seeing whether the
2367 * expression references more than one column. (If the user
2368 * played by the rules, the result is the same...)
2370 * Note: pull_var_clause() doesn't descend into sublinks, but we
2371 * eliminated those above; and anyway this only needs to be an
2372 * approximate answer.
2377 vars = pull_var_clause(expr, 0);
2379 /* eliminate duplicates */
2380 vars = list_union(NIL, vars);
2382 if (list_length(vars) == 1)
2383 colname = get_attname(RelationGetRelid(rel),
2384 ((Var *) linitial(vars))->varattno);
2388 ccname = ChooseConstraintName(RelationGetRelationName(rel),
2391 RelationGetNamespace(rel),
2394 /* save name for future checks */
2395 checknames = lappend(checknames, ccname);
2402 StoreRelCheck(rel, ccname, expr, cdef->initially_valid, is_local,
2403 is_local ? 0 : 1, cdef->is_no_inherit, is_internal);
2407 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2408 cooked->contype = CONSTR_CHECK;
2409 cooked->conoid = constrOid;
2410 cooked->name = ccname;
2412 cooked->expr = expr;
2413 cooked->skip_validation = cdef->skip_validation;
2414 cooked->is_local = is_local;
2415 cooked->inhcount = is_local ? 0 : 1;
2416 cooked->is_no_inherit = cdef->is_no_inherit;
2417 cookedConstraints = lappend(cookedConstraints, cooked);
2421 * Update the count of constraints in the relation's pg_class tuple. We do
2422 * this even if there was no change, in order to ensure that an SI update
2423 * message is sent out for the pg_class tuple, which will force other
2424 * backends to rebuild their relcache entries for the rel. (This is
2425 * critical if we added defaults but not constraints.)
2427 SetRelationNumChecks(rel, numchecks);
2429 return cookedConstraints;
2433 * Check for a pre-existing check constraint that conflicts with a proposed
2434 * new one, and either adjust its conislocal/coninhcount settings or throw
2437 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
2438 * got a so-far-unique name, or throws error if conflict.
2440 * XXX See MergeConstraintsIntoExisting too if you change this code.
2443 MergeWithExistingConstraint(Relation rel, char *ccname, Node *expr,
2444 bool allow_merge, bool is_local,
2445 bool is_initially_valid,
2450 SysScanDesc conscan;
2451 ScanKeyData skey[2];
2454 /* Search for a pg_constraint entry with same name and relation */
2455 conDesc = heap_open(ConstraintRelationId, RowExclusiveLock);
2459 ScanKeyInit(&skey[0],
2460 Anum_pg_constraint_conname,
2461 BTEqualStrategyNumber, F_NAMEEQ,
2462 CStringGetDatum(ccname));
2464 ScanKeyInit(&skey[1],
2465 Anum_pg_constraint_connamespace,
2466 BTEqualStrategyNumber, F_OIDEQ,
2467 ObjectIdGetDatum(RelationGetNamespace(rel)));
2469 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
2472 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
2474 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2476 if (con->conrelid == RelationGetRelid(rel))
2478 /* Found it. Conflicts if not identical check constraint */
2479 if (con->contype == CONSTRAINT_CHECK)
2484 val = fastgetattr(tup,
2485 Anum_pg_constraint_conbin,
2486 conDesc->rd_att, &isnull);
2488 elog(ERROR, "null conbin for rel %s",
2489 RelationGetRelationName(rel));
2490 if (equal(expr, stringToNode(TextDatumGetCString(val))))
2495 * If the existing constraint is purely inherited (no local
2496 * definition) then interpret addition of a local constraint as a
2497 * legal merge. This allows ALTER ADD CONSTRAINT on parent and
2498 * child tables to be given in either order with same end state.
2499 * However if the relation is a partition, all inherited
2500 * constraints are always non-local, including those that were
2503 if (is_local && !con->conislocal && !rel->rd_rel->relispartition)
2506 if (!found || !allow_merge)
2508 (errcode(ERRCODE_DUPLICATE_OBJECT),
2509 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2510 ccname, RelationGetRelationName(rel))));
2512 /* If the child constraint is "no inherit" then cannot merge */
2513 if (con->connoinherit)
2515 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2516 errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
2517 ccname, RelationGetRelationName(rel))));
2520 * Must not change an existing inherited constraint to "no
2521 * inherit" status. That's because inherited constraints should
2522 * be able to propagate to lower-level children.
2524 if (con->coninhcount > 0 && is_no_inherit)
2526 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2527 errmsg("constraint \"%s\" conflicts with inherited constraint on relation \"%s\"",
2528 ccname, RelationGetRelationName(rel))));
2531 * If the child constraint is "not valid" then cannot merge with a
2532 * valid parent constraint
2534 if (is_initially_valid && !con->convalidated)
2536 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2537 errmsg("constraint \"%s\" conflicts with NOT VALID constraint on relation \"%s\"",
2538 ccname, RelationGetRelationName(rel))));
2540 /* OK to update the tuple */
2542 (errmsg("merging constraint \"%s\" with inherited definition",
2545 tup = heap_copytuple(tup);
2546 con = (Form_pg_constraint) GETSTRUCT(tup);
2549 * In case of partitions, an inherited constraint must be
2550 * inherited only once since it cannot have multiple parents and
2551 * it is never considered local.
2553 if (rel->rd_rel->relispartition)
2555 con->coninhcount = 1;
2556 con->conislocal = false;
2561 con->conislocal = true;
2569 con->connoinherit = true;
2571 simple_heap_update(conDesc, &tup->t_self, tup);
2572 CatalogUpdateIndexes(conDesc, tup);
2577 systable_endscan(conscan);
2578 heap_close(conDesc, RowExclusiveLock);
2584 * Update the count of constraints in the relation's pg_class tuple.
2586 * Caller had better hold exclusive lock on the relation.
2588 * An important side effect is that a SI update message will be sent out for
2589 * the pg_class tuple, which will force other backends to rebuild their
2590 * relcache entries for the rel. Also, this backend will rebuild its
2591 * own relcache entry at the next CommandCounterIncrement.
2594 SetRelationNumChecks(Relation rel, int numchecks)
2598 Form_pg_class relStruct;
2600 relrel = heap_open(RelationRelationId, RowExclusiveLock);
2601 reltup = SearchSysCacheCopy1(RELOID,
2602 ObjectIdGetDatum(RelationGetRelid(rel)));
2603 if (!HeapTupleIsValid(reltup))
2604 elog(ERROR, "cache lookup failed for relation %u",
2605 RelationGetRelid(rel));
2606 relStruct = (Form_pg_class) GETSTRUCT(reltup);
2608 if (relStruct->relchecks != numchecks)
2610 relStruct->relchecks = numchecks;
2612 simple_heap_update(relrel, &reltup->t_self, reltup);
2614 /* keep catalog indexes current */
2615 CatalogUpdateIndexes(relrel, reltup);
2619 /* Skip the disk update, but force relcache inval anyway */
2620 CacheInvalidateRelcache(rel);
2623 heap_freetuple(reltup);
2624 heap_close(relrel, RowExclusiveLock);
2628 * Take a raw default and convert it to a cooked format ready for
2631 * Parse state should be set up to recognize any vars that might appear
2632 * in the expression. (Even though we plan to reject vars, it's more
2633 * user-friendly to give the correct error message than "unknown var".)
2635 * If atttypid is not InvalidOid, coerce the expression to the specified
2636 * type (and typmod atttypmod). attname is only needed in this case:
2637 * it is used in the error message, if any.
2640 cookDefault(ParseState *pstate,
2648 Assert(raw_default != NULL);
2651 * Transform raw parsetree to executable expression.
2653 expr = transformExpr(pstate, raw_default, EXPR_KIND_COLUMN_DEFAULT);
2656 * Make sure default expr does not refer to any vars (we need this check
2657 * since the pstate includes the target table).
2659 if (contain_var_clause(expr))
2661 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2662 errmsg("cannot use column references in default expression")));
2665 * transformExpr() should have already rejected subqueries, aggregates,
2666 * window functions, and SRFs, based on the EXPR_KIND_ for a default
2671 * Coerce the expression to the correct type and typmod, if given. This
2672 * should match the parser's processing of non-defaulted expressions ---
2673 * see transformAssignedExpr().
2675 if (OidIsValid(atttypid))
2677 Oid type_id = exprType(expr);
2679 expr = coerce_to_target_type(pstate, expr, type_id,
2680 atttypid, atttypmod,
2681 COERCION_ASSIGNMENT,
2682 COERCE_IMPLICIT_CAST,
2686 (errcode(ERRCODE_DATATYPE_MISMATCH),
2687 errmsg("column \"%s\" is of type %s"
2688 " but default expression is of type %s",
2690 format_type_be(atttypid),
2691 format_type_be(type_id)),
2692 errhint("You will need to rewrite or cast the expression.")));
2696 * Finally, take care of collations in the finished expression.
2698 assign_expr_collations(pstate, expr);
2704 * Take a raw CHECK constraint expression and convert it to a cooked format
2705 * ready for storage.
2707 * Parse state must be set up to recognize any vars that might appear
2708 * in the expression.
2711 cookConstraint(ParseState *pstate,
2712 Node *raw_constraint,
2718 * Transform raw parsetree to executable expression.
2720 expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
2723 * Make sure it yields a boolean result.
2725 expr = coerce_to_boolean(pstate, expr, "CHECK");
2728 * Take care of collations.
2730 assign_expr_collations(pstate, expr);
2733 * Make sure no outside relations are referred to (this is probably dead
2734 * code now that add_missing_from is history).
2736 if (list_length(pstate->p_rtable) != 1)
2738 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2739 errmsg("only table \"%s\" can be referenced in check constraint",
2747 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2749 * If attnum is zero, remove all entries for rel; else remove only the one(s)
2753 RemoveStatistics(Oid relid, AttrNumber attnum)
2755 Relation pgstatistic;
2761 pgstatistic = heap_open(StatisticRelationId, RowExclusiveLock);
2763 ScanKeyInit(&key[0],
2764 Anum_pg_statistic_starelid,
2765 BTEqualStrategyNumber, F_OIDEQ,
2766 ObjectIdGetDatum(relid));
2772 ScanKeyInit(&key[1],
2773 Anum_pg_statistic_staattnum,
2774 BTEqualStrategyNumber, F_INT2EQ,
2775 Int16GetDatum(attnum));
2779 scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
2782 /* we must loop even when attnum != 0, in case of inherited stats */
2783 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2784 simple_heap_delete(pgstatistic, &tuple->t_self);
2786 systable_endscan(scan);
2788 heap_close(pgstatistic, RowExclusiveLock);
2793 * RelationTruncateIndexes - truncate all indexes associated
2794 * with the heap relation to zero tuples.
2796 * The routine will truncate and then reconstruct the indexes on
2797 * the specified relation. Caller must hold exclusive lock on rel.
2800 RelationTruncateIndexes(Relation heapRelation)
2804 /* Ask the relcache to produce a list of the indexes of the rel */
2805 foreach(indlist, RelationGetIndexList(heapRelation))
2807 Oid indexId = lfirst_oid(indlist);
2808 Relation currentIndex;
2809 IndexInfo *indexInfo;
2811 /* Open the index relation; use exclusive lock, just to be sure */
2812 currentIndex = index_open(indexId, AccessExclusiveLock);
2814 /* Fetch info needed for index_build */
2815 indexInfo = BuildIndexInfo(currentIndex);
2818 * Now truncate the actual file (and discard buffers).
2820 RelationTruncate(currentIndex, 0);
2822 /* Initialize the index and rebuild */
2823 /* Note: we do not need to re-establish pkey setting */
2824 index_build(heapRelation, currentIndex, indexInfo, false, true);
2826 /* We're done with this index */
2827 index_close(currentIndex, NoLock);
2834 * This routine deletes all data within all the specified relations.
2836 * This is not transaction-safe! There is another, transaction-safe
2837 * implementation in commands/tablecmds.c. We now use this only for
2838 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2841 heap_truncate(List *relids)
2843 List *relations = NIL;
2846 /* Open relations for processing, and grab exclusive access on each */
2847 foreach(cell, relids)
2849 Oid rid = lfirst_oid(cell);
2852 rel = heap_open(rid, AccessExclusiveLock);
2853 relations = lappend(relations, rel);
2856 /* Don't allow truncate on tables that are referenced by foreign keys */
2857 heap_truncate_check_FKs(relations, true);
2860 foreach(cell, relations)
2862 Relation rel = lfirst(cell);
2864 /* Truncate the relation */
2865 heap_truncate_one_rel(rel);
2867 /* Close the relation, but keep exclusive lock on it until commit */
2868 heap_close(rel, NoLock);
2873 * heap_truncate_one_rel
2875 * This routine deletes all data within the specified relation.
2877 * This is not transaction-safe, because the truncation is done immediately
2878 * and cannot be rolled back later. Caller is responsible for having
2879 * checked permissions etc, and must have obtained AccessExclusiveLock.
2882 heap_truncate_one_rel(Relation rel)
2886 /* Truncate the actual file (and discard buffers) */
2887 RelationTruncate(rel, 0);
2889 /* If the relation has indexes, truncate the indexes too */
2890 RelationTruncateIndexes(rel);
2892 /* If there is a toast table, truncate that too */
2893 toastrelid = rel->rd_rel->reltoastrelid;
2894 if (OidIsValid(toastrelid))
2896 Relation toastrel = heap_open(toastrelid, AccessExclusiveLock);
2898 RelationTruncate(toastrel, 0);
2899 RelationTruncateIndexes(toastrel);
2900 /* keep the lock... */
2901 heap_close(toastrel, NoLock);
2906 * heap_truncate_check_FKs
2907 * Check for foreign keys referencing a list of relations that
2908 * are to be truncated, and raise error if there are any
2910 * We disallow such FKs (except self-referential ones) since the whole point
2911 * of TRUNCATE is to not scan the individual rows to be thrown away.
2913 * This is split out so it can be shared by both implementations of truncate.
2914 * Caller should already hold a suitable lock on the relations.
2916 * tempTables is only used to select an appropriate error message.
2919 heap_truncate_check_FKs(List *relations, bool tempTables)
2926 * Build a list of OIDs of the interesting relations.
2928 * If a relation has no triggers, then it can neither have FKs nor be
2929 * referenced by a FK from another table, so we can ignore it.
2931 foreach(cell, relations)
2933 Relation rel = lfirst(cell);
2935 if (rel->rd_rel->relhastriggers)
2936 oids = lappend_oid(oids, RelationGetRelid(rel));
2940 * Fast path: if no relation has triggers, none has FKs either.
2946 * Otherwise, must scan pg_constraint. We make one pass with all the
2947 * relations considered; if this finds nothing, then all is well.
2949 dependents = heap_truncate_find_FKs(oids);
2950 if (dependents == NIL)
2954 * Otherwise we repeat the scan once per relation to identify a particular
2955 * pair of relations to complain about. This is pretty slow, but
2956 * performance shouldn't matter much in a failure path. The reason for
2957 * doing things this way is to ensure that the message produced is not
2958 * dependent on chance row locations within pg_constraint.
2962 Oid relid = lfirst_oid(cell);
2965 dependents = heap_truncate_find_FKs(list_make1_oid(relid));
2967 foreach(cell2, dependents)
2969 Oid relid2 = lfirst_oid(cell2);
2971 if (!list_member_oid(oids, relid2))
2973 char *relname = get_rel_name(relid);
2974 char *relname2 = get_rel_name(relid2);
2978 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2979 errmsg("unsupported ON COMMIT and foreign key combination"),
2980 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2981 relname2, relname)));
2984 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2985 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2986 errdetail("Table \"%s\" references \"%s\".",
2988 errhint("Truncate table \"%s\" at the same time, "
2989 "or use TRUNCATE ... CASCADE.",
2997 * heap_truncate_find_FKs
2998 * Find relations having foreign keys referencing any of the given rels
3000 * Input and result are both lists of relation OIDs. The result contains
3001 * no duplicates, does *not* include any rels that were already in the input
3002 * list, and is sorted in OID order. (The last property is enforced mainly
3003 * to guarantee consistent behavior in the regression tests; we don't want
3004 * behavior to change depending on chance locations of rows in pg_constraint.)
3006 * Note: caller should already have appropriate lock on all rels mentioned
3007 * in relationIds. Since adding or dropping an FK requires exclusive lock
3008 * on both rels, this ensures that the answer will be stable.
3011 heap_truncate_find_FKs(List *relationIds)
3015 SysScanDesc fkeyScan;
3019 * Must scan pg_constraint. Right now, it is a seqscan because there is
3020 * no available index on confrelid.
3022 fkeyRel = heap_open(ConstraintRelationId, AccessShareLock);
3024 fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
3027 while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
3029 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
3031 /* Not a foreign key */
3032 if (con->contype != CONSTRAINT_FOREIGN)
3035 /* Not referencing one of our list of tables */
3036 if (!list_member_oid(relationIds, con->confrelid))
3039 /* Add referencer unless already in input or result list */
3040 if (!list_member_oid(relationIds, con->conrelid))
3041 result = insert_ordered_unique_oid(result, con->conrelid);
3044 systable_endscan(fkeyScan);
3045 heap_close(fkeyRel, AccessShareLock);
3051 * insert_ordered_unique_oid
3052 * Insert a new Oid into a sorted list of Oids, preserving ordering,
3053 * and eliminating duplicates
3055 * Building the ordered list this way is O(N^2), but with a pretty small
3056 * constant, so for the number of entries we expect it will probably be
3057 * faster than trying to apply qsort(). It seems unlikely someone would be
3058 * trying to truncate a table with thousands of dependent tables ...
3061 insert_ordered_unique_oid(List *list, Oid datum)
3065 /* Does the datum belong at the front? */
3066 if (list == NIL || datum < linitial_oid(list))
3067 return lcons_oid(datum, list);
3068 /* Does it match the first entry? */
3069 if (datum == linitial_oid(list))
3070 return list; /* duplicate, so don't insert */
3071 /* No, so find the entry it belongs after */
3072 prev = list_head(list);
3075 ListCell *curr = lnext(prev);
3077 if (curr == NULL || datum < lfirst_oid(curr))
3078 break; /* it belongs after 'prev', before 'curr' */
3080 if (datum == lfirst_oid(curr))
3081 return list; /* duplicate, so don't insert */
3085 /* Insert datum into list after 'prev' */
3086 lappend_cell_oid(list, prev, datum);
3092 * Store information about the partition key rel into the catalog
3095 StorePartitionKey(Relation rel,
3098 AttrNumber *partattrs,
3104 int2vector *partattrs_vec;
3105 oidvector *partopclass_vec;
3106 oidvector *partcollation_vec;
3107 Datum partexprDatum;
3108 Relation pg_partitioned_table;
3110 Datum values[Natts_pg_partitioned_table];
3111 bool nulls[Natts_pg_partitioned_table];
3112 ObjectAddress myself;
3113 ObjectAddress referenced;
3115 Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3117 tuple = SearchSysCache1(PARTRELID,
3118 ObjectIdGetDatum(RelationGetRelid(rel)));
3120 /* Copy the partition attribute numbers, opclass OIDs into arrays */
3121 partattrs_vec = buildint2vector(partattrs, partnatts);
3122 partopclass_vec = buildoidvector(partopclass, partnatts);
3123 partcollation_vec = buildoidvector(partcollation, partnatts);
3125 /* Convert the expressions (if any) to a text datum */
3130 exprString = nodeToString(partexprs);
3131 partexprDatum = CStringGetTextDatum(exprString);
3135 partexprDatum = (Datum) 0;
3137 pg_partitioned_table = heap_open(PartitionedRelationId, RowExclusiveLock);
3139 MemSet(nulls, false, sizeof(nulls));
3141 /* Only this can ever be NULL */
3143 nulls[Anum_pg_partitioned_table_partexprs - 1] = true;
3145 values[Anum_pg_partitioned_table_partrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
3146 values[Anum_pg_partitioned_table_partstrat - 1] = CharGetDatum(strategy);
3147 values[Anum_pg_partitioned_table_partnatts - 1] = Int16GetDatum(partnatts);
3148 values[Anum_pg_partitioned_table_partattrs - 1] = PointerGetDatum(partattrs_vec);
3149 values[Anum_pg_partitioned_table_partclass - 1] = PointerGetDatum(partopclass_vec);
3150 values[Anum_pg_partitioned_table_partcollation - 1] = PointerGetDatum(partcollation_vec);
3151 values[Anum_pg_partitioned_table_partexprs - 1] = partexprDatum;
3153 tuple = heap_form_tuple(RelationGetDescr(pg_partitioned_table), values, nulls);
3155 simple_heap_insert(pg_partitioned_table, tuple);
3157 /* Update the indexes on pg_partitioned_table */
3158 CatalogUpdateIndexes(pg_partitioned_table, tuple);
3159 heap_close(pg_partitioned_table, RowExclusiveLock);
3161 /* Mark this relation as dependent on a few things as follows */
3162 myself.classId = RelationRelationId;
3163 myself.objectId = RelationGetRelid(rel);;
3164 myself.objectSubId = 0;
3166 /* Operator class and collation per key column */
3167 for (i = 0; i < partnatts; i++)
3169 referenced.classId = OperatorClassRelationId;
3170 referenced.objectId = partopclass[i];
3171 referenced.objectSubId = 0;
3173 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3175 referenced.classId = CollationRelationId;
3176 referenced.objectId = partcollation[i];
3177 referenced.objectSubId = 0;
3179 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3183 * Anything mentioned in the expressions. We must ignore the column
3184 * references, which will depend on the table itself; there is no
3185 * separate partition key object.
3188 recordDependencyOnSingleRelExpr(&myself,
3190 RelationGetRelid(rel),
3192 DEPENDENCY_AUTO, true);
3195 * We must invalidate the relcache so that the next
3196 * CommandCounterIncrement() will cause the same to be rebuilt using the
3197 * information in just created catalog entry.
3199 CacheInvalidateRelcache(rel);
3203 * RemovePartitionKeyByRelId
3204 * Remove pg_partitioned_table entry for a relation
3207 RemovePartitionKeyByRelId(Oid relid)
3212 rel = heap_open(PartitionedRelationId, RowExclusiveLock);
3214 tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
3215 if (!HeapTupleIsValid(tuple))
3216 elog(ERROR, "cache lookup failed for partition key of relation %u",
3219 simple_heap_delete(rel, &tuple->t_self);
3221 ReleaseSysCache(tuple);
3222 heap_close(rel, RowExclusiveLock);
3226 * StorePartitionBound
3227 * Update pg_class tuple of rel to store the partition bound and set
3228 * relispartition to true
3231 StorePartitionBound(Relation rel, Node *bound)
3236 Datum new_val[Natts_pg_class];
3237 bool new_null[Natts_pg_class],
3238 new_repl[Natts_pg_class];
3240 /* Update pg_class tuple */
3241 classRel = heap_open(RelationRelationId, RowExclusiveLock);
3242 tuple = SearchSysCacheCopy1(RELOID,
3243 ObjectIdGetDatum(RelationGetRelid(rel)));
3244 #ifdef USE_ASSERT_CHECKING
3246 Form_pg_class classForm;
3249 classForm = (Form_pg_class) GETSTRUCT(tuple);
3250 Assert(!classForm->relispartition);
3251 (void) SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relpartbound,
3257 /* Fill in relpartbound value */
3258 memset(new_val, 0, sizeof(new_val));
3259 memset(new_null, false, sizeof(new_null));
3260 memset(new_repl, false, sizeof(new_repl));
3261 new_val[Anum_pg_class_relpartbound - 1] = CStringGetTextDatum(nodeToString(bound));
3262 new_null[Anum_pg_class_relpartbound - 1] = false;
3263 new_repl[Anum_pg_class_relpartbound - 1] = true;
3264 newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
3265 new_val, new_null, new_repl);
3266 /* Also set the flag */
3267 ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = true;
3268 simple_heap_update(classRel, &newtuple->t_self, newtuple);
3269 CatalogUpdateIndexes(classRel, newtuple);
3270 heap_freetuple(newtuple);
3271 heap_close(classRel, RowExclusiveLock);