Search code examples
ruby-on-railspostgresqltransactionstruncatepg

Keep data available during a transaction (postgresql)


Why can't I access data during a transaction with a truncate statement ?

I though it would be possible to read the data of a table while a transaction is running on the same table. It is possible as long as you don't do a truncate statement. And I didn't found anything against it in the documentation.

Here is a sample project to illustrate this behavior and the README try to explain how to reproduce : https://github.com/Haelle/pg_transaction_tests

If it is not supposed to happen, it could be either an issue with ? :

  • my code...
  • ActiveRecord
  • gem pg
  • an option in Postgresql

Solution

  • This is something specific to postgresql, from the TRUNCATE documentation:

    TRUNCATE acquires an ACCESS EXCLUSIVE lock on each table it operates on, which blocks all other concurrent operations on the table. When RESTART IDENTITY is specified, any sequences that are to be restarted are likewise locked exclusively. If concurrent access to a table is required, then the DELETE command should be used instead.

    This is a very specific use-case you are stuck with. Not sure why one would need to be able to access the table, which is about to be truncated, during the transaction of the truncate. But, as the note says: use delete instead. In rails this means: .destroy_all (checks rails validations) or .delete_all (does not check rails validations)