1 /*-------------------------------------------------------------------------
4 * code to create and destroy POSTGRES heap relations
6 * Portions Copyright (c) 1996-2008, 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
,
83 static void RelationRemoveInheritance(Oid relid
);
84 static void StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
85 bool is_local
, int inhcount
);
86 static void StoreConstraints(Relation rel
, List
*cooked_constraints
);
87 static bool MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
88 bool allow_merge
, bool is_local
);
89 static void SetRelationNumChecks(Relation rel
, int numchecks
);
90 static Node
*cookConstraint(ParseState
*pstate
,
93 static List
*insert_ordered_unique_oid(List
*list
, Oid datum
);
96 /* ----------------------------------------------------------------
97 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
99 * these should all be moved to someplace in the lib/catalog
100 * module, if not obliterated first.
101 * ----------------------------------------------------------------
107 * Should the system special case these attributes in the future?
108 * Advantage: consume much less space in the ATTRIBUTE relation.
109 * Disadvantage: special cases will be all over the place.
112 static FormData_pg_attribute a1
= {
113 0, {"ctid"}, TIDOID
, 0, sizeof(ItemPointerData
),
114 SelfItemPointerAttributeNumber
, 0, -1, -1,
115 false, 'p', 's', true, false, false, true, 0
118 static FormData_pg_attribute a2
= {
119 0, {"oid"}, OIDOID
, 0, sizeof(Oid
),
120 ObjectIdAttributeNumber
, 0, -1, -1,
121 true, 'p', 'i', true, false, false, true, 0
124 static FormData_pg_attribute a3
= {
125 0, {"xmin"}, XIDOID
, 0, sizeof(TransactionId
),
126 MinTransactionIdAttributeNumber
, 0, -1, -1,
127 true, 'p', 'i', true, false, false, true, 0
130 static FormData_pg_attribute a4
= {
131 0, {"cmin"}, CIDOID
, 0, sizeof(CommandId
),
132 MinCommandIdAttributeNumber
, 0, -1, -1,
133 true, 'p', 'i', true, false, false, true, 0
136 static FormData_pg_attribute a5
= {
137 0, {"xmax"}, XIDOID
, 0, sizeof(TransactionId
),
138 MaxTransactionIdAttributeNumber
, 0, -1, -1,
139 true, 'p', 'i', true, false, false, true, 0
142 static FormData_pg_attribute a6
= {
143 0, {"cmax"}, CIDOID
, 0, sizeof(CommandId
),
144 MaxCommandIdAttributeNumber
, 0, -1, -1,
145 true, 'p', 'i', true, false, false, true, 0
149 * We decided to call this attribute "tableoid" rather than say
150 * "classoid" on the basis that in the future there may be more than one
151 * table of a particular class/type. In any case table is still the word
154 static FormData_pg_attribute a7
= {
155 0, {"tableoid"}, OIDOID
, 0, sizeof(Oid
),
156 TableOidAttributeNumber
, 0, -1, -1,
157 true, 'p', 'i', true, false, false, true, 0
160 static const Form_pg_attribute SysAtt
[] = {&a1
, &a2
, &a3
, &a4
, &a5
, &a6
, &a7
};
163 * This function returns a Form_pg_attribute pointer for a system attribute.
164 * Note that we elog if the presented attno is invalid, which would only
165 * happen if there's a problem upstream.
168 SystemAttributeDefinition(AttrNumber attno
, bool relhasoids
)
170 if (attno
>= 0 || attno
< -(int) lengthof(SysAtt
))
171 elog(ERROR
, "invalid system attribute number %d", attno
);
172 if (attno
== ObjectIdAttributeNumber
&& !relhasoids
)
173 elog(ERROR
, "invalid system attribute number %d", attno
);
174 return SysAtt
[-attno
- 1];
178 * If the given name is a system attribute name, return a Form_pg_attribute
179 * pointer for a prototype definition. If not, return NULL.
182 SystemAttributeByName(const char *attname
, bool relhasoids
)
186 for (j
= 0; j
< (int) lengthof(SysAtt
); j
++)
188 Form_pg_attribute att
= SysAtt
[j
];
190 if (relhasoids
|| att
->attnum
!= ObjectIdAttributeNumber
)
192 if (strcmp(NameStr(att
->attname
), attname
) == 0)
201 /* ----------------------------------------------------------------
202 * XXX END OF UGLY HARD CODED BADNESS XXX
203 * ---------------------------------------------------------------- */
206 /* ----------------------------------------------------------------
207 * heap_create - Create an uncataloged heap relation
209 * Note API change: the caller must now always provide the OID
210 * to use for the relation.
212 * rel->rd_rel is initialized by RelationBuildLocalRelation,
213 * and is mostly zeroes at return.
214 * ----------------------------------------------------------------
217 heap_create(const char *relname
,
223 bool shared_relation
,
224 bool allow_system_table_mods
)
229 /* The caller must have provided an OID for the relation. */
230 Assert(OidIsValid(relid
));
235 if (!allow_system_table_mods
&&
236 (IsSystemNamespace(relnamespace
) || IsToastNamespace(relnamespace
)) &&
237 IsNormalProcessingMode())
239 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
240 errmsg("permission denied to create \"%s.%s\"",
241 get_namespace_name(relnamespace
), relname
),
242 errdetail("System catalog modifications are currently disallowed.")));
245 * Decide if we need storage or not, and handle a couple other special
246 * cases for particular relkinds.
251 case RELKIND_COMPOSITE_TYPE
:
252 create_storage
= false;
255 * Force reltablespace to zero if the relation has no physical
256 * storage. This is mainly just for cleanliness' sake.
258 reltablespace
= InvalidOid
;
260 case RELKIND_SEQUENCE
:
261 create_storage
= true;
264 * Force reltablespace to zero for sequences, since we don't
265 * support moving them around into different tablespaces.
267 reltablespace
= InvalidOid
;
270 create_storage
= true;
275 * Never allow a pg_class entry to explicitly specify the database's
276 * default tablespace in reltablespace; force it to zero instead. This
277 * ensures that if the database is cloned with a different default
278 * tablespace, the pg_class entry will still match where CREATE DATABASE
279 * will put the physically copied relation.
281 * Yes, this is a bit of a hack.
283 if (reltablespace
== MyDatabaseTableSpace
)
284 reltablespace
= InvalidOid
;
287 * build the relcache entry.
289 rel
= RelationBuildLocalRelation(relname
,
297 * Have the storage manager create the relation's disk file, if needed.
299 * We only create the main fork here, other forks will be created on
304 RelationOpenSmgr(rel
);
305 RelationCreateStorage(rel
->rd_node
, rel
->rd_istemp
);
311 /* ----------------------------------------------------------------
312 * heap_create_with_catalog - Create a cataloged relation
314 * this is done in multiple steps:
316 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
317 * descriptor contains a valid set of attribute names and types
319 * 2) pg_class is opened and get_relname_relid()
320 * performs a scan to ensure that no relation with the
321 * same name already exists.
323 * 3) heap_create() is called to create the new relation on disk.
325 * 4) TypeCreate() is called to define a new type corresponding
326 * to the new relation.
328 * 5) AddNewRelationTuple() is called to register the
329 * relation in pg_class.
331 * 6) AddNewAttributeTuples() is called to register the
332 * new relation's schema in pg_attribute.
334 * 7) StoreConstraints is called () - vadim 08/22/97
336 * 8) the relations are closed and the new relation's oid
339 * ----------------------------------------------------------------
342 /* --------------------------------
343 * CheckAttributeNamesTypes
345 * this is used to make certain the tuple descriptor contains a
346 * valid set of attribute names and datatypes. a problem simply
347 * generates ereport(ERROR) which aborts the current transaction.
348 * --------------------------------
351 CheckAttributeNamesTypes(TupleDesc tupdesc
, char relkind
)
355 int natts
= tupdesc
->natts
;
357 /* Sanity check on column count */
358 if (natts
< 0 || natts
> MaxHeapAttributeNumber
)
360 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
361 errmsg("tables can have at most %d columns",
362 MaxHeapAttributeNumber
)));
365 * first check for collision with system attribute names
367 * Skip this for a view or type relation, since those don't have system
370 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
372 for (i
= 0; i
< natts
; i
++)
374 if (SystemAttributeByName(NameStr(tupdesc
->attrs
[i
]->attname
),
375 tupdesc
->tdhasoid
) != NULL
)
377 (errcode(ERRCODE_DUPLICATE_COLUMN
),
378 errmsg("column name \"%s\" conflicts with a system column name",
379 NameStr(tupdesc
->attrs
[i
]->attname
))));
384 * next check for repeated attribute names
386 for (i
= 1; i
< natts
; i
++)
388 for (j
= 0; j
< i
; j
++)
390 if (strcmp(NameStr(tupdesc
->attrs
[j
]->attname
),
391 NameStr(tupdesc
->attrs
[i
]->attname
)) == 0)
393 (errcode(ERRCODE_DUPLICATE_COLUMN
),
394 errmsg("column name \"%s\" specified more than once",
395 NameStr(tupdesc
->attrs
[j
]->attname
))));
400 * next check the attribute types
402 for (i
= 0; i
< natts
; i
++)
404 CheckAttributeType(NameStr(tupdesc
->attrs
[i
]->attname
),
405 tupdesc
->attrs
[i
]->atttypid
);
409 /* --------------------------------
412 * Verify that the proposed datatype of an attribute is legal.
413 * This is needed because there are types (and pseudo-types)
414 * in the catalogs that we do not support as elements of real tuples.
415 * --------------------------------
418 CheckAttributeType(const char *attname
, Oid atttypid
)
420 char att_typtype
= get_typtype(atttypid
);
422 if (atttypid
== UNKNOWNOID
)
425 * Warn user, but don't fail, if column to be created has UNKNOWN type
426 * (usually as a result of a 'retrieve into' - jolly)
429 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
430 errmsg("column \"%s\" has type \"unknown\"", attname
),
431 errdetail("Proceeding with relation creation anyway.")));
433 else if (att_typtype
== TYPTYPE_PSEUDO
)
436 * Refuse any attempt to create a pseudo-type column, except for a
437 * special hack for pg_statistic: allow ANYARRAY during initdb
439 if (atttypid
!= ANYARRAYOID
|| IsUnderPostmaster
)
441 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
442 errmsg("column \"%s\" has pseudo-type %s",
443 attname
, format_type_be(atttypid
))));
445 else if (att_typtype
== TYPTYPE_COMPOSITE
)
448 * For a composite type, recurse into its attributes. You might think
449 * this isn't necessary, but since we allow system catalogs to break
450 * the rule, we have to guard against the case.
456 relation
= relation_open(get_typ_typrelid(atttypid
), AccessShareLock
);
458 tupdesc
= RelationGetDescr(relation
);
460 for (i
= 0; i
< tupdesc
->natts
; i
++)
462 Form_pg_attribute attr
= tupdesc
->attrs
[i
];
464 if (attr
->attisdropped
)
466 CheckAttributeType(NameStr(attr
->attname
), attr
->atttypid
);
469 relation_close(relation
, AccessShareLock
);
474 * InsertPgAttributeTuple
475 * Construct and insert a new tuple in pg_attribute.
477 * Caller has already opened and locked pg_attribute. new_attribute is the
478 * attribute to insert.
480 * indstate is the index state for CatalogIndexInsert. It can be passed as
481 * NULL, in which case we'll fetch the necessary info. (Don't do this when
482 * inserting multiple attributes, because it's a tad more expensive.)
485 InsertPgAttributeTuple(Relation pg_attribute_rel
,
486 Form_pg_attribute new_attribute
,
487 CatalogIndexState indstate
)
489 Datum values
[Natts_pg_attribute
];
490 bool nulls
[Natts_pg_attribute
];
493 /* This is a tad tedious, but way cleaner than what we used to do... */
494 memset(values
, 0, sizeof(values
));
495 memset(nulls
, false, sizeof(nulls
));
497 values
[Anum_pg_attribute_attrelid
- 1] = ObjectIdGetDatum(new_attribute
->attrelid
);
498 values
[Anum_pg_attribute_attname
- 1] = NameGetDatum(&new_attribute
->attname
);
499 values
[Anum_pg_attribute_atttypid
- 1] = ObjectIdGetDatum(new_attribute
->atttypid
);
500 values
[Anum_pg_attribute_attstattarget
- 1] = Int32GetDatum(new_attribute
->attstattarget
);
501 values
[Anum_pg_attribute_attlen
- 1] = Int16GetDatum(new_attribute
->attlen
);
502 values
[Anum_pg_attribute_attnum
- 1] = Int16GetDatum(new_attribute
->attnum
);
503 values
[Anum_pg_attribute_attndims
- 1] = Int32GetDatum(new_attribute
->attndims
);
504 values
[Anum_pg_attribute_attcacheoff
- 1] = Int32GetDatum(new_attribute
->attcacheoff
);
505 values
[Anum_pg_attribute_atttypmod
- 1] = Int32GetDatum(new_attribute
->atttypmod
);
506 values
[Anum_pg_attribute_attbyval
- 1] = BoolGetDatum(new_attribute
->attbyval
);
507 values
[Anum_pg_attribute_attstorage
- 1] = CharGetDatum(new_attribute
->attstorage
);
508 values
[Anum_pg_attribute_attalign
- 1] = CharGetDatum(new_attribute
->attalign
);
509 values
[Anum_pg_attribute_attnotnull
- 1] = BoolGetDatum(new_attribute
->attnotnull
);
510 values
[Anum_pg_attribute_atthasdef
- 1] = BoolGetDatum(new_attribute
->atthasdef
);
511 values
[Anum_pg_attribute_attisdropped
- 1] = BoolGetDatum(new_attribute
->attisdropped
);
512 values
[Anum_pg_attribute_attislocal
- 1] = BoolGetDatum(new_attribute
->attislocal
);
513 values
[Anum_pg_attribute_attinhcount
- 1] = Int32GetDatum(new_attribute
->attinhcount
);
515 tup
= heap_form_tuple(RelationGetDescr(pg_attribute_rel
), values
, nulls
);
517 /* finally insert the new tuple, update the indexes, and clean up */
518 simple_heap_insert(pg_attribute_rel
, tup
);
520 if (indstate
!= NULL
)
521 CatalogIndexInsert(indstate
, tup
);
523 CatalogUpdateIndexes(pg_attribute_rel
, tup
);
527 /* --------------------------------
528 * AddNewAttributeTuples
530 * this registers the new relation's schema by adding
531 * tuples to pg_attribute.
532 * --------------------------------
535 AddNewAttributeTuples(Oid new_rel_oid
,
541 Form_pg_attribute attr
;
544 CatalogIndexState indstate
;
545 int natts
= tupdesc
->natts
;
546 ObjectAddress myself
,
550 * open pg_attribute and its indexes.
552 rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
554 indstate
= CatalogOpenIndexes(rel
);
557 * First we add the user attributes. This is also a convenient place to
558 * add dependencies on their datatypes.
560 for (i
= 0; i
< natts
; i
++)
562 attr
= tupdesc
->attrs
[i
];
563 /* Fill in the correct relation OID */
564 attr
->attrelid
= new_rel_oid
;
565 /* Make sure these are OK, too */
566 attr
->attstattarget
= -1;
567 attr
->attcacheoff
= -1;
569 InsertPgAttributeTuple(rel
, attr
, indstate
);
571 /* Add dependency info */
572 myself
.classId
= RelationRelationId
;
573 myself
.objectId
= new_rel_oid
;
574 myself
.objectSubId
= i
+ 1;
575 referenced
.classId
= TypeRelationId
;
576 referenced
.objectId
= attr
->atttypid
;
577 referenced
.objectSubId
= 0;
578 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
582 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
583 * all for a view or type relation. We don't bother with making datatype
584 * dependencies here, since presumably all these types are pinned.
586 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
588 for (i
= 0; i
< (int) lengthof(SysAtt
); i
++)
590 FormData_pg_attribute attStruct
;
592 /* skip OID where appropriate */
593 if (!tupdesc
->tdhasoid
&&
594 SysAtt
[i
]->attnum
== ObjectIdAttributeNumber
)
597 memcpy(&attStruct
, (char *) SysAtt
[i
], sizeof(FormData_pg_attribute
));
599 /* Fill in the correct relation OID in the copied tuple */
600 attStruct
.attrelid
= new_rel_oid
;
602 /* Fill in correct inheritance info for the OID column */
603 if (attStruct
.attnum
== ObjectIdAttributeNumber
)
605 attStruct
.attislocal
= oidislocal
;
606 attStruct
.attinhcount
= oidinhcount
;
609 InsertPgAttributeTuple(rel
, &attStruct
, indstate
);
616 CatalogCloseIndexes(indstate
);
618 heap_close(rel
, RowExclusiveLock
);
621 /* --------------------------------
624 * Construct and insert a new tuple in pg_class.
626 * Caller has already opened and locked pg_class.
627 * Tuple data is taken from new_rel_desc->rd_rel, except for the
628 * variable-width fields which are not present in a cached reldesc.
629 * We always initialize relacl to NULL (i.e., default permissions),
630 * and reloptions is set to the passed-in text array (if any).
631 * --------------------------------
634 InsertPgClassTuple(Relation pg_class_desc
,
635 Relation new_rel_desc
,
639 Form_pg_class rd_rel
= new_rel_desc
->rd_rel
;
640 Datum values
[Natts_pg_class
];
641 bool nulls
[Natts_pg_class
];
644 /* This is a tad tedious, but way cleaner than what we used to do... */
645 memset(values
, 0, sizeof(values
));
646 memset(nulls
, false, sizeof(nulls
));
648 values
[Anum_pg_class_relname
- 1] = NameGetDatum(&rd_rel
->relname
);
649 values
[Anum_pg_class_relnamespace
- 1] = ObjectIdGetDatum(rd_rel
->relnamespace
);
650 values
[Anum_pg_class_reltype
- 1] = ObjectIdGetDatum(rd_rel
->reltype
);
651 values
[Anum_pg_class_relowner
- 1] = ObjectIdGetDatum(rd_rel
->relowner
);
652 values
[Anum_pg_class_relam
- 1] = ObjectIdGetDatum(rd_rel
->relam
);
653 values
[Anum_pg_class_relfilenode
- 1] = ObjectIdGetDatum(rd_rel
->relfilenode
);
654 values
[Anum_pg_class_reltablespace
- 1] = ObjectIdGetDatum(rd_rel
->reltablespace
);
655 values
[Anum_pg_class_relpages
- 1] = Int32GetDatum(rd_rel
->relpages
);
656 values
[Anum_pg_class_reltuples
- 1] = Float4GetDatum(rd_rel
->reltuples
);
657 values
[Anum_pg_class_reltoastrelid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastrelid
);
658 values
[Anum_pg_class_reltoastidxid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastidxid
);
659 values
[Anum_pg_class_relhasindex
- 1] = BoolGetDatum(rd_rel
->relhasindex
);
660 values
[Anum_pg_class_relisshared
- 1] = BoolGetDatum(rd_rel
->relisshared
);
661 values
[Anum_pg_class_relkind
- 1] = CharGetDatum(rd_rel
->relkind
);
662 values
[Anum_pg_class_relnatts
- 1] = Int16GetDatum(rd_rel
->relnatts
);
663 values
[Anum_pg_class_relchecks
- 1] = Int16GetDatum(rd_rel
->relchecks
);
664 values
[Anum_pg_class_relhasoids
- 1] = BoolGetDatum(rd_rel
->relhasoids
);
665 values
[Anum_pg_class_relhaspkey
- 1] = BoolGetDatum(rd_rel
->relhaspkey
);
666 values
[Anum_pg_class_relhasrules
- 1] = BoolGetDatum(rd_rel
->relhasrules
);
667 values
[Anum_pg_class_relhastriggers
- 1] = BoolGetDatum(rd_rel
->relhastriggers
);
668 values
[Anum_pg_class_relhassubclass
- 1] = BoolGetDatum(rd_rel
->relhassubclass
);
669 values
[Anum_pg_class_relfrozenxid
- 1] = TransactionIdGetDatum(rd_rel
->relfrozenxid
);
670 /* start out with empty permissions */
671 nulls
[Anum_pg_class_relacl
- 1] = true;
672 if (reloptions
!= (Datum
) 0)
673 values
[Anum_pg_class_reloptions
- 1] = reloptions
;
675 nulls
[Anum_pg_class_reloptions
- 1] = true;
677 tup
= heap_form_tuple(RelationGetDescr(pg_class_desc
), values
, nulls
);
680 * The new tuple must have the oid already chosen for the rel. Sure would
681 * be embarrassing to do this sort of thing in polite company.
683 HeapTupleSetOid(tup
, new_rel_oid
);
685 /* finally insert the new tuple, update the indexes, and clean up */
686 simple_heap_insert(pg_class_desc
, tup
);
688 CatalogUpdateIndexes(pg_class_desc
, tup
);
693 /* --------------------------------
694 * AddNewRelationTuple
696 * this registers the new relation in the catalogs by
697 * adding a tuple to pg_class.
698 * --------------------------------
701 AddNewRelationTuple(Relation pg_class_desc
,
702 Relation new_rel_desc
,
709 Form_pg_class new_rel_reltup
;
712 * first we update some of the information in our uncataloged relation's
713 * relation descriptor.
715 new_rel_reltup
= new_rel_desc
->rd_rel
;
719 case RELKIND_RELATION
:
721 case RELKIND_TOASTVALUE
:
722 /* The relation is real, but as yet empty */
723 new_rel_reltup
->relpages
= 0;
724 new_rel_reltup
->reltuples
= 0;
726 case RELKIND_SEQUENCE
:
727 /* Sequences always have a known size */
728 new_rel_reltup
->relpages
= 1;
729 new_rel_reltup
->reltuples
= 1;
732 /* Views, etc, have no disk storage */
733 new_rel_reltup
->relpages
= 0;
734 new_rel_reltup
->reltuples
= 0;
738 /* Initialize relfrozenxid */
739 if (relkind
== RELKIND_RELATION
||
740 relkind
== RELKIND_TOASTVALUE
)
743 * Initialize to the minimum XID that could put tuples in the table.
744 * We know that no xacts older than RecentXmin are still running, so
747 new_rel_reltup
->relfrozenxid
= RecentXmin
;
752 * Other relation types will not contain XIDs, so set relfrozenxid to
753 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
754 * we force its xmin to be FrozenTransactionId always; see
755 * commands/sequence.c.)
757 new_rel_reltup
->relfrozenxid
= InvalidTransactionId
;
760 new_rel_reltup
->relowner
= relowner
;
761 new_rel_reltup
->reltype
= new_type_oid
;
762 new_rel_reltup
->relkind
= relkind
;
764 new_rel_desc
->rd_att
->tdtypeid
= new_type_oid
;
766 /* Now build and insert the tuple */
767 InsertPgClassTuple(pg_class_desc
, new_rel_desc
, new_rel_oid
, reloptions
);
771 /* --------------------------------
772 * AddNewRelationType -
774 * define a composite type corresponding to the new relation
775 * --------------------------------
778 AddNewRelationType(const char *typeName
,
785 TypeCreate(InvalidOid
, /* no predetermined OID */
786 typeName
, /* type name */
787 typeNamespace
, /* type namespace */
788 new_rel_oid
, /* relation oid */
789 new_rel_kind
, /* relation kind */
790 -1, /* internal size (varlena) */
791 TYPTYPE_COMPOSITE
, /* type-type (composite) */
792 TYPCATEGORY_COMPOSITE
, /* type-category (ditto) */
793 false, /* composite types are never preferred */
794 DEFAULT_TYPDELIM
, /* default array delimiter */
795 F_RECORD_IN
, /* input procedure */
796 F_RECORD_OUT
, /* output procedure */
797 F_RECORD_RECV
, /* receive procedure */
798 F_RECORD_SEND
, /* send procedure */
799 InvalidOid
, /* typmodin procedure - none */
800 InvalidOid
, /* typmodout procedure - none */
801 InvalidOid
, /* analyze procedure - default */
802 InvalidOid
, /* array element type - irrelevant */
803 false, /* this is not an array type */
804 new_array_type
, /* array type if any */
805 InvalidOid
, /* domain base type - irrelevant */
806 NULL
, /* default value - none */
807 NULL
, /* default binary representation */
808 false, /* passed by reference */
809 'd', /* alignment - must be the largest! */
810 'x', /* fully TOASTable */
812 0, /* array dimensions for typBaseType */
813 false); /* Type NOT NULL */
816 /* --------------------------------
817 * heap_create_with_catalog
819 * creates a new cataloged relation. see comments above.
820 * --------------------------------
823 heap_create_with_catalog(const char *relname
,
829 List
*cooked_constraints
,
831 bool shared_relation
,
834 OnCommitAction oncommit
,
836 bool allow_system_table_mods
)
838 Relation pg_class_desc
;
839 Relation new_rel_desc
;
842 Oid new_array_oid
= InvalidOid
;
844 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
849 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
851 CheckAttributeNamesTypes(tupdesc
, relkind
);
853 if (get_relname_relid(relname
, relnamespace
))
855 (errcode(ERRCODE_DUPLICATE_TABLE
),
856 errmsg("relation \"%s\" already exists", relname
)));
859 * Since we are going to create a rowtype as well, also check for
860 * collision with an existing type name. If there is one and it's an
861 * autogenerated array, we can rename it out of the way; otherwise we can
862 * at least give a good error message.
864 old_type_oid
= GetSysCacheOid(TYPENAMENSP
,
865 CStringGetDatum(relname
),
866 ObjectIdGetDatum(relnamespace
),
868 if (OidIsValid(old_type_oid
))
870 if (!moveArrayTypeName(old_type_oid
, relname
, relnamespace
))
872 (errcode(ERRCODE_DUPLICATE_OBJECT
),
873 errmsg("type \"%s\" already exists", relname
),
874 errhint("A relation has an associated type of the same name, "
875 "so you must use a name that doesn't conflict "
876 "with any existing type.")));
880 * Validate shared/non-shared tablespace (must check this before doing
881 * GetNewRelFileNode, to prevent Assert therein)
885 if (reltablespace
!= GLOBALTABLESPACE_OID
)
886 /* elog since this is not a user-facing error */
888 "shared relations must be placed in pg_global tablespace");
892 if (reltablespace
== GLOBALTABLESPACE_OID
)
894 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
895 errmsg("only shared relations can be placed in pg_global tablespace")));
899 * Allocate an OID for the relation, unless we were told what to use.
901 * The OID will be the relfilenode as well, so make sure it doesn't
902 * collide with either pg_class OIDs or existing physical files.
904 if (!OidIsValid(relid
))
905 relid
= GetNewRelFileNode(reltablespace
, shared_relation
,
909 * Create the relcache entry (mostly dummy at this point) and the physical
910 * disk file. (If we fail further down, it's the smgr's responsibility to
911 * remove the disk file again.)
913 new_rel_desc
= heap_create(relname
,
920 allow_system_table_mods
);
922 Assert(relid
== RelationGetRelid(new_rel_desc
));
925 * Decide whether to create an array type over the relation's rowtype. We
926 * do not create any array types for system catalogs (ie, those made
927 * during initdb). We create array types for regular relations, views,
928 * and composite types ... but not, eg, for toast tables or sequences.
930 if (IsUnderPostmaster
&& (relkind
== RELKIND_RELATION
||
931 relkind
== RELKIND_VIEW
||
932 relkind
== RELKIND_COMPOSITE_TYPE
))
934 /* OK, so pre-assign a type OID for the array type */
935 Relation pg_type
= heap_open(TypeRelationId
, AccessShareLock
);
937 new_array_oid
= GetNewOid(pg_type
);
938 heap_close(pg_type
, AccessShareLock
);
942 * Since defining a relation also defines a complex type, we add a new
943 * system type corresponding to the new relation.
945 * NOTE: we could get a unique-index failure here, in case someone else is
946 * creating the same type name in parallel but hadn't committed yet when
947 * we checked for a duplicate name above.
949 new_type_oid
= AddNewRelationType(relname
,
956 * Now make the array type if wanted.
958 if (OidIsValid(new_array_oid
))
962 relarrayname
= makeArrayTypeName(relname
, relnamespace
);
964 TypeCreate(new_array_oid
, /* force the type's OID to this */
965 relarrayname
, /* Array type name */
966 relnamespace
, /* Same namespace as parent */
967 InvalidOid
, /* Not composite, no relationOid */
968 0, /* relkind, also N/A here */
969 -1, /* Internal size (varlena) */
970 TYPTYPE_BASE
, /* Not composite - typelem is */
971 TYPCATEGORY_ARRAY
, /* type-category (array) */
972 false, /* array types are never preferred */
973 DEFAULT_TYPDELIM
, /* default array delimiter */
974 F_ARRAY_IN
, /* array input proc */
975 F_ARRAY_OUT
, /* array output proc */
976 F_ARRAY_RECV
, /* array recv (bin) proc */
977 F_ARRAY_SEND
, /* array send (bin) proc */
978 InvalidOid
, /* typmodin procedure - none */
979 InvalidOid
, /* typmodout procedure - none */
980 InvalidOid
, /* analyze procedure - default */
981 new_type_oid
, /* array element type - the rowtype */
982 true, /* yes, this is an array type */
983 InvalidOid
, /* this has no array type */
984 InvalidOid
, /* domain base type - irrelevant */
985 NULL
, /* default value - none */
986 NULL
, /* default binary representation */
987 false, /* passed by reference */
988 'd', /* alignment - must be the largest! */
989 'x', /* fully TOASTable */
991 0, /* array dimensions for typBaseType */
992 false); /* Type NOT NULL */
998 * now create an entry in pg_class for the relation.
1000 * NOTE: we could get a unique-index failure here, in case someone else is
1001 * creating the same relation name in parallel but hadn't committed yet
1002 * when we checked for a duplicate name above.
1004 AddNewRelationTuple(pg_class_desc
,
1013 * now add tuples to pg_attribute for the attributes in our new relation.
1015 AddNewAttributeTuples(relid
, new_rel_desc
->rd_att
, relkind
,
1016 oidislocal
, oidinhcount
);
1019 * Make a dependency link to force the relation to be deleted if its
1020 * namespace is. Also make a dependency link to its owner.
1022 * For composite types, these dependencies are tracked for the pg_type
1023 * entry, so we needn't record them here. Likewise, TOAST tables don't
1024 * need a namespace dependency (they live in a pinned namespace) nor an
1025 * owner dependency (they depend indirectly through the parent table).
1026 * Also, skip this in bootstrap mode, since we don't make dependencies
1027 * while bootstrapping.
1029 if (relkind
!= RELKIND_COMPOSITE_TYPE
&&
1030 relkind
!= RELKIND_TOASTVALUE
&&
1031 !IsBootstrapProcessingMode())
1033 ObjectAddress myself
,
1036 myself
.classId
= RelationRelationId
;
1037 myself
.objectId
= relid
;
1038 myself
.objectSubId
= 0;
1039 referenced
.classId
= NamespaceRelationId
;
1040 referenced
.objectId
= relnamespace
;
1041 referenced
.objectSubId
= 0;
1042 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
1044 recordDependencyOnOwner(RelationRelationId
, relid
, ownerid
);
1048 * Store any supplied constraints and defaults.
1050 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1051 * entry, so the relation must be valid and self-consistent at this point.
1052 * In particular, there are not yet constraints and defaults anywhere.
1054 StoreConstraints(new_rel_desc
, cooked_constraints
);
1057 * If there's a special on-commit action, remember it
1059 if (oncommit
!= ONCOMMIT_NOOP
)
1060 register_on_commit_action(relid
, oncommit
);
1063 * ok, the relation has been cataloged, so close our relations and return
1064 * the OID of the newly created relation.
1066 heap_close(new_rel_desc
, NoLock
); /* do not unlock till end of xact */
1067 heap_close(pg_class_desc
, RowExclusiveLock
);
1074 * RelationRemoveInheritance
1076 * Formerly, this routine checked for child relations and aborted the
1077 * deletion if any were found. Now we rely on the dependency mechanism
1078 * to check for or delete child relations. By the time we get here,
1079 * there are no children and we need only remove any pg_inherits rows
1080 * linking this relation to its parent(s).
1083 RelationRemoveInheritance(Oid relid
)
1085 Relation catalogRelation
;
1090 catalogRelation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
1093 Anum_pg_inherits_inhrelid
,
1094 BTEqualStrategyNumber
, F_OIDEQ
,
1095 ObjectIdGetDatum(relid
));
1097 scan
= systable_beginscan(catalogRelation
, InheritsRelidSeqnoIndexId
, true,
1098 SnapshotNow
, 1, &key
);
1100 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1101 simple_heap_delete(catalogRelation
, &tuple
->t_self
);
1103 systable_endscan(scan
);
1104 heap_close(catalogRelation
, RowExclusiveLock
);
1108 * DeleteRelationTuple
1110 * Remove pg_class row for the given relid.
1112 * Note: this is shared by relation deletion and index deletion. It's
1113 * not intended for use anyplace else.
1116 DeleteRelationTuple(Oid relid
)
1118 Relation pg_class_desc
;
1121 /* Grab an appropriate lock on the pg_class relation */
1122 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
1124 tup
= SearchSysCache(RELOID
,
1125 ObjectIdGetDatum(relid
),
1127 if (!HeapTupleIsValid(tup
))
1128 elog(ERROR
, "cache lookup failed for relation %u", relid
);
1130 /* delete the relation tuple from pg_class, and finish up */
1131 simple_heap_delete(pg_class_desc
, &tup
->t_self
);
1133 ReleaseSysCache(tup
);
1135 heap_close(pg_class_desc
, RowExclusiveLock
);
1139 * DeleteAttributeTuples
1141 * Remove pg_attribute rows for the given relid.
1143 * Note: this is shared by relation deletion and index deletion. It's
1144 * not intended for use anyplace else.
1147 DeleteAttributeTuples(Oid relid
)
1154 /* Grab an appropriate lock on the pg_attribute relation */
1155 attrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1157 /* Use the index to scan only attributes of the target relation */
1158 ScanKeyInit(&key
[0],
1159 Anum_pg_attribute_attrelid
,
1160 BTEqualStrategyNumber
, F_OIDEQ
,
1161 ObjectIdGetDatum(relid
));
1163 scan
= systable_beginscan(attrel
, AttributeRelidNumIndexId
, true,
1164 SnapshotNow
, 1, key
);
1166 /* Delete all the matching tuples */
1167 while ((atttup
= systable_getnext(scan
)) != NULL
)
1168 simple_heap_delete(attrel
, &atttup
->t_self
);
1170 /* Clean up after the scan */
1171 systable_endscan(scan
);
1172 heap_close(attrel
, RowExclusiveLock
);
1176 * RemoveAttributeById
1178 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1179 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1180 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1181 * is handled by dependency.c.)
1184 RemoveAttributeById(Oid relid
, AttrNumber attnum
)
1189 Form_pg_attribute attStruct
;
1190 char newattname
[NAMEDATALEN
];
1193 * Grab an exclusive lock on the target table, which we will NOT release
1194 * until end of transaction. (In the simple case where we are directly
1195 * dropping this column, AlterTableDropColumn already did this ... but
1196 * when cascading from a drop of some other object, we may not have any
1199 rel
= relation_open(relid
, AccessExclusiveLock
);
1201 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1203 tuple
= SearchSysCacheCopy(ATTNUM
,
1204 ObjectIdGetDatum(relid
),
1205 Int16GetDatum(attnum
),
1207 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1208 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1210 attStruct
= (Form_pg_attribute
) GETSTRUCT(tuple
);
1214 /* System attribute (probably OID) ... just delete the row */
1216 simple_heap_delete(attr_rel
, &tuple
->t_self
);
1220 /* Dropping user attributes is lots harder */
1222 /* Mark the attribute as dropped */
1223 attStruct
->attisdropped
= true;
1226 * Set the type OID to invalid. A dropped attribute's type link
1227 * cannot be relied on (once the attribute is dropped, the type might
1228 * be too). Fortunately we do not need the type row --- the only
1229 * really essential information is the type's typlen and typalign,
1230 * which are preserved in the attribute's attlen and attalign. We set
1231 * atttypid to zero here as a means of catching code that incorrectly
1232 * expects it to be valid.
1234 attStruct
->atttypid
= InvalidOid
;
1236 /* Remove any NOT NULL constraint the column may have */
1237 attStruct
->attnotnull
= false;
1239 /* We don't want to keep stats for it anymore */
1240 attStruct
->attstattarget
= 0;
1243 * Change the column name to something that isn't likely to conflict
1245 snprintf(newattname
, sizeof(newattname
),
1246 "........pg.dropped.%d........", attnum
);
1247 namestrcpy(&(attStruct
->attname
), newattname
);
1249 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1251 /* keep the system catalog indexes current */
1252 CatalogUpdateIndexes(attr_rel
, tuple
);
1256 * Because updating the pg_attribute row will trigger a relcache flush for
1257 * the target relation, we need not do anything else to notify other
1258 * backends of the change.
1261 heap_close(attr_rel
, RowExclusiveLock
);
1264 RemoveStatistics(relid
, attnum
);
1266 relation_close(rel
, NoLock
);
1272 * If the specified relation/attribute has a default, remove it.
1273 * (If no default, raise error if complain is true, else return quietly.)
1276 RemoveAttrDefault(Oid relid
, AttrNumber attnum
,
1277 DropBehavior behavior
, bool complain
)
1279 Relation attrdef_rel
;
1280 ScanKeyData scankeys
[2];
1285 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1287 ScanKeyInit(&scankeys
[0],
1288 Anum_pg_attrdef_adrelid
,
1289 BTEqualStrategyNumber
, F_OIDEQ
,
1290 ObjectIdGetDatum(relid
));
1291 ScanKeyInit(&scankeys
[1],
1292 Anum_pg_attrdef_adnum
,
1293 BTEqualStrategyNumber
, F_INT2EQ
,
1294 Int16GetDatum(attnum
));
1296 scan
= systable_beginscan(attrdef_rel
, AttrDefaultIndexId
, true,
1297 SnapshotNow
, 2, scankeys
);
1299 /* There should be at most one matching tuple, but we loop anyway */
1300 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1302 ObjectAddress object
;
1304 object
.classId
= AttrDefaultRelationId
;
1305 object
.objectId
= HeapTupleGetOid(tuple
);
1306 object
.objectSubId
= 0;
1308 performDeletion(&object
, behavior
);
1313 systable_endscan(scan
);
1314 heap_close(attrdef_rel
, RowExclusiveLock
);
1316 if (complain
&& !found
)
1317 elog(ERROR
, "could not find attrdef tuple for relation %u attnum %d",
1322 * RemoveAttrDefaultById
1324 * Remove a pg_attrdef entry specified by OID. This is the guts of
1325 * attribute-default removal. Note it should be called via performDeletion,
1329 RemoveAttrDefaultById(Oid attrdefId
)
1331 Relation attrdef_rel
;
1334 ScanKeyData scankeys
[1];
1338 AttrNumber myattnum
;
1340 /* Grab an appropriate lock on the pg_attrdef relation */
1341 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1343 /* Find the pg_attrdef tuple */
1344 ScanKeyInit(&scankeys
[0],
1345 ObjectIdAttributeNumber
,
1346 BTEqualStrategyNumber
, F_OIDEQ
,
1347 ObjectIdGetDatum(attrdefId
));
1349 scan
= systable_beginscan(attrdef_rel
, AttrDefaultOidIndexId
, true,
1350 SnapshotNow
, 1, scankeys
);
1352 tuple
= systable_getnext(scan
);
1353 if (!HeapTupleIsValid(tuple
))
1354 elog(ERROR
, "could not find tuple for attrdef %u", attrdefId
);
1356 myrelid
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adrelid
;
1357 myattnum
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adnum
;
1359 /* Get an exclusive lock on the relation owning the attribute */
1360 myrel
= relation_open(myrelid
, AccessExclusiveLock
);
1362 /* Now we can delete the pg_attrdef row */
1363 simple_heap_delete(attrdef_rel
, &tuple
->t_self
);
1365 systable_endscan(scan
);
1366 heap_close(attrdef_rel
, RowExclusiveLock
);
1368 /* Fix the pg_attribute row */
1369 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1371 tuple
= SearchSysCacheCopy(ATTNUM
,
1372 ObjectIdGetDatum(myrelid
),
1373 Int16GetDatum(myattnum
),
1375 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1376 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1379 ((Form_pg_attribute
) GETSTRUCT(tuple
))->atthasdef
= false;
1381 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1383 /* keep the system catalog indexes current */
1384 CatalogUpdateIndexes(attr_rel
, tuple
);
1387 * Our update of the pg_attribute row will force a relcache rebuild, so
1388 * there's nothing else to do here.
1390 heap_close(attr_rel
, RowExclusiveLock
);
1392 /* Keep lock on attribute's rel until end of xact */
1393 relation_close(myrel
, NoLock
);
1397 * heap_drop_with_catalog - removes specified relation from catalogs
1399 * Note that this routine is not responsible for dropping objects that are
1400 * linked to the pg_class entry via dependencies (for example, indexes and
1401 * constraints). Those are deleted by the dependency-tracing logic in
1402 * dependency.c before control gets here. In general, therefore, this routine
1403 * should never be called directly; go through performDeletion() instead.
1406 heap_drop_with_catalog(Oid relid
)
1411 * Open and lock the relation.
1413 rel
= relation_open(relid
, AccessExclusiveLock
);
1416 * Schedule unlinking of the relation's physical files at commit.
1418 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
&&
1419 rel
->rd_rel
->relkind
!= RELKIND_COMPOSITE_TYPE
)
1421 RelationDropStorage(rel
);
1425 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1426 * until transaction commit. This ensures no one else will try to do
1427 * something with the doomed relation.
1429 relation_close(rel
, NoLock
);
1432 * Forget any ON COMMIT action for the rel
1434 remove_on_commit_action(relid
);
1437 * Flush the relation from the relcache. We want to do this before
1438 * starting to remove catalog entries, just to be certain that no relcache
1439 * entry rebuild will happen partway through. (That should not really
1440 * matter, since we don't do CommandCounterIncrement here, but let's be
1443 RelationForgetRelation(relid
);
1446 * remove inheritance information
1448 RelationRemoveInheritance(relid
);
1453 RemoveStatistics(relid
, 0);
1456 * delete attribute tuples
1458 DeleteAttributeTuples(relid
);
1461 * delete relation tuple
1463 DeleteRelationTuple(relid
);
1468 * Store a default expression for column attnum of relation rel.
1471 StoreAttrDefault(Relation rel
, AttrNumber attnum
, Node
*expr
)
1478 static bool nulls
[4] = {false, false, false, false};
1481 Form_pg_attribute attStruct
;
1483 ObjectAddress colobject
,
1487 * Flatten expression to string form for storage.
1489 adbin
= nodeToString(expr
);
1492 * Also deparse it to form the mostly-obsolete adsrc field.
1494 adsrc
= deparse_expression(expr
,
1495 deparse_context_for(RelationGetRelationName(rel
),
1496 RelationGetRelid(rel
)),
1500 * Make the pg_attrdef entry.
1502 values
[Anum_pg_attrdef_adrelid
- 1] = RelationGetRelid(rel
);
1503 values
[Anum_pg_attrdef_adnum
- 1] = attnum
;
1504 values
[Anum_pg_attrdef_adbin
- 1] = CStringGetTextDatum(adbin
);
1505 values
[Anum_pg_attrdef_adsrc
- 1] = CStringGetTextDatum(adsrc
);
1507 adrel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1509 tuple
= heap_form_tuple(adrel
->rd_att
, values
, nulls
);
1510 attrdefOid
= simple_heap_insert(adrel
, tuple
);
1512 CatalogUpdateIndexes(adrel
, tuple
);
1514 defobject
.classId
= AttrDefaultRelationId
;
1515 defobject
.objectId
= attrdefOid
;
1516 defobject
.objectSubId
= 0;
1518 heap_close(adrel
, RowExclusiveLock
);
1520 /* now can free some of the stuff allocated above */
1521 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adbin
- 1]));
1522 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adsrc
- 1]));
1523 heap_freetuple(tuple
);
1528 * Update the pg_attribute entry for the column to show that a default
1531 attrrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1532 atttup
= SearchSysCacheCopy(ATTNUM
,
1533 ObjectIdGetDatum(RelationGetRelid(rel
)),
1534 Int16GetDatum(attnum
),
1536 if (!HeapTupleIsValid(atttup
))
1537 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1538 attnum
, RelationGetRelid(rel
));
1539 attStruct
= (Form_pg_attribute
) GETSTRUCT(atttup
);
1540 if (!attStruct
->atthasdef
)
1542 attStruct
->atthasdef
= true;
1543 simple_heap_update(attrrel
, &atttup
->t_self
, atttup
);
1544 /* keep catalog indexes current */
1545 CatalogUpdateIndexes(attrrel
, atttup
);
1547 heap_close(attrrel
, RowExclusiveLock
);
1548 heap_freetuple(atttup
);
1551 * Make a dependency so that the pg_attrdef entry goes away if the column
1552 * (or whole table) is deleted.
1554 colobject
.classId
= RelationRelationId
;
1555 colobject
.objectId
= RelationGetRelid(rel
);
1556 colobject
.objectSubId
= attnum
;
1558 recordDependencyOn(&defobject
, &colobject
, DEPENDENCY_AUTO
);
1561 * Record dependencies on objects used in the expression, too.
1563 recordDependencyOnExpr(&defobject
, expr
, NIL
, DEPENDENCY_NORMAL
);
1567 * Store a check-constraint expression for the given relation.
1569 * Caller is responsible for updating the count of constraints
1570 * in the pg_class entry for the relation.
1573 StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
1574 bool is_local
, int inhcount
)
1583 * Flatten expression to string form for storage.
1585 ccbin
= nodeToString(expr
);
1588 * Also deparse it to form the mostly-obsolete consrc field.
1590 ccsrc
= deparse_expression(expr
,
1591 deparse_context_for(RelationGetRelationName(rel
),
1592 RelationGetRelid(rel
)),
1596 * Find columns of rel that are used in expr
1598 * NB: pull_var_clause is okay here only because we don't allow subselects
1599 * in check constraints; it would fail to examine the contents of
1602 varList
= pull_var_clause(expr
, false);
1603 keycount
= list_length(varList
);
1610 attNos
= (int16
*) palloc(keycount
* sizeof(int16
));
1611 foreach(vl
, varList
)
1613 Var
*var
= (Var
*) lfirst(vl
);
1616 for (j
= 0; j
< i
; j
++)
1617 if (attNos
[j
] == var
->varattno
)
1620 attNos
[i
++] = var
->varattno
;
1628 * Create the Check Constraint
1630 CreateConstraintEntry(ccname
, /* Constraint Name */
1631 RelationGetNamespace(rel
), /* namespace */
1632 CONSTRAINT_CHECK
, /* Constraint Type */
1633 false, /* Is Deferrable */
1634 false, /* Is Deferred */
1635 RelationGetRelid(rel
), /* relation */
1636 attNos
, /* attrs in the constraint */
1637 keycount
, /* # attrs in the constraint */
1638 InvalidOid
, /* not a domain constraint */
1639 InvalidOid
, /* Foreign key fields */
1648 InvalidOid
, /* no associated index */
1649 expr
, /* Tree form check constraint */
1650 ccbin
, /* Binary form check constraint */
1651 ccsrc
, /* Source form check constraint */
1652 is_local
, /* conislocal */
1653 inhcount
); /* coninhcount */
1660 * Store defaults and constraints (passed as a list of CookedConstraint).
1662 * NOTE: only pre-cooked expressions will be passed this way, which is to
1663 * say expressions inherited from an existing relation. Newly parsed
1664 * expressions can be added later, by direct calls to StoreAttrDefault
1665 * and StoreRelCheck (see AddRelationNewConstraints()).
1668 StoreConstraints(Relation rel
, List
*cooked_constraints
)
1673 if (!cooked_constraints
)
1674 return; /* nothing to do */
1677 * Deparsing of constraint expressions will fail unless the just-created
1678 * pg_attribute tuples for this relation are made visible. So, bump the
1679 * command counter. CAUTION: this will cause a relcache entry rebuild.
1681 CommandCounterIncrement();
1683 foreach(lc
, cooked_constraints
)
1685 CookedConstraint
*con
= (CookedConstraint
*) lfirst(lc
);
1687 switch (con
->contype
)
1689 case CONSTR_DEFAULT
:
1690 StoreAttrDefault(rel
, con
->attnum
, con
->expr
);
1693 StoreRelCheck(rel
, con
->name
, con
->expr
,
1694 con
->is_local
, con
->inhcount
);
1698 elog(ERROR
, "unrecognized constraint type: %d",
1699 (int) con
->contype
);
1704 SetRelationNumChecks(rel
, numchecks
);
1708 * AddRelationNewConstraints
1710 * Add new column default expressions and/or constraint check expressions
1711 * to an existing relation. This is defined to do both for efficiency in
1712 * DefineRelation, but of course you can do just one or the other by passing
1715 * rel: relation to be modified
1716 * newColDefaults: list of RawColumnDefault structures
1717 * newConstraints: list of Constraint nodes
1718 * allow_merge: TRUE if check constraints may be merged with existing ones
1719 * is_local: TRUE if definition is local, FALSE if it's inherited
1721 * All entries in newColDefaults will be processed. Entries in newConstraints
1722 * will be processed only if they are CONSTR_CHECK type.
1724 * Returns a list of CookedConstraint nodes that shows the cooked form of
1725 * the default and constraint expressions added to the relation.
1727 * NB: caller should have opened rel with AccessExclusiveLock, and should
1728 * hold that lock till end of transaction. Also, we assume the caller has
1729 * done a CommandCounterIncrement if necessary to make the relation's catalog
1733 AddRelationNewConstraints(Relation rel
,
1734 List
*newColDefaults
,
1735 List
*newConstraints
,
1739 List
*cookedConstraints
= NIL
;
1740 TupleDesc tupleDesc
;
1741 TupleConstr
*oldconstr
;
1749 CookedConstraint
*cooked
;
1752 * Get info about existing constraints.
1754 tupleDesc
= RelationGetDescr(rel
);
1755 oldconstr
= tupleDesc
->constr
;
1757 numoldchecks
= oldconstr
->num_check
;
1762 * Create a dummy ParseState and insert the target relation as its sole
1763 * rangetable entry. We need a ParseState for transformExpr.
1765 pstate
= make_parsestate(NULL
);
1766 rte
= addRangeTableEntryForRelation(pstate
,
1771 addRTEtoQuery(pstate
, rte
, true, true, true);
1774 * Process column default expressions.
1776 foreach(cell
, newColDefaults
)
1778 RawColumnDefault
*colDef
= (RawColumnDefault
*) lfirst(cell
);
1779 Form_pg_attribute atp
= rel
->rd_att
->attrs
[colDef
->attnum
- 1];
1781 expr
= cookDefault(pstate
, colDef
->raw_default
,
1782 atp
->atttypid
, atp
->atttypmod
,
1783 NameStr(atp
->attname
));
1786 * If the expression is just a NULL constant, we do not bother to make
1787 * an explicit pg_attrdef entry, since the default behavior is
1790 * Note a nonobvious property of this test: if the column is of a
1791 * domain type, what we'll get is not a bare null Const but a
1792 * CoerceToDomain expr, so we will not discard the default. This is
1793 * critical because the column default needs to be retained to
1794 * override any default that the domain might have.
1797 (IsA(expr
, Const
) &&((Const
*) expr
)->constisnull
))
1800 StoreAttrDefault(rel
, colDef
->attnum
, expr
);
1802 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1803 cooked
->contype
= CONSTR_DEFAULT
;
1804 cooked
->name
= NULL
;
1805 cooked
->attnum
= colDef
->attnum
;
1806 cooked
->expr
= expr
;
1807 cooked
->is_local
= is_local
;
1808 cooked
->inhcount
= is_local
? 0 : 1;
1809 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1813 * Process constraint expressions.
1815 numchecks
= numoldchecks
;
1817 foreach(cell
, newConstraints
)
1819 Constraint
*cdef
= (Constraint
*) lfirst(cell
);
1822 if (cdef
->contype
!= CONSTR_CHECK
)
1825 if (cdef
->raw_expr
!= NULL
)
1827 Assert(cdef
->cooked_expr
== NULL
);
1830 * Transform raw parsetree to executable expression, and verify
1831 * it's valid as a CHECK constraint.
1833 expr
= cookConstraint(pstate
, cdef
->raw_expr
,
1834 RelationGetRelationName(rel
));
1838 Assert(cdef
->cooked_expr
!= NULL
);
1841 * Here, we assume the parser will only pass us valid CHECK
1842 * expressions, so we do no particular checking.
1844 expr
= stringToNode(cdef
->cooked_expr
);
1848 * Check name uniqueness, or generate a name if none was given.
1850 if (cdef
->name
!= NULL
)
1854 ccname
= cdef
->name
;
1855 /* Check against other new constraints */
1856 /* Needed because we don't do CommandCounterIncrement in loop */
1857 foreach(cell2
, checknames
)
1859 if (strcmp((char *) lfirst(cell2
), ccname
) == 0)
1861 (errcode(ERRCODE_DUPLICATE_OBJECT
),
1862 errmsg("check constraint \"%s\" already exists",
1866 /* save name for future checks */
1867 checknames
= lappend(checknames
, ccname
);
1870 * Check against pre-existing constraints. If we are allowed
1871 * to merge with an existing constraint, there's no more to
1872 * do here. (We omit the duplicate constraint from the result,
1873 * which is what ATAddCheckConstraint wants.)
1875 if (MergeWithExistingConstraint(rel
, ccname
, expr
,
1876 allow_merge
, is_local
))
1882 * When generating a name, we want to create "tab_col_check" for a
1883 * column constraint and "tab_check" for a table constraint. We
1884 * no longer have any info about the syntactic positioning of the
1885 * constraint phrase, so we approximate this by seeing whether the
1886 * expression references more than one column. (If the user
1887 * played by the rules, the result is the same...)
1889 * Note: pull_var_clause() doesn't descend into sublinks, but we
1890 * eliminated those above; and anyway this only needs to be an
1891 * approximate answer.
1896 vars
= pull_var_clause(expr
, false);
1898 /* eliminate duplicates */
1899 vars
= list_union(NIL
, vars
);
1901 if (list_length(vars
) == 1)
1902 colname
= get_attname(RelationGetRelid(rel
),
1903 ((Var
*) linitial(vars
))->varattno
);
1907 ccname
= ChooseConstraintName(RelationGetRelationName(rel
),
1910 RelationGetNamespace(rel
),
1913 /* save name for future checks */
1914 checknames
= lappend(checknames
, ccname
);
1920 StoreRelCheck(rel
, ccname
, expr
, is_local
, is_local
? 0 : 1);
1924 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1925 cooked
->contype
= CONSTR_CHECK
;
1926 cooked
->name
= ccname
;
1928 cooked
->expr
= expr
;
1929 cooked
->is_local
= is_local
;
1930 cooked
->inhcount
= is_local
? 0 : 1;
1931 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1935 * Update the count of constraints in the relation's pg_class tuple. We do
1936 * this even if there was no change, in order to ensure that an SI update
1937 * message is sent out for the pg_class tuple, which will force other
1938 * backends to rebuild their relcache entries for the rel. (This is
1939 * critical if we added defaults but not constraints.)
1941 SetRelationNumChecks(rel
, numchecks
);
1943 return cookedConstraints
;
1947 * Check for a pre-existing check constraint that conflicts with a proposed
1948 * new one, and either adjust its conislocal/coninhcount settings or throw
1951 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1952 * got a so-far-unique name, or throws error if conflict.
1955 MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
1956 bool allow_merge
, bool is_local
)
1960 SysScanDesc conscan
;
1961 ScanKeyData skey
[2];
1964 /* Search for a pg_constraint entry with same name and relation */
1965 conDesc
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
1969 ScanKeyInit(&skey
[0],
1970 Anum_pg_constraint_conname
,
1971 BTEqualStrategyNumber
, F_NAMEEQ
,
1972 CStringGetDatum(ccname
));
1974 ScanKeyInit(&skey
[1],
1975 Anum_pg_constraint_connamespace
,
1976 BTEqualStrategyNumber
, F_OIDEQ
,
1977 ObjectIdGetDatum(RelationGetNamespace(rel
)));
1979 conscan
= systable_beginscan(conDesc
, ConstraintNameNspIndexId
, true,
1980 SnapshotNow
, 2, skey
);
1982 while (HeapTupleIsValid(tup
= systable_getnext(conscan
)))
1984 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tup
);
1986 if (con
->conrelid
== RelationGetRelid(rel
))
1988 /* Found it. Conflicts if not identical check constraint */
1989 if (con
->contype
== CONSTRAINT_CHECK
)
1994 val
= fastgetattr(tup
,
1995 Anum_pg_constraint_conbin
,
1996 conDesc
->rd_att
, &isnull
);
1998 elog(ERROR
, "null conbin for rel %s",
1999 RelationGetRelationName(rel
));
2000 if (equal(expr
, stringToNode(TextDatumGetCString(val
))))
2003 if (!found
|| !allow_merge
)
2005 (errcode(ERRCODE_DUPLICATE_OBJECT
),
2006 errmsg("constraint \"%s\" for relation \"%s\" already exists",
2007 ccname
, RelationGetRelationName(rel
))));
2008 /* OK to update the tuple */
2010 (errmsg("merging constraint \"%s\" with inherited definition",
2012 tup
= heap_copytuple(tup
);
2013 con
= (Form_pg_constraint
) GETSTRUCT(tup
);
2015 con
->conislocal
= true;
2018 simple_heap_update(conDesc
, &tup
->t_self
, tup
);
2019 CatalogUpdateIndexes(conDesc
, tup
);
2024 systable_endscan(conscan
);
2025 heap_close(conDesc
, RowExclusiveLock
);
2031 * Update the count of constraints in the relation's pg_class tuple.
2033 * Caller had better hold exclusive lock on the relation.
2035 * An important side effect is that a SI update message will be sent out for
2036 * the pg_class tuple, which will force other backends to rebuild their
2037 * relcache entries for the rel. Also, this backend will rebuild its
2038 * own relcache entry at the next CommandCounterIncrement.
2041 SetRelationNumChecks(Relation rel
, int numchecks
)
2045 Form_pg_class relStruct
;
2047 relrel
= heap_open(RelationRelationId
, RowExclusiveLock
);
2048 reltup
= SearchSysCacheCopy(RELOID
,
2049 ObjectIdGetDatum(RelationGetRelid(rel
)),
2051 if (!HeapTupleIsValid(reltup
))
2052 elog(ERROR
, "cache lookup failed for relation %u",
2053 RelationGetRelid(rel
));
2054 relStruct
= (Form_pg_class
) GETSTRUCT(reltup
);
2056 if (relStruct
->relchecks
!= numchecks
)
2058 relStruct
->relchecks
= numchecks
;
2060 simple_heap_update(relrel
, &reltup
->t_self
, reltup
);
2062 /* keep catalog indexes current */
2063 CatalogUpdateIndexes(relrel
, reltup
);
2067 /* Skip the disk update, but force relcache inval anyway */
2068 CacheInvalidateRelcache(rel
);
2071 heap_freetuple(reltup
);
2072 heap_close(relrel
, RowExclusiveLock
);
2076 * Take a raw default and convert it to a cooked format ready for
2079 * Parse state should be set up to recognize any vars that might appear
2080 * in the expression. (Even though we plan to reject vars, it's more
2081 * user-friendly to give the correct error message than "unknown var".)
2083 * If atttypid is not InvalidOid, coerce the expression to the specified
2084 * type (and typmod atttypmod). attname is only needed in this case:
2085 * it is used in the error message, if any.
2088 cookDefault(ParseState
*pstate
,
2096 Assert(raw_default
!= NULL
);
2099 * Transform raw parsetree to executable expression.
2101 expr
= transformExpr(pstate
, raw_default
);
2104 * Make sure default expr does not refer to any vars.
2106 if (contain_var_clause(expr
))
2108 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2109 errmsg("cannot use column references in default expression")));
2112 * It can't return a set either.
2114 if (expression_returns_set(expr
))
2116 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2117 errmsg("default expression must not return a set")));
2120 * No subplans or aggregates, either...
2122 if (pstate
->p_hasSubLinks
)
2124 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2125 errmsg("cannot use subquery in default expression")));
2126 if (pstate
->p_hasAggs
)
2128 (errcode(ERRCODE_GROUPING_ERROR
),
2129 errmsg("cannot use aggregate function in default expression")));
2132 * Coerce the expression to the correct type and typmod, if given. This
2133 * should match the parser's processing of non-defaulted expressions ---
2134 * see transformAssignedExpr().
2136 if (OidIsValid(atttypid
))
2138 Oid type_id
= exprType(expr
);
2140 expr
= coerce_to_target_type(pstate
, expr
, type_id
,
2141 atttypid
, atttypmod
,
2142 COERCION_ASSIGNMENT
,
2143 COERCE_IMPLICIT_CAST
,
2147 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2148 errmsg("column \"%s\" is of type %s"
2149 " but default expression is of type %s",
2151 format_type_be(atttypid
),
2152 format_type_be(type_id
)),
2153 errhint("You will need to rewrite or cast the expression.")));
2160 * Take a raw CHECK constraint expression and convert it to a cooked format
2161 * ready for storage.
2163 * Parse state must be set up to recognize any vars that might appear
2164 * in the expression.
2167 cookConstraint(ParseState
*pstate
,
2168 Node
*raw_constraint
,
2174 * Transform raw parsetree to executable expression.
2176 expr
= transformExpr(pstate
, raw_constraint
);
2179 * Make sure it yields a boolean result.
2181 expr
= coerce_to_boolean(pstate
, expr
, "CHECK");
2184 * Make sure no outside relations are referred to.
2186 if (list_length(pstate
->p_rtable
) != 1)
2188 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2189 errmsg("only table \"%s\" can be referenced in check constraint",
2193 * No subplans or aggregates, either...
2195 if (pstate
->p_hasSubLinks
)
2197 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2198 errmsg("cannot use subquery in check constraint")));
2199 if (pstate
->p_hasAggs
)
2201 (errcode(ERRCODE_GROUPING_ERROR
),
2202 errmsg("cannot use aggregate function in check constraint")));
2209 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2211 * If attnum is zero, remove all entries for rel; else remove only the one
2215 RemoveStatistics(Oid relid
, AttrNumber attnum
)
2217 Relation pgstatistic
;
2223 pgstatistic
= heap_open(StatisticRelationId
, RowExclusiveLock
);
2225 ScanKeyInit(&key
[0],
2226 Anum_pg_statistic_starelid
,
2227 BTEqualStrategyNumber
, F_OIDEQ
,
2228 ObjectIdGetDatum(relid
));
2234 ScanKeyInit(&key
[1],
2235 Anum_pg_statistic_staattnum
,
2236 BTEqualStrategyNumber
, F_INT2EQ
,
2237 Int16GetDatum(attnum
));
2241 scan
= systable_beginscan(pgstatistic
, StatisticRelidAttnumIndexId
, true,
2242 SnapshotNow
, nkeys
, key
);
2244 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
2245 simple_heap_delete(pgstatistic
, &tuple
->t_self
);
2247 systable_endscan(scan
);
2249 heap_close(pgstatistic
, RowExclusiveLock
);
2254 * RelationTruncateIndexes - truncate all indexes associated
2255 * with the heap relation to zero tuples.
2257 * The routine will truncate and then reconstruct the indexes on
2258 * the specified relation. Caller must hold exclusive lock on rel.
2261 RelationTruncateIndexes(Relation heapRelation
)
2265 /* Ask the relcache to produce a list of the indexes of the rel */
2266 foreach(indlist
, RelationGetIndexList(heapRelation
))
2268 Oid indexId
= lfirst_oid(indlist
);
2269 Relation currentIndex
;
2270 IndexInfo
*indexInfo
;
2272 /* Open the index relation; use exclusive lock, just to be sure */
2273 currentIndex
= index_open(indexId
, AccessExclusiveLock
);
2275 /* Fetch info needed for index_build */
2276 indexInfo
= BuildIndexInfo(currentIndex
);
2279 * Now truncate the actual file (and discard buffers).
2281 RelationTruncate(currentIndex
, 0);
2283 /* Initialize the index and rebuild */
2284 /* Note: we do not need to re-establish pkey setting */
2285 index_build(heapRelation
, currentIndex
, indexInfo
, false);
2287 /* We're done with this index */
2288 index_close(currentIndex
, NoLock
);
2295 * This routine deletes all data within all the specified relations.
2297 * This is not transaction-safe! There is another, transaction-safe
2298 * implementation in commands/tablecmds.c. We now use this only for
2299 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2302 heap_truncate(List
*relids
)
2304 List
*relations
= NIL
;
2307 /* Open relations for processing, and grab exclusive access on each */
2308 foreach(cell
, relids
)
2310 Oid rid
= lfirst_oid(cell
);
2314 rel
= heap_open(rid
, AccessExclusiveLock
);
2315 relations
= lappend(relations
, rel
);
2317 /* If there is a toast table, add it to the list too */
2318 toastrelid
= rel
->rd_rel
->reltoastrelid
;
2319 if (OidIsValid(toastrelid
))
2321 rel
= heap_open(toastrelid
, AccessExclusiveLock
);
2322 relations
= lappend(relations
, rel
);
2326 /* Don't allow truncate on tables that are referenced by foreign keys */
2327 heap_truncate_check_FKs(relations
, true);
2330 foreach(cell
, relations
)
2332 Relation rel
= lfirst(cell
);
2334 /* Truncate the actual file (and discard buffers) */
2335 RelationTruncate(rel
, 0);
2337 /* If this relation has indexes, truncate the indexes too */
2338 RelationTruncateIndexes(rel
);
2341 * Close the relation, but keep exclusive lock on it until commit.
2343 heap_close(rel
, NoLock
);
2348 * heap_truncate_check_FKs
2349 * Check for foreign keys referencing a list of relations that
2350 * are to be truncated, and raise error if there are any
2352 * We disallow such FKs (except self-referential ones) since the whole point
2353 * of TRUNCATE is to not scan the individual rows to be thrown away.
2355 * This is split out so it can be shared by both implementations of truncate.
2356 * Caller should already hold a suitable lock on the relations.
2358 * tempTables is only used to select an appropriate error message.
2361 heap_truncate_check_FKs(List
*relations
, bool tempTables
)
2368 * Build a list of OIDs of the interesting relations.
2370 * If a relation has no triggers, then it can neither have FKs nor be
2371 * referenced by a FK from another table, so we can ignore it.
2373 foreach(cell
, relations
)
2375 Relation rel
= lfirst(cell
);
2377 if (rel
->rd_rel
->relhastriggers
)
2378 oids
= lappend_oid(oids
, RelationGetRelid(rel
));
2382 * Fast path: if no relation has triggers, none has FKs either.
2388 * Otherwise, must scan pg_constraint. We make one pass with all the
2389 * relations considered; if this finds nothing, then all is well.
2391 dependents
= heap_truncate_find_FKs(oids
);
2392 if (dependents
== NIL
)
2396 * Otherwise we repeat the scan once per relation to identify a particular
2397 * pair of relations to complain about. This is pretty slow, but
2398 * performance shouldn't matter much in a failure path. The reason for
2399 * doing things this way is to ensure that the message produced is not
2400 * dependent on chance row locations within pg_constraint.
2404 Oid relid
= lfirst_oid(cell
);
2407 dependents
= heap_truncate_find_FKs(list_make1_oid(relid
));
2409 foreach(cell2
, dependents
)
2411 Oid relid2
= lfirst_oid(cell2
);
2413 if (!list_member_oid(oids
, relid2
))
2415 char *relname
= get_rel_name(relid
);
2416 char *relname2
= get_rel_name(relid2
);
2420 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2421 errmsg("unsupported ON COMMIT and foreign key combination"),
2422 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2423 relname2
, relname
)));
2426 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2427 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2428 errdetail("Table \"%s\" references \"%s\".",
2430 errhint("Truncate table \"%s\" at the same time, "
2431 "or use TRUNCATE ... CASCADE.",
2439 * heap_truncate_find_FKs
2440 * Find relations having foreign keys referencing any of the given rels
2442 * Input and result are both lists of relation OIDs. The result contains
2443 * no duplicates, does *not* include any rels that were already in the input
2444 * list, and is sorted in OID order. (The last property is enforced mainly
2445 * to guarantee consistent behavior in the regression tests; we don't want
2446 * behavior to change depending on chance locations of rows in pg_constraint.)
2448 * Note: caller should already have appropriate lock on all rels mentioned
2449 * in relationIds. Since adding or dropping an FK requires exclusive lock
2450 * on both rels, this ensures that the answer will be stable.
2453 heap_truncate_find_FKs(List
*relationIds
)
2457 SysScanDesc fkeyScan
;
2461 * Must scan pg_constraint. Right now, it is a seqscan because there is
2462 * no available index on confrelid.
2464 fkeyRel
= heap_open(ConstraintRelationId
, AccessShareLock
);
2466 fkeyScan
= systable_beginscan(fkeyRel
, InvalidOid
, false,
2467 SnapshotNow
, 0, NULL
);
2469 while (HeapTupleIsValid(tuple
= systable_getnext(fkeyScan
)))
2471 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tuple
);
2473 /* Not a foreign key */
2474 if (con
->contype
!= CONSTRAINT_FOREIGN
)
2477 /* Not referencing one of our list of tables */
2478 if (!list_member_oid(relationIds
, con
->confrelid
))
2481 /* Add referencer unless already in input or result list */
2482 if (!list_member_oid(relationIds
, con
->conrelid
))
2483 result
= insert_ordered_unique_oid(result
, con
->conrelid
);
2486 systable_endscan(fkeyScan
);
2487 heap_close(fkeyRel
, AccessShareLock
);
2493 * insert_ordered_unique_oid
2494 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2495 * and eliminating duplicates
2497 * Building the ordered list this way is O(N^2), but with a pretty small
2498 * constant, so for the number of entries we expect it will probably be
2499 * faster than trying to apply qsort(). It seems unlikely someone would be
2500 * trying to truncate a table with thousands of dependent tables ...
2503 insert_ordered_unique_oid(List
*list
, Oid datum
)
2507 /* Does the datum belong at the front? */
2508 if (list
== NIL
|| datum
< linitial_oid(list
))
2509 return lcons_oid(datum
, list
);
2510 /* Does it match the first entry? */
2511 if (datum
== linitial_oid(list
))
2512 return list
; /* duplicate, so don't insert */
2513 /* No, so find the entry it belongs after */
2514 prev
= list_head(list
);
2517 ListCell
*curr
= lnext(prev
);
2519 if (curr
== NULL
|| datum
< lfirst_oid(curr
))
2520 break; /* it belongs after 'prev', before 'curr' */
2522 if (datum
== lfirst_oid(curr
))
2523 return list
; /* duplicate, so don't insert */
2527 /* Insert datum into list after 'prev' */
2528 lappend_cell_oid(list
, prev
, datum
);