1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
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/pg_attrdef.h"
43 #include "catalog/pg_constraint.h"
44 #include "catalog/pg_inherits.h"
45 #include "catalog/pg_namespace.h"
46 #include "catalog/pg_statistic.h"
47 #include "catalog/pg_tablespace.h"
48 #include "catalog/pg_type.h"
49 #include "catalog/pg_type_fn.h"
50 #include "catalog/storage.h"
51 #include "commands/tablecmds.h"
52 #include "commands/typecmds.h"
53 #include "miscadmin.h"
54 #include "nodes/nodeFuncs.h"
55 #include "optimizer/var.h"
56 #include "parser/parse_coerce.h"
57 #include "parser/parse_expr.h"
58 #include "parser/parse_relation.h"
59 #include "storage/bufmgr.h"
60 #include "storage/freespace.h"
61 #include "storage/smgr.h"
62 #include "utils/builtins.h"
63 #include "utils/fmgroids.h"
64 #include "utils/inval.h"
65 #include "utils/lsyscache.h"
66 #include "utils/relcache.h"
67 #include "utils/snapmgr.h"
68 #include "utils/syscache.h"
69 #include "utils/tqual.h"
72 static void AddNewRelationTuple(Relation pg_class_desc
,
73 Relation new_rel_desc
,
74 Oid new_rel_oid
, Oid new_type_oid
,
78 static Oid
AddNewRelationType(const char *typeName
,
84 static void RelationRemoveInheritance(Oid relid
);
85 static void StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
86 bool is_local
, int inhcount
);
87 static void StoreConstraints(Relation rel
, List
*cooked_constraints
);
88 static bool MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
89 bool allow_merge
, bool is_local
);
90 static void SetRelationNumChecks(Relation rel
, int numchecks
);
91 static Node
*cookConstraint(ParseState
*pstate
,
94 static List
*insert_ordered_unique_oid(List
*list
, Oid datum
);
97 /* ----------------------------------------------------------------
98 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
100 * these should all be moved to someplace in the lib/catalog
101 * module, if not obliterated first.
102 * ----------------------------------------------------------------
108 * Should the system special case these attributes in the future?
109 * Advantage: consume much less space in the ATTRIBUTE relation.
110 * Disadvantage: special cases will be all over the place.
113 static FormData_pg_attribute a1
= {
114 0, {"ctid"}, TIDOID
, 0, sizeof(ItemPointerData
),
115 SelfItemPointerAttributeNumber
, 0, -1, -1,
116 false, 'p', 's', true, false, false, true, 0, { 0 }
119 static FormData_pg_attribute a2
= {
120 0, {"oid"}, OIDOID
, 0, sizeof(Oid
),
121 ObjectIdAttributeNumber
, 0, -1, -1,
122 true, 'p', 'i', true, false, false, true, 0, { 0 }
125 static FormData_pg_attribute a3
= {
126 0, {"xmin"}, XIDOID
, 0, sizeof(TransactionId
),
127 MinTransactionIdAttributeNumber
, 0, -1, -1,
128 true, 'p', 'i', true, false, false, true, 0, { 0 }
131 static FormData_pg_attribute a4
= {
132 0, {"cmin"}, CIDOID
, 0, sizeof(CommandId
),
133 MinCommandIdAttributeNumber
, 0, -1, -1,
134 true, 'p', 'i', true, false, false, true, 0, { 0 }
137 static FormData_pg_attribute a5
= {
138 0, {"xmax"}, XIDOID
, 0, sizeof(TransactionId
),
139 MaxTransactionIdAttributeNumber
, 0, -1, -1,
140 true, 'p', 'i', true, false, false, true, 0, { 0 }
143 static FormData_pg_attribute a6
= {
144 0, {"cmax"}, CIDOID
, 0, sizeof(CommandId
),
145 MaxCommandIdAttributeNumber
, 0, -1, -1,
146 true, 'p', 'i', true, false, false, true, 0, { 0 }
150 * We decided to call this attribute "tableoid" rather than say
151 * "classoid" on the basis that in the future there may be more than one
152 * table of a particular class/type. In any case table is still the word
155 static FormData_pg_attribute a7
= {
156 0, {"tableoid"}, OIDOID
, 0, sizeof(Oid
),
157 TableOidAttributeNumber
, 0, -1, -1,
158 true, 'p', 'i', true, false, false, true, 0, { 0 }
161 static const Form_pg_attribute SysAtt
[] = {&a1
, &a2
, &a3
, &a4
, &a5
, &a6
, &a7
};
164 * This function returns a Form_pg_attribute pointer for a system attribute.
165 * Note that we elog if the presented attno is invalid, which would only
166 * happen if there's a problem upstream.
169 SystemAttributeDefinition(AttrNumber attno
, bool relhasoids
)
171 if (attno
>= 0 || attno
< -(int) lengthof(SysAtt
))
172 elog(ERROR
, "invalid system attribute number %d", attno
);
173 if (attno
== ObjectIdAttributeNumber
&& !relhasoids
)
174 elog(ERROR
, "invalid system attribute number %d", attno
);
175 return SysAtt
[-attno
- 1];
179 * If the given name is a system attribute name, return a Form_pg_attribute
180 * pointer for a prototype definition. If not, return NULL.
183 SystemAttributeByName(const char *attname
, bool relhasoids
)
187 for (j
= 0; j
< (int) lengthof(SysAtt
); j
++)
189 Form_pg_attribute att
= SysAtt
[j
];
191 if (relhasoids
|| att
->attnum
!= ObjectIdAttributeNumber
)
193 if (strcmp(NameStr(att
->attname
), attname
) == 0)
202 /* ----------------------------------------------------------------
203 * XXX END OF UGLY HARD CODED BADNESS XXX
204 * ---------------------------------------------------------------- */
207 /* ----------------------------------------------------------------
208 * heap_create - Create an uncataloged heap relation
210 * Note API change: the caller must now always provide the OID
211 * to use for the relation.
213 * rel->rd_rel is initialized by RelationBuildLocalRelation,
214 * and is mostly zeroes at return.
215 * ----------------------------------------------------------------
218 heap_create(const char *relname
,
224 bool shared_relation
,
225 bool allow_system_table_mods
)
230 /* The caller must have provided an OID for the relation. */
231 Assert(OidIsValid(relid
));
236 if (!allow_system_table_mods
&&
237 (IsSystemNamespace(relnamespace
) || IsToastNamespace(relnamespace
)) &&
238 IsNormalProcessingMode())
240 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
241 errmsg("permission denied to create \"%s.%s\"",
242 get_namespace_name(relnamespace
), relname
),
243 errdetail("System catalog modifications are currently disallowed.")));
246 * Decide if we need storage or not, and handle a couple other special
247 * cases for particular relkinds.
252 case RELKIND_COMPOSITE_TYPE
:
253 create_storage
= false;
256 * Force reltablespace to zero if the relation has no physical
257 * storage. This is mainly just for cleanliness' sake.
259 reltablespace
= InvalidOid
;
261 case RELKIND_SEQUENCE
:
262 create_storage
= true;
265 * Force reltablespace to zero for sequences, since we don't
266 * support moving them around into different tablespaces.
268 reltablespace
= InvalidOid
;
271 create_storage
= true;
276 * Never allow a pg_class entry to explicitly specify the database's
277 * default tablespace in reltablespace; force it to zero instead. This
278 * ensures that if the database is cloned with a different default
279 * tablespace, the pg_class entry will still match where CREATE DATABASE
280 * will put the physically copied relation.
282 * Yes, this is a bit of a hack.
284 if (reltablespace
== MyDatabaseTableSpace
)
285 reltablespace
= InvalidOid
;
288 * build the relcache entry.
290 rel
= RelationBuildLocalRelation(relname
,
298 * Have the storage manager create the relation's disk file, if needed.
300 * We only create the main fork here, other forks will be created on
305 RelationOpenSmgr(rel
);
306 RelationCreateStorage(rel
->rd_node
, rel
->rd_istemp
);
312 /* ----------------------------------------------------------------
313 * heap_create_with_catalog - Create a cataloged relation
315 * this is done in multiple steps:
317 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
318 * descriptor contains a valid set of attribute names and types
320 * 2) pg_class is opened and get_relname_relid()
321 * performs a scan to ensure that no relation with the
322 * same name already exists.
324 * 3) heap_create() is called to create the new relation on disk.
326 * 4) TypeCreate() is called to define a new type corresponding
327 * to the new relation.
329 * 5) AddNewRelationTuple() is called to register the
330 * relation in pg_class.
332 * 6) AddNewAttributeTuples() is called to register the
333 * new relation's schema in pg_attribute.
335 * 7) StoreConstraints is called () - vadim 08/22/97
337 * 8) the relations are closed and the new relation's oid
340 * ----------------------------------------------------------------
343 /* --------------------------------
344 * CheckAttributeNamesTypes
346 * this is used to make certain the tuple descriptor contains a
347 * valid set of attribute names and datatypes. a problem simply
348 * generates ereport(ERROR) which aborts the current transaction.
349 * --------------------------------
352 CheckAttributeNamesTypes(TupleDesc tupdesc
, char relkind
)
356 int natts
= tupdesc
->natts
;
358 /* Sanity check on column count */
359 if (natts
< 0 || natts
> MaxHeapAttributeNumber
)
361 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
362 errmsg("tables can have at most %d columns",
363 MaxHeapAttributeNumber
)));
366 * first check for collision with system attribute names
368 * Skip this for a view or type relation, since those don't have system
371 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
373 for (i
= 0; i
< natts
; i
++)
375 if (SystemAttributeByName(NameStr(tupdesc
->attrs
[i
]->attname
),
376 tupdesc
->tdhasoid
) != NULL
)
378 (errcode(ERRCODE_DUPLICATE_COLUMN
),
379 errmsg("column name \"%s\" conflicts with a system column name",
380 NameStr(tupdesc
->attrs
[i
]->attname
))));
385 * next check for repeated attribute names
387 for (i
= 1; i
< natts
; i
++)
389 for (j
= 0; j
< i
; j
++)
391 if (strcmp(NameStr(tupdesc
->attrs
[j
]->attname
),
392 NameStr(tupdesc
->attrs
[i
]->attname
)) == 0)
394 (errcode(ERRCODE_DUPLICATE_COLUMN
),
395 errmsg("column name \"%s\" specified more than once",
396 NameStr(tupdesc
->attrs
[j
]->attname
))));
401 * next check the attribute types
403 for (i
= 0; i
< natts
; i
++)
405 CheckAttributeType(NameStr(tupdesc
->attrs
[i
]->attname
),
406 tupdesc
->attrs
[i
]->atttypid
);
410 /* --------------------------------
413 * Verify that the proposed datatype of an attribute is legal.
414 * This is needed because there are types (and pseudo-types)
415 * in the catalogs that we do not support as elements of real tuples.
416 * --------------------------------
419 CheckAttributeType(const char *attname
, Oid atttypid
)
421 char att_typtype
= get_typtype(atttypid
);
423 if (atttypid
== UNKNOWNOID
)
426 * Warn user, but don't fail, if column to be created has UNKNOWN type
427 * (usually as a result of a 'retrieve into' - jolly)
430 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
431 errmsg("column \"%s\" has type \"unknown\"", attname
),
432 errdetail("Proceeding with relation creation anyway.")));
434 else if (att_typtype
== TYPTYPE_PSEUDO
)
437 * Refuse any attempt to create a pseudo-type column, except for a
438 * special hack for pg_statistic: allow ANYARRAY during initdb
440 if (atttypid
!= ANYARRAYOID
|| IsUnderPostmaster
)
442 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
443 errmsg("column \"%s\" has pseudo-type %s",
444 attname
, format_type_be(atttypid
))));
446 else if (att_typtype
== TYPTYPE_COMPOSITE
)
449 * For a composite type, recurse into its attributes. You might think
450 * this isn't necessary, but since we allow system catalogs to break
451 * the rule, we have to guard against the case.
457 relation
= relation_open(get_typ_typrelid(atttypid
), AccessShareLock
);
459 tupdesc
= RelationGetDescr(relation
);
461 for (i
= 0; i
< tupdesc
->natts
; i
++)
463 Form_pg_attribute attr
= tupdesc
->attrs
[i
];
465 if (attr
->attisdropped
)
467 CheckAttributeType(NameStr(attr
->attname
), attr
->atttypid
);
470 relation_close(relation
, AccessShareLock
);
475 * InsertPgAttributeTuple
476 * Construct and insert a new tuple in pg_attribute.
478 * Caller has already opened and locked pg_attribute. new_attribute is the
479 * attribute to insert (but we ignore its attacl, if indeed it has one).
481 * indstate is the index state for CatalogIndexInsert. It can be passed as
482 * NULL, in which case we'll fetch the necessary info. (Don't do this when
483 * inserting multiple attributes, because it's a tad more expensive.)
485 * We always initialize attacl to NULL (i.e., default permissions).
488 InsertPgAttributeTuple(Relation pg_attribute_rel
,
489 Form_pg_attribute new_attribute
,
490 CatalogIndexState indstate
)
492 Datum values
[Natts_pg_attribute
];
493 bool nulls
[Natts_pg_attribute
];
496 /* This is a tad tedious, but way cleaner than what we used to do... */
497 memset(values
, 0, sizeof(values
));
498 memset(nulls
, false, sizeof(nulls
));
500 values
[Anum_pg_attribute_attrelid
- 1] = ObjectIdGetDatum(new_attribute
->attrelid
);
501 values
[Anum_pg_attribute_attname
- 1] = NameGetDatum(&new_attribute
->attname
);
502 values
[Anum_pg_attribute_atttypid
- 1] = ObjectIdGetDatum(new_attribute
->atttypid
);
503 values
[Anum_pg_attribute_attstattarget
- 1] = Int32GetDatum(new_attribute
->attstattarget
);
504 values
[Anum_pg_attribute_attlen
- 1] = Int16GetDatum(new_attribute
->attlen
);
505 values
[Anum_pg_attribute_attnum
- 1] = Int16GetDatum(new_attribute
->attnum
);
506 values
[Anum_pg_attribute_attndims
- 1] = Int32GetDatum(new_attribute
->attndims
);
507 values
[Anum_pg_attribute_attcacheoff
- 1] = Int32GetDatum(new_attribute
->attcacheoff
);
508 values
[Anum_pg_attribute_atttypmod
- 1] = Int32GetDatum(new_attribute
->atttypmod
);
509 values
[Anum_pg_attribute_attbyval
- 1] = BoolGetDatum(new_attribute
->attbyval
);
510 values
[Anum_pg_attribute_attstorage
- 1] = CharGetDatum(new_attribute
->attstorage
);
511 values
[Anum_pg_attribute_attalign
- 1] = CharGetDatum(new_attribute
->attalign
);
512 values
[Anum_pg_attribute_attnotnull
- 1] = BoolGetDatum(new_attribute
->attnotnull
);
513 values
[Anum_pg_attribute_atthasdef
- 1] = BoolGetDatum(new_attribute
->atthasdef
);
514 values
[Anum_pg_attribute_attisdropped
- 1] = BoolGetDatum(new_attribute
->attisdropped
);
515 values
[Anum_pg_attribute_attislocal
- 1] = BoolGetDatum(new_attribute
->attislocal
);
516 values
[Anum_pg_attribute_attinhcount
- 1] = Int32GetDatum(new_attribute
->attinhcount
);
518 /* start out with empty permissions */
519 nulls
[Anum_pg_attribute_attacl
- 1] = true;
521 tup
= heap_form_tuple(RelationGetDescr(pg_attribute_rel
), values
, nulls
);
523 /* finally insert the new tuple, update the indexes, and clean up */
524 simple_heap_insert(pg_attribute_rel
, tup
);
526 if (indstate
!= NULL
)
527 CatalogIndexInsert(indstate
, tup
);
529 CatalogUpdateIndexes(pg_attribute_rel
, tup
);
533 /* --------------------------------
534 * AddNewAttributeTuples
536 * this registers the new relation's schema by adding
537 * tuples to pg_attribute.
538 * --------------------------------
541 AddNewAttributeTuples(Oid new_rel_oid
,
547 Form_pg_attribute attr
;
550 CatalogIndexState indstate
;
551 int natts
= tupdesc
->natts
;
552 ObjectAddress myself
,
556 * open pg_attribute and its indexes.
558 rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
560 indstate
= CatalogOpenIndexes(rel
);
563 * First we add the user attributes. This is also a convenient place to
564 * add dependencies on their datatypes.
566 for (i
= 0; i
< natts
; i
++)
568 attr
= tupdesc
->attrs
[i
];
569 /* Fill in the correct relation OID */
570 attr
->attrelid
= new_rel_oid
;
571 /* Make sure these are OK, too */
572 attr
->attstattarget
= -1;
573 attr
->attcacheoff
= -1;
575 InsertPgAttributeTuple(rel
, attr
, indstate
);
577 /* Add dependency info */
578 myself
.classId
= RelationRelationId
;
579 myself
.objectId
= new_rel_oid
;
580 myself
.objectSubId
= i
+ 1;
581 referenced
.classId
= TypeRelationId
;
582 referenced
.objectId
= attr
->atttypid
;
583 referenced
.objectSubId
= 0;
584 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
588 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
589 * all for a view or type relation. We don't bother with making datatype
590 * dependencies here, since presumably all these types are pinned.
592 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
594 for (i
= 0; i
< (int) lengthof(SysAtt
); i
++)
596 FormData_pg_attribute attStruct
;
598 /* skip OID where appropriate */
599 if (!tupdesc
->tdhasoid
&&
600 SysAtt
[i
]->attnum
== ObjectIdAttributeNumber
)
603 memcpy(&attStruct
, (char *) SysAtt
[i
], sizeof(FormData_pg_attribute
));
605 /* Fill in the correct relation OID in the copied tuple */
606 attStruct
.attrelid
= new_rel_oid
;
608 /* Fill in correct inheritance info for the OID column */
609 if (attStruct
.attnum
== ObjectIdAttributeNumber
)
611 attStruct
.attislocal
= oidislocal
;
612 attStruct
.attinhcount
= oidinhcount
;
615 InsertPgAttributeTuple(rel
, &attStruct
, indstate
);
622 CatalogCloseIndexes(indstate
);
624 heap_close(rel
, RowExclusiveLock
);
627 /* --------------------------------
630 * Construct and insert a new tuple in pg_class.
632 * Caller has already opened and locked pg_class.
633 * Tuple data is taken from new_rel_desc->rd_rel, except for the
634 * variable-width fields which are not present in a cached reldesc.
635 * We always initialize relacl to NULL (i.e., default permissions),
636 * and reloptions is set to the passed-in text array (if any).
637 * --------------------------------
640 InsertPgClassTuple(Relation pg_class_desc
,
641 Relation new_rel_desc
,
645 Form_pg_class rd_rel
= new_rel_desc
->rd_rel
;
646 Datum values
[Natts_pg_class
];
647 bool nulls
[Natts_pg_class
];
650 /* This is a tad tedious, but way cleaner than what we used to do... */
651 memset(values
, 0, sizeof(values
));
652 memset(nulls
, false, sizeof(nulls
));
654 values
[Anum_pg_class_relname
- 1] = NameGetDatum(&rd_rel
->relname
);
655 values
[Anum_pg_class_relnamespace
- 1] = ObjectIdGetDatum(rd_rel
->relnamespace
);
656 values
[Anum_pg_class_reltype
- 1] = ObjectIdGetDatum(rd_rel
->reltype
);
657 values
[Anum_pg_class_relowner
- 1] = ObjectIdGetDatum(rd_rel
->relowner
);
658 values
[Anum_pg_class_relam
- 1] = ObjectIdGetDatum(rd_rel
->relam
);
659 values
[Anum_pg_class_relfilenode
- 1] = ObjectIdGetDatum(rd_rel
->relfilenode
);
660 values
[Anum_pg_class_reltablespace
- 1] = ObjectIdGetDatum(rd_rel
->reltablespace
);
661 values
[Anum_pg_class_relpages
- 1] = Int32GetDatum(rd_rel
->relpages
);
662 values
[Anum_pg_class_reltuples
- 1] = Float4GetDatum(rd_rel
->reltuples
);
663 values
[Anum_pg_class_reltoastrelid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastrelid
);
664 values
[Anum_pg_class_reltoastidxid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastidxid
);
665 values
[Anum_pg_class_relhasindex
- 1] = BoolGetDatum(rd_rel
->relhasindex
);
666 values
[Anum_pg_class_relisshared
- 1] = BoolGetDatum(rd_rel
->relisshared
);
667 values
[Anum_pg_class_relistemp
- 1] = BoolGetDatum(rd_rel
->relistemp
);
668 values
[Anum_pg_class_relkind
- 1] = CharGetDatum(rd_rel
->relkind
);
669 values
[Anum_pg_class_relnatts
- 1] = Int16GetDatum(rd_rel
->relnatts
);
670 values
[Anum_pg_class_relchecks
- 1] = Int16GetDatum(rd_rel
->relchecks
);
671 values
[Anum_pg_class_relhasoids
- 1] = BoolGetDatum(rd_rel
->relhasoids
);
672 values
[Anum_pg_class_relhaspkey
- 1] = BoolGetDatum(rd_rel
->relhaspkey
);
673 values
[Anum_pg_class_relhasrules
- 1] = BoolGetDatum(rd_rel
->relhasrules
);
674 values
[Anum_pg_class_relhastriggers
- 1] = BoolGetDatum(rd_rel
->relhastriggers
);
675 values
[Anum_pg_class_relhassubclass
- 1] = BoolGetDatum(rd_rel
->relhassubclass
);
676 values
[Anum_pg_class_relfrozenxid
- 1] = TransactionIdGetDatum(rd_rel
->relfrozenxid
);
677 /* start out with empty permissions */
678 nulls
[Anum_pg_class_relacl
- 1] = true;
679 if (reloptions
!= (Datum
) 0)
680 values
[Anum_pg_class_reloptions
- 1] = reloptions
;
682 nulls
[Anum_pg_class_reloptions
- 1] = true;
684 tup
= heap_form_tuple(RelationGetDescr(pg_class_desc
), values
, nulls
);
687 * The new tuple must have the oid already chosen for the rel. Sure would
688 * be embarrassing to do this sort of thing in polite company.
690 HeapTupleSetOid(tup
, new_rel_oid
);
692 /* finally insert the new tuple, update the indexes, and clean up */
693 simple_heap_insert(pg_class_desc
, tup
);
695 CatalogUpdateIndexes(pg_class_desc
, tup
);
700 /* --------------------------------
701 * AddNewRelationTuple
703 * this registers the new relation in the catalogs by
704 * adding a tuple to pg_class.
705 * --------------------------------
708 AddNewRelationTuple(Relation pg_class_desc
,
709 Relation new_rel_desc
,
716 Form_pg_class new_rel_reltup
;
719 * first we update some of the information in our uncataloged relation's
720 * relation descriptor.
722 new_rel_reltup
= new_rel_desc
->rd_rel
;
726 case RELKIND_RELATION
:
728 case RELKIND_TOASTVALUE
:
729 /* The relation is real, but as yet empty */
730 new_rel_reltup
->relpages
= 0;
731 new_rel_reltup
->reltuples
= 0;
733 case RELKIND_SEQUENCE
:
734 /* Sequences always have a known size */
735 new_rel_reltup
->relpages
= 1;
736 new_rel_reltup
->reltuples
= 1;
739 /* Views, etc, have no disk storage */
740 new_rel_reltup
->relpages
= 0;
741 new_rel_reltup
->reltuples
= 0;
745 /* Initialize relfrozenxid */
746 if (relkind
== RELKIND_RELATION
||
747 relkind
== RELKIND_TOASTVALUE
)
750 * Initialize to the minimum XID that could put tuples in the table.
751 * We know that no xacts older than RecentXmin are still running, so
754 new_rel_reltup
->relfrozenxid
= RecentXmin
;
759 * Other relation types will not contain XIDs, so set relfrozenxid to
760 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
761 * we force its xmin to be FrozenTransactionId always; see
762 * commands/sequence.c.)
764 new_rel_reltup
->relfrozenxid
= InvalidTransactionId
;
767 new_rel_reltup
->relowner
= relowner
;
768 new_rel_reltup
->reltype
= new_type_oid
;
769 new_rel_reltup
->relkind
= relkind
;
771 new_rel_desc
->rd_att
->tdtypeid
= new_type_oid
;
773 /* Now build and insert the tuple */
774 InsertPgClassTuple(pg_class_desc
, new_rel_desc
, new_rel_oid
, reloptions
);
778 /* --------------------------------
779 * AddNewRelationType -
781 * define a composite type corresponding to the new relation
782 * --------------------------------
785 AddNewRelationType(const char *typeName
,
793 TypeCreate(InvalidOid
, /* no predetermined OID */
794 typeName
, /* type name */
795 typeNamespace
, /* type namespace */
796 new_rel_oid
, /* relation oid */
797 new_rel_kind
, /* relation kind */
798 ownerid
, /* owner's ID */
799 -1, /* internal size (varlena) */
800 TYPTYPE_COMPOSITE
, /* type-type (composite) */
801 TYPCATEGORY_COMPOSITE
, /* type-category (ditto) */
802 false, /* composite types are never preferred */
803 DEFAULT_TYPDELIM
, /* default array delimiter */
804 F_RECORD_IN
, /* input procedure */
805 F_RECORD_OUT
, /* output procedure */
806 F_RECORD_RECV
, /* receive procedure */
807 F_RECORD_SEND
, /* send procedure */
808 InvalidOid
, /* typmodin procedure - none */
809 InvalidOid
, /* typmodout procedure - none */
810 InvalidOid
, /* analyze procedure - default */
811 InvalidOid
, /* array element type - irrelevant */
812 false, /* this is not an array type */
813 new_array_type
, /* array type if any */
814 InvalidOid
, /* domain base type - irrelevant */
815 NULL
, /* default value - none */
816 NULL
, /* default binary representation */
817 false, /* passed by reference */
818 'd', /* alignment - must be the largest! */
819 'x', /* fully TOASTable */
821 0, /* array dimensions for typBaseType */
822 false); /* Type NOT NULL */
825 /* --------------------------------
826 * heap_create_with_catalog
828 * creates a new cataloged relation. see comments above.
829 * --------------------------------
832 heap_create_with_catalog(const char *relname
,
838 List
*cooked_constraints
,
840 bool shared_relation
,
843 OnCommitAction oncommit
,
845 bool allow_system_table_mods
)
847 Relation pg_class_desc
;
848 Relation new_rel_desc
;
851 Oid new_array_oid
= InvalidOid
;
853 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
858 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
860 CheckAttributeNamesTypes(tupdesc
, relkind
);
862 if (get_relname_relid(relname
, relnamespace
))
864 (errcode(ERRCODE_DUPLICATE_TABLE
),
865 errmsg("relation \"%s\" already exists", relname
)));
868 * Since we are going to create a rowtype as well, also check for
869 * collision with an existing type name. If there is one and it's an
870 * autogenerated array, we can rename it out of the way; otherwise we can
871 * at least give a good error message.
873 old_type_oid
= GetSysCacheOid(TYPENAMENSP
,
874 CStringGetDatum(relname
),
875 ObjectIdGetDatum(relnamespace
),
877 if (OidIsValid(old_type_oid
))
879 if (!moveArrayTypeName(old_type_oid
, relname
, relnamespace
))
881 (errcode(ERRCODE_DUPLICATE_OBJECT
),
882 errmsg("type \"%s\" already exists", relname
),
883 errhint("A relation has an associated type of the same name, "
884 "so you must use a name that doesn't conflict "
885 "with any existing type.")));
889 * Validate shared/non-shared tablespace (must check this before doing
890 * GetNewRelFileNode, to prevent Assert therein)
894 if (reltablespace
!= GLOBALTABLESPACE_OID
)
895 /* elog since this is not a user-facing error */
897 "shared relations must be placed in pg_global tablespace");
901 if (reltablespace
== GLOBALTABLESPACE_OID
)
903 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
904 errmsg("only shared relations can be placed in pg_global tablespace")));
908 * Allocate an OID for the relation, unless we were told what to use.
910 * The OID will be the relfilenode as well, so make sure it doesn't
911 * collide with either pg_class OIDs or existing physical files.
913 if (!OidIsValid(relid
))
914 relid
= GetNewRelFileNode(reltablespace
, shared_relation
,
918 * Create the relcache entry (mostly dummy at this point) and the physical
919 * disk file. (If we fail further down, it's the smgr's responsibility to
920 * remove the disk file again.)
922 new_rel_desc
= heap_create(relname
,
929 allow_system_table_mods
);
931 Assert(relid
== RelationGetRelid(new_rel_desc
));
934 * Decide whether to create an array type over the relation's rowtype. We
935 * do not create any array types for system catalogs (ie, those made
936 * during initdb). We create array types for regular relations, views,
937 * and composite types ... but not, eg, for toast tables or sequences.
939 if (IsUnderPostmaster
&& (relkind
== RELKIND_RELATION
||
940 relkind
== RELKIND_VIEW
||
941 relkind
== RELKIND_COMPOSITE_TYPE
))
943 /* OK, so pre-assign a type OID for the array type */
944 Relation pg_type
= heap_open(TypeRelationId
, AccessShareLock
);
946 new_array_oid
= GetNewOid(pg_type
);
947 heap_close(pg_type
, AccessShareLock
);
951 * Since defining a relation also defines a complex type, we add a new
952 * system type corresponding to the new relation.
954 * NOTE: we could get a unique-index failure here, in case someone else is
955 * creating the same type name in parallel but hadn't committed yet when
956 * we checked for a duplicate name above.
958 new_type_oid
= AddNewRelationType(relname
,
966 * Now make the array type if wanted.
968 if (OidIsValid(new_array_oid
))
972 relarrayname
= makeArrayTypeName(relname
, relnamespace
);
974 TypeCreate(new_array_oid
, /* force the type's OID to this */
975 relarrayname
, /* Array type name */
976 relnamespace
, /* Same namespace as parent */
977 InvalidOid
, /* Not composite, no relationOid */
978 0, /* relkind, also N/A here */
979 ownerid
, /* owner's ID */
980 -1, /* Internal size (varlena) */
981 TYPTYPE_BASE
, /* Not composite - typelem is */
982 TYPCATEGORY_ARRAY
, /* type-category (array) */
983 false, /* array types are never preferred */
984 DEFAULT_TYPDELIM
, /* default array delimiter */
985 F_ARRAY_IN
, /* array input proc */
986 F_ARRAY_OUT
, /* array output proc */
987 F_ARRAY_RECV
, /* array recv (bin) proc */
988 F_ARRAY_SEND
, /* array send (bin) proc */
989 InvalidOid
, /* typmodin procedure - none */
990 InvalidOid
, /* typmodout procedure - none */
991 InvalidOid
, /* analyze procedure - default */
992 new_type_oid
, /* array element type - the rowtype */
993 true, /* yes, this is an array type */
994 InvalidOid
, /* this has no array type */
995 InvalidOid
, /* domain base type - irrelevant */
996 NULL
, /* default value - none */
997 NULL
, /* default binary representation */
998 false, /* passed by reference */
999 'd', /* alignment - must be the largest! */
1000 'x', /* fully TOASTable */
1002 0, /* array dimensions for typBaseType */
1003 false); /* Type NOT NULL */
1005 pfree(relarrayname
);
1009 * now create an entry in pg_class for the relation.
1011 * NOTE: we could get a unique-index failure here, in case someone else is
1012 * creating the same relation name in parallel but hadn't committed yet
1013 * when we checked for a duplicate name above.
1015 AddNewRelationTuple(pg_class_desc
,
1024 * now add tuples to pg_attribute for the attributes in our new relation.
1026 AddNewAttributeTuples(relid
, new_rel_desc
->rd_att
, relkind
,
1027 oidislocal
, oidinhcount
);
1030 * Make a dependency link to force the relation to be deleted if its
1031 * namespace is. Also make a dependency link to its owner.
1033 * For composite types, these dependencies are tracked for the pg_type
1034 * entry, so we needn't record them here. Likewise, TOAST tables don't
1035 * need a namespace dependency (they live in a pinned namespace) nor an
1036 * owner dependency (they depend indirectly through the parent table).
1037 * Also, skip this in bootstrap mode, since we don't make dependencies
1038 * while bootstrapping.
1040 if (relkind
!= RELKIND_COMPOSITE_TYPE
&&
1041 relkind
!= RELKIND_TOASTVALUE
&&
1042 !IsBootstrapProcessingMode())
1044 ObjectAddress myself
,
1047 myself
.classId
= RelationRelationId
;
1048 myself
.objectId
= relid
;
1049 myself
.objectSubId
= 0;
1050 referenced
.classId
= NamespaceRelationId
;
1051 referenced
.objectId
= relnamespace
;
1052 referenced
.objectSubId
= 0;
1053 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
1055 recordDependencyOnOwner(RelationRelationId
, relid
, ownerid
);
1059 * Store any supplied constraints and defaults.
1061 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1062 * entry, so the relation must be valid and self-consistent at this point.
1063 * In particular, there are not yet constraints and defaults anywhere.
1065 StoreConstraints(new_rel_desc
, cooked_constraints
);
1068 * If there's a special on-commit action, remember it
1070 if (oncommit
!= ONCOMMIT_NOOP
)
1071 register_on_commit_action(relid
, oncommit
);
1074 * ok, the relation has been cataloged, so close our relations and return
1075 * the OID of the newly created relation.
1077 heap_close(new_rel_desc
, NoLock
); /* do not unlock till end of xact */
1078 heap_close(pg_class_desc
, RowExclusiveLock
);
1085 * RelationRemoveInheritance
1087 * Formerly, this routine checked for child relations and aborted the
1088 * deletion if any were found. Now we rely on the dependency mechanism
1089 * to check for or delete child relations. By the time we get here,
1090 * there are no children and we need only remove any pg_inherits rows
1091 * linking this relation to its parent(s).
1094 RelationRemoveInheritance(Oid relid
)
1096 Relation catalogRelation
;
1101 catalogRelation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
1104 Anum_pg_inherits_inhrelid
,
1105 BTEqualStrategyNumber
, F_OIDEQ
,
1106 ObjectIdGetDatum(relid
));
1108 scan
= systable_beginscan(catalogRelation
, InheritsRelidSeqnoIndexId
, true,
1109 SnapshotNow
, 1, &key
);
1111 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1112 simple_heap_delete(catalogRelation
, &tuple
->t_self
);
1114 systable_endscan(scan
);
1115 heap_close(catalogRelation
, RowExclusiveLock
);
1119 * DeleteRelationTuple
1121 * Remove pg_class row for the given relid.
1123 * Note: this is shared by relation deletion and index deletion. It's
1124 * not intended for use anyplace else.
1127 DeleteRelationTuple(Oid relid
)
1129 Relation pg_class_desc
;
1132 /* Grab an appropriate lock on the pg_class relation */
1133 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
1135 tup
= SearchSysCache(RELOID
,
1136 ObjectIdGetDatum(relid
),
1138 if (!HeapTupleIsValid(tup
))
1139 elog(ERROR
, "cache lookup failed for relation %u", relid
);
1141 /* delete the relation tuple from pg_class, and finish up */
1142 simple_heap_delete(pg_class_desc
, &tup
->t_self
);
1144 ReleaseSysCache(tup
);
1146 heap_close(pg_class_desc
, RowExclusiveLock
);
1150 * DeleteAttributeTuples
1152 * Remove pg_attribute rows for the given relid.
1154 * Note: this is shared by relation deletion and index deletion. It's
1155 * not intended for use anyplace else.
1158 DeleteAttributeTuples(Oid relid
)
1165 /* Grab an appropriate lock on the pg_attribute relation */
1166 attrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1168 /* Use the index to scan only attributes of the target relation */
1169 ScanKeyInit(&key
[0],
1170 Anum_pg_attribute_attrelid
,
1171 BTEqualStrategyNumber
, F_OIDEQ
,
1172 ObjectIdGetDatum(relid
));
1174 scan
= systable_beginscan(attrel
, AttributeRelidNumIndexId
, true,
1175 SnapshotNow
, 1, key
);
1177 /* Delete all the matching tuples */
1178 while ((atttup
= systable_getnext(scan
)) != NULL
)
1179 simple_heap_delete(attrel
, &atttup
->t_self
);
1181 /* Clean up after the scan */
1182 systable_endscan(scan
);
1183 heap_close(attrel
, RowExclusiveLock
);
1187 * RemoveAttributeById
1189 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1190 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1191 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1192 * is handled by dependency.c.)
1195 RemoveAttributeById(Oid relid
, AttrNumber attnum
)
1200 Form_pg_attribute attStruct
;
1201 char newattname
[NAMEDATALEN
];
1204 * Grab an exclusive lock on the target table, which we will NOT release
1205 * until end of transaction. (In the simple case where we are directly
1206 * dropping this column, AlterTableDropColumn already did this ... but
1207 * when cascading from a drop of some other object, we may not have any
1210 rel
= relation_open(relid
, AccessExclusiveLock
);
1212 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1214 tuple
= SearchSysCacheCopy(ATTNUM
,
1215 ObjectIdGetDatum(relid
),
1216 Int16GetDatum(attnum
),
1218 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1219 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1221 attStruct
= (Form_pg_attribute
) GETSTRUCT(tuple
);
1225 /* System attribute (probably OID) ... just delete the row */
1227 simple_heap_delete(attr_rel
, &tuple
->t_self
);
1231 /* Dropping user attributes is lots harder */
1233 /* Mark the attribute as dropped */
1234 attStruct
->attisdropped
= true;
1237 * Set the type OID to invalid. A dropped attribute's type link
1238 * cannot be relied on (once the attribute is dropped, the type might
1239 * be too). Fortunately we do not need the type row --- the only
1240 * really essential information is the type's typlen and typalign,
1241 * which are preserved in the attribute's attlen and attalign. We set
1242 * atttypid to zero here as a means of catching code that incorrectly
1243 * expects it to be valid.
1245 attStruct
->atttypid
= InvalidOid
;
1247 /* Remove any NOT NULL constraint the column may have */
1248 attStruct
->attnotnull
= false;
1250 /* We don't want to keep stats for it anymore */
1251 attStruct
->attstattarget
= 0;
1254 * Change the column name to something that isn't likely to conflict
1256 snprintf(newattname
, sizeof(newattname
),
1257 "........pg.dropped.%d........", attnum
);
1258 namestrcpy(&(attStruct
->attname
), newattname
);
1260 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1262 /* keep the system catalog indexes current */
1263 CatalogUpdateIndexes(attr_rel
, tuple
);
1267 * Because updating the pg_attribute row will trigger a relcache flush for
1268 * the target relation, we need not do anything else to notify other
1269 * backends of the change.
1272 heap_close(attr_rel
, RowExclusiveLock
);
1275 RemoveStatistics(relid
, attnum
);
1277 relation_close(rel
, NoLock
);
1283 * If the specified relation/attribute has a default, remove it.
1284 * (If no default, raise error if complain is true, else return quietly.)
1287 RemoveAttrDefault(Oid relid
, AttrNumber attnum
,
1288 DropBehavior behavior
, bool complain
)
1290 Relation attrdef_rel
;
1291 ScanKeyData scankeys
[2];
1296 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1298 ScanKeyInit(&scankeys
[0],
1299 Anum_pg_attrdef_adrelid
,
1300 BTEqualStrategyNumber
, F_OIDEQ
,
1301 ObjectIdGetDatum(relid
));
1302 ScanKeyInit(&scankeys
[1],
1303 Anum_pg_attrdef_adnum
,
1304 BTEqualStrategyNumber
, F_INT2EQ
,
1305 Int16GetDatum(attnum
));
1307 scan
= systable_beginscan(attrdef_rel
, AttrDefaultIndexId
, true,
1308 SnapshotNow
, 2, scankeys
);
1310 /* There should be at most one matching tuple, but we loop anyway */
1311 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1313 ObjectAddress object
;
1315 object
.classId
= AttrDefaultRelationId
;
1316 object
.objectId
= HeapTupleGetOid(tuple
);
1317 object
.objectSubId
= 0;
1319 performDeletion(&object
, behavior
);
1324 systable_endscan(scan
);
1325 heap_close(attrdef_rel
, RowExclusiveLock
);
1327 if (complain
&& !found
)
1328 elog(ERROR
, "could not find attrdef tuple for relation %u attnum %d",
1333 * RemoveAttrDefaultById
1335 * Remove a pg_attrdef entry specified by OID. This is the guts of
1336 * attribute-default removal. Note it should be called via performDeletion,
1340 RemoveAttrDefaultById(Oid attrdefId
)
1342 Relation attrdef_rel
;
1345 ScanKeyData scankeys
[1];
1349 AttrNumber myattnum
;
1351 /* Grab an appropriate lock on the pg_attrdef relation */
1352 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1354 /* Find the pg_attrdef tuple */
1355 ScanKeyInit(&scankeys
[0],
1356 ObjectIdAttributeNumber
,
1357 BTEqualStrategyNumber
, F_OIDEQ
,
1358 ObjectIdGetDatum(attrdefId
));
1360 scan
= systable_beginscan(attrdef_rel
, AttrDefaultOidIndexId
, true,
1361 SnapshotNow
, 1, scankeys
);
1363 tuple
= systable_getnext(scan
);
1364 if (!HeapTupleIsValid(tuple
))
1365 elog(ERROR
, "could not find tuple for attrdef %u", attrdefId
);
1367 myrelid
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adrelid
;
1368 myattnum
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adnum
;
1370 /* Get an exclusive lock on the relation owning the attribute */
1371 myrel
= relation_open(myrelid
, AccessExclusiveLock
);
1373 /* Now we can delete the pg_attrdef row */
1374 simple_heap_delete(attrdef_rel
, &tuple
->t_self
);
1376 systable_endscan(scan
);
1377 heap_close(attrdef_rel
, RowExclusiveLock
);
1379 /* Fix the pg_attribute row */
1380 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1382 tuple
= SearchSysCacheCopy(ATTNUM
,
1383 ObjectIdGetDatum(myrelid
),
1384 Int16GetDatum(myattnum
),
1386 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1387 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1390 ((Form_pg_attribute
) GETSTRUCT(tuple
))->atthasdef
= false;
1392 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1394 /* keep the system catalog indexes current */
1395 CatalogUpdateIndexes(attr_rel
, tuple
);
1398 * Our update of the pg_attribute row will force a relcache rebuild, so
1399 * there's nothing else to do here.
1401 heap_close(attr_rel
, RowExclusiveLock
);
1403 /* Keep lock on attribute's rel until end of xact */
1404 relation_close(myrel
, NoLock
);
1408 * heap_drop_with_catalog - removes specified relation from catalogs
1410 * Note that this routine is not responsible for dropping objects that are
1411 * linked to the pg_class entry via dependencies (for example, indexes and
1412 * constraints). Those are deleted by the dependency-tracing logic in
1413 * dependency.c before control gets here. In general, therefore, this routine
1414 * should never be called directly; go through performDeletion() instead.
1417 heap_drop_with_catalog(Oid relid
)
1422 * Open and lock the relation.
1424 rel
= relation_open(relid
, AccessExclusiveLock
);
1427 * There can no longer be anyone *else* touching the relation, but we
1428 * might still have open queries or cursors in our own session.
1430 if (rel
->rd_refcnt
!= 1)
1432 (errcode(ERRCODE_OBJECT_IN_USE
),
1433 errmsg("cannot drop \"%s\" because "
1434 "it is being used by active queries in this session",
1435 RelationGetRelationName(rel
))));
1438 * Schedule unlinking of the relation's physical files at commit.
1440 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
&&
1441 rel
->rd_rel
->relkind
!= RELKIND_COMPOSITE_TYPE
)
1443 RelationDropStorage(rel
);
1447 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1448 * until transaction commit. This ensures no one else will try to do
1449 * something with the doomed relation.
1451 relation_close(rel
, NoLock
);
1454 * Forget any ON COMMIT action for the rel
1456 remove_on_commit_action(relid
);
1459 * Flush the relation from the relcache. We want to do this before
1460 * starting to remove catalog entries, just to be certain that no relcache
1461 * entry rebuild will happen partway through. (That should not really
1462 * matter, since we don't do CommandCounterIncrement here, but let's be
1465 RelationForgetRelation(relid
);
1468 * remove inheritance information
1470 RelationRemoveInheritance(relid
);
1475 RemoveStatistics(relid
, 0);
1478 * delete attribute tuples
1480 DeleteAttributeTuples(relid
);
1483 * delete relation tuple
1485 DeleteRelationTuple(relid
);
1490 * Store a default expression for column attnum of relation rel.
1493 StoreAttrDefault(Relation rel
, AttrNumber attnum
, Node
*expr
)
1500 static bool nulls
[4] = {false, false, false, false};
1503 Form_pg_attribute attStruct
;
1505 ObjectAddress colobject
,
1509 * Flatten expression to string form for storage.
1511 adbin
= nodeToString(expr
);
1514 * Also deparse it to form the mostly-obsolete adsrc field.
1516 adsrc
= deparse_expression(expr
,
1517 deparse_context_for(RelationGetRelationName(rel
),
1518 RelationGetRelid(rel
)),
1522 * Make the pg_attrdef entry.
1524 values
[Anum_pg_attrdef_adrelid
- 1] = RelationGetRelid(rel
);
1525 values
[Anum_pg_attrdef_adnum
- 1] = attnum
;
1526 values
[Anum_pg_attrdef_adbin
- 1] = CStringGetTextDatum(adbin
);
1527 values
[Anum_pg_attrdef_adsrc
- 1] = CStringGetTextDatum(adsrc
);
1529 adrel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1531 tuple
= heap_form_tuple(adrel
->rd_att
, values
, nulls
);
1532 attrdefOid
= simple_heap_insert(adrel
, tuple
);
1534 CatalogUpdateIndexes(adrel
, tuple
);
1536 defobject
.classId
= AttrDefaultRelationId
;
1537 defobject
.objectId
= attrdefOid
;
1538 defobject
.objectSubId
= 0;
1540 heap_close(adrel
, RowExclusiveLock
);
1542 /* now can free some of the stuff allocated above */
1543 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adbin
- 1]));
1544 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adsrc
- 1]));
1545 heap_freetuple(tuple
);
1550 * Update the pg_attribute entry for the column to show that a default
1553 attrrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1554 atttup
= SearchSysCacheCopy(ATTNUM
,
1555 ObjectIdGetDatum(RelationGetRelid(rel
)),
1556 Int16GetDatum(attnum
),
1558 if (!HeapTupleIsValid(atttup
))
1559 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1560 attnum
, RelationGetRelid(rel
));
1561 attStruct
= (Form_pg_attribute
) GETSTRUCT(atttup
);
1562 if (!attStruct
->atthasdef
)
1564 attStruct
->atthasdef
= true;
1565 simple_heap_update(attrrel
, &atttup
->t_self
, atttup
);
1566 /* keep catalog indexes current */
1567 CatalogUpdateIndexes(attrrel
, atttup
);
1569 heap_close(attrrel
, RowExclusiveLock
);
1570 heap_freetuple(atttup
);
1573 * Make a dependency so that the pg_attrdef entry goes away if the column
1574 * (or whole table) is deleted.
1576 colobject
.classId
= RelationRelationId
;
1577 colobject
.objectId
= RelationGetRelid(rel
);
1578 colobject
.objectSubId
= attnum
;
1580 recordDependencyOn(&defobject
, &colobject
, DEPENDENCY_AUTO
);
1583 * Record dependencies on objects used in the expression, too.
1585 recordDependencyOnExpr(&defobject
, expr
, NIL
, DEPENDENCY_NORMAL
);
1589 * Store a check-constraint expression for the given relation.
1591 * Caller is responsible for updating the count of constraints
1592 * in the pg_class entry for the relation.
1595 StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
1596 bool is_local
, int inhcount
)
1605 * Flatten expression to string form for storage.
1607 ccbin
= nodeToString(expr
);
1610 * Also deparse it to form the mostly-obsolete consrc field.
1612 ccsrc
= deparse_expression(expr
,
1613 deparse_context_for(RelationGetRelationName(rel
),
1614 RelationGetRelid(rel
)),
1618 * Find columns of rel that are used in expr
1620 * NB: pull_var_clause is okay here only because we don't allow subselects
1621 * in check constraints; it would fail to examine the contents of
1624 varList
= pull_var_clause(expr
, PVC_REJECT_PLACEHOLDERS
);
1625 keycount
= list_length(varList
);
1632 attNos
= (int16
*) palloc(keycount
* sizeof(int16
));
1633 foreach(vl
, varList
)
1635 Var
*var
= (Var
*) lfirst(vl
);
1638 for (j
= 0; j
< i
; j
++)
1639 if (attNos
[j
] == var
->varattno
)
1642 attNos
[i
++] = var
->varattno
;
1650 * Create the Check Constraint
1652 CreateConstraintEntry(ccname
, /* Constraint Name */
1653 RelationGetNamespace(rel
), /* namespace */
1654 CONSTRAINT_CHECK
, /* Constraint Type */
1655 false, /* Is Deferrable */
1656 false, /* Is Deferred */
1657 RelationGetRelid(rel
), /* relation */
1658 attNos
, /* attrs in the constraint */
1659 keycount
, /* # attrs in the constraint */
1660 InvalidOid
, /* not a domain constraint */
1661 InvalidOid
, /* Foreign key fields */
1670 InvalidOid
, /* no associated index */
1671 expr
, /* Tree form check constraint */
1672 ccbin
, /* Binary form check constraint */
1673 ccsrc
, /* Source form check constraint */
1674 is_local
, /* conislocal */
1675 inhcount
); /* coninhcount */
1682 * Store defaults and constraints (passed as a list of CookedConstraint).
1684 * NOTE: only pre-cooked expressions will be passed this way, which is to
1685 * say expressions inherited from an existing relation. Newly parsed
1686 * expressions can be added later, by direct calls to StoreAttrDefault
1687 * and StoreRelCheck (see AddRelationNewConstraints()).
1690 StoreConstraints(Relation rel
, List
*cooked_constraints
)
1695 if (!cooked_constraints
)
1696 return; /* nothing to do */
1699 * Deparsing of constraint expressions will fail unless the just-created
1700 * pg_attribute tuples for this relation are made visible. So, bump the
1701 * command counter. CAUTION: this will cause a relcache entry rebuild.
1703 CommandCounterIncrement();
1705 foreach(lc
, cooked_constraints
)
1707 CookedConstraint
*con
= (CookedConstraint
*) lfirst(lc
);
1709 switch (con
->contype
)
1711 case CONSTR_DEFAULT
:
1712 StoreAttrDefault(rel
, con
->attnum
, con
->expr
);
1715 StoreRelCheck(rel
, con
->name
, con
->expr
,
1716 con
->is_local
, con
->inhcount
);
1720 elog(ERROR
, "unrecognized constraint type: %d",
1721 (int) con
->contype
);
1726 SetRelationNumChecks(rel
, numchecks
);
1730 * AddRelationNewConstraints
1732 * Add new column default expressions and/or constraint check expressions
1733 * to an existing relation. This is defined to do both for efficiency in
1734 * DefineRelation, but of course you can do just one or the other by passing
1737 * rel: relation to be modified
1738 * newColDefaults: list of RawColumnDefault structures
1739 * newConstraints: list of Constraint nodes
1740 * allow_merge: TRUE if check constraints may be merged with existing ones
1741 * is_local: TRUE if definition is local, FALSE if it's inherited
1743 * All entries in newColDefaults will be processed. Entries in newConstraints
1744 * will be processed only if they are CONSTR_CHECK type.
1746 * Returns a list of CookedConstraint nodes that shows the cooked form of
1747 * the default and constraint expressions added to the relation.
1749 * NB: caller should have opened rel with AccessExclusiveLock, and should
1750 * hold that lock till end of transaction. Also, we assume the caller has
1751 * done a CommandCounterIncrement if necessary to make the relation's catalog
1755 AddRelationNewConstraints(Relation rel
,
1756 List
*newColDefaults
,
1757 List
*newConstraints
,
1761 List
*cookedConstraints
= NIL
;
1762 TupleDesc tupleDesc
;
1763 TupleConstr
*oldconstr
;
1771 CookedConstraint
*cooked
;
1774 * Get info about existing constraints.
1776 tupleDesc
= RelationGetDescr(rel
);
1777 oldconstr
= tupleDesc
->constr
;
1779 numoldchecks
= oldconstr
->num_check
;
1784 * Create a dummy ParseState and insert the target relation as its sole
1785 * rangetable entry. We need a ParseState for transformExpr.
1787 pstate
= make_parsestate(NULL
);
1788 rte
= addRangeTableEntryForRelation(pstate
,
1793 addRTEtoQuery(pstate
, rte
, true, true, true);
1796 * Process column default expressions.
1798 foreach(cell
, newColDefaults
)
1800 RawColumnDefault
*colDef
= (RawColumnDefault
*) lfirst(cell
);
1801 Form_pg_attribute atp
= rel
->rd_att
->attrs
[colDef
->attnum
- 1];
1803 expr
= cookDefault(pstate
, colDef
->raw_default
,
1804 atp
->atttypid
, atp
->atttypmod
,
1805 NameStr(atp
->attname
));
1808 * If the expression is just a NULL constant, we do not bother to make
1809 * an explicit pg_attrdef entry, since the default behavior is
1812 * Note a nonobvious property of this test: if the column is of a
1813 * domain type, what we'll get is not a bare null Const but a
1814 * CoerceToDomain expr, so we will not discard the default. This is
1815 * critical because the column default needs to be retained to
1816 * override any default that the domain might have.
1819 (IsA(expr
, Const
) &&((Const
*) expr
)->constisnull
))
1822 StoreAttrDefault(rel
, colDef
->attnum
, expr
);
1824 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1825 cooked
->contype
= CONSTR_DEFAULT
;
1826 cooked
->name
= NULL
;
1827 cooked
->attnum
= colDef
->attnum
;
1828 cooked
->expr
= expr
;
1829 cooked
->is_local
= is_local
;
1830 cooked
->inhcount
= is_local
? 0 : 1;
1831 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1835 * Process constraint expressions.
1837 numchecks
= numoldchecks
;
1839 foreach(cell
, newConstraints
)
1841 Constraint
*cdef
= (Constraint
*) lfirst(cell
);
1844 if (cdef
->contype
!= CONSTR_CHECK
)
1847 if (cdef
->raw_expr
!= NULL
)
1849 Assert(cdef
->cooked_expr
== NULL
);
1852 * Transform raw parsetree to executable expression, and verify
1853 * it's valid as a CHECK constraint.
1855 expr
= cookConstraint(pstate
, cdef
->raw_expr
,
1856 RelationGetRelationName(rel
));
1860 Assert(cdef
->cooked_expr
!= NULL
);
1863 * Here, we assume the parser will only pass us valid CHECK
1864 * expressions, so we do no particular checking.
1866 expr
= stringToNode(cdef
->cooked_expr
);
1870 * Check name uniqueness, or generate a name if none was given.
1872 if (cdef
->name
!= NULL
)
1876 ccname
= cdef
->name
;
1877 /* Check against other new constraints */
1878 /* Needed because we don't do CommandCounterIncrement in loop */
1879 foreach(cell2
, checknames
)
1881 if (strcmp((char *) lfirst(cell2
), ccname
) == 0)
1883 (errcode(ERRCODE_DUPLICATE_OBJECT
),
1884 errmsg("check constraint \"%s\" already exists",
1888 /* save name for future checks */
1889 checknames
= lappend(checknames
, ccname
);
1892 * Check against pre-existing constraints. If we are allowed
1893 * to merge with an existing constraint, there's no more to
1894 * do here. (We omit the duplicate constraint from the result,
1895 * which is what ATAddCheckConstraint wants.)
1897 if (MergeWithExistingConstraint(rel
, ccname
, expr
,
1898 allow_merge
, is_local
))
1904 * When generating a name, we want to create "tab_col_check" for a
1905 * column constraint and "tab_check" for a table constraint. We
1906 * no longer have any info about the syntactic positioning of the
1907 * constraint phrase, so we approximate this by seeing whether the
1908 * expression references more than one column. (If the user
1909 * played by the rules, the result is the same...)
1911 * Note: pull_var_clause() doesn't descend into sublinks, but we
1912 * eliminated those above; and anyway this only needs to be an
1913 * approximate answer.
1918 vars
= pull_var_clause(expr
, PVC_REJECT_PLACEHOLDERS
);
1920 /* eliminate duplicates */
1921 vars
= list_union(NIL
, vars
);
1923 if (list_length(vars
) == 1)
1924 colname
= get_attname(RelationGetRelid(rel
),
1925 ((Var
*) linitial(vars
))->varattno
);
1929 ccname
= ChooseConstraintName(RelationGetRelationName(rel
),
1932 RelationGetNamespace(rel
),
1935 /* save name for future checks */
1936 checknames
= lappend(checknames
, ccname
);
1942 StoreRelCheck(rel
, ccname
, expr
, is_local
, is_local
? 0 : 1);
1946 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1947 cooked
->contype
= CONSTR_CHECK
;
1948 cooked
->name
= ccname
;
1950 cooked
->expr
= expr
;
1951 cooked
->is_local
= is_local
;
1952 cooked
->inhcount
= is_local
? 0 : 1;
1953 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1957 * Update the count of constraints in the relation's pg_class tuple. We do
1958 * this even if there was no change, in order to ensure that an SI update
1959 * message is sent out for the pg_class tuple, which will force other
1960 * backends to rebuild their relcache entries for the rel. (This is
1961 * critical if we added defaults but not constraints.)
1963 SetRelationNumChecks(rel
, numchecks
);
1965 return cookedConstraints
;
1969 * Check for a pre-existing check constraint that conflicts with a proposed
1970 * new one, and either adjust its conislocal/coninhcount settings or throw
1973 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1974 * got a so-far-unique name, or throws error if conflict.
1977 MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
1978 bool allow_merge
, bool is_local
)
1982 SysScanDesc conscan
;
1983 ScanKeyData skey
[2];
1986 /* Search for a pg_constraint entry with same name and relation */
1987 conDesc
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
1991 ScanKeyInit(&skey
[0],
1992 Anum_pg_constraint_conname
,
1993 BTEqualStrategyNumber
, F_NAMEEQ
,
1994 CStringGetDatum(ccname
));
1996 ScanKeyInit(&skey
[1],
1997 Anum_pg_constraint_connamespace
,
1998 BTEqualStrategyNumber
, F_OIDEQ
,
1999 ObjectIdGetDatum(RelationGetNamespace(rel
)));
2001 conscan
= systable_beginscan(conDesc
, ConstraintNameNspIndexId
, true,
2002 SnapshotNow
, 2, skey
);
2004 while (HeapTupleIsValid(tup
= systable_getnext(conscan
)))
2006 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tup
);
2008 if (con
->conrelid
== RelationGetRelid(rel
))
2010 /* Found it. Conflicts if not identical check constraint */
2011 if (con
->contype
== CONSTRAINT_CHECK
)
2016 val
= fastgetattr(tup
,
2017 Anum_pg_constraint_conbin
,
2018 conDesc
->rd_att
, &isnull
);
2020 elog(ERROR
, "null conbin for rel %s",
2021 RelationGetRelationName(rel
));
2022 if (equal(expr
, stringToNode(TextDatumGetCString(val
))))
2025 if (!found
|| !allow_merge
)
2027 (errcode(ERRCODE_DUPLICATE_OBJECT
),
2028 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2029 ccname
, RelationGetRelationName(rel
))));
2030 /* OK to update the tuple */
2032 (errmsg("merging constraint \"%s\" with inherited definition",
2034 tup
= heap_copytuple(tup
);
2035 con
= (Form_pg_constraint
) GETSTRUCT(tup
);
2037 con
->conislocal
= true;
2040 simple_heap_update(conDesc
, &tup
->t_self
, tup
);
2041 CatalogUpdateIndexes(conDesc
, tup
);
2046 systable_endscan(conscan
);
2047 heap_close(conDesc
, RowExclusiveLock
);
2053 * Update the count of constraints in the relation's pg_class tuple.
2055 * Caller had better hold exclusive lock on the relation.
2057 * An important side effect is that a SI update message will be sent out for
2058 * the pg_class tuple, which will force other backends to rebuild their
2059 * relcache entries for the rel. Also, this backend will rebuild its
2060 * own relcache entry at the next CommandCounterIncrement.
2063 SetRelationNumChecks(Relation rel
, int numchecks
)
2067 Form_pg_class relStruct
;
2069 relrel
= heap_open(RelationRelationId
, RowExclusiveLock
);
2070 reltup
= SearchSysCacheCopy(RELOID
,
2071 ObjectIdGetDatum(RelationGetRelid(rel
)),
2073 if (!HeapTupleIsValid(reltup
))
2074 elog(ERROR
, "cache lookup failed for relation %u",
2075 RelationGetRelid(rel
));
2076 relStruct
= (Form_pg_class
) GETSTRUCT(reltup
);
2078 if (relStruct
->relchecks
!= numchecks
)
2080 relStruct
->relchecks
= numchecks
;
2082 simple_heap_update(relrel
, &reltup
->t_self
, reltup
);
2084 /* keep catalog indexes current */
2085 CatalogUpdateIndexes(relrel
, reltup
);
2089 /* Skip the disk update, but force relcache inval anyway */
2090 CacheInvalidateRelcache(rel
);
2093 heap_freetuple(reltup
);
2094 heap_close(relrel
, RowExclusiveLock
);
2098 * Take a raw default and convert it to a cooked format ready for
2101 * Parse state should be set up to recognize any vars that might appear
2102 * in the expression. (Even though we plan to reject vars, it's more
2103 * user-friendly to give the correct error message than "unknown var".)
2105 * If atttypid is not InvalidOid, coerce the expression to the specified
2106 * type (and typmod atttypmod). attname is only needed in this case:
2107 * it is used in the error message, if any.
2110 cookDefault(ParseState
*pstate
,
2118 Assert(raw_default
!= NULL
);
2121 * Transform raw parsetree to executable expression.
2123 expr
= transformExpr(pstate
, raw_default
);
2126 * Make sure default expr does not refer to any vars.
2128 if (contain_var_clause(expr
))
2130 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2131 errmsg("cannot use column references in default expression")));
2134 * It can't return a set either.
2136 if (expression_returns_set(expr
))
2138 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2139 errmsg("default expression must not return a set")));
2142 * No subplans or aggregates, either...
2144 if (pstate
->p_hasSubLinks
)
2146 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2147 errmsg("cannot use subquery in default expression")));
2148 if (pstate
->p_hasAggs
)
2150 (errcode(ERRCODE_GROUPING_ERROR
),
2151 errmsg("cannot use aggregate function in default expression")));
2152 if (pstate
->p_hasWindowFuncs
)
2154 (errcode(ERRCODE_WINDOWING_ERROR
),
2155 errmsg("cannot use window function in default expression")));
2158 * Coerce the expression to the correct type and typmod, if given. This
2159 * should match the parser's processing of non-defaulted expressions ---
2160 * see transformAssignedExpr().
2162 if (OidIsValid(atttypid
))
2164 Oid type_id
= exprType(expr
);
2166 expr
= coerce_to_target_type(pstate
, expr
, type_id
,
2167 atttypid
, atttypmod
,
2168 COERCION_ASSIGNMENT
,
2169 COERCE_IMPLICIT_CAST
,
2173 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2174 errmsg("column \"%s\" is of type %s"
2175 " but default expression is of type %s",
2177 format_type_be(atttypid
),
2178 format_type_be(type_id
)),
2179 errhint("You will need to rewrite or cast the expression.")));
2186 * Take a raw CHECK constraint expression and convert it to a cooked format
2187 * ready for storage.
2189 * Parse state must be set up to recognize any vars that might appear
2190 * in the expression.
2193 cookConstraint(ParseState
*pstate
,
2194 Node
*raw_constraint
,
2200 * Transform raw parsetree to executable expression.
2202 expr
= transformExpr(pstate
, raw_constraint
);
2205 * Make sure it yields a boolean result.
2207 expr
= coerce_to_boolean(pstate
, expr
, "CHECK");
2210 * Make sure no outside relations are referred to.
2212 if (list_length(pstate
->p_rtable
) != 1)
2214 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2215 errmsg("only table \"%s\" can be referenced in check constraint",
2219 * No subplans or aggregates, either...
2221 if (pstate
->p_hasSubLinks
)
2223 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2224 errmsg("cannot use subquery in check constraint")));
2225 if (pstate
->p_hasAggs
)
2227 (errcode(ERRCODE_GROUPING_ERROR
),
2228 errmsg("cannot use aggregate function in check constraint")));
2229 if (pstate
->p_hasWindowFuncs
)
2231 (errcode(ERRCODE_WINDOWING_ERROR
),
2232 errmsg("cannot use window function in check constraint")));
2239 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2241 * If attnum is zero, remove all entries for rel; else remove only the one
2245 RemoveStatistics(Oid relid
, AttrNumber attnum
)
2247 Relation pgstatistic
;
2253 pgstatistic
= heap_open(StatisticRelationId
, RowExclusiveLock
);
2255 ScanKeyInit(&key
[0],
2256 Anum_pg_statistic_starelid
,
2257 BTEqualStrategyNumber
, F_OIDEQ
,
2258 ObjectIdGetDatum(relid
));
2264 ScanKeyInit(&key
[1],
2265 Anum_pg_statistic_staattnum
,
2266 BTEqualStrategyNumber
, F_INT2EQ
,
2267 Int16GetDatum(attnum
));
2271 scan
= systable_beginscan(pgstatistic
, StatisticRelidAttnumIndexId
, true,
2272 SnapshotNow
, nkeys
, key
);
2274 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
2275 simple_heap_delete(pgstatistic
, &tuple
->t_self
);
2277 systable_endscan(scan
);
2279 heap_close(pgstatistic
, RowExclusiveLock
);
2284 * RelationTruncateIndexes - truncate all indexes associated
2285 * with the heap relation to zero tuples.
2287 * The routine will truncate and then reconstruct the indexes on
2288 * the specified relation. Caller must hold exclusive lock on rel.
2291 RelationTruncateIndexes(Relation heapRelation
)
2295 /* Ask the relcache to produce a list of the indexes of the rel */
2296 foreach(indlist
, RelationGetIndexList(heapRelation
))
2298 Oid indexId
= lfirst_oid(indlist
);
2299 Relation currentIndex
;
2300 IndexInfo
*indexInfo
;
2302 /* Open the index relation; use exclusive lock, just to be sure */
2303 currentIndex
= index_open(indexId
, AccessExclusiveLock
);
2305 /* Fetch info needed for index_build */
2306 indexInfo
= BuildIndexInfo(currentIndex
);
2309 * Now truncate the actual file (and discard buffers).
2311 RelationTruncate(currentIndex
, 0);
2313 /* Initialize the index and rebuild */
2314 /* Note: we do not need to re-establish pkey setting */
2315 index_build(heapRelation
, currentIndex
, indexInfo
, false);
2317 /* We're done with this index */
2318 index_close(currentIndex
, NoLock
);
2325 * This routine deletes all data within all the specified relations.
2327 * This is not transaction-safe! There is another, transaction-safe
2328 * implementation in commands/tablecmds.c. We now use this only for
2329 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2332 heap_truncate(List
*relids
)
2334 List
*relations
= NIL
;
2337 /* Open relations for processing, and grab exclusive access on each */
2338 foreach(cell
, relids
)
2340 Oid rid
= lfirst_oid(cell
);
2344 rel
= heap_open(rid
, AccessExclusiveLock
);
2345 relations
= lappend(relations
, rel
);
2347 /* If there is a toast table, add it to the list too */
2348 toastrelid
= rel
->rd_rel
->reltoastrelid
;
2349 if (OidIsValid(toastrelid
))
2351 rel
= heap_open(toastrelid
, AccessExclusiveLock
);
2352 relations
= lappend(relations
, rel
);
2356 /* Don't allow truncate on tables that are referenced by foreign keys */
2357 heap_truncate_check_FKs(relations
, true);
2360 foreach(cell
, relations
)
2362 Relation rel
= lfirst(cell
);
2364 /* Truncate the actual file (and discard buffers) */
2365 RelationTruncate(rel
, 0);
2367 /* If this relation has indexes, truncate the indexes too */
2368 RelationTruncateIndexes(rel
);
2371 * Close the relation, but keep exclusive lock on it until commit.
2373 heap_close(rel
, NoLock
);
2378 * heap_truncate_check_FKs
2379 * Check for foreign keys referencing a list of relations that
2380 * are to be truncated, and raise error if there are any
2382 * We disallow such FKs (except self-referential ones) since the whole point
2383 * of TRUNCATE is to not scan the individual rows to be thrown away.
2385 * This is split out so it can be shared by both implementations of truncate.
2386 * Caller should already hold a suitable lock on the relations.
2388 * tempTables is only used to select an appropriate error message.
2391 heap_truncate_check_FKs(List
*relations
, bool tempTables
)
2398 * Build a list of OIDs of the interesting relations.
2400 * If a relation has no triggers, then it can neither have FKs nor be
2401 * referenced by a FK from another table, so we can ignore it.
2403 foreach(cell
, relations
)
2405 Relation rel
= lfirst(cell
);
2407 if (rel
->rd_rel
->relhastriggers
)
2408 oids
= lappend_oid(oids
, RelationGetRelid(rel
));
2412 * Fast path: if no relation has triggers, none has FKs either.
2418 * Otherwise, must scan pg_constraint. We make one pass with all the
2419 * relations considered; if this finds nothing, then all is well.
2421 dependents
= heap_truncate_find_FKs(oids
);
2422 if (dependents
== NIL
)
2426 * Otherwise we repeat the scan once per relation to identify a particular
2427 * pair of relations to complain about. This is pretty slow, but
2428 * performance shouldn't matter much in a failure path. The reason for
2429 * doing things this way is to ensure that the message produced is not
2430 * dependent on chance row locations within pg_constraint.
2434 Oid relid
= lfirst_oid(cell
);
2437 dependents
= heap_truncate_find_FKs(list_make1_oid(relid
));
2439 foreach(cell2
, dependents
)
2441 Oid relid2
= lfirst_oid(cell2
);
2443 if (!list_member_oid(oids
, relid2
))
2445 char *relname
= get_rel_name(relid
);
2446 char *relname2
= get_rel_name(relid2
);
2450 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2451 errmsg("unsupported ON COMMIT and foreign key combination"),
2452 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2453 relname2
, relname
)));
2456 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2457 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2458 errdetail("Table \"%s\" references \"%s\".",
2460 errhint("Truncate table \"%s\" at the same time, "
2461 "or use TRUNCATE ... CASCADE.",
2469 * heap_truncate_find_FKs
2470 * Find relations having foreign keys referencing any of the given rels
2472 * Input and result are both lists of relation OIDs. The result contains
2473 * no duplicates, does *not* include any rels that were already in the input
2474 * list, and is sorted in OID order. (The last property is enforced mainly
2475 * to guarantee consistent behavior in the regression tests; we don't want
2476 * behavior to change depending on chance locations of rows in pg_constraint.)
2478 * Note: caller should already have appropriate lock on all rels mentioned
2479 * in relationIds. Since adding or dropping an FK requires exclusive lock
2480 * on both rels, this ensures that the answer will be stable.
2483 heap_truncate_find_FKs(List
*relationIds
)
2487 SysScanDesc fkeyScan
;
2491 * Must scan pg_constraint. Right now, it is a seqscan because there is
2492 * no available index on confrelid.
2494 fkeyRel
= heap_open(ConstraintRelationId
, AccessShareLock
);
2496 fkeyScan
= systable_beginscan(fkeyRel
, InvalidOid
, false,
2497 SnapshotNow
, 0, NULL
);
2499 while (HeapTupleIsValid(tuple
= systable_getnext(fkeyScan
)))
2501 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tuple
);
2503 /* Not a foreign key */
2504 if (con
->contype
!= CONSTRAINT_FOREIGN
)
2507 /* Not referencing one of our list of tables */
2508 if (!list_member_oid(relationIds
, con
->confrelid
))
2511 /* Add referencer unless already in input or result list */
2512 if (!list_member_oid(relationIds
, con
->conrelid
))
2513 result
= insert_ordered_unique_oid(result
, con
->conrelid
);
2516 systable_endscan(fkeyScan
);
2517 heap_close(fkeyRel
, AccessShareLock
);
2523 * insert_ordered_unique_oid
2524 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2525 * and eliminating duplicates
2527 * Building the ordered list this way is O(N^2), but with a pretty small
2528 * constant, so for the number of entries we expect it will probably be
2529 * faster than trying to apply qsort(). It seems unlikely someone would be
2530 * trying to truncate a table with thousands of dependent tables ...
2533 insert_ordered_unique_oid(List
*list
, Oid datum
)
2537 /* Does the datum belong at the front? */
2538 if (list
== NIL
|| datum
< linitial_oid(list
))
2539 return lcons_oid(datum
, list
);
2540 /* Does it match the first entry? */
2541 if (datum
== linitial_oid(list
))
2542 return list
; /* duplicate, so don't insert */
2543 /* No, so find the entry it belongs after */
2544 prev
= list_head(list
);
2547 ListCell
*curr
= lnext(prev
);
2549 if (curr
== NULL
|| datum
< lfirst_oid(curr
))
2550 break; /* it belongs after 'prev', before 'curr' */
2552 if (datum
== lfirst_oid(curr
))
2553 return list
; /* duplicate, so don't insert */
2557 /* Insert datum into list after 'prev' */
2558 lappend_cell_oid(list
, prev
, datum
);