1
0
mirror of https://github.com/postgres/postgres.git synced 2025-11-10 17:42:29 +03:00

Generalize TRUNCATE to support truncating multiple tables in one

command.  This is useful because we can allow truncation of tables
referenced by foreign keys, so long as the referencing table is
truncated in the same command.

Alvaro Herrera
This commit is contained in:
Tom Lane
2005-01-27 03:19:37 +00:00
parent 4fe201237f
commit f07b9689c9
14 changed files with 398 additions and 180 deletions

View File

@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.279 2005/01/10 20:02:19 tgl Exp $
* $PostgreSQL: pgsql/src/backend/catalog/heap.c,v 1.280 2005/01/27 03:17:17 tgl Exp $
*
*
* INTERFACE ROUTINES
@@ -1985,99 +1985,149 @@ RelationTruncateIndexes(Oid heapId)
/*
* heap_truncate
*
* This routine deletes all data within the specified relation.
* This routine deletes all data within all the specified relations.
*
* This is not transaction-safe! There is another, transaction-safe
* implementation in commands/cluster.c. We now use this only for
* implementation in commands/tablecmds.c. We now use this only for
* ON COMMIT truncation of temporary tables, where it doesn't matter.
*/
void
heap_truncate(Oid rid)
heap_truncate(List *relids)
{
Relation rel;
Oid toastrelid;
List *relations = NIL;
ListCell *cell;
/* Open relation for processing, and grab exclusive access on it. */
rel = heap_open(rid, AccessExclusiveLock);
/* Open relations for processing, and grab exclusive access on each */
foreach(cell, relids)
{
Oid rid = lfirst_oid(cell);
Relation rel;
Oid toastrelid;
rel = heap_open(rid, AccessExclusiveLock);
relations = lappend(relations, rel);
/* If there is a toast table, add it to the list too */
toastrelid = rel->rd_rel->reltoastrelid;
if (OidIsValid(toastrelid))
{
rel = heap_open(toastrelid, AccessExclusiveLock);
relations = lappend(relations, rel);
}
}
/* Don't allow truncate on tables that are referenced by foreign keys */
heap_truncate_check_FKs(rel);
heap_truncate_check_FKs(relations, true);
/*
* Release any buffers associated with this relation. If they're
* dirty, they're just dropped without bothering to flush to disk.
*/
DropRelationBuffers(rel);
/* OK to do it */
foreach(cell, relations)
{
Relation rel = lfirst(cell);
/* Now truncate the actual data */
RelationTruncate(rel, 0);
/*
* Release any buffers associated with this relation. If they're
* dirty, they're just dropped without bothering to flush to disk.
*/
DropRelationBuffers(rel);
/* If this relation has indexes, truncate the indexes too */
RelationTruncateIndexes(rid);
/* Now truncate the actual data */
RelationTruncate(rel, 0);
/* If it has a toast table, recursively truncate that too */
toastrelid = rel->rd_rel->reltoastrelid;
if (OidIsValid(toastrelid))
heap_truncate(toastrelid);
/* If this relation has indexes, truncate the indexes too */
RelationTruncateIndexes(RelationGetRelid(rel));
/*
* Close the relation, but keep exclusive lock on it until commit.
*/
heap_close(rel, NoLock);
/*
* Close the relation, but keep exclusive lock on it until commit.
*/
heap_close(rel, NoLock);
}
}
/*
* heap_truncate_check_FKs
* Check for foreign keys referencing a relation that's to be truncated
* Check for foreign keys referencing a list of relations that
* are to be truncated
*
* We disallow such FKs (except self-referential ones) since the whole point
* of TRUNCATE is to not scan the individual rows to be thrown away.
*
* This is split out so it can be shared by both implementations of truncate.
* Caller should already hold a suitable lock on the relation.
* Caller should already hold a suitable lock on the relations.
*
* tempTables is only used to select an appropriate error message.
*/
void
heap_truncate_check_FKs(Relation rel)
heap_truncate_check_FKs(List *relations, bool tempTables)
{
Oid relid = RelationGetRelid(rel);
ScanKeyData key;
List *oids = NIL;
ListCell *cell;
Relation fkeyRel;
SysScanDesc fkeyScan;
HeapTuple tuple;
/*
* Fast path: if the relation has no triggers, it surely has no FKs
* either.
* Build a list of OIDs of the interesting relations.
*
* If a relation has no triggers, then it can neither have FKs nor be
* referenced by a FK from another table, so we can ignore it.
*/
if (rel->rd_rel->reltriggers == 0)
foreach(cell, relations)
{
Relation rel = lfirst(cell);
if (rel->rd_rel->reltriggers != 0)
oids = lappend_oid(oids, RelationGetRelid(rel));
}
/*
* Fast path: if no relation has triggers, none has FKs either.
*/
if (oids == NIL)
return;
/*
* Otherwise, must scan pg_constraint. Right now, this is a seqscan
* Otherwise, must scan pg_constraint. Right now, it is a seqscan
* because there is no available index on confrelid.
*/
fkeyRel = heap_openr(ConstraintRelationName, AccessShareLock);
ScanKeyInit(&key,
Anum_pg_constraint_confrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relid));
fkeyScan = systable_beginscan(fkeyRel, NULL, false,
SnapshotNow, 1, &key);
SnapshotNow, 0, NULL);
while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
{
Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
if (con->contype == CONSTRAINT_FOREIGN && con->conrelid != relid)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate a table referenced in a foreign key constraint"),
errdetail("Table \"%s\" references \"%s\" via foreign key constraint \"%s\".",
get_rel_name(con->conrelid),
RelationGetRelationName(rel),
NameStr(con->conname))));
/* Not a foreign key */
if (con->contype != CONSTRAINT_FOREIGN)
continue;
/* Not for one of our list of tables */
if (! list_member_oid(oids, con->confrelid))
continue;
/* The referencer should be in our list too */
if (! list_member_oid(oids, con->conrelid))
{
if (tempTables)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("unsupported ON COMMIT and foreign key combination"),
errdetail("Table \"%s\" references \"%s\" via foreign key constraint \"%s\", but they do not have the same ON COMMIT setting.",
get_rel_name(con->conrelid),
get_rel_name(con->confrelid),
NameStr(con->conname))));
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate a table referenced in a foreign key constraint"),
errdetail("Table \"%s\" references \"%s\" via foreign key constraint \"%s\".",
get_rel_name(con->conrelid),
get_rel_name(con->confrelid),
NameStr(con->conname)),
errhint("Truncate table \"%s\" at the same time.",
get_rel_name(con->conrelid))));
}
}
systable_endscan(fkeyScan);

