Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAVEPOINT mechanism in SQLite

I am trying to understand Savepoints and Transactions in SQLite. I had the following commands on a Table/Database and I am using Savepoints.

SAVEPOINT aaa;
RELEASE aaa;
BEGIN;

Now, if I execute all the above statements at once, its throwing an error saying that A transaction cannot be started inside another transaction. If I run them one at a time, it works fine. if I run the first two Savepoint and release commands and try to start another transaction by executing the Begin. it again throws the same error as previous.

The link here says that

If the SAVEPOINT command is issued when SQLite is in autocommit mode—that is, outside of a transaction—then a standard autocommit BEGIN DEFERRED TRANSACTION will be started. However, unlike with most commands, the autocommit transaction will not automatically commit after the SAVEPOINT command returns, leaving the system inside an open transaction. The automatic transaction will remain active until the original save-point is released, or the outer transaction is either explicitly committed or rolled back. `

So, Is it absolutely necessary for a Commit or Rollback command after the Release Savepoint Command? Doesn't release command commit and allow us to start a new transaction using BEGIN?

like image 641
Programmerzzz Avatar asked Nov 08 '22 11:11

Programmerzzz


1 Answers

SAVEPOINT aaa; RELEASE aaa; BEGIN;

is interpreted by sqlite as

BEGIN DEFERRED TRANSACTION; SAVEPOINT aaa; // Create a transaction, and mark current db state as savepoint "aaa" [1] RELEASE aaa; // Remove all db changes made since savepoint "aaa", but keep on executing the transaction BEGIN; // Create another transaction, while there is already a transaction. This will FAIL because there cannot be 2 transactions executed simultaneously

The following would be fine:

BEGIN; SAVEPOINT "aaa"; RELEASE "aaa"; COMMIT; BEGIN;

[1] https://sqlite.org/lang_savepoint.html

like image 109
David Andreoletti Avatar answered Nov 15 '22 12:11

David Andreoletti