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 "commands/tablecmds.h"
51 #include "commands/typecmds.h"
52 #include "miscadmin.h"
53 #include "optimizer/clauses.h"
54 #include "optimizer/var.h"
55 #include "parser/parse_coerce.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_relation.h"
58 #include "storage/bufmgr.h"
59 #include "storage/smgr.h"
60 #include "utils/builtins.h"
61 #include "utils/fmgroids.h"
62 #include "utils/inval.h"
63 #include "utils/lsyscache.h"
64 #include "utils/relcache.h"
65 #include "utils/snapmgr.h"
66 #include "utils/syscache.h"
67 #include "utils/tqual.h"
70 static void AddNewRelationTuple(Relation pg_class_desc
,
71 Relation new_rel_desc
,
72 Oid new_rel_oid
, Oid new_type_oid
,
76 static Oid
AddNewRelationType(const char *typeName
,
81 static void RelationRemoveInheritance(Oid relid
);
82 static void StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
83 bool is_local
, int inhcount
);
84 static void StoreConstraints(Relation rel
, List
*cooked_constraints
);
85 static bool MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
86 bool allow_merge
, bool is_local
);
87 static void SetRelationNumChecks(Relation rel
, int numchecks
);
88 static Node
*cookConstraint(ParseState
*pstate
,
91 static List
*insert_ordered_unique_oid(List
*list
, Oid datum
);
94 /* ----------------------------------------------------------------
95 * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
97 * these should all be moved to someplace in the lib/catalog
98 * module, if not obliterated first.
99 * ----------------------------------------------------------------
105 * Should the system special case these attributes in the future?
106 * Advantage: consume much less space in the ATTRIBUTE relation.
107 * Disadvantage: special cases will be all over the place.
110 static FormData_pg_attribute a1
= {
111 0, {"ctid"}, TIDOID
, 0, sizeof(ItemPointerData
),
112 SelfItemPointerAttributeNumber
, 0, -1, -1,
113 false, 'p', 's', true, false, false, true, 0
116 static FormData_pg_attribute a2
= {
117 0, {"oid"}, OIDOID
, 0, sizeof(Oid
),
118 ObjectIdAttributeNumber
, 0, -1, -1,
119 true, 'p', 'i', true, false, false, true, 0
122 static FormData_pg_attribute a3
= {
123 0, {"xmin"}, XIDOID
, 0, sizeof(TransactionId
),
124 MinTransactionIdAttributeNumber
, 0, -1, -1,
125 true, 'p', 'i', true, false, false, true, 0
128 static FormData_pg_attribute a4
= {
129 0, {"cmin"}, CIDOID
, 0, sizeof(CommandId
),
130 MinCommandIdAttributeNumber
, 0, -1, -1,
131 true, 'p', 'i', true, false, false, true, 0
134 static FormData_pg_attribute a5
= {
135 0, {"xmax"}, XIDOID
, 0, sizeof(TransactionId
),
136 MaxTransactionIdAttributeNumber
, 0, -1, -1,
137 true, 'p', 'i', true, false, false, true, 0
140 static FormData_pg_attribute a6
= {
141 0, {"cmax"}, CIDOID
, 0, sizeof(CommandId
),
142 MaxCommandIdAttributeNumber
, 0, -1, -1,
143 true, 'p', 'i', true, false, false, true, 0
147 * We decided to call this attribute "tableoid" rather than say
148 * "classoid" on the basis that in the future there may be more than one
149 * table of a particular class/type. In any case table is still the word
152 static FormData_pg_attribute a7
= {
153 0, {"tableoid"}, OIDOID
, 0, sizeof(Oid
),
154 TableOidAttributeNumber
, 0, -1, -1,
155 true, 'p', 'i', true, false, false, true, 0
158 static const Form_pg_attribute SysAtt
[] = {&a1
, &a2
, &a3
, &a4
, &a5
, &a6
, &a7
};
161 * This function returns a Form_pg_attribute pointer for a system attribute.
162 * Note that we elog if the presented attno is invalid, which would only
163 * happen if there's a problem upstream.
166 SystemAttributeDefinition(AttrNumber attno
, bool relhasoids
)
168 if (attno
>= 0 || attno
< -(int) lengthof(SysAtt
))
169 elog(ERROR
, "invalid system attribute number %d", attno
);
170 if (attno
== ObjectIdAttributeNumber
&& !relhasoids
)
171 elog(ERROR
, "invalid system attribute number %d", attno
);
172 return SysAtt
[-attno
- 1];
176 * If the given name is a system attribute name, return a Form_pg_attribute
177 * pointer for a prototype definition. If not, return NULL.
180 SystemAttributeByName(const char *attname
, bool relhasoids
)
184 for (j
= 0; j
< (int) lengthof(SysAtt
); j
++)
186 Form_pg_attribute att
= SysAtt
[j
];
188 if (relhasoids
|| att
->attnum
!= ObjectIdAttributeNumber
)
190 if (strcmp(NameStr(att
->attname
), attname
) == 0)
199 /* ----------------------------------------------------------------
200 * XXX END OF UGLY HARD CODED BADNESS XXX
201 * ---------------------------------------------------------------- */
204 /* ----------------------------------------------------------------
205 * heap_create - Create an uncataloged heap relation
207 * Note API change: the caller must now always provide the OID
208 * to use for the relation.
210 * rel->rd_rel is initialized by RelationBuildLocalRelation,
211 * and is mostly zeroes at return.
212 * ----------------------------------------------------------------
215 heap_create(const char *relname
,
221 bool shared_relation
,
222 bool allow_system_table_mods
)
227 /* The caller must have provided an OID for the relation. */
228 Assert(OidIsValid(relid
));
233 if (!allow_system_table_mods
&&
234 (IsSystemNamespace(relnamespace
) || IsToastNamespace(relnamespace
)) &&
235 IsNormalProcessingMode())
237 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
238 errmsg("permission denied to create \"%s.%s\"",
239 get_namespace_name(relnamespace
), relname
),
240 errdetail("System catalog modifications are currently disallowed.")));
243 * Decide if we need storage or not, and handle a couple other special
244 * cases for particular relkinds.
249 case RELKIND_COMPOSITE_TYPE
:
250 create_storage
= false;
253 * Force reltablespace to zero if the relation has no physical
254 * storage. This is mainly just for cleanliness' sake.
256 reltablespace
= InvalidOid
;
258 case RELKIND_SEQUENCE
:
259 create_storage
= true;
262 * Force reltablespace to zero for sequences, since we don't
263 * support moving them around into different tablespaces.
265 reltablespace
= InvalidOid
;
268 create_storage
= true;
273 * Never allow a pg_class entry to explicitly specify the database's
274 * default tablespace in reltablespace; force it to zero instead. This
275 * ensures that if the database is cloned with a different default
276 * tablespace, the pg_class entry will still match where CREATE DATABASE
277 * will put the physically copied relation.
279 * Yes, this is a bit of a hack.
281 if (reltablespace
== MyDatabaseTableSpace
)
282 reltablespace
= InvalidOid
;
285 * build the relcache entry.
287 rel
= RelationBuildLocalRelation(relname
,
295 * Have the storage manager create the relation's disk file, if needed.
297 * We only create storage for the main fork here. The caller is
298 * responsible for creating any additional forks if needed.
302 Assert(rel
->rd_smgr
== NULL
);
303 RelationOpenSmgr(rel
);
304 smgrcreate(rel
->rd_smgr
, MAIN_FORKNUM
, rel
->rd_istemp
, false);
310 /* ----------------------------------------------------------------
311 * heap_create_with_catalog - Create a cataloged relation
313 * this is done in multiple steps:
315 * 1) CheckAttributeNamesTypes() is used to make certain the tuple
316 * descriptor contains a valid set of attribute names and types
318 * 2) pg_class is opened and get_relname_relid()
319 * performs a scan to ensure that no relation with the
320 * same name already exists.
322 * 3) heap_create() is called to create the new relation on disk.
324 * 4) TypeCreate() is called to define a new type corresponding
325 * to the new relation.
327 * 5) AddNewRelationTuple() is called to register the
328 * relation in pg_class.
330 * 6) AddNewAttributeTuples() is called to register the
331 * new relation's schema in pg_attribute.
333 * 7) StoreConstraints is called () - vadim 08/22/97
335 * 8) the relations are closed and the new relation's oid
338 * ----------------------------------------------------------------
341 /* --------------------------------
342 * CheckAttributeNamesTypes
344 * this is used to make certain the tuple descriptor contains a
345 * valid set of attribute names and datatypes. a problem simply
346 * generates ereport(ERROR) which aborts the current transaction.
347 * --------------------------------
350 CheckAttributeNamesTypes(TupleDesc tupdesc
, char relkind
)
354 int natts
= tupdesc
->natts
;
356 /* Sanity check on column count */
357 if (natts
< 0 || natts
> MaxHeapAttributeNumber
)
359 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
360 errmsg("tables can have at most %d columns",
361 MaxHeapAttributeNumber
)));
364 * first check for collision with system attribute names
366 * Skip this for a view or type relation, since those don't have system
369 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
371 for (i
= 0; i
< natts
; i
++)
373 if (SystemAttributeByName(NameStr(tupdesc
->attrs
[i
]->attname
),
374 tupdesc
->tdhasoid
) != NULL
)
376 (errcode(ERRCODE_DUPLICATE_COLUMN
),
377 errmsg("column name \"%s\" conflicts with a system column name",
378 NameStr(tupdesc
->attrs
[i
]->attname
))));
383 * next check for repeated attribute names
385 for (i
= 1; i
< natts
; i
++)
387 for (j
= 0; j
< i
; j
++)
389 if (strcmp(NameStr(tupdesc
->attrs
[j
]->attname
),
390 NameStr(tupdesc
->attrs
[i
]->attname
)) == 0)
392 (errcode(ERRCODE_DUPLICATE_COLUMN
),
393 errmsg("column name \"%s\" specified more than once",
394 NameStr(tupdesc
->attrs
[j
]->attname
))));
399 * next check the attribute types
401 for (i
= 0; i
< natts
; i
++)
403 CheckAttributeType(NameStr(tupdesc
->attrs
[i
]->attname
),
404 tupdesc
->attrs
[i
]->atttypid
);
408 /* --------------------------------
411 * Verify that the proposed datatype of an attribute is legal.
412 * This is needed because there are types (and pseudo-types)
413 * in the catalogs that we do not support as elements of real tuples.
414 * --------------------------------
417 CheckAttributeType(const char *attname
, Oid atttypid
)
419 char att_typtype
= get_typtype(atttypid
);
421 if (atttypid
== UNKNOWNOID
)
424 * Warn user, but don't fail, if column to be created has UNKNOWN type
425 * (usually as a result of a 'retrieve into' - jolly)
428 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
429 errmsg("column \"%s\" has type \"unknown\"", attname
),
430 errdetail("Proceeding with relation creation anyway.")));
432 else if (att_typtype
== TYPTYPE_PSEUDO
)
435 * Refuse any attempt to create a pseudo-type column, except for a
436 * special hack for pg_statistic: allow ANYARRAY during initdb
438 if (atttypid
!= ANYARRAYOID
|| IsUnderPostmaster
)
440 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
441 errmsg("column \"%s\" has pseudo-type %s",
442 attname
, format_type_be(atttypid
))));
444 else if (att_typtype
== TYPTYPE_COMPOSITE
)
447 * For a composite type, recurse into its attributes. You might think
448 * this isn't necessary, but since we allow system catalogs to break
449 * the rule, we have to guard against the case.
455 relation
= relation_open(get_typ_typrelid(atttypid
), AccessShareLock
);
457 tupdesc
= RelationGetDescr(relation
);
459 for (i
= 0; i
< tupdesc
->natts
; i
++)
461 Form_pg_attribute attr
= tupdesc
->attrs
[i
];
463 if (attr
->attisdropped
)
465 CheckAttributeType(NameStr(attr
->attname
), attr
->atttypid
);
468 relation_close(relation
, AccessShareLock
);
472 /* --------------------------------
473 * AddNewAttributeTuples
475 * this registers the new relation's schema by adding
476 * tuples to pg_attribute.
477 * --------------------------------
480 AddNewAttributeTuples(Oid new_rel_oid
,
486 const Form_pg_attribute
*dpp
;
490 CatalogIndexState indstate
;
491 int natts
= tupdesc
->natts
;
492 ObjectAddress myself
,
496 * open pg_attribute and its indexes.
498 rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
500 indstate
= CatalogOpenIndexes(rel
);
503 * First we add the user attributes. This is also a convenient place to
504 * add dependencies on their datatypes.
506 dpp
= tupdesc
->attrs
;
507 for (i
= 0; i
< natts
; i
++)
509 /* Fill in the correct relation OID */
510 (*dpp
)->attrelid
= new_rel_oid
;
511 /* Make sure these are OK, too */
512 (*dpp
)->attstattarget
= -1;
513 (*dpp
)->attcacheoff
= -1;
515 tup
= heap_addheader(Natts_pg_attribute
,
517 ATTRIBUTE_TUPLE_SIZE
,
520 simple_heap_insert(rel
, tup
);
522 CatalogIndexInsert(indstate
, tup
);
526 myself
.classId
= RelationRelationId
;
527 myself
.objectId
= new_rel_oid
;
528 myself
.objectSubId
= i
+ 1;
529 referenced
.classId
= TypeRelationId
;
530 referenced
.objectId
= (*dpp
)->atttypid
;
531 referenced
.objectSubId
= 0;
532 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
538 * Next we add the system attributes. Skip OID if rel has no OIDs. Skip
539 * all for a view or type relation. We don't bother with making datatype
540 * dependencies here, since presumably all these types are pinned.
542 if (relkind
!= RELKIND_VIEW
&& relkind
!= RELKIND_COMPOSITE_TYPE
)
545 for (i
= 0; i
< -1 - FirstLowInvalidHeapAttributeNumber
; i
++)
547 if (tupdesc
->tdhasoid
||
548 (*dpp
)->attnum
!= ObjectIdAttributeNumber
)
550 Form_pg_attribute attStruct
;
552 tup
= heap_addheader(Natts_pg_attribute
,
554 ATTRIBUTE_TUPLE_SIZE
,
556 attStruct
= (Form_pg_attribute
) GETSTRUCT(tup
);
558 /* Fill in the correct relation OID in the copied tuple */
559 attStruct
->attrelid
= new_rel_oid
;
561 /* Fill in correct inheritance info for the OID column */
562 if (attStruct
->attnum
== ObjectIdAttributeNumber
)
564 attStruct
->attislocal
= oidislocal
;
565 attStruct
->attinhcount
= oidinhcount
;
569 * Unneeded since they should be OK in the constant data
572 /* attStruct->attstattarget = 0; */
573 /* attStruct->attcacheoff = -1; */
575 simple_heap_insert(rel
, tup
);
577 CatalogIndexInsert(indstate
, tup
);
588 CatalogCloseIndexes(indstate
);
590 heap_close(rel
, RowExclusiveLock
);
593 /* --------------------------------
596 * Construct and insert a new tuple in pg_class.
598 * Caller has already opened and locked pg_class.
599 * Tuple data is taken from new_rel_desc->rd_rel, except for the
600 * variable-width fields which are not present in a cached reldesc.
601 * We always initialize relacl to NULL (i.e., default permissions),
602 * and reloptions is set to the passed-in text array (if any).
603 * --------------------------------
606 InsertPgClassTuple(Relation pg_class_desc
,
607 Relation new_rel_desc
,
611 Form_pg_class rd_rel
= new_rel_desc
->rd_rel
;
612 Datum values
[Natts_pg_class
];
613 char nulls
[Natts_pg_class
];
616 /* This is a tad tedious, but way cleaner than what we used to do... */
617 memset(values
, 0, sizeof(values
));
618 memset(nulls
, ' ', sizeof(nulls
));
620 values
[Anum_pg_class_relname
- 1] = NameGetDatum(&rd_rel
->relname
);
621 values
[Anum_pg_class_relnamespace
- 1] = ObjectIdGetDatum(rd_rel
->relnamespace
);
622 values
[Anum_pg_class_reltype
- 1] = ObjectIdGetDatum(rd_rel
->reltype
);
623 values
[Anum_pg_class_relowner
- 1] = ObjectIdGetDatum(rd_rel
->relowner
);
624 values
[Anum_pg_class_relam
- 1] = ObjectIdGetDatum(rd_rel
->relam
);
625 values
[Anum_pg_class_relfilenode
- 1] = ObjectIdGetDatum(rd_rel
->relfilenode
);
626 values
[Anum_pg_class_reltablespace
- 1] = ObjectIdGetDatum(rd_rel
->reltablespace
);
627 values
[Anum_pg_class_relpages
- 1] = Int32GetDatum(rd_rel
->relpages
);
628 values
[Anum_pg_class_reltuples
- 1] = Float4GetDatum(rd_rel
->reltuples
);
629 values
[Anum_pg_class_reltoastrelid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastrelid
);
630 values
[Anum_pg_class_reltoastidxid
- 1] = ObjectIdGetDatum(rd_rel
->reltoastidxid
);
631 values
[Anum_pg_class_relhasindex
- 1] = BoolGetDatum(rd_rel
->relhasindex
);
632 values
[Anum_pg_class_relisshared
- 1] = BoolGetDatum(rd_rel
->relisshared
);
633 values
[Anum_pg_class_relkind
- 1] = CharGetDatum(rd_rel
->relkind
);
634 values
[Anum_pg_class_relnatts
- 1] = Int16GetDatum(rd_rel
->relnatts
);
635 values
[Anum_pg_class_relchecks
- 1] = Int16GetDatum(rd_rel
->relchecks
);
636 values
[Anum_pg_class_reltriggers
- 1] = Int16GetDatum(rd_rel
->reltriggers
);
637 values
[Anum_pg_class_relukeys
- 1] = Int16GetDatum(rd_rel
->relukeys
);
638 values
[Anum_pg_class_relfkeys
- 1] = Int16GetDatum(rd_rel
->relfkeys
);
639 values
[Anum_pg_class_relrefs
- 1] = Int16GetDatum(rd_rel
->relrefs
);
640 values
[Anum_pg_class_relhasoids
- 1] = BoolGetDatum(rd_rel
->relhasoids
);
641 values
[Anum_pg_class_relhaspkey
- 1] = BoolGetDatum(rd_rel
->relhaspkey
);
642 values
[Anum_pg_class_relhasrules
- 1] = BoolGetDatum(rd_rel
->relhasrules
);
643 values
[Anum_pg_class_relhassubclass
- 1] = BoolGetDatum(rd_rel
->relhassubclass
);
644 values
[Anum_pg_class_relfrozenxid
- 1] = TransactionIdGetDatum(rd_rel
->relfrozenxid
);
645 /* start out with empty permissions */
646 nulls
[Anum_pg_class_relacl
- 1] = 'n';
647 if (reloptions
!= (Datum
) 0)
648 values
[Anum_pg_class_reloptions
- 1] = reloptions
;
650 nulls
[Anum_pg_class_reloptions
- 1] = 'n';
652 tup
= heap_formtuple(RelationGetDescr(pg_class_desc
), values
, nulls
);
655 * The new tuple must have the oid already chosen for the rel. Sure would
656 * be embarrassing to do this sort of thing in polite company.
658 HeapTupleSetOid(tup
, new_rel_oid
);
660 /* finally insert the new tuple, update the indexes, and clean up */
661 simple_heap_insert(pg_class_desc
, tup
);
663 CatalogUpdateIndexes(pg_class_desc
, tup
);
668 /* --------------------------------
669 * AddNewRelationTuple
671 * this registers the new relation in the catalogs by
672 * adding a tuple to pg_class.
673 * --------------------------------
676 AddNewRelationTuple(Relation pg_class_desc
,
677 Relation new_rel_desc
,
684 Form_pg_class new_rel_reltup
;
687 * first we update some of the information in our uncataloged relation's
688 * relation descriptor.
690 new_rel_reltup
= new_rel_desc
->rd_rel
;
694 case RELKIND_RELATION
:
696 case RELKIND_TOASTVALUE
:
697 /* The relation is real, but as yet empty */
698 new_rel_reltup
->relpages
= 0;
699 new_rel_reltup
->reltuples
= 0;
701 case RELKIND_SEQUENCE
:
702 /* Sequences always have a known size */
703 new_rel_reltup
->relpages
= 1;
704 new_rel_reltup
->reltuples
= 1;
707 /* Views, etc, have no disk storage */
708 new_rel_reltup
->relpages
= 0;
709 new_rel_reltup
->reltuples
= 0;
713 /* Initialize relfrozenxid */
714 if (relkind
== RELKIND_RELATION
||
715 relkind
== RELKIND_TOASTVALUE
)
718 * Initialize to the minimum XID that could put tuples in the table.
719 * We know that no xacts older than RecentXmin are still running, so
722 new_rel_reltup
->relfrozenxid
= RecentXmin
;
727 * Other relation types will not contain XIDs, so set relfrozenxid to
728 * InvalidTransactionId. (Note: a sequence does contain a tuple, but
729 * we force its xmin to be FrozenTransactionId always; see
730 * commands/sequence.c.)
732 new_rel_reltup
->relfrozenxid
= InvalidTransactionId
;
735 new_rel_reltup
->relowner
= relowner
;
736 new_rel_reltup
->reltype
= new_type_oid
;
737 new_rel_reltup
->relkind
= relkind
;
739 new_rel_desc
->rd_att
->tdtypeid
= new_type_oid
;
741 /* Now build and insert the tuple */
742 InsertPgClassTuple(pg_class_desc
, new_rel_desc
, new_rel_oid
, reloptions
);
746 /* --------------------------------
747 * AddNewRelationType -
749 * define a composite type corresponding to the new relation
750 * --------------------------------
753 AddNewRelationType(const char *typeName
,
760 TypeCreate(InvalidOid
, /* no predetermined OID */
761 typeName
, /* type name */
762 typeNamespace
, /* type namespace */
763 new_rel_oid
, /* relation oid */
764 new_rel_kind
, /* relation kind */
765 -1, /* internal size (varlena) */
766 TYPTYPE_COMPOSITE
, /* type-type (composite) */
767 TYPCATEGORY_COMPOSITE
, /* type-category (ditto) */
768 false, /* composite types are never preferred */
769 DEFAULT_TYPDELIM
, /* default array delimiter */
770 F_RECORD_IN
, /* input procedure */
771 F_RECORD_OUT
, /* output procedure */
772 F_RECORD_RECV
, /* receive procedure */
773 F_RECORD_SEND
, /* send procedure */
774 InvalidOid
, /* typmodin procedure - none */
775 InvalidOid
, /* typmodout procedure - none */
776 InvalidOid
, /* analyze procedure - default */
777 InvalidOid
, /* array element type - irrelevant */
778 false, /* this is not an array type */
779 new_array_type
, /* array type if any */
780 InvalidOid
, /* domain base type - irrelevant */
781 NULL
, /* default value - none */
782 NULL
, /* default binary representation */
783 false, /* passed by reference */
784 'd', /* alignment - must be the largest! */
785 'x', /* fully TOASTable */
787 0, /* array dimensions for typBaseType */
788 false); /* Type NOT NULL */
791 /* --------------------------------
792 * heap_create_with_catalog
794 * creates a new cataloged relation. see comments above.
795 * --------------------------------
798 heap_create_with_catalog(const char *relname
,
804 List
*cooked_constraints
,
806 bool shared_relation
,
809 OnCommitAction oncommit
,
811 bool allow_system_table_mods
)
813 Relation pg_class_desc
;
814 Relation new_rel_desc
;
817 Oid new_array_oid
= InvalidOid
;
819 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
824 Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
826 CheckAttributeNamesTypes(tupdesc
, relkind
);
828 if (get_relname_relid(relname
, relnamespace
))
830 (errcode(ERRCODE_DUPLICATE_TABLE
),
831 errmsg("relation \"%s\" already exists", relname
)));
834 * Since we are going to create a rowtype as well, also check for
835 * collision with an existing type name. If there is one and it's an
836 * autogenerated array, we can rename it out of the way; otherwise we can
837 * at least give a good error message.
839 old_type_oid
= GetSysCacheOid(TYPENAMENSP
,
840 CStringGetDatum(relname
),
841 ObjectIdGetDatum(relnamespace
),
843 if (OidIsValid(old_type_oid
))
845 if (!moveArrayTypeName(old_type_oid
, relname
, relnamespace
))
847 (errcode(ERRCODE_DUPLICATE_OBJECT
),
848 errmsg("type \"%s\" already exists", relname
),
849 errhint("A relation has an associated type of the same name, "
850 "so you must use a name that doesn't conflict "
851 "with any existing type.")));
855 * Validate shared/non-shared tablespace (must check this before doing
856 * GetNewRelFileNode, to prevent Assert therein)
860 if (reltablespace
!= GLOBALTABLESPACE_OID
)
861 /* elog since this is not a user-facing error */
863 "shared relations must be placed in pg_global tablespace");
867 if (reltablespace
== GLOBALTABLESPACE_OID
)
869 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
870 errmsg("only shared relations can be placed in pg_global tablespace")));
874 * Allocate an OID for the relation, unless we were told what to use.
876 * The OID will be the relfilenode as well, so make sure it doesn't
877 * collide with either pg_class OIDs or existing physical files.
879 if (!OidIsValid(relid
))
880 relid
= GetNewRelFileNode(reltablespace
, shared_relation
,
884 * Create the relcache entry (mostly dummy at this point) and the physical
885 * disk file. (If we fail further down, it's the smgr's responsibility to
886 * remove the disk file again.)
888 new_rel_desc
= heap_create(relname
,
895 allow_system_table_mods
);
897 Assert(relid
== RelationGetRelid(new_rel_desc
));
900 * Decide whether to create an array type over the relation's rowtype. We
901 * do not create any array types for system catalogs (ie, those made
902 * during initdb). We create array types for regular relations, views,
903 * and composite types ... but not, eg, for toast tables or sequences.
905 if (IsUnderPostmaster
&& (relkind
== RELKIND_RELATION
||
906 relkind
== RELKIND_VIEW
||
907 relkind
== RELKIND_COMPOSITE_TYPE
))
909 /* OK, so pre-assign a type OID for the array type */
910 Relation pg_type
= heap_open(TypeRelationId
, AccessShareLock
);
912 new_array_oid
= GetNewOid(pg_type
);
913 heap_close(pg_type
, AccessShareLock
);
917 * Since defining a relation also defines a complex type, we add a new
918 * system type corresponding to the new relation.
920 * NOTE: we could get a unique-index failure here, in case someone else is
921 * creating the same type name in parallel but hadn't committed yet when
922 * we checked for a duplicate name above.
924 new_type_oid
= AddNewRelationType(relname
,
931 * Now make the array type if wanted.
933 if (OidIsValid(new_array_oid
))
937 relarrayname
= makeArrayTypeName(relname
, relnamespace
);
939 TypeCreate(new_array_oid
, /* force the type's OID to this */
940 relarrayname
, /* Array type name */
941 relnamespace
, /* Same namespace as parent */
942 InvalidOid
, /* Not composite, no relationOid */
943 0, /* relkind, also N/A here */
944 -1, /* Internal size (varlena) */
945 TYPTYPE_BASE
, /* Not composite - typelem is */
946 TYPCATEGORY_ARRAY
, /* type-category (array) */
947 false, /* array types are never preferred */
948 DEFAULT_TYPDELIM
, /* default array delimiter */
949 F_ARRAY_IN
, /* array input proc */
950 F_ARRAY_OUT
, /* array output proc */
951 F_ARRAY_RECV
, /* array recv (bin) proc */
952 F_ARRAY_SEND
, /* array send (bin) proc */
953 InvalidOid
, /* typmodin procedure - none */
954 InvalidOid
, /* typmodout procedure - none */
955 InvalidOid
, /* analyze procedure - default */
956 new_type_oid
, /* array element type - the rowtype */
957 true, /* yes, this is an array type */
958 InvalidOid
, /* this has no array type */
959 InvalidOid
, /* domain base type - irrelevant */
960 NULL
, /* default value - none */
961 NULL
, /* default binary representation */
962 false, /* passed by reference */
963 'd', /* alignment - must be the largest! */
964 'x', /* fully TOASTable */
966 0, /* array dimensions for typBaseType */
967 false); /* Type NOT NULL */
973 * now create an entry in pg_class for the relation.
975 * NOTE: we could get a unique-index failure here, in case someone else is
976 * creating the same relation name in parallel but hadn't committed yet
977 * when we checked for a duplicate name above.
979 AddNewRelationTuple(pg_class_desc
,
988 * now add tuples to pg_attribute for the attributes in our new relation.
990 AddNewAttributeTuples(relid
, new_rel_desc
->rd_att
, relkind
,
991 oidislocal
, oidinhcount
);
994 * Make a dependency link to force the relation to be deleted if its
995 * namespace is. Also make a dependency link to its owner.
997 * For composite types, these dependencies are tracked for the pg_type
998 * entry, so we needn't record them here. Likewise, TOAST tables don't
999 * need a namespace dependency (they live in a pinned namespace) nor an
1000 * owner dependency (they depend indirectly through the parent table).
1001 * Also, skip this in bootstrap mode, since we don't make dependencies
1002 * while bootstrapping.
1004 if (relkind
!= RELKIND_COMPOSITE_TYPE
&&
1005 relkind
!= RELKIND_TOASTVALUE
&&
1006 !IsBootstrapProcessingMode())
1008 ObjectAddress myself
,
1011 myself
.classId
= RelationRelationId
;
1012 myself
.objectId
= relid
;
1013 myself
.objectSubId
= 0;
1014 referenced
.classId
= NamespaceRelationId
;
1015 referenced
.objectId
= relnamespace
;
1016 referenced
.objectSubId
= 0;
1017 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
1019 recordDependencyOnOwner(RelationRelationId
, relid
, ownerid
);
1023 * Store any supplied constraints and defaults.
1025 * NB: this may do a CommandCounterIncrement and rebuild the relcache
1026 * entry, so the relation must be valid and self-consistent at this point.
1027 * In particular, there are not yet constraints and defaults anywhere.
1029 StoreConstraints(new_rel_desc
, cooked_constraints
);
1032 * If there's a special on-commit action, remember it
1034 if (oncommit
!= ONCOMMIT_NOOP
)
1035 register_on_commit_action(relid
, oncommit
);
1038 * ok, the relation has been cataloged, so close our relations and return
1039 * the OID of the newly created relation.
1041 heap_close(new_rel_desc
, NoLock
); /* do not unlock till end of xact */
1042 heap_close(pg_class_desc
, RowExclusiveLock
);
1049 * RelationRemoveInheritance
1051 * Formerly, this routine checked for child relations and aborted the
1052 * deletion if any were found. Now we rely on the dependency mechanism
1053 * to check for or delete child relations. By the time we get here,
1054 * there are no children and we need only remove any pg_inherits rows
1055 * linking this relation to its parent(s).
1058 RelationRemoveInheritance(Oid relid
)
1060 Relation catalogRelation
;
1065 catalogRelation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
1068 Anum_pg_inherits_inhrelid
,
1069 BTEqualStrategyNumber
, F_OIDEQ
,
1070 ObjectIdGetDatum(relid
));
1072 scan
= systable_beginscan(catalogRelation
, InheritsRelidSeqnoIndexId
, true,
1073 SnapshotNow
, 1, &key
);
1075 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1076 simple_heap_delete(catalogRelation
, &tuple
->t_self
);
1078 systable_endscan(scan
);
1079 heap_close(catalogRelation
, RowExclusiveLock
);
1083 * DeleteRelationTuple
1085 * Remove pg_class row for the given relid.
1087 * Note: this is shared by relation deletion and index deletion. It's
1088 * not intended for use anyplace else.
1091 DeleteRelationTuple(Oid relid
)
1093 Relation pg_class_desc
;
1096 /* Grab an appropriate lock on the pg_class relation */
1097 pg_class_desc
= heap_open(RelationRelationId
, RowExclusiveLock
);
1099 tup
= SearchSysCache(RELOID
,
1100 ObjectIdGetDatum(relid
),
1102 if (!HeapTupleIsValid(tup
))
1103 elog(ERROR
, "cache lookup failed for relation %u", relid
);
1105 /* delete the relation tuple from pg_class, and finish up */
1106 simple_heap_delete(pg_class_desc
, &tup
->t_self
);
1108 ReleaseSysCache(tup
);
1110 heap_close(pg_class_desc
, RowExclusiveLock
);
1114 * DeleteAttributeTuples
1116 * Remove pg_attribute rows for the given relid.
1118 * Note: this is shared by relation deletion and index deletion. It's
1119 * not intended for use anyplace else.
1122 DeleteAttributeTuples(Oid relid
)
1129 /* Grab an appropriate lock on the pg_attribute relation */
1130 attrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1132 /* Use the index to scan only attributes of the target relation */
1133 ScanKeyInit(&key
[0],
1134 Anum_pg_attribute_attrelid
,
1135 BTEqualStrategyNumber
, F_OIDEQ
,
1136 ObjectIdGetDatum(relid
));
1138 scan
= systable_beginscan(attrel
, AttributeRelidNumIndexId
, true,
1139 SnapshotNow
, 1, key
);
1141 /* Delete all the matching tuples */
1142 while ((atttup
= systable_getnext(scan
)) != NULL
)
1143 simple_heap_delete(attrel
, &atttup
->t_self
);
1145 /* Clean up after the scan */
1146 systable_endscan(scan
);
1147 heap_close(attrel
, RowExclusiveLock
);
1151 * RemoveAttributeById
1153 * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1154 * deleted in pg_attribute. We also remove pg_statistic entries for it.
1155 * (Everything else needed, such as getting rid of any pg_attrdef entry,
1156 * is handled by dependency.c.)
1159 RemoveAttributeById(Oid relid
, AttrNumber attnum
)
1164 Form_pg_attribute attStruct
;
1165 char newattname
[NAMEDATALEN
];
1168 * Grab an exclusive lock on the target table, which we will NOT release
1169 * until end of transaction. (In the simple case where we are directly
1170 * dropping this column, AlterTableDropColumn already did this ... but
1171 * when cascading from a drop of some other object, we may not have any
1174 rel
= relation_open(relid
, AccessExclusiveLock
);
1176 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1178 tuple
= SearchSysCacheCopy(ATTNUM
,
1179 ObjectIdGetDatum(relid
),
1180 Int16GetDatum(attnum
),
1182 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1183 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1185 attStruct
= (Form_pg_attribute
) GETSTRUCT(tuple
);
1189 /* System attribute (probably OID) ... just delete the row */
1191 simple_heap_delete(attr_rel
, &tuple
->t_self
);
1195 /* Dropping user attributes is lots harder */
1197 /* Mark the attribute as dropped */
1198 attStruct
->attisdropped
= true;
1201 * Set the type OID to invalid. A dropped attribute's type link
1202 * cannot be relied on (once the attribute is dropped, the type might
1203 * be too). Fortunately we do not need the type row --- the only
1204 * really essential information is the type's typlen and typalign,
1205 * which are preserved in the attribute's attlen and attalign. We set
1206 * atttypid to zero here as a means of catching code that incorrectly
1207 * expects it to be valid.
1209 attStruct
->atttypid
= InvalidOid
;
1211 /* Remove any NOT NULL constraint the column may have */
1212 attStruct
->attnotnull
= false;
1214 /* We don't want to keep stats for it anymore */
1215 attStruct
->attstattarget
= 0;
1218 * Change the column name to something that isn't likely to conflict
1220 snprintf(newattname
, sizeof(newattname
),
1221 "........pg.dropped.%d........", attnum
);
1222 namestrcpy(&(attStruct
->attname
), newattname
);
1224 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1226 /* keep the system catalog indexes current */
1227 CatalogUpdateIndexes(attr_rel
, tuple
);
1231 * Because updating the pg_attribute row will trigger a relcache flush for
1232 * the target relation, we need not do anything else to notify other
1233 * backends of the change.
1236 heap_close(attr_rel
, RowExclusiveLock
);
1239 RemoveStatistics(relid
, attnum
);
1241 relation_close(rel
, NoLock
);
1247 * If the specified relation/attribute has a default, remove it.
1248 * (If no default, raise error if complain is true, else return quietly.)
1251 RemoveAttrDefault(Oid relid
, AttrNumber attnum
,
1252 DropBehavior behavior
, bool complain
)
1254 Relation attrdef_rel
;
1255 ScanKeyData scankeys
[2];
1260 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1262 ScanKeyInit(&scankeys
[0],
1263 Anum_pg_attrdef_adrelid
,
1264 BTEqualStrategyNumber
, F_OIDEQ
,
1265 ObjectIdGetDatum(relid
));
1266 ScanKeyInit(&scankeys
[1],
1267 Anum_pg_attrdef_adnum
,
1268 BTEqualStrategyNumber
, F_INT2EQ
,
1269 Int16GetDatum(attnum
));
1271 scan
= systable_beginscan(attrdef_rel
, AttrDefaultIndexId
, true,
1272 SnapshotNow
, 2, scankeys
);
1274 /* There should be at most one matching tuple, but we loop anyway */
1275 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
1277 ObjectAddress object
;
1279 object
.classId
= AttrDefaultRelationId
;
1280 object
.objectId
= HeapTupleGetOid(tuple
);
1281 object
.objectSubId
= 0;
1283 performDeletion(&object
, behavior
);
1288 systable_endscan(scan
);
1289 heap_close(attrdef_rel
, RowExclusiveLock
);
1291 if (complain
&& !found
)
1292 elog(ERROR
, "could not find attrdef tuple for relation %u attnum %d",
1297 * RemoveAttrDefaultById
1299 * Remove a pg_attrdef entry specified by OID. This is the guts of
1300 * attribute-default removal. Note it should be called via performDeletion,
1304 RemoveAttrDefaultById(Oid attrdefId
)
1306 Relation attrdef_rel
;
1309 ScanKeyData scankeys
[1];
1313 AttrNumber myattnum
;
1315 /* Grab an appropriate lock on the pg_attrdef relation */
1316 attrdef_rel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1318 /* Find the pg_attrdef tuple */
1319 ScanKeyInit(&scankeys
[0],
1320 ObjectIdAttributeNumber
,
1321 BTEqualStrategyNumber
, F_OIDEQ
,
1322 ObjectIdGetDatum(attrdefId
));
1324 scan
= systable_beginscan(attrdef_rel
, AttrDefaultOidIndexId
, true,
1325 SnapshotNow
, 1, scankeys
);
1327 tuple
= systable_getnext(scan
);
1328 if (!HeapTupleIsValid(tuple
))
1329 elog(ERROR
, "could not find tuple for attrdef %u", attrdefId
);
1331 myrelid
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adrelid
;
1332 myattnum
= ((Form_pg_attrdef
) GETSTRUCT(tuple
))->adnum
;
1334 /* Get an exclusive lock on the relation owning the attribute */
1335 myrel
= relation_open(myrelid
, AccessExclusiveLock
);
1337 /* Now we can delete the pg_attrdef row */
1338 simple_heap_delete(attrdef_rel
, &tuple
->t_self
);
1340 systable_endscan(scan
);
1341 heap_close(attrdef_rel
, RowExclusiveLock
);
1343 /* Fix the pg_attribute row */
1344 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1346 tuple
= SearchSysCacheCopy(ATTNUM
,
1347 ObjectIdGetDatum(myrelid
),
1348 Int16GetDatum(myattnum
),
1350 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
1351 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1354 ((Form_pg_attribute
) GETSTRUCT(tuple
))->atthasdef
= false;
1356 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
1358 /* keep the system catalog indexes current */
1359 CatalogUpdateIndexes(attr_rel
, tuple
);
1362 * Our update of the pg_attribute row will force a relcache rebuild, so
1363 * there's nothing else to do here.
1365 heap_close(attr_rel
, RowExclusiveLock
);
1367 /* Keep lock on attribute's rel until end of xact */
1368 relation_close(myrel
, NoLock
);
1372 * heap_drop_with_catalog - removes specified relation from catalogs
1374 * Note that this routine is not responsible for dropping objects that are
1375 * linked to the pg_class entry via dependencies (for example, indexes and
1376 * constraints). Those are deleted by the dependency-tracing logic in
1377 * dependency.c before control gets here. In general, therefore, this routine
1378 * should never be called directly; go through performDeletion() instead.
1381 heap_drop_with_catalog(Oid relid
)
1386 * Open and lock the relation.
1388 rel
= relation_open(relid
, AccessExclusiveLock
);
1391 * Schedule unlinking of the relation's physical files at commit.
1393 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
&&
1394 rel
->rd_rel
->relkind
!= RELKIND_COMPOSITE_TYPE
)
1398 RelationOpenSmgr(rel
);
1399 for (forknum
= 0; forknum
<= MAX_FORKNUM
; forknum
++)
1400 if (smgrexists(rel
->rd_smgr
, forknum
))
1401 smgrscheduleunlink(rel
->rd_smgr
, forknum
, rel
->rd_istemp
);
1402 RelationCloseSmgr(rel
);
1406 * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1407 * until transaction commit. This ensures no one else will try to do
1408 * something with the doomed relation.
1410 relation_close(rel
, NoLock
);
1413 * Forget any ON COMMIT action for the rel
1415 remove_on_commit_action(relid
);
1418 * Flush the relation from the relcache. We want to do this before
1419 * starting to remove catalog entries, just to be certain that no relcache
1420 * entry rebuild will happen partway through. (That should not really
1421 * matter, since we don't do CommandCounterIncrement here, but let's be
1424 RelationForgetRelation(relid
);
1427 * remove inheritance information
1429 RelationRemoveInheritance(relid
);
1434 RemoveStatistics(relid
, 0);
1437 * delete attribute tuples
1439 DeleteAttributeTuples(relid
);
1442 * delete relation tuple
1444 DeleteRelationTuple(relid
);
1449 * Store a default expression for column attnum of relation rel.
1452 StoreAttrDefault(Relation rel
, AttrNumber attnum
, Node
*expr
)
1459 static char nulls
[4] = {' ', ' ', ' ', ' '};
1462 Form_pg_attribute attStruct
;
1464 ObjectAddress colobject
,
1468 * Flatten expression to string form for storage.
1470 adbin
= nodeToString(expr
);
1473 * Also deparse it to form the mostly-obsolete adsrc field.
1475 adsrc
= deparse_expression(expr
,
1476 deparse_context_for(RelationGetRelationName(rel
),
1477 RelationGetRelid(rel
)),
1481 * Make the pg_attrdef entry.
1483 values
[Anum_pg_attrdef_adrelid
- 1] = RelationGetRelid(rel
);
1484 values
[Anum_pg_attrdef_adnum
- 1] = attnum
;
1485 values
[Anum_pg_attrdef_adbin
- 1] = CStringGetTextDatum(adbin
);
1486 values
[Anum_pg_attrdef_adsrc
- 1] = CStringGetTextDatum(adsrc
);
1488 adrel
= heap_open(AttrDefaultRelationId
, RowExclusiveLock
);
1490 tuple
= heap_formtuple(adrel
->rd_att
, values
, nulls
);
1491 attrdefOid
= simple_heap_insert(adrel
, tuple
);
1493 CatalogUpdateIndexes(adrel
, tuple
);
1495 defobject
.classId
= AttrDefaultRelationId
;
1496 defobject
.objectId
= attrdefOid
;
1497 defobject
.objectSubId
= 0;
1499 heap_close(adrel
, RowExclusiveLock
);
1501 /* now can free some of the stuff allocated above */
1502 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adbin
- 1]));
1503 pfree(DatumGetPointer(values
[Anum_pg_attrdef_adsrc
- 1]));
1504 heap_freetuple(tuple
);
1509 * Update the pg_attribute entry for the column to show that a default
1512 attrrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1513 atttup
= SearchSysCacheCopy(ATTNUM
,
1514 ObjectIdGetDatum(RelationGetRelid(rel
)),
1515 Int16GetDatum(attnum
),
1517 if (!HeapTupleIsValid(atttup
))
1518 elog(ERROR
, "cache lookup failed for attribute %d of relation %u",
1519 attnum
, RelationGetRelid(rel
));
1520 attStruct
= (Form_pg_attribute
) GETSTRUCT(atttup
);
1521 if (!attStruct
->atthasdef
)
1523 attStruct
->atthasdef
= true;
1524 simple_heap_update(attrrel
, &atttup
->t_self
, atttup
);
1525 /* keep catalog indexes current */
1526 CatalogUpdateIndexes(attrrel
, atttup
);
1528 heap_close(attrrel
, RowExclusiveLock
);
1529 heap_freetuple(atttup
);
1532 * Make a dependency so that the pg_attrdef entry goes away if the column
1533 * (or whole table) is deleted.
1535 colobject
.classId
= RelationRelationId
;
1536 colobject
.objectId
= RelationGetRelid(rel
);
1537 colobject
.objectSubId
= attnum
;
1539 recordDependencyOn(&defobject
, &colobject
, DEPENDENCY_AUTO
);
1542 * Record dependencies on objects used in the expression, too.
1544 recordDependencyOnExpr(&defobject
, expr
, NIL
, DEPENDENCY_NORMAL
);
1548 * Store a check-constraint expression for the given relation.
1550 * Caller is responsible for updating the count of constraints
1551 * in the pg_class entry for the relation.
1554 StoreRelCheck(Relation rel
, char *ccname
, Node
*expr
,
1555 bool is_local
, int inhcount
)
1564 * Flatten expression to string form for storage.
1566 ccbin
= nodeToString(expr
);
1569 * Also deparse it to form the mostly-obsolete consrc field.
1571 ccsrc
= deparse_expression(expr
,
1572 deparse_context_for(RelationGetRelationName(rel
),
1573 RelationGetRelid(rel
)),
1577 * Find columns of rel that are used in expr
1579 * NB: pull_var_clause is okay here only because we don't allow subselects
1580 * in check constraints; it would fail to examine the contents of
1583 varList
= pull_var_clause(expr
, false);
1584 keycount
= list_length(varList
);
1591 attNos
= (int16
*) palloc(keycount
* sizeof(int16
));
1592 foreach(vl
, varList
)
1594 Var
*var
= (Var
*) lfirst(vl
);
1597 for (j
= 0; j
< i
; j
++)
1598 if (attNos
[j
] == var
->varattno
)
1601 attNos
[i
++] = var
->varattno
;
1609 * Create the Check Constraint
1611 CreateConstraintEntry(ccname
, /* Constraint Name */
1612 RelationGetNamespace(rel
), /* namespace */
1613 CONSTRAINT_CHECK
, /* Constraint Type */
1614 false, /* Is Deferrable */
1615 false, /* Is Deferred */
1616 RelationGetRelid(rel
), /* relation */
1617 attNos
, /* attrs in the constraint */
1618 keycount
, /* # attrs in the constraint */
1619 InvalidOid
, /* not a domain constraint */
1620 InvalidOid
, /* Foreign key fields */
1629 InvalidOid
, /* no associated index */
1630 expr
, /* Tree form check constraint */
1631 ccbin
, /* Binary form check constraint */
1632 ccsrc
, /* Source form check constraint */
1633 is_local
, /* conislocal */
1634 inhcount
); /* coninhcount */
1641 * Store defaults and constraints (passed as a list of CookedConstraint).
1643 * NOTE: only pre-cooked expressions will be passed this way, which is to
1644 * say expressions inherited from an existing relation. Newly parsed
1645 * expressions can be added later, by direct calls to StoreAttrDefault
1646 * and StoreRelCheck (see AddRelationNewConstraints()).
1649 StoreConstraints(Relation rel
, List
*cooked_constraints
)
1654 if (!cooked_constraints
)
1655 return; /* nothing to do */
1658 * Deparsing of constraint expressions will fail unless the just-created
1659 * pg_attribute tuples for this relation are made visible. So, bump the
1660 * command counter. CAUTION: this will cause a relcache entry rebuild.
1662 CommandCounterIncrement();
1664 foreach(lc
, cooked_constraints
)
1666 CookedConstraint
*con
= (CookedConstraint
*) lfirst(lc
);
1668 switch (con
->contype
)
1670 case CONSTR_DEFAULT
:
1671 StoreAttrDefault(rel
, con
->attnum
, con
->expr
);
1674 StoreRelCheck(rel
, con
->name
, con
->expr
,
1675 con
->is_local
, con
->inhcount
);
1679 elog(ERROR
, "unrecognized constraint type: %d",
1680 (int) con
->contype
);
1685 SetRelationNumChecks(rel
, numchecks
);
1689 * AddRelationNewConstraints
1691 * Add new column default expressions and/or constraint check expressions
1692 * to an existing relation. This is defined to do both for efficiency in
1693 * DefineRelation, but of course you can do just one or the other by passing
1696 * rel: relation to be modified
1697 * newColDefaults: list of RawColumnDefault structures
1698 * newConstraints: list of Constraint nodes
1699 * allow_merge: TRUE if check constraints may be merged with existing ones
1700 * is_local: TRUE if definition is local, FALSE if it's inherited
1702 * All entries in newColDefaults will be processed. Entries in newConstraints
1703 * will be processed only if they are CONSTR_CHECK type.
1705 * Returns a list of CookedConstraint nodes that shows the cooked form of
1706 * the default and constraint expressions added to the relation.
1708 * NB: caller should have opened rel with AccessExclusiveLock, and should
1709 * hold that lock till end of transaction. Also, we assume the caller has
1710 * done a CommandCounterIncrement if necessary to make the relation's catalog
1714 AddRelationNewConstraints(Relation rel
,
1715 List
*newColDefaults
,
1716 List
*newConstraints
,
1720 List
*cookedConstraints
= NIL
;
1721 TupleDesc tupleDesc
;
1722 TupleConstr
*oldconstr
;
1730 CookedConstraint
*cooked
;
1733 * Get info about existing constraints.
1735 tupleDesc
= RelationGetDescr(rel
);
1736 oldconstr
= tupleDesc
->constr
;
1738 numoldchecks
= oldconstr
->num_check
;
1743 * Create a dummy ParseState and insert the target relation as its sole
1744 * rangetable entry. We need a ParseState for transformExpr.
1746 pstate
= make_parsestate(NULL
);
1747 rte
= addRangeTableEntryForRelation(pstate
,
1752 addRTEtoQuery(pstate
, rte
, true, true, true);
1755 * Process column default expressions.
1757 foreach(cell
, newColDefaults
)
1759 RawColumnDefault
*colDef
= (RawColumnDefault
*) lfirst(cell
);
1760 Form_pg_attribute atp
= rel
->rd_att
->attrs
[colDef
->attnum
- 1];
1762 expr
= cookDefault(pstate
, colDef
->raw_default
,
1763 atp
->atttypid
, atp
->atttypmod
,
1764 NameStr(atp
->attname
));
1767 * If the expression is just a NULL constant, we do not bother to make
1768 * an explicit pg_attrdef entry, since the default behavior is
1771 * Note a nonobvious property of this test: if the column is of a
1772 * domain type, what we'll get is not a bare null Const but a
1773 * CoerceToDomain expr, so we will not discard the default. This is
1774 * critical because the column default needs to be retained to
1775 * override any default that the domain might have.
1778 (IsA(expr
, Const
) &&((Const
*) expr
)->constisnull
))
1781 StoreAttrDefault(rel
, colDef
->attnum
, expr
);
1783 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1784 cooked
->contype
= CONSTR_DEFAULT
;
1785 cooked
->name
= NULL
;
1786 cooked
->attnum
= colDef
->attnum
;
1787 cooked
->expr
= expr
;
1788 cooked
->is_local
= is_local
;
1789 cooked
->inhcount
= is_local
? 0 : 1;
1790 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1794 * Process constraint expressions.
1796 numchecks
= numoldchecks
;
1798 foreach(cell
, newConstraints
)
1800 Constraint
*cdef
= (Constraint
*) lfirst(cell
);
1803 if (cdef
->contype
!= CONSTR_CHECK
)
1806 if (cdef
->raw_expr
!= NULL
)
1808 Assert(cdef
->cooked_expr
== NULL
);
1811 * Transform raw parsetree to executable expression, and verify
1812 * it's valid as a CHECK constraint.
1814 expr
= cookConstraint(pstate
, cdef
->raw_expr
,
1815 RelationGetRelationName(rel
));
1819 Assert(cdef
->cooked_expr
!= NULL
);
1822 * Here, we assume the parser will only pass us valid CHECK
1823 * expressions, so we do no particular checking.
1825 expr
= stringToNode(cdef
->cooked_expr
);
1829 * Check name uniqueness, or generate a name if none was given.
1831 if (cdef
->name
!= NULL
)
1835 ccname
= cdef
->name
;
1836 /* Check against other new constraints */
1837 /* Needed because we don't do CommandCounterIncrement in loop */
1838 foreach(cell2
, checknames
)
1840 if (strcmp((char *) lfirst(cell2
), ccname
) == 0)
1842 (errcode(ERRCODE_DUPLICATE_OBJECT
),
1843 errmsg("check constraint \"%s\" already exists",
1847 /* save name for future checks */
1848 checknames
= lappend(checknames
, ccname
);
1851 * Check against pre-existing constraints. If we are allowed
1852 * to merge with an existing constraint, there's no more to
1853 * do here. (We omit the duplicate constraint from the result,
1854 * which is what ATAddCheckConstraint wants.)
1856 if (MergeWithExistingConstraint(rel
, ccname
, expr
,
1857 allow_merge
, is_local
))
1863 * When generating a name, we want to create "tab_col_check" for a
1864 * column constraint and "tab_check" for a table constraint. We
1865 * no longer have any info about the syntactic positioning of the
1866 * constraint phrase, so we approximate this by seeing whether the
1867 * expression references more than one column. (If the user
1868 * played by the rules, the result is the same...)
1870 * Note: pull_var_clause() doesn't descend into sublinks, but we
1871 * eliminated those above; and anyway this only needs to be an
1872 * approximate answer.
1877 vars
= pull_var_clause(expr
, false);
1879 /* eliminate duplicates */
1880 vars
= list_union(NIL
, vars
);
1882 if (list_length(vars
) == 1)
1883 colname
= get_attname(RelationGetRelid(rel
),
1884 ((Var
*) linitial(vars
))->varattno
);
1888 ccname
= ChooseConstraintName(RelationGetRelationName(rel
),
1891 RelationGetNamespace(rel
),
1894 /* save name for future checks */
1895 checknames
= lappend(checknames
, ccname
);
1901 StoreRelCheck(rel
, ccname
, expr
, is_local
, is_local
? 0 : 1);
1905 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1906 cooked
->contype
= CONSTR_CHECK
;
1907 cooked
->name
= ccname
;
1909 cooked
->expr
= expr
;
1910 cooked
->is_local
= is_local
;
1911 cooked
->inhcount
= is_local
? 0 : 1;
1912 cookedConstraints
= lappend(cookedConstraints
, cooked
);
1916 * Update the count of constraints in the relation's pg_class tuple. We do
1917 * this even if there was no change, in order to ensure that an SI update
1918 * message is sent out for the pg_class tuple, which will force other
1919 * backends to rebuild their relcache entries for the rel. (This is
1920 * critical if we added defaults but not constraints.)
1922 SetRelationNumChecks(rel
, numchecks
);
1924 return cookedConstraints
;
1928 * Check for a pre-existing check constraint that conflicts with a proposed
1929 * new one, and either adjust its conislocal/coninhcount settings or throw
1932 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1933 * got a so-far-unique name, or throws error if conflict.
1936 MergeWithExistingConstraint(Relation rel
, char *ccname
, Node
*expr
,
1937 bool allow_merge
, bool is_local
)
1941 SysScanDesc conscan
;
1942 ScanKeyData skey
[2];
1945 /* Search for a pg_constraint entry with same name and relation */
1946 conDesc
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
1950 ScanKeyInit(&skey
[0],
1951 Anum_pg_constraint_conname
,
1952 BTEqualStrategyNumber
, F_NAMEEQ
,
1953 CStringGetDatum(ccname
));
1955 ScanKeyInit(&skey
[1],
1956 Anum_pg_constraint_connamespace
,
1957 BTEqualStrategyNumber
, F_OIDEQ
,
1958 ObjectIdGetDatum(RelationGetNamespace(rel
)));
1960 conscan
= systable_beginscan(conDesc
, ConstraintNameNspIndexId
, true,
1961 SnapshotNow
, 2, skey
);
1963 while (HeapTupleIsValid(tup
= systable_getnext(conscan
)))
1965 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tup
);
1967 if (con
->conrelid
== RelationGetRelid(rel
))
1969 /* Found it. Conflicts if not identical check constraint */
1970 if (con
->contype
== CONSTRAINT_CHECK
)
1975 val
= fastgetattr(tup
,
1976 Anum_pg_constraint_conbin
,
1977 conDesc
->rd_att
, &isnull
);
1979 elog(ERROR
, "null conbin for rel %s",
1980 RelationGetRelationName(rel
));
1981 if (equal(expr
, stringToNode(TextDatumGetCString(val
))))
1984 if (!found
|| !allow_merge
)
1986 (errcode(ERRCODE_DUPLICATE_OBJECT
),
1987 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1988 ccname
, RelationGetRelationName(rel
))));
1989 /* OK to update the tuple */
1991 (errmsg("merging constraint \"%s\" with inherited definition",
1993 tup
= heap_copytuple(tup
);
1994 con
= (Form_pg_constraint
) GETSTRUCT(tup
);
1996 con
->conislocal
= true;
1999 simple_heap_update(conDesc
, &tup
->t_self
, tup
);
2000 CatalogUpdateIndexes(conDesc
, tup
);
2005 systable_endscan(conscan
);
2006 heap_close(conDesc
, RowExclusiveLock
);
2012 * Update the count of constraints in the relation's pg_class tuple.
2014 * Caller had better hold exclusive lock on the relation.
2016 * An important side effect is that a SI update message will be sent out for
2017 * the pg_class tuple, which will force other backends to rebuild their
2018 * relcache entries for the rel. Also, this backend will rebuild its
2019 * own relcache entry at the next CommandCounterIncrement.
2022 SetRelationNumChecks(Relation rel
, int numchecks
)
2026 Form_pg_class relStruct
;
2028 relrel
= heap_open(RelationRelationId
, RowExclusiveLock
);
2029 reltup
= SearchSysCacheCopy(RELOID
,
2030 ObjectIdGetDatum(RelationGetRelid(rel
)),
2032 if (!HeapTupleIsValid(reltup
))
2033 elog(ERROR
, "cache lookup failed for relation %u",
2034 RelationGetRelid(rel
));
2035 relStruct
= (Form_pg_class
) GETSTRUCT(reltup
);
2037 if (relStruct
->relchecks
!= numchecks
)
2039 relStruct
->relchecks
= numchecks
;
2041 simple_heap_update(relrel
, &reltup
->t_self
, reltup
);
2043 /* keep catalog indexes current */
2044 CatalogUpdateIndexes(relrel
, reltup
);
2048 /* Skip the disk update, but force relcache inval anyway */
2049 CacheInvalidateRelcache(rel
);
2052 heap_freetuple(reltup
);
2053 heap_close(relrel
, RowExclusiveLock
);
2057 * Take a raw default and convert it to a cooked format ready for
2060 * Parse state should be set up to recognize any vars that might appear
2061 * in the expression. (Even though we plan to reject vars, it's more
2062 * user-friendly to give the correct error message than "unknown var".)
2064 * If atttypid is not InvalidOid, coerce the expression to the specified
2065 * type (and typmod atttypmod). attname is only needed in this case:
2066 * it is used in the error message, if any.
2069 cookDefault(ParseState
*pstate
,
2077 Assert(raw_default
!= NULL
);
2080 * Transform raw parsetree to executable expression.
2082 expr
= transformExpr(pstate
, raw_default
);
2085 * Make sure default expr does not refer to any vars.
2087 if (contain_var_clause(expr
))
2089 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2090 errmsg("cannot use column references in default expression")));
2093 * It can't return a set either.
2095 if (expression_returns_set(expr
))
2097 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2098 errmsg("default expression must not return a set")));
2101 * No subplans or aggregates, either...
2103 if (pstate
->p_hasSubLinks
)
2105 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2106 errmsg("cannot use subquery in default expression")));
2107 if (pstate
->p_hasAggs
)
2109 (errcode(ERRCODE_GROUPING_ERROR
),
2110 errmsg("cannot use aggregate function in default expression")));
2113 * Coerce the expression to the correct type and typmod, if given. This
2114 * should match the parser's processing of non-defaulted expressions ---
2115 * see transformAssignedExpr().
2117 if (OidIsValid(atttypid
))
2119 Oid type_id
= exprType(expr
);
2121 expr
= coerce_to_target_type(pstate
, expr
, type_id
,
2122 atttypid
, atttypmod
,
2123 COERCION_ASSIGNMENT
,
2124 COERCE_IMPLICIT_CAST
);
2127 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2128 errmsg("column \"%s\" is of type %s"
2129 " but default expression is of type %s",
2131 format_type_be(atttypid
),
2132 format_type_be(type_id
)),
2133 errhint("You will need to rewrite or cast the expression.")));
2140 * Take a raw CHECK constraint expression and convert it to a cooked format
2141 * ready for storage.
2143 * Parse state must be set up to recognize any vars that might appear
2144 * in the expression.
2147 cookConstraint(ParseState
*pstate
,
2148 Node
*raw_constraint
,
2154 * Transform raw parsetree to executable expression.
2156 expr
= transformExpr(pstate
, raw_constraint
);
2159 * Make sure it yields a boolean result.
2161 expr
= coerce_to_boolean(pstate
, expr
, "CHECK");
2164 * Make sure no outside relations are referred to.
2166 if (list_length(pstate
->p_rtable
) != 1)
2168 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2169 errmsg("only table \"%s\" can be referenced in check constraint",
2173 * No subplans or aggregates, either...
2175 if (pstate
->p_hasSubLinks
)
2177 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2178 errmsg("cannot use subquery in check constraint")));
2179 if (pstate
->p_hasAggs
)
2181 (errcode(ERRCODE_GROUPING_ERROR
),
2182 errmsg("cannot use aggregate function in check constraint")));
2189 * RemoveStatistics --- remove entries in pg_statistic for a rel or column
2191 * If attnum is zero, remove all entries for rel; else remove only the one
2195 RemoveStatistics(Oid relid
, AttrNumber attnum
)
2197 Relation pgstatistic
;
2203 pgstatistic
= heap_open(StatisticRelationId
, RowExclusiveLock
);
2205 ScanKeyInit(&key
[0],
2206 Anum_pg_statistic_starelid
,
2207 BTEqualStrategyNumber
, F_OIDEQ
,
2208 ObjectIdGetDatum(relid
));
2214 ScanKeyInit(&key
[1],
2215 Anum_pg_statistic_staattnum
,
2216 BTEqualStrategyNumber
, F_INT2EQ
,
2217 Int16GetDatum(attnum
));
2221 scan
= systable_beginscan(pgstatistic
, StatisticRelidAttnumIndexId
, true,
2222 SnapshotNow
, nkeys
, key
);
2224 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
2225 simple_heap_delete(pgstatistic
, &tuple
->t_self
);
2227 systable_endscan(scan
);
2229 heap_close(pgstatistic
, RowExclusiveLock
);
2234 * RelationTruncateIndexes - truncate all indexes associated
2235 * with the heap relation to zero tuples.
2237 * The routine will truncate and then reconstruct the indexes on
2238 * the specified relation. Caller must hold exclusive lock on rel.
2241 RelationTruncateIndexes(Relation heapRelation
)
2245 /* Ask the relcache to produce a list of the indexes of the rel */
2246 foreach(indlist
, RelationGetIndexList(heapRelation
))
2248 Oid indexId
= lfirst_oid(indlist
);
2249 Relation currentIndex
;
2250 IndexInfo
*indexInfo
;
2252 /* Open the index relation; use exclusive lock, just to be sure */
2253 currentIndex
= index_open(indexId
, AccessExclusiveLock
);
2255 /* Fetch info needed for index_build */
2256 indexInfo
= BuildIndexInfo(currentIndex
);
2258 /* Now truncate the actual file (and discard buffers) */
2259 RelationTruncate(currentIndex
, 0);
2261 /* Initialize the index and rebuild */
2262 /* Note: we do not need to re-establish pkey setting */
2263 index_build(heapRelation
, currentIndex
, indexInfo
, false);
2265 /* We're done with this index */
2266 index_close(currentIndex
, NoLock
);
2273 * This routine deletes all data within all the specified relations.
2275 * This is not transaction-safe! There is another, transaction-safe
2276 * implementation in commands/tablecmds.c. We now use this only for
2277 * ON COMMIT truncation of temporary tables, where it doesn't matter.
2280 heap_truncate(List
*relids
)
2282 List
*relations
= NIL
;
2285 /* Open relations for processing, and grab exclusive access on each */
2286 foreach(cell
, relids
)
2288 Oid rid
= lfirst_oid(cell
);
2292 rel
= heap_open(rid
, AccessExclusiveLock
);
2293 relations
= lappend(relations
, rel
);
2295 /* If there is a toast table, add it to the list too */
2296 toastrelid
= rel
->rd_rel
->reltoastrelid
;
2297 if (OidIsValid(toastrelid
))
2299 rel
= heap_open(toastrelid
, AccessExclusiveLock
);
2300 relations
= lappend(relations
, rel
);
2304 /* Don't allow truncate on tables that are referenced by foreign keys */
2305 heap_truncate_check_FKs(relations
, true);
2308 foreach(cell
, relations
)
2310 Relation rel
= lfirst(cell
);
2312 /* Truncate the actual file (and discard buffers) */
2313 RelationTruncate(rel
, 0);
2315 /* If this relation has indexes, truncate the indexes too */
2316 RelationTruncateIndexes(rel
);
2319 * Close the relation, but keep exclusive lock on it until commit.
2321 heap_close(rel
, NoLock
);
2326 * heap_truncate_check_FKs
2327 * Check for foreign keys referencing a list of relations that
2328 * are to be truncated, and raise error if there are any
2330 * We disallow such FKs (except self-referential ones) since the whole point
2331 * of TRUNCATE is to not scan the individual rows to be thrown away.
2333 * This is split out so it can be shared by both implementations of truncate.
2334 * Caller should already hold a suitable lock on the relations.
2336 * tempTables is only used to select an appropriate error message.
2339 heap_truncate_check_FKs(List
*relations
, bool tempTables
)
2346 * Build a list of OIDs of the interesting relations.
2348 * If a relation has no triggers, then it can neither have FKs nor be
2349 * referenced by a FK from another table, so we can ignore it.
2351 foreach(cell
, relations
)
2353 Relation rel
= lfirst(cell
);
2355 if (rel
->rd_rel
->reltriggers
!= 0)
2356 oids
= lappend_oid(oids
, RelationGetRelid(rel
));
2360 * Fast path: if no relation has triggers, none has FKs either.
2366 * Otherwise, must scan pg_constraint. We make one pass with all the
2367 * relations considered; if this finds nothing, then all is well.
2369 dependents
= heap_truncate_find_FKs(oids
);
2370 if (dependents
== NIL
)
2374 * Otherwise we repeat the scan once per relation to identify a particular
2375 * pair of relations to complain about. This is pretty slow, but
2376 * performance shouldn't matter much in a failure path. The reason for
2377 * doing things this way is to ensure that the message produced is not
2378 * dependent on chance row locations within pg_constraint.
2382 Oid relid
= lfirst_oid(cell
);
2385 dependents
= heap_truncate_find_FKs(list_make1_oid(relid
));
2387 foreach(cell2
, dependents
)
2389 Oid relid2
= lfirst_oid(cell2
);
2391 if (!list_member_oid(oids
, relid2
))
2393 char *relname
= get_rel_name(relid
);
2394 char *relname2
= get_rel_name(relid2
);
2398 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2399 errmsg("unsupported ON COMMIT and foreign key combination"),
2400 errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
2401 relname2
, relname
)));
2404 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2405 errmsg("cannot truncate a table referenced in a foreign key constraint"),
2406 errdetail("Table \"%s\" references \"%s\".",
2408 errhint("Truncate table \"%s\" at the same time, "
2409 "or use TRUNCATE ... CASCADE.",
2417 * heap_truncate_find_FKs
2418 * Find relations having foreign keys referencing any of the given rels
2420 * Input and result are both lists of relation OIDs. The result contains
2421 * no duplicates, does *not* include any rels that were already in the input
2422 * list, and is sorted in OID order. (The last property is enforced mainly
2423 * to guarantee consistent behavior in the regression tests; we don't want
2424 * behavior to change depending on chance locations of rows in pg_constraint.)
2426 * Note: caller should already have appropriate lock on all rels mentioned
2427 * in relationIds. Since adding or dropping an FK requires exclusive lock
2428 * on both rels, this ensures that the answer will be stable.
2431 heap_truncate_find_FKs(List
*relationIds
)
2435 SysScanDesc fkeyScan
;
2439 * Must scan pg_constraint. Right now, it is a seqscan because there is
2440 * no available index on confrelid.
2442 fkeyRel
= heap_open(ConstraintRelationId
, AccessShareLock
);
2444 fkeyScan
= systable_beginscan(fkeyRel
, InvalidOid
, false,
2445 SnapshotNow
, 0, NULL
);
2447 while (HeapTupleIsValid(tuple
= systable_getnext(fkeyScan
)))
2449 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(tuple
);
2451 /* Not a foreign key */
2452 if (con
->contype
!= CONSTRAINT_FOREIGN
)
2455 /* Not referencing one of our list of tables */
2456 if (!list_member_oid(relationIds
, con
->confrelid
))
2459 /* Add referencer unless already in input or result list */
2460 if (!list_member_oid(relationIds
, con
->conrelid
))
2461 result
= insert_ordered_unique_oid(result
, con
->conrelid
);
2464 systable_endscan(fkeyScan
);
2465 heap_close(fkeyRel
, AccessShareLock
);
2471 * insert_ordered_unique_oid
2472 * Insert a new Oid into a sorted list of Oids, preserving ordering,
2473 * and eliminating duplicates
2475 * Building the ordered list this way is O(N^2), but with a pretty small
2476 * constant, so for the number of entries we expect it will probably be
2477 * faster than trying to apply qsort(). It seems unlikely someone would be
2478 * trying to truncate a table with thousands of dependent tables ...
2481 insert_ordered_unique_oid(List
*list
, Oid datum
)
2485 /* Does the datum belong at the front? */
2486 if (list
== NIL
|| datum
< linitial_oid(list
))
2487 return lcons_oid(datum
, list
);
2488 /* Does it match the first entry? */
2489 if (datum
== linitial_oid(list
))
2490 return list
; /* duplicate, so don't insert */
2491 /* No, so find the entry it belongs after */
2492 prev
= list_head(list
);
2495 ListCell
*curr
= lnext(prev
);
2497 if (curr
== NULL
|| datum
< lfirst_oid(curr
))
2498 break; /* it belongs after 'prev', before 'curr' */
2500 if (datum
== lfirst_oid(curr
))
2501 return list
; /* duplicate, so don't insert */
2505 /* Insert datum into list after 'prev' */
2506 lappend_cell_oid(list
, prev
, datum
);