View File

@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.143 2005/01/24 23:21:57 tgl Exp $
* $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.144 2005/01/27 03:17:30 tgl Exp $
*
*-------------------------------------------------------------------------
*/
@@ -525,88 +525,113 @@ RemoveRelation(const RangeVar *relation, DropBehavior behavior)
}
/*
* TruncateRelation
* Removes all the rows from a relation.
* ExecuteTruncate
* Executes a TRUNCATE command.
*
* This is a multi-relation truncate. It first opens and grabs exclusive
* locks on all relations involved, checking permissions and otherwise
* verifying that the relation is OK for truncation. When they are all
* open, it checks foreign key references on them, namely that FK references
* are all internal to the group that's being truncated. Finally all
* relations are truncated and reindexed.
*/
void
TruncateRelation(const RangeVar *relation)
ExecuteTruncate(List *relations)
{
Relation rel;
Oid heap_relid;
Oid toast_relid;
List *rels = NIL;
ListCell *cell;
/* Grab exclusive lock in preparation for truncate */
rel = heap_openrv(relation, AccessExclusiveLock);
/* Only allow truncate on regular tables */
if (rel->rd_rel->relkind != RELKIND_RELATION)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table",
RelationGetRelationName(rel))));
/* Permissions checks */
if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(rel));
if (!allowSystemTableMods && IsSystemRelation(rel))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
RelationGetRelationName(rel))));
/*
* We can never allow truncation of shared or nailed-in-cache
* relations, because we can't support changing their relfilenode
* values.
*/
if (rel->rd_rel->relisshared || rel->rd_isnailed)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate system relation \"%s\"",
RelationGetRelationName(rel))));
/*
* Don't allow truncate on temp tables of other backends ... their
* local buffer manager is not going to cope.
*/
if (isOtherTempNamespace(RelationGetNamespace(rel)))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate temporary tables of other sessions")));
/*
* Don't allow truncate on tables which are referenced by foreign keys
*/
heap_truncate_check_FKs(rel);
/*
* Okay, here we go: create a new empty storage file for the relation,
* and assign it as the relfilenode value. The old storage file is
* scheduled for deletion at commit.
*/
setNewRelfilenode(rel);
heap_relid = RelationGetRelid(rel);
toast_relid = rel->rd_rel->reltoastrelid;
heap_close(rel, NoLock);
/*
* The same for the toast table, if any.
*/
if (OidIsValid(toast_relid))
foreach(cell, relations)
{
rel = relation_open(toast_relid, AccessExclusiveLock);
setNewRelfilenode(rel);
heap_close(rel, NoLock);
RangeVar *rv = lfirst(cell);
Relation rel;
/* Grab exclusive lock in preparation for truncate */
rel = heap_openrv(rv, AccessExclusiveLock);
/* Only allow truncate on regular tables */
if (rel->rd_rel->relkind != RELKIND_RELATION)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table",
RelationGetRelationName(rel))));
/* Permissions checks */
if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
RelationGetRelationName(rel));
if (!allowSystemTableMods && IsSystemRelation(rel))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied: \"%s\" is a system catalog",
RelationGetRelationName(rel))));
/*
* We can never allow truncation of shared or nailed-in-cache
* relations, because we can't support changing their relfilenode
* values.
*/
if (rel->rd_rel->relisshared || rel->rd_isnailed)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate system relation \"%s\"",
RelationGetRelationName(rel))));
/*
* Don't allow truncate on temp tables of other backends ... their
* local buffer manager is not going to cope.
*/
if (isOtherTempNamespace(RelationGetNamespace(rel)))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot truncate temporary tables of other sessions")));
/* Save it into the list of rels to truncate */
rels = lappend(rels, rel);
}
/*
* Reconstruct the indexes to match, and we're done.
* Check foreign key references.
*/
reindex_relation(heap_relid, true);
heap_truncate_check_FKs(rels, false);
/*
* OK, truncate each table.
*/
foreach(cell, rels)
{
Relation rel = lfirst(cell);
Oid heap_relid;
Oid toast_relid;
/*
* Create a new empty storage file for the relation, and assign it as
* the relfilenode value. The old storage file is scheduled for
* deletion at commit.
*/
setNewRelfilenode(rel);
heap_relid = RelationGetRelid(rel);
toast_relid = rel->rd_rel->reltoastrelid;
heap_close(rel, NoLock);
/*
* The same for the toast table, if any.
*/
if (OidIsValid(toast_relid))
{
rel = relation_open(toast_relid, AccessExclusiveLock);
setNewRelfilenode(rel);
heap_close(rel, NoLock);
}
/*
* Reconstruct the indexes to match, and we're done.
*/
reindex_relation(heap_relid, true);
}
}
/*----------
@@ -6013,6 +6038,7 @@ void
PreCommit_on_commit_actions(void)
{
ListCell *l;
List *oids_to_truncate = NIL;
foreach(l, on_commits)
{
@@ -6029,8 +6055,7 @@ PreCommit_on_commit_actions(void)
/* Do nothing (there shouldn't be such entries, actually) */
break;
case ONCOMMIT_DELETE_ROWS:
heap_truncate(oc->relid);
CommandCounterIncrement(); /* XXX needed? */
oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
break;
case ONCOMMIT_DROP:
{
@@ -6051,6 +6076,11 @@ PreCommit_on_commit_actions(void)
}
}
}
if (oids_to_truncate != NIL)
{
heap_truncate(oids_to_truncate);
CommandCounterIncrement(); /* XXX needed? */
}
}
/*

View File

@@ -15,7 +15,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/copyfuncs.c,v 1.295 2004/12/31 21:59:55 pgsql Exp $
* $PostgreSQL: pgsql/src/backend/nodes/copyfuncs.c,v 1.296 2005/01/27 03:17:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
@@ -1815,7 +1815,7 @@ _copyTruncateStmt(TruncateStmt *from)
{
TruncateStmt *newnode = makeNode(TruncateStmt);
COPY_NODE_FIELD(relation);
COPY_NODE_FIELD(relations);
return newnode;
}

View File

@@ -18,7 +18,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/equalfuncs.c,v 1.234 2004/12/31 21:59:55 pgsql Exp $
* $PostgreSQL: pgsql/src/backend/nodes/equalfuncs.c,v 1.235 2005/01/27 03:17:45 tgl Exp $
*
*-------------------------------------------------------------------------
*/
@@ -891,7 +891,7 @@ _equalDropStmt(DropStmt *a, DropStmt *b)
static bool
_equalTruncateStmt(TruncateStmt *a, TruncateStmt *b)
{
COMPARE_NODE_FIELD(relation);
COMPARE_NODE_FIELD(relations);
return true;
}

