pgsql: Make TRUNCATE ... RESTART IDENTITY restart sequences transaction

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: pgsql-committers(at)postgresql(dot)org
Subject: pgsql: Make TRUNCATE ... RESTART IDENTITY restart sequences transaction
Date: 2010-11-17 21:43:06
Message-ID: E1PIpmU-0007j5-Av@gemulon.postgresql.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Make TRUNCATE ... RESTART IDENTITY restart sequences transactionally.

In the previous coding, we simply issued ALTER SEQUENCE RESTART commands,
which do not roll back on error. This meant that an error between
truncating and committing left the sequences out of sync with the table
contents, with potentially bad consequences as were noted in a Warning on
the TRUNCATE man page.

To fix, create a new storage file (relfilenode) for a sequence that is to
be reset due to RESTART IDENTITY. If the transaction aborts, we'll
automatically revert to the old storage file. This acts just like a
rewriting ALTER TABLE operation. A penalty is that we have to take
exclusive lock on the sequence, but since we've already got exclusive lock
on its owning table, that seems unlikely to be much of a problem.

The interaction of this with usual nontransactional behaviors of sequence
operations is a bit weird, but it's hard to see what would be completely
consistent. Our choice is to discard cached-but-unissued sequence values
both when the RESTART is executed, and at rollback if any; but to not touch
the currval() state either time.

In passing, move the sequence reset operations to happen before not after
any AFTER TRUNCATE triggers are fired. The previous ordering was not
logically sensible, but was forced by the need to minimize inconsistency
if the triggers caused an error. Transactional rollback is a much better
solution to that.

Patch by Steve Singer, rather heavily adjusted by me.

Branch
------
master

Details
-------
http://git.postgresql.org/gitweb?p=postgresql.git;a=commitdiff;h=511e902b51c2a1c0d012426ceb6486b1202120f3

Modified Files
--------------
doc/src/sgml/ref/truncate.sgml | 63 ++++++-------
src/backend/commands/sequence.c | 152 ++++++++++++++++++++++++-------
src/backend/commands/tablecmds.c | 38 +++-----
src/backend/utils/cache/relcache.c | 18 +++--
src/include/commands/sequence.h | 2 +-
src/test/regress/expected/truncate.out | 22 +++++
src/test/regress/sql/truncate.sql | 10 ++
7 files changed, 203 insertions(+), 102 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Robert Haas 2010-11-18 01:51:21 pgsql: Document the dummy_seclabel contrib module.
Previous Message Peter Eisentraut 2010-11-17 06:09:43 pgsql: Additional fixes for parallel make