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
);
534 /* --------------------------------
535 * AddNewAttributeTuples
537 * this registers the new relation's schema by adding
538 * tuples to pg_attribute.
539 * --------------------------------
542 AddNewAttributeTuples(Oid new_rel_oid
,
548 Form_pg_attribute attr
;
551 CatalogIndexState indstate
;
552 int natts
= tupdesc
->natts
;
553 ObjectAddress myself
,
557 * open pg_attribute and its indexes.
559 rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
561 indstate
= CatalogOpenIndexes(rel
);
564 * First we add the user attributes. This is also a convenient place to
565 * add dependencies on their datatypes.
567 for (i
= 0; i
< natts
; i
++)
569 attr
= tupdesc
->attrs
[i
];
570 /* Fill in the correct relation OID */
571 attr
->attrelid
= new_rel_oid
;
572 /* Make sure these are OK, too */
573 attr
->attstattarget
= -1;
574 attr
->attcacheoff
= -1;
576 InsertPgAttributeTuple(rel
, attr
, indstate
);
578 /* Add dependency info */
579 myself
.classId
= RelationRelationId
;
580 myself
.objectId
= new_rel_oid
;
581 myself
.objectSubId
= i
+ 1;
582 referenced
.classId
= TypeRelationId
;
583 referenced
.objectId
= attr
->atttypid
;
584 referenced
.objectSubId
= 0;
585 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
589 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
590 * all for a view or type relation. We don't bother with making datatype
591 * dependencies here, since presumably all these types are pinned.
593 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
595 for (i
= 0; i
< (int) lengthof(SysAtt
); i
++)
597 FormData_pg_attribute attStruct
;
599 /* skip OID where appropriate */
600 if (!tupdesc
->tdhasoid
&&
601 SysAtt
[i
]->attnum
== ObjectIdAttributeNumber
)
604 memcpy(&attStruct
, (char *) SysAtt
[i
], sizeof(FormData_pg_attribute
));
606 /* Fill in the correct relation OID in the copied tuple */
607 attStruct
.attrelid
= new_rel_oid
;
609 /* Fill in correct inheritance info for the OID column */
610 if (attStruct
.attnum
== ObjectIdAttributeNumber
)
612 attStruct
.attislocal
= oidislocal
;
613 attStruct
.attinhcount
= oidinhcount
;
616 InsertPgAttributeTuple(rel
, &attStruct
, indstate
);
623 CatalogCloseIndexes(indstate
);
625 heap_close(rel
, RowExclusiveLock
);
628 /* --------------------------------
631 * Construct and insert a new tuple in pg_class.
633 * Caller has already opened and locked pg_class.
634 * Tuple data is taken from new_rel_desc->rd_rel, except for the
635 * variable-width fields which are not present in a cached reldesc.
636 * We always initialize relacl to NULL (i.e., default permissions),
637 * and reloptions is set to the passed-in text array (if any).
638 * --------------------------------
641 InsertPgClassTuple(Relation pg_class_desc
,
642 Relation new_rel_desc
,
646 Form_pg_class rd_rel
= new_rel_desc
->rd_rel
;
647 Datum values
[Natts_pg_class
];
648 bool nulls
[Natts_pg_class
];
651 /* This is a tad tedious, but way cleaner than what we used to do... */
652 memset(values
, 0, sizeof(values
));
653 memset(nulls
, false, sizeof(nulls
));
655 values
[Anum_pg_class_relname
- 1] = NameGetDatum(&rd_rel
->relname
);
656 values
[Anum_pg_class_relnamespace
- 1] = ObjectIdGetDatum(rd_rel
->relnamespace
);
657 values
[Anum_pg_class_reltype
- 1] = ObjectIdGetDatum(rd_rel
->reltype
);
658 values
[Anum_pg_class_relowner
- 1] = ObjectIdGetDatum(rd_rel
->relowner
);
659 values
[Anum_pg_class_relam
- 1] = ObjectIdGetDatum(rd_rel
->relam
);
660 values
[Anum_pg_class_relfilenode
- 1] = ObjectIdGetDatum(rd_rel
->relfilenode
);
661 values
[Anum_pg_class_reltablespace
- 1] = ObjectIdGetDatum(rd_rel
->reltablespace
);
662 values
[Anum_pg_class_relpages
- 1] = Int32GetDatum(rd_rel
->relpages
);
663 values
[Anum_pg_class_reltuples
- 1] = Float4GetDatum(rd_rel
->reltuples
);
664 values
[Anum_pg_class_reltoastrelid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastrelid
);
665 values
[Anum_pg_class_reltoastidxid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastidxid
);
666 values
[Anum_pg_class_relhasindex
- 1] = BoolGetDatum(rd_rel
->relhasindex
);
667 values
[Anum_pg_class_relisshared
- 1] = BoolGetDatum(rd_rel
->relisshared
);
668 values
[Anum_pg_class_relistemp
- 1] = BoolGetDatum(rd_rel
->relistemp
);
669 values
[Anum_pg_class_relkind
- 1] = CharGetDatum(rd_rel
->relkind
);
670 values
[Anum_pg_class_relnatts
- 1] = Int16GetDatum(rd_rel
->relnatts
);
671 values
[Anum_pg_class_relchecks
- 1] = Int16GetDatum(rd_rel
->relchecks
);
672 values
[Anum_pg_class_relhasoids
- 1] = BoolGetDatum(rd_rel
->relhasoids
);
673 values
[Anum_pg_class_relhaspkey
- 1] = BoolGetDatum(rd_rel
->relhaspkey
);
674 values
[Anum_pg_class_relhasrules
- 1] = BoolGetDatum(rd_rel
->relhasrules
);
675 values
[Anum_pg_class_relhastriggers
- 1] = BoolGetDatum(rd_rel
->relhastriggers
);
676 values
[Anum_pg_class_relhassubclass
- 1] = BoolGetDatum(rd_rel
->relhassubclass
);
677 values
[Anum_pg_class_relfrozenxid
- 1] = TransactionIdGetDatum(rd_rel
->relfrozenxid
);
678 /* start out with empty permissions */
679 nulls
[Anum_pg_class_relacl
- 1] = true;
680 if (reloptions
!= (Datum
) 0)
681 values
[Anum_pg_class_reloptions
- 1] = reloptions
;
683 nulls
[Anum_pg_class_reloptions
- 1] = true;
685 tup
= heap_form_tuple(RelationGetDescr(pg_class_desc
), values
, nulls
);
688 * The new tuple must have the oid already chosen for the rel. Sure would
689 * be embarrassing to do this sort of thing in polite company.
691 HeapTupleSetOid(tup
, new_rel_oid
);
693 /* finally insert the new tuple, update the indexes, and clean up */
694 simple_heap_insert(pg_class_desc
, tup
);
696 CatalogUpdateIndexes(pg_class_desc
, tup
);
701 /* --------------------------------
702 * AddNewRelationTuple
704 * this registers the new relation in the catalogs by
705 * adding a tuple to pg_class.
706 * --------------------------------
709 AddNewRelationTuple(Relation pg_class_desc
,
710 Relation new_rel_desc
,
717 Form_pg_class new_rel_reltup
;
720 * first we update some of the information in our uncataloged relation's
721 * relation descriptor.
723 new_rel_reltup
= new_rel_desc
->rd_rel
;
727 case RELKIND_RELATION
:
729 case RELKIND_TOASTVALUE
:
730 /* The relation is real, but as yet empty */
731 new_rel_reltup
->relpages
= 0;
732 new_rel_reltup
->reltuples
= 0;
734 case RELKIND_SEQUENCE
:
735 /* Sequences always have a known size */
736 new_rel_reltup
->relpages
= 1;
737 new_rel_reltup
->reltuples
= 1;
740 /* Views, etc, have no disk storage */
741 new_rel_reltup
->relpages
= 0;
742 new_rel_reltup
->reltuples
= 0;
746 /* Initialize relfrozenxid */
747 if (relkind
== RELKIND_RELATION
||
748 relkind
== RELKIND_TOASTVALUE
)
751 * Initialize to the minimum XID that could put tuples in the table.
752 * We know that no xacts older than RecentXmin are still running, so
755 new_rel_reltup
->relfrozenxid
= RecentXmin
;
760 * Other relation types will not contain XIDs, so set relfrozenxid to
761 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
762 * we force its xmin to be FrozenTransactionId always; see
763 * commands/sequence.c.)
765 new_rel_reltup
->relfrozenxid
= InvalidTransactionId
;
768 new_rel_reltup
->relowner
= relowner
;
769 new_rel_reltup
->reltype
= new_type_oid
;
770 new_rel_reltup
->relkind
= relkind
;
772 new_rel_desc
->rd_att
->tdtypeid
= new_type_oid
;
774 /* Now build and insert the tuple */
775 InsertPgClassTuple(pg_class_desc
, new_rel_desc
, new_rel_oid
, reloptions
);
779 /* --------------------------------
780 * AddNewRelationType -
782 * define a composite type corresponding to the new relation
783 * --------------------------------
786 AddNewRelationType(const char *typeName
,
794 TypeCreate(InvalidOid
, /* no predetermined OID */
795 typeName
, /* type name */
796 typeNamespace
, /* type namespace */
797 new_rel_oid
, /* relation oid */
798 new_rel_kind
, /* relation kind */
799 ownerid
, /* owner's ID */
800 -1, /* internal size (varlena) */
801 TYPTYPE_COMPOSITE
, /* type-type (composite) */
802 TYPCATEGORY_COMPOSITE
, /* type-category (ditto) */
803 false, /* composite types are never preferred */
804 DEFAULT_TYPDELIM
, /* default array delimiter */
805 F_RECORD_IN
, /* input procedure */
806 F_RECORD_OUT
, /* output procedure */
807 F_RECORD_RECV
, /* receive procedure */
808 F_RECORD_SEND
, /* send procedure */
809 InvalidOid
, /* typmodin procedure - none */
810 InvalidOid
, /* typmodout procedure - none */
811 InvalidOid
, /* analyze procedure - default */
812 InvalidOid
, /* array element type - irrelevant */
813 false, /* this is not an array type */
814 new_array_type
, /* array type if any */
815 InvalidOid
, /* domain base type - irrelevant */
816 NULL
, /* default value - none */
817 NULL
, /* default binary representation */
818 false, /* passed by reference */
819 'd', /* alignment - must be the largest! */
820 'x', /* fully TOASTable */
822 0, /* array dimensions for typBaseType */
823 false); /* Type NOT NULL */
826 /* --------------------------------
827 * heap_create_with_catalog
829 * creates a new cataloged relation. see comments above.
830 * --------------------------------
833 heap_create_with_catalog(const char *relname
,
839 List
*cooked_constraints
,
841 bool shared_relation
,
844 OnCommitAction oncommit
,
846 bool allow_system_table_mods
)
848 Relation pg_class_desc
;
849 Relation new_rel_desc
;
852 Oid new_array_oid
= InvalidOid
;
854 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
859 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
861 CheckAttributeNamesTypes(tupdesc
, relkind
);
863 if (get_relname_relid(relname
, relnamespace
))
865 (errcode(ERRCODE_DUPLICATE_TABLE
),
866 errmsg("relation \"%s\" already exists", relname
)));
869 * Since we are going to create a rowtype as well, also check for
870 * collision with an existing type name. If there is one and it's an
871 * autogenerated array, we can rename it out of the way; otherwise we can
872 * at least give a good error message.
874 old_type_oid
= GetSysCacheOid(TYPENAMENSP
,
875 CStringGetDatum(relname
),
876 ObjectIdGetDatum(relnamespace
),
878 if (OidIsValid(old_type_oid
))
880 if (!moveArrayTypeName(old_type_oid
, relname
, relnamespace
))
882 (errcode(ERRCODE_DUPLICATE_OBJECT
),
883 errmsg("type \"%s\" already exists", relname
),
884 errhint("A relation has an associated type of the same name, "
885 "so you must use a name that doesn't conflict "
886 "with any existing type.")));
890 * Validate shared/non-shared tablespace (must check this before doing
891 * GetNewRelFileNode, to prevent Assert therein)
895 if (reltablespace
!= GLOBALTABLESPACE_OID
)
896 /* elog since this is not a user-facing error */
898 "shared relations must be placed in pg_global tablespace");
902 if (reltablespace
== GLOBALTABLESPACE_OID
)
904 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
905 errmsg("only shared relations can be placed in pg_global tablespace")));
909 * Allocate an OID for the relation, unless we were told what to use.
911 * The OID will be the relfilenode as well, so make sure it doesn't
912 * collide with either pg_class OIDs or existing physical files.
914 if (!OidIsValid(relid
))
915 relid
= GetNewRelFileNode(reltablespace
, shared_relation
,
919 * Create the relcache entry (mostly dummy at this point) and the physical
920 * disk file. (If we fail further down, it's the smgr's responsibility to
921 * remove the disk file again.)
923 new_rel_desc
= heap_create(relname
,
930 allow_system_table_mods
);
932 Assert(relid
== RelationGetRelid(new_rel_desc
));
935 * Decide whether to create an array type over the relation's rowtype. We
936 * do not create any array types for system catalogs (ie, those made
937 * during initdb). We create array types for regular relations, views,
938 * and composite types ... but not, eg, for toast tables or sequences.
940 if (IsUnderPostmaster
&& (relkind
== RELKIND_RELATION
||
941 relkind
== RELKIND_VIEW
||
942 relkind
== RELKIND_COMPOSITE_TYPE
))
944 /* OK, so pre-assign a type OID for the array type */
945 Relation pg_type
= heap_open(TypeRelationId
, AccessShareLock
);
947 new_array_oid
= GetNewOid(pg_type
);
948 heap_close(pg_type
, AccessShareLock
);
952 * Since defining a relation also defines a complex type, we add a new
953 * system type corresponding to the new relation.
955 * NOTE: we could get a unique-index failure here, in case someone else is
956 * creating the same type name in parallel but hadn't committed yet when
957 * we checked for a duplicate name above.
959 new_type_oid
= AddNewRelationType(relname
,
967 * Now make the array type if wanted.
969 if (OidIsValid(new_array_oid
))
973 relarrayname
= makeArrayTypeName(relname
, relnamespace
);
975 TypeCreate(new_array_oid
, /* force the type's OID to this */
976 relarrayname
, /* Array type name */
977 relnamespace
, /* Same namespace as parent */
978 InvalidOid
, /* Not composite, no relationOid */
979 0, /* relkind, also N/A here */
980 ownerid
, /* owner's ID */
981 -1, /* Internal size (varlena) */
982 TYPTYPE_BASE
, /* Not composite - typelem is */
983 TYPCATEGORY_ARRAY
, /* type-category (array) */
984 false, /* array types are never preferred */
985 DEFAULT_TYPDELIM
, /* default array delimiter */
986 F_ARRAY_IN
, /* array input proc */
987 F_ARRAY_OUT
, /* array output proc */
988 F_ARRAY_RECV
, /* array recv (bin) proc */
989 F_ARRAY_SEND
, /* array send (bin) proc */
990 InvalidOid
, /* typmodin procedure - none */
991 InvalidOid
, /* typmodout procedure - none */
992 InvalidOid
, /* analyze procedure - default */
993 new_type_oid
, /* array element type - the rowtype */
994 true, /* yes, this is an array type */
995 InvalidOid
, /* this has no array type */
996 InvalidOid
, /* domain base type - irrelevant */
997 NULL
, /* default value - none */
998 NULL
, /* default binary representation */
999 false, /* passed by reference */
1000 'd', /* alignment - must be the largest! */
1001 'x', /* fully TOASTable */
1003 0, /* array dimensions for typBaseType */
1004 false); /* Type NOT NULL */
1006 pfree(relarrayname
);
1010 * now create an entry in pg_class for the relation.
1012 * NOTE: we could get a unique-index failure here, in case someone else is
1013 * creating the same relation name in parallel but hadn't committed yet
1014 * when we checked for a duplicate name above.
1016 AddNewRelationTuple(pg_class_desc
,
1025 * now add tuples to pg_attribute for the attributes in our new relation.
1027 AddNewAttributeTuples(relid
, new_rel_desc
->rd_att
, relkind
,
1028 oidislocal
, oidinhcount
);
1031 * Make a dependency link to force the relation to be deleted if its
1032 * namespace is. Also make a dependency link to its owner.
1034 * For composite types, these dependencies are tracked for the pg_type
1035 * entry, so we needn't record them here. Likewise, TOAST tables don't
1036 * need a namespace dependency (they live in a pinned namespace) nor an
1037 * owner dependency (they depend indirectly through the parent table).
1038 * Also, skip this in bootstrap mode, since we don't make dependencies
1039 * while bootstrapping.
1041 if (relkind
!= RELKIND_COMPOSITE_TYPE
&&
1042 relkind
!= RELKIND_TOASTVALUE
&&
1043 !IsBootstrapProcessingMode())
1045 ObjectAddress myself
,
1048 myself
.classId
= RelationRelationId
;
1049 myself
.objectId
= relid
;
1050 myself
.objectSubId
= 0;
1051 referenced
.classId
= NamespaceRelationId
;
1052 referenced
.objectId
= relnamespace
;
1053 referenced
.objectSubId
= 0;
1054 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
1056 recordDependencyOnOwner(RelationRelationId
, relid
, ownerid
);
1060 * Store any supplied constraints and defaults.
1062 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1063 * entry, so the relation must be valid and self-consistent at this point.
1064 * In particular, there are not yet constraints and defaults anywhere.
1066 StoreConstraints(new_rel_desc
, cooked_constraints
);
1069 * If there's a special on-commit action, remember it
1071 if (oncommit
!= ONCOMMIT_NOOP
)
1072 register_on_commit_action(relid
, oncommit
);
1075 * ok, the relation has been cataloged, so close our relations and return
1076 * the OID of the newly created relation.
1078 heap_close(new_rel_desc
, NoLock
); /* do not unlock till end of xact */
1079 heap_close(pg_class_desc
, RowExclusiveLock
);
1086 * RelationRemoveInheritance
1088 * Formerly, this routine checked for child relations and aborted the
1089 * deletion if any were found. Now we rely on the dependency mechanism
1090 * to check for or delete child relations. By the time we get here,
1091 * there are no children and we need only remove any pg_inherits rows
1092 * linking this relation to its parent(s).
1095 RelationRemoveInheritance(Oid relid
)
1097 Relation catalogRelation
;
1102 catalogRelation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
1105 Anum_pg_inherits_inhrelid
,
1106 BTEqualStrategyNumber
, F_OIDEQ
,
1107 ObjectIdGetDatum(relid
));
1109 scan
= systable_beginscan(catalogRelation
, InheritsRelidSeqnoIndexId
, true,
1110 SnapshotNow
, 1, &key
);
1112 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1113 simple_heap_delete(catalogRelation
, &tuple
->t_self
);
1115 systable_endscan(scan
);
1116 heap_close(catalogRelation
, RowExclusiveLock
);
1120 * DeleteRelationTuple
1122 * Remove pg_class row for the given relid.
1124 * Note: this is shared by relation deletion and index deletion. It's
1125 * not intended for use anyplace else.
1128 DeleteRelationTuple(Oid relid
)
1130 Relation pg_class_desc
;
1133 /* Grab an appropriate lock on the pg_class relation */
1134 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
1136 tup
= SearchSysCache(RELOID
,
1137 ObjectIdGetDatum(relid
),
1139 if (!HeapTupleIsValid(tup
))
1140 elog(ERROR
, "cache lookup failed for relation %u", relid
);
1142 /* delete the relation tuple from pg_class, and finish up */
1143 simple_heap_delete(pg_class_desc
, &tup
->t_self
);
1145 ReleaseSysCache(tup
);
1147 heap_close(pg_class_desc
, RowExclusiveLock
);
1151 * DeleteAttributeTuples
1153 * Remove pg_attribute rows for the given relid.
1155 * Note: this is shared by relation deletion and index deletion. It's
1156 * not intended for use anyplace else.
1159 DeleteAttributeTuples(Oid relid
)
1166 /* Grab an appropriate lock on the pg_attribute relation */
1167 attrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1169 /* Use the index to scan only attributes of the target relation */
1170 ScanKeyInit(&key
[0],
1171 Anum_pg_attribute_attrelid
,
1172 BTEqualStrategyNumber
, F_OIDEQ
,
1173 ObjectIdGetDatum(relid
));
1175 scan
= systable_beginscan(attrel
, AttributeRelidNumIndexId
, true,
1176 SnapshotNow
, 1, key
);
1178 /* Delete all the matching tuples */
1179 while ((atttup
= systable_getnext(scan
)) != NULL
)
1180 simple_heap_delete(attrel
, &atttup
->t_self
);
1182 /* Clean up after the scan */
1183 systable_endscan(scan
);
1184 heap_close(attrel
, RowExclusiveLock
);
1188 * RemoveAttributeById
1190 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1191 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1192 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1193 * is handled by dependency.c.)
1196 RemoveAttributeById(Oid relid
, AttrNumber attnum
)
1201 Form_pg_attribute attStruct
;
1202 char newattname
[NAMEDATALEN
];
1205 * Grab an exclusive lock on the target table, which we will NOT release
1206 * until end of transaction. (In the simple case where we are directly
1207 * dropping this column, AlterTableDropColumn already did this ... but
1208 * when cascading from a drop of some other object, we may not have any
1211 rel
= relation_open(relid
, AccessExclusiveLock
);
1213 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1215 tuple
= SearchSysCacheCopy(ATTNUM
,
1216 ObjectIdGetDatum(relid
),
1217 Int16GetDatum(attnum
),
1219 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1220 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1222 attStruct
= (Form_pg_attribute
) GETSTRUCT(tuple
);
1226 /* System attribute (probably OID) ... just delete the row */
1228 simple_heap_delete(attr_rel
, &tuple
->t_self
);
1232 /* Dropping user attributes is lots harder */
1234 /* Mark the attribute as dropped */
1235 attStruct
->attisdropped
= true;
1238 * Set the type OID to invalid. A dropped attribute's type link
1239 * cannot be relied on (once the attribute is dropped, the type might
1240 * be too). Fortunately we do not need the type row --- the only
1241 * really essential information is the type's typlen and typalign,
1242 * which are preserved in the attribute's attlen and attalign. We set
1243 * atttypid to zero here as a means of catching code that incorrectly
1244 * expects it to be valid.
1246 attStruct
->atttypid
= InvalidOid
;
1248 /* Remove any NOT NULL constraint the column may have */
1249 attStruct
->attnotnull
= false;
1251 /* We don't want to keep stats for it anymore */
1252 attStruct
->attstattarget
= 0;
1255 * Change the column name to something that isn't likely to conflict
1257 snprintf(newattname
, sizeof(newattname
),
1258 "........pg.dropped.%d........", attnum
);
1259 namestrcpy(&(attStruct
->attname
), newattname
);
1261 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1263 /* keep the system catalog indexes current */
1264 CatalogUpdateIndexes(attr_rel
, tuple
);
1268 * Because updating the pg_attribute row will trigger a relcache flush for
1269 * the target relation, we need not do anything else to notify other
1270 * backends of the change.
1273 heap_close(attr_rel
, RowExclusiveLock
);
1276 RemoveStatistics(relid
, attnum
);
1278 relation_close(rel
, NoLock
);
1284 * If the specified relation/attribute has a default, remove it.
1285 * (If no default, raise error if complain is true, else return quietly.)
1288 RemoveAttrDefault(Oid relid
, AttrNumber attnum
,
1289 DropBehavior behavior
, bool complain
)
1291 Relation attrdef_rel
;
1292 ScanKeyData scankeys
[2];
1297 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1299 ScanKeyInit(&scankeys
[0],
1300 Anum_pg_attrdef_adrelid
,
1301 BTEqualStrategyNumber
, F_OIDEQ
,
1302 ObjectIdGetDatum(relid
));
1303 ScanKeyInit(&scankeys
[1],
1304 Anum_pg_attrdef_adnum
,
1305 BTEqualStrategyNumber
, F_INT2EQ
,
1306 Int16GetDatum(attnum
));
1308 scan
= systable_beginscan(attrdef_rel
, AttrDefaultIndexId
, true,
1309 SnapshotNow
, 2, scankeys
);
1311 /* There should be at most one matching tuple, but we loop anyway */
1312 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1314 ObjectAddress object
;
1316 object
.classId
= AttrDefaultRelationId
;
1317 object
.objectId
= HeapTupleGetOid(tuple
);
1318 object
.objectSubId
= 0;
1320 performDeletion(&object
, behavior
);
1325 systable_endscan(scan
);
1326 heap_close(attrdef_rel
, RowExclusiveLock
);
1328 if (complain
&& !found
)
1329 elog(ERROR
, "could not find attrdef tuple for relation %u attnum %d",
1334 * RemoveAttrDefaultById
1336 * Remove a pg_attrdef entry specified by OID. This is the guts of
1337 * attribute-default removal. Note it should be called via performDeletion,
1341 RemoveAttrDefaultById(Oid attrdefId
)
1343 Relation attrdef_rel
;
1346 ScanKeyData scankeys
[1];
1350 AttrNumber myattnum
;
1352 /* Grab an appropriate lock on the pg_attrdef relation */
1353 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1355 /* Find the pg_attrdef tuple */
1356 ScanKeyInit(&scankeys
[0],
1357 ObjectIdAttributeNumber
,
1358 BTEqualStrategyNumber
, F_OIDEQ
,
1359 ObjectIdGetDatum(attrdefId
));
1361 scan
= systable_beginscan(attrdef_rel
, AttrDefaultOidIndexId
, true,
1362 SnapshotNow
, 1, scankeys
);
1364 tuple
= systable_getnext(scan
);
1365 if (!HeapTupleIsValid(tuple
))
1366 elog(ERROR
, "could not find tuple for attrdef %u", attrdefId
);
1368 myrelid
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adrelid
;
1369 myattnum
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adnum
;
1371 /* Get an exclusive lock on the relation owning the attribute */
1372 myrel
= relation_open(myrelid
, AccessExclusiveLock
);
1374 /* Now we can delete the pg_attrdef row */
1375 simple_heap_delete(attrdef_rel
, &tuple
->t_self
);
1377 systable_endscan(scan
);
1378 heap_close(attrdef_rel
, RowExclusiveLock
);
1380 /* Fix the pg_attribute row */
1381 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1383 tuple
= SearchSysCacheCopy(ATTNUM
,
1384 ObjectIdGetDatum(myrelid
),
1385 Int16GetDatum(myattnum
),
1387 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1388 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1391 ((Form_pg_attribute
) GETSTRUCT(tuple
))->atthasdef
= false;
1393 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1395 /* keep the system catalog indexes current */
1396 CatalogUpdateIndexes(attr_rel
, tuple
);
1399 * Our update of the pg_attribute row will force a relcache rebuild, so
1400 * there's nothing else to do here.
1402 heap_close(attr_rel
, RowExclusiveLock
);
1404 /* Keep lock on attribute's rel until end of xact */
1405 relation_close(myrel
, NoLock
);
1409 * heap_drop_with_catalog - removes specified relation from catalogs
1411 * Note that this routine is not responsible for dropping objects that are
1412 * linked to the pg_class entry via dependencies (for example, indexes and
1413 * constraints). Those are deleted by the dependency-tracing logic in
1414 * dependency.c before control gets here. In general, therefore, this routine
1415 * should never be called directly; go through performDeletion() instead.
1418 heap_drop_with_catalog(Oid relid
)
1423 * Open and lock the relation.
1425 rel
= relation_open(relid
, AccessExclusiveLock
);
1428 * There can no longer be anyone *else* touching the relation, but we
1429 * might still have open queries or cursors in our own session.
1431 if (rel
->rd_refcnt
!= 1)
1433 (errcode(ERRCODE_OBJECT_IN_USE
),
1434 errmsg("cannot drop \"%s\" because "
1435 "it is being used by active queries in this session",
1436 RelationGetRelationName(rel
))));
1439 * Schedule unlinking of the relation's physical files at commit.
1441 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
&&
1442 rel
->rd_rel
->relkind
!= RELKIND_COMPOSITE_TYPE
)
1444 RelationDropStorage(rel
);
1448 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1449 * until transaction commit. This ensures no one else will try to do
1450 * something with the doomed relation.
1452 relation_close(rel
, NoLock
);
1455 * Forget any ON COMMIT action for the rel
1457 remove_on_commit_action(relid
);
1460 * Flush the relation from the relcache. We want to do this before
1461 * starting to remove catalog entries, just to be certain that no relcache
1462 * entry rebuild will happen partway through. (That should not really
1463 * matter, since we don't do CommandCounterIncrement here, but let's be
1466 RelationForgetRelation(relid
);
1469 * remove inheritance information
1471 RelationRemoveInheritance(relid
);
1476 RemoveStatistics(relid
, 0);
1479 * delete attribute tuples
1481 DeleteAttributeTuples(relid
);
1484 * delete relation tuple
1486 DeleteRelationTuple(relid
);
1491 * Store a default expression for column attnum of relation rel.
1494 StoreAttrDefault(Relation rel
, AttrNumber attnum
, Node
*expr
)
1501 static bool nulls
[4] = {false, false, false, false};
1504 Form_pg_attribute attStruct
;
1506 ObjectAddress colobject
,
1510 * Flatten expression to string form for storage.
1512 adbin
= nodeToString(expr
);
1515 * Also deparse it to form the mostly-obsolete adsrc field.
1517 adsrc
= deparse_expression(expr
,
1518 deparse_context_for(RelationGetRelationName(rel
),
1519 RelationGetRelid(rel
)),
1523 * Make the pg_attrdef entry.
1525 values
[Anum_pg_attrdef_adrelid
- 1] = RelationGetRelid(rel
);
1526 values
[Anum_pg_attrdef_adnum
- 1] = attnum
;
1527 values
[Anum_pg_attrdef_adbin
- 1] = CStringGetTextDatum(adbin
);
1528 values
[Anum_pg_attrdef_adsrc
- 1] = CStringGetTextDatum(adsrc
);
1530 adrel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1532 tuple
= heap_form_tuple(adrel
->rd_att
, values
, nulls
);
1533 attrdefOid
= simple_heap_insert(adrel
, tuple
);
1535 CatalogUpdateIndexes(adrel
, tuple
);
1537 defobject
.classId
= AttrDefaultRelationId
;
1538 defobject
.objectId
= attrdefOid
;
1539 defobject
.objectSubId
= 0;
1541 heap_close(adrel
, RowExclusiveLock
);
1543 /* now can free some of the stuff allocated above */
1544 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adbin
- 1]));
1545 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adsrc
- 1]));
1546 heap_freetuple(tuple
);
1551 * Update the pg_attribute entry for the column to show that a default
1554 attrrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1555 atttup
= SearchSysCacheCopy(ATTNUM
,
1556 ObjectIdGetDatum(RelationGetRelid(rel
)),
1557 Int16GetDatum(attnum
),
1559 if (!HeapTupleIsValid(atttup
))
1560 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1561 attnum
, RelationGetRelid(rel
));
1562 attStruct
= (Form_pg_attribute
) GETSTRUCT(atttup
);
1563 if (!attStruct
->atthasdef
)
1565 attStruct
->atthasdef
= true;
1566 simple_heap_update(attrrel
, &atttup
->t_self
, atttup
);
1567 /* keep catalog indexes current */
1568 CatalogUpdateIndexes(attrrel
, atttup
);
1570 heap_close(attrrel
, RowExclusiveLock
);
1571 heap_freetuple(atttup
);
1574 * Make a dependency so that the pg_attrdef entry goes away if the column
1575 * (or whole table) is deleted.
1577 colobject
.classId
= RelationRelationId
;
1578 colobject
.objectId
= RelationGetRelid(rel
);
1579 colobject
.objectSubId
= attnum
;
1581 recordDependencyOn(&defobject
, &colobject
, DEPENDENCY_AUTO
);
1584 * Record dependencies on objects used in the expression, too.
1586 recordDependencyOnExpr(&defobject
, expr
, NIL
, DEPENDENCY_NORMAL
);
1590 * Store a check-constraint expression for the given relation.
1592 * Caller is responsible for updating the count of constraints
1593 * in the pg_class entry for the relation.
1596 StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
1597 bool is_local
, int inhcount
)
1606 * Flatten expression to string form for storage.
1608 ccbin
= nodeToString(expr
);
1611 * Also deparse it to form the mostly-obsolete consrc field.
1613 ccsrc
= deparse_expression(expr
,
1614 deparse_context_for(RelationGetRelationName(rel
),
1615 RelationGetRelid(rel
)),
1619 * Find columns of rel that are used in expr
1621 * NB: pull_var_clause is okay here only because we don't allow subselects
1622 * in check constraints; it would fail to examine the contents of
1625 varList
= pull_var_clause(expr
, PVC_REJECT_PLACEHOLDERS
);
1626 keycount
= list_length(varList
);
1633 attNos
= (int16
*) palloc(keycount
* sizeof(int16
));
1634 foreach(vl
, varList
)
1636 Var
*var
= (Var
*) lfirst(vl
);
1639 for (j
= 0; j
< i
; j
++)
1640 if (attNos
[j
] == var
->varattno
)
1643 attNos
[i
++] = var
->varattno
;
1651 * Create the Check Constraint
1653 CreateConstraintEntry(ccname
, /* Constraint Name */
1654 RelationGetNamespace(rel
), /* namespace */
1655 CONSTRAINT_CHECK
, /* Constraint Type */
1656 false, /* Is Deferrable */
1657 false, /* Is Deferred */
1658 RelationGetRelid(rel
), /* relation */
1659 attNos
, /* attrs in the constraint */
1660 keycount
, /* # attrs in the constraint */
1661 InvalidOid
, /* not a domain constraint */
1662 InvalidOid
, /* Foreign key fields */
1671 InvalidOid
, /* no associated index */
1672 expr
, /* Tree form check constraint */
1673 ccbin
, /* Binary form check constraint */
1674 ccsrc
, /* Source form check constraint */
1675 is_local
, /* conislocal */
1676 inhcount
); /* coninhcount */
1683 * Store defaults and constraints (passed as a list of CookedConstraint).
1685 * NOTE: only pre-cooked expressions will be passed this way, which is to
1686 * say expressions inherited from an existing relation. Newly parsed
1687 * expressions can be added later, by direct calls to StoreAttrDefault
1688 * and StoreRelCheck (see AddRelationNewConstraints()).
1691 StoreConstraints(Relation rel
, List
*cooked_constraints
)
1696 if (!cooked_constraints
)
1697 return; /* nothing to do */
1700 * Deparsing of constraint expressions will fail unless the just-created
1701 * pg_attribute tuples for this relation are made visible. So, bump the
1702 * command counter. CAUTION: this will cause a relcache entry rebuild.
1704 CommandCounterIncrement();
1706 foreach(lc
, cooked_constraints
)
1708 CookedConstraint
*con
= (CookedConstraint
*) lfirst(lc
);
1710 switch (con
->contype
)
1712 case CONSTR_DEFAULT
:
1713 StoreAttrDefault(rel
, con
->attnum
, con
->expr
);
1716 StoreRelCheck(rel
, con
->name
, con
->expr
,
1717 con
->is_local
, con
->inhcount
);
1721 elog(ERROR
, "unrecognized constraint type: %d",
1722 (int) con
->contype
);
1727 SetRelationNumChecks(rel
, numchecks
);
1731 * AddRelationNewConstraints
1733 * Add new column default expressions and/or constraint check expressions
1734 * to an existing relation. This is defined to do both for efficiency in
1735 * DefineRelation, but of course you can do just one or the other by passing
1738 * rel: relation to be modified
1739 * newColDefaults: list of RawColumnDefault structures
1740 * newConstraints: list of Constraint nodes
1741 * allow_merge: TRUE if check constraints may be merged with existing ones
1742 * is_local: TRUE if definition is local, FALSE if it's inherited
1744 * All entries in newColDefaults will be processed. Entries in newConstraints
1745 * will be processed only if they are CONSTR_CHECK type.
1747 * Returns a list of CookedConstraint nodes that shows the cooked form of
1748 * the default and constraint expressions added to the relation.
1750 * NB: caller should have opened rel with AccessExclusiveLock, and should
1751 * hold that lock till end of transaction. Also, we assume the caller has
1752 * done a CommandCounterIncrement if necessary to make the relation's catalog
1756 AddRelationNewConstraints(Relation rel
,
1757 List
*newColDefaults
,
1758 List
*newConstraints
,
1762 List
*cookedConstraints
= NIL
;
1763 TupleDesc tupleDesc
;
1764 TupleConstr
*oldconstr
;
1772 CookedConstraint
*cooked
;
1775 * Get info about existing constraints.
1777 tupleDesc
= RelationGetDescr(rel
);
1778 oldconstr
= tupleDesc
->constr
;
1780 numoldchecks
= oldconstr
->num_check
;
1785 * Create a dummy ParseState and insert the target relation as its sole
1786 * rangetable entry. We need a ParseState for transformExpr.
1788 pstate
= make_parsestate(NULL
);
1789 rte
= addRangeTableEntryForRelation(pstate
,
1794 addRTEtoQuery(pstate
, rte
, true, true, true);
1797 * Process column default expressions.
1799 foreach(cell
, newColDefaults
)
1801 RawColumnDefault
*colDef
= (RawColumnDefault
*) lfirst(cell
);
1802 Form_pg_attribute atp
= rel
->rd_att
->attrs
[colDef
->attnum
- 1];
1804 expr
= cookDefault(pstate
, colDef
->raw_default
,
1805 atp
->atttypid
, atp
->atttypmod
,
1806 NameStr(atp
->attname
));
1809 * If the expression is just a NULL constant, we do not bother to make
1810 * an explicit pg_attrdef entry, since the default behavior is
1813 * Note a nonobvious property of this test: if the column is of a
1814 * domain type, what we'll get is not a bare null Const but a
1815 * CoerceToDomain expr, so we will not discard the default. This is
1816 * critical because the column default needs to be retained to
1817 * override any default that the domain might have.
1820 (IsA(expr
, Const
) &&((Const
*) expr
)->constisnull
))
1823 StoreAttrDefault(rel
, colDef
->attnum
, expr
);
1825 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1826 cooked
->contype
= CONSTR_DEFAULT
;
1827 cooked
->name
= NULL
;
1828 cooked
->attnum
= colDef
->attnum
;
1829 cooked
->expr
= expr
;
1830 cooked
->is_local
= is_local
;
1831 cooked
->inhcount
= is_local
? 0 : 1;
1832 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1836 * Process constraint expressions.
1838 numchecks
= numoldchecks
;
1840 foreach(cell
, newConstraints
)
1842 Constraint
*cdef
= (Constraint
*) lfirst(cell
);
1845 if (cdef
->contype
!= CONSTR_CHECK
)
1848 if (cdef
->raw_expr
!= NULL
)
1850 Assert(cdef
->cooked_expr
== NULL
);
1853 * Transform raw parsetree to executable expression, and verify
1854 * it's valid as a CHECK constraint.
1856 expr
= cookConstraint(pstate
, cdef
->raw_expr
,
1857 RelationGetRelationName(rel
));
1861 Assert(cdef
->cooked_expr
!= NULL
);
1864 * Here, we assume the parser will only pass us valid CHECK
1865 * expressions, so we do no particular checking.
1867 expr
= stringToNode(cdef
->cooked_expr
);
1871 * Check name uniqueness, or generate a name if none was given.
1873 if (cdef
->name
!= NULL
)
1877 ccname
= cdef
->name
;
1878 /* Check against other new constraints */
1879 /* Needed because we don't do CommandCounterIncrement in loop */
1880 foreach(cell2
, checknames
)
1882 if (strcmp((char *) lfirst(cell2
), ccname
) == 0)
1884 (errcode(ERRCODE_DUPLICATE_OBJECT
),
1885 errmsg("check constraint \"%s\" already exists",
1889 /* save name for future checks */
1890 checknames
= lappend(checknames
, ccname
);
1893 * Check against pre-existing constraints. If we are allowed to
1894 * merge with an existing constraint, there's no more to do here.
1895 * (We omit the duplicate constraint from the result, which is
1896 * what ATAddCheckConstraint wants.)
1898 if (MergeWithExistingConstraint(rel
, ccname
, expr
,
1899 allow_merge
, is_local
))
1905 * When generating a name, we want to create "tab_col_check" for a
1906 * column constraint and "tab_check" for a table constraint. We
1907 * no longer have any info about the syntactic positioning of the
1908 * constraint phrase, so we approximate this by seeing whether the
1909 * expression references more than one column. (If the user
1910 * played by the rules, the result is the same...)
1912 * Note: pull_var_clause() doesn't descend into sublinks, but we
1913 * eliminated those above; and anyway this only needs to be an
1914 * approximate answer.
1919 vars
= pull_var_clause(expr
, PVC_REJECT_PLACEHOLDERS
);
1921 /* eliminate duplicates */
1922 vars
= list_union(NIL
, vars
);
1924 if (list_length(vars
) == 1)
1925 colname
= get_attname(RelationGetRelid(rel
),
1926 ((Var
*) linitial(vars
))->varattno
);
1930 ccname
= ChooseConstraintName(RelationGetRelationName(rel
),
1933 RelationGetNamespace(rel
),
1936 /* save name for future checks */
1937 checknames
= lappend(checknames
, ccname
);
1943 StoreRelCheck(rel
, ccname
, expr
, is_local
, is_local
? 0 : 1);
1947 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1948 cooked
->contype
= CONSTR_CHECK
;
1949 cooked
->name
= ccname
;
1951 cooked
->expr
= expr
;
1952 cooked
->is_local
= is_local
;
1953 cooked
->inhcount
= is_local
? 0 : 1;
1954 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1958 * Update the count of constraints in the relation's pg_class tuple. We do
1959 * this even if there was no change, in order to ensure that an SI update
1960 * message is sent out for the pg_class tuple, which will force other
1961 * backends to rebuild their relcache entries for the rel. (This is
1962 * critical if we added defaults but not constraints.)
1964 SetRelationNumChecks(rel
, numchecks
);
1966 return cookedConstraints
;
1970 * Check for a pre-existing check constraint that conflicts with a proposed
1971 * new one, and either adjust its conislocal/coninhcount settings or throw
1974 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1975 * got a so-far-unique name, or throws error if conflict.
1978 MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
1979 bool allow_merge
, bool is_local
)
1983 SysScanDesc conscan
;
1984 ScanKeyData skey
[2];
1987 /* Search for a pg_constraint entry with same name and relation */
1988 conDesc
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
1992 ScanKeyInit(&skey
[0],
1993 Anum_pg_constraint_conname
,
1994 BTEqualStrategyNumber
, F_NAMEEQ
,
1995 CStringGetDatum(ccname
));
1997 ScanKeyInit(&skey
[1],
1998 Anum_pg_constraint_connamespace
,
1999 BTEqualStrategyNumber
, F_OIDEQ
,
2000 ObjectIdGetDatum(RelationGetNamespace(rel
)));
2002 conscan
= systable_beginscan(conDesc
, ConstraintNameNspIndexId
, true,
2003 SnapshotNow
, 2, skey
);
2005 while (HeapTupleIsValid(tup
= systable_getnext(conscan
)))
2007 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tup
);
2009 if (con
->conrelid
== RelationGetRelid(rel
))
2011 /* Found it. Conflicts if not identical check constraint */
2012 if (con
->contype
== CONSTRAINT_CHECK
)
2017 val
= fastgetattr(tup
,
2018 Anum_pg_constraint_conbin
,
2019 conDesc
->rd_att
, &isnull
);
2021 elog(ERROR
, "null conbin for rel %s",
2022 RelationGetRelationName(rel
));
2023 if (equal(expr
, stringToNode(TextDatumGetCString(val
))))
2026 if (!found
|| !allow_merge
)
2028 (errcode(ERRCODE_DUPLICATE_OBJECT
),
2029 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2030 ccname
, RelationGetRelationName(rel
))));
2031 /* OK to update the tuple */
2033 (errmsg("merging constraint \"%s\" with inherited definition",
2035 tup
= heap_copytuple(tup
);
2036 con
= (Form_pg_constraint
) GETSTRUCT(tup
);
2038 con
->conislocal
= true;
2041 simple_heap_update(conDesc
, &tup
->t_self
, tup
);
2042 CatalogUpdateIndexes(conDesc
, tup
);
2047 systable_endscan(conscan
);
2048 heap_close(conDesc
, RowExclusiveLock
);
2054 * Update the count of constraints in the relation's pg_class tuple.
2056 * Caller had better hold exclusive lock on the relation.
2058 * An important side effect is that a SI update message will be sent out for
2059 * the pg_class tuple, which will force other backends to rebuild their
2060 * relcache entries for the rel. Also, this backend will rebuild its
2061 * own relcache entry at the next CommandCounterIncrement.
2064 SetRelationNumChecks(Relation rel
, int numchecks
)
2068 Form_pg_class relStruct
;
2070 relrel
= heap_open(RelationRelationId
, RowExclusiveLock
);
2071 reltup
= SearchSysCacheCopy(RELOID
,
2072 ObjectIdGetDatum(RelationGetRelid(rel
)),
2074 if (!HeapTupleIsValid(reltup
))
2075 elog(ERROR
, "cache lookup failed for relation %u",
2076 RelationGetRelid(rel
));
2077 relStruct
= (Form_pg_class
) GETSTRUCT(reltup
);
2079 if (relStruct
->relchecks
!= numchecks
)
2081 relStruct
->relchecks
= numchecks
;
2083 simple_heap_update(relrel
, &reltup
->t_self
, reltup
);
2085 /* keep catalog indexes current */
2086 CatalogUpdateIndexes(relrel
, reltup
);
2090 /* Skip the disk update, but force relcache inval anyway */
2091 CacheInvalidateRelcache(rel
);
2094 heap_freetuple(reltup
);
2095 heap_close(relrel
, RowExclusiveLock
);
2099 * Take a raw default and convert it to a cooked format ready for
2102 * Parse state should be set up to recognize any vars that might appear
2103 * in the expression. (Even though we plan to reject vars, it's more
2104 * user-friendly to give the correct error message than "unknown var".)
2106 * If atttypid is not InvalidOid, coerce the expression to the specified
2107 * type (and typmod atttypmod). attname is only needed in this case:
2108 * it is used in the error message, if any.
2111 cookDefault(ParseState
*pstate
,
2119 Assert(raw_default
!= NULL
);
2122 * Transform raw parsetree to executable expression.
2124 expr
= transformExpr(pstate
, raw_default
);
2127 * Make sure default expr does not refer to any vars.
2129 if (contain_var_clause(expr
))
2131 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2132 errmsg("cannot use column references in default expression")));
2135 * It can't return a set either.
2137 if (expression_returns_set(expr
))
2139 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2140 errmsg("default expression must not return a set")));
2143 * No subplans or aggregates, either...
2145 if (pstate
->p_hasSubLinks
)
2147 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2148 errmsg("cannot use subquery in default expression")));
2149 if (pstate
->p_hasAggs
)
2151 (errcode(ERRCODE_GROUPING_ERROR
),
2152 errmsg("cannot use aggregate function in default expression")));
2153 if (pstate
->p_hasWindowFuncs
)
2155 (errcode(ERRCODE_WINDOWING_ERROR
),
2156 errmsg("cannot use window function in default expression")));
2159 * Coerce the expression to the correct type and typmod, if given. This
2160 * should match the parser's processing of non-defaulted expressions ---
2161 * see transformAssignedExpr().
2163 if (OidIsValid(atttypid
))
2165 Oid type_id
= exprType(expr
);
2167 expr
= coerce_to_target_type(pstate
, expr
, type_id
,
2168 atttypid
, atttypmod
,
2169 COERCION_ASSIGNMENT
,
2170 COERCE_IMPLICIT_CAST
,
2174 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2175 errmsg("column \"%s\" is of type %s"
2176 " but default expression is of type %s",
2178 format_type_be(atttypid
),
2179 format_type_be(type_id
)),
2180 errhint("You will need to rewrite or cast the expression.")));
2187 * Take a raw CHECK constraint expression and convert it to a cooked format
2188 * ready for storage.
2190 * Parse state must be set up to recognize any vars that might appear
2191 * in the expression.
2194 cookConstraint(ParseState
*pstate
,
2195 Node
*raw_constraint
,
2201 * Transform raw parsetree to executable expression.
2203 expr
= transformExpr(pstate
, raw_constraint
);
2206 * Make sure it yields a boolean result.
2208 expr
= coerce_to_boolean(pstate
, expr
, "CHECK");
2211 * Make sure no outside relations are referred to.
2213 if (list_length(pstate
->p_rtable
) != 1)
2215 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2216 errmsg("only table \"%s\" can be referenced in check constraint",
2220 * No subplans or aggregates, either...
2222 if (pstate
->p_hasSubLinks
)
2224 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2225 errmsg("cannot use subquery in check constraint")));
2226 if (pstate
->p_hasAggs
)
2228 (errcode(ERRCODE_GROUPING_ERROR
),
2229 errmsg("cannot use aggregate function in check constraint")));
2230 if (pstate
->p_hasWindowFuncs
)
2232 (errcode(ERRCODE_WINDOWING_ERROR
),
2233 errmsg("cannot use window function in check constraint")));
2240 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2242 * If attnum is zero, remove all entries for rel; else remove only the one
2246 RemoveStatistics(Oid relid
, AttrNumber attnum
)
2248 Relation pgstatistic
;
2254 pgstatistic
= heap_open(StatisticRelationId
, RowExclusiveLock
);
2256 ScanKeyInit(&key
[0],
2257 Anum_pg_statistic_starelid
,
2258 BTEqualStrategyNumber
, F_OIDEQ
,
2259 ObjectIdGetDatum(relid
));
2265 ScanKeyInit(&key
[1],
2266 Anum_pg_statistic_staattnum
,
2267 BTEqualStrategyNumber
, F_INT2EQ
,
2268 Int16GetDatum(attnum
));
2272 scan
= systable_beginscan(pgstatistic
, StatisticRelidAttnumIndexId
, true,
2273 SnapshotNow
, nkeys
, key
);
2275 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
2276 simple_heap_delete(pgstatistic
, &tuple
->t_self
);
2278 systable_endscan(scan
);
2280 heap_close(pgstatistic
, RowExclusiveLock
);
2285 * RelationTruncateIndexes - truncate all indexes associated
2286 * with the heap relation to zero tuples.
2288 * The routine will truncate and then reconstruct the indexes on
2289 * the specified relation. Caller must hold exclusive lock on rel.
2292 RelationTruncateIndexes(Relation heapRelation
)
2296 /* Ask the relcache to produce a list of the indexes of the rel */
2297 foreach(indlist
, RelationGetIndexList(heapRelation
))
2299 Oid indexId
= lfirst_oid(indlist
);
2300 Relation currentIndex
;
2301 IndexInfo
*indexInfo
;
2303 /* Open the index relation; use exclusive lock, just to be sure */
2304 currentIndex
= index_open(indexId
, AccessExclusiveLock
);
2306 /* Fetch info needed for index_build */
2307 indexInfo
= BuildIndexInfo(currentIndex
);
2310 * Now truncate the actual file (and discard buffers).
2312 RelationTruncate(currentIndex
, 0);
2314 /* Initialize the index and rebuild */
2315 /* Note: we do not need to re-establish pkey setting */
2316 index_build(heapRelation
, currentIndex
, indexInfo
, false);
2318 /* We're done with this index */
2319 index_close(currentIndex
, NoLock
);
2326 * This routine deletes all data within all the specified relations.
2328 * This is not transaction-safe! There is another, transaction-safe
2329 * implementation in commands/tablecmds.c. We now use this only for
2330 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2333 heap_truncate(List
*relids
)
2335 List
*relations
= NIL
;
2338 /* Open relations for processing, and grab exclusive access on each */
2339 foreach(cell
, relids
)
2341 Oid rid
= lfirst_oid(cell
);
2345 rel
= heap_open(rid
, AccessExclusiveLock
);
2346 relations
= lappend(relations
, rel
);
2348 /* If there is a toast table, add it to the list too */
2349 toastrelid
= rel
->rd_rel
->reltoastrelid
;
2350 if (OidIsValid(toastrelid
))
2352 rel
= heap_open(toastrelid
, AccessExclusiveLock
);
2353 relations
= lappend(relations
, rel
);
2357 /* Don't allow truncate on tables that are referenced by foreign keys */
2358 heap_truncate_check_FKs(relations
, true);
2361 foreach(cell
, relations
)
2363 Relation rel
= lfirst(cell
);
2365 /* Truncate the actual file (and discard buffers) */
2366 RelationTruncate(rel
, 0);
2368 /* If this relation has indexes, truncate the indexes too */
2369 RelationTruncateIndexes(rel
);
2372 * Close the relation, but keep exclusive lock on it until commit.
2374 heap_close(rel
, NoLock
);
2379 * heap_truncate_check_FKs
2380 * Check for foreign keys referencing a list of relations that
2381 * are to be truncated, and raise error if there are any
2383 * We disallow such FKs (except self-referential ones) since the whole point
2384 * of TRUNCATE is to not scan the individual rows to be thrown away.
2386 * This is split out so it can be shared by both implementations of truncate.
2387 * Caller should already hold a suitable lock on the relations.
2389 * tempTables is only used to select an appropriate error message.
2392 heap_truncate_check_FKs(List
*relations
, bool tempTables
)
2399 * Build a list of OIDs of the interesting relations.
2401 * If a relation has no triggers, then it can neither have FKs nor be
2402 * referenced by a FK from another table, so we can ignore it.
2404 foreach(cell
, relations
)
2406 Relation rel
= lfirst(cell
);
2408 if (rel
->rd_rel
->relhastriggers
)
2409 oids
= lappend_oid(oids
, RelationGetRelid(rel
));
2413 * Fast path: if no relation has triggers, none has FKs either.
2419 * Otherwise, must scan pg_constraint. We make one pass with all the
2420 * relations considered; if this finds nothing, then all is well.
2422 dependents
= heap_truncate_find_FKs(oids
);
2423 if (dependents
== NIL
)
2427 * Otherwise we repeat the scan once per relation to identify a particular
2428 * pair of relations to complain about. This is pretty slow, but
2429 * performance shouldn't matter much in a failure path. The reason for
2430 * doing things this way is to ensure that the message produced is not
2431 * dependent on chance row locations within pg_constraint.
2435 Oid relid
= lfirst_oid(cell
);
2438 dependents
= heap_truncate_find_FKs(list_make1_oid(relid
));
2440 foreach(cell2
, dependents
)
2442 Oid relid2
= lfirst_oid(cell2
);
2444 if (!list_member_oid(oids
, relid2
))
2446 char *relname
= get_rel_name(relid
);
2447 char *relname2
= get_rel_name(relid2
);
2451 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2452 errmsg("unsupported ON COMMIT and foreign key combination"),
2453 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2454 relname2
, relname
)));
2457 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2458 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2459 errdetail("Table \"%s\" references \"%s\".",
2461 errhint("Truncate table \"%s\" at the same time, "
2462 "or use TRUNCATE ... CASCADE.",
2470 * heap_truncate_find_FKs
2471 * Find relations having foreign keys referencing any of the given rels
2473 * Input and result are both lists of relation OIDs. The result contains
2474 * no duplicates, does *not* include any rels that were already in the input
2475 * list, and is sorted in OID order. (The last property is enforced mainly
2476 * to guarantee consistent behavior in the regression tests; we don't want
2477 * behavior to change depending on chance locations of rows in pg_constraint.)
2479 * Note: caller should already have appropriate lock on all rels mentioned
2480 * in relationIds. Since adding or dropping an FK requires exclusive lock
2481 * on both rels, this ensures that the answer will be stable.
2484 heap_truncate_find_FKs(List
*relationIds
)
2488 SysScanDesc fkeyScan
;
2492 * Must scan pg_constraint. Right now, it is a seqscan because there is
2493 * no available index on confrelid.
2495 fkeyRel
= heap_open(ConstraintRelationId
, AccessShareLock
);
2497 fkeyScan
= systable_beginscan(fkeyRel
, InvalidOid
, false,
2498 SnapshotNow
, 0, NULL
);
2500 while (HeapTupleIsValid(tuple
= systable_getnext(fkeyScan
)))
2502 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tuple
);
2504 /* Not a foreign key */
2505 if (con
->contype
!= CONSTRAINT_FOREIGN
)
2508 /* Not referencing one of our list of tables */
2509 if (!list_member_oid(relationIds
, con
->confrelid
))
2512 /* Add referencer unless already in input or result list */
2513 if (!list_member_oid(relationIds
, con
->conrelid
))
2514 result
= insert_ordered_unique_oid(result
, con
->conrelid
);
2517 systable_endscan(fkeyScan
);
2518 heap_close(fkeyRel
, AccessShareLock
);
2524 * insert_ordered_unique_oid
2525 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2526 * and eliminating duplicates
2528 * Building the ordered list this way is O(N^2), but with a pretty small
2529 * constant, so for the number of entries we expect it will probably be
2530 * faster than trying to apply qsort(). It seems unlikely someone would be
2531 * trying to truncate a table with thousands of dependent tables ...
2534 insert_ordered_unique_oid(List
*list
, Oid datum
)
2538 /* Does the datum belong at the front? */
2539 if (list
== NIL
|| datum
< linitial_oid(list
))
2540 return lcons_oid(datum
, list
);
2541 /* Does it match the first entry? */
2542 if (datum
== linitial_oid(list
))
2543 return list
; /* duplicate, so don't insert */
2544 /* No, so find the entry it belongs after */
2545 prev
= list_head(list
);
2548 ListCell
*curr
= lnext(prev
);
2550 if (curr
== NULL
|| datum
< lfirst_oid(curr
))
2551 break; /* it belongs after 'prev', before 'curr' */
2553 if (datum
== lfirst_oid(curr
))
2554 return list
; /* duplicate, so don't insert */
2558 /* Insert datum into list after 'prev' */
2559 lappend_cell_oid(list
, prev
, datum
);