View File

@@ -11,7 +11,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.481 2004/12/31 22:00:27 pgsql Exp $
* $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.482 2005/01/27 03:17:59 tgl Exp $
*
* HISTORY
* AUTHOR DATE MAJOR EVENT
@@ -2681,15 +2681,15 @@ attrs: '.' attr_name
/*****************************************************************************
*
* QUERY:
* truncate table relname
* truncate table relname1, relname2, ...
*
*****************************************************************************/
TruncateStmt:
TRUNCATE opt_table qualified_name
TRUNCATE opt_table qualified_name_list
{
TruncateStmt *n = makeNode(TruncateStmt);
n->relation = $3;
n->relations = $3;
$$ = (Node *)n;
}
;

View File

@@ -10,7 +10,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/tcop/utility.c,v 1.232 2005/01/24 17:46:16 tgl Exp $
* $PostgreSQL: pgsql/src/backend/tcop/utility.c,v 1.233 2005/01/27 03:18:10 tgl Exp $
*
*-------------------------------------------------------------------------
*/
@@ -575,7 +575,7 @@ ProcessUtility(Node *parsetree,
{
TruncateStmt *stmt = (TruncateStmt *) parsetree;
TruncateRelation(stmt->relation);
ExecuteTruncate(stmt->relations);
}
break;