Suppose a power loss or operating-system crash occurs in the middle of a transaction commit in SQLite. Only part of the changes associated with the commit will have been written to disk. This page overviews how the database is restored to its original state and made to appear as if nothing had ever been modified in the first place.
The diagram on the right shows the initial state of the disk following a power failure that occurred in the middle of a commit. We had intended to modify three pages of the database file, but only one page was fully written and another page was partially written. (The writes are shown in red.) The rollback journal still exists as a separate file on disk.
The next time SQLite tries to open the database file, it first obtains a shared lock (as described in Step 1 of SqliteTransaction). After obtaining a shared lock, SQLite always checks to see if there is a "hot journal" file. A hot journal is a rollback journal that is not part of a ongoing write by another process and which has not been deleted.
In this example, there is a hot journal.
Upon seeing a hot journal, SQLite realizes that it has to restore the database to its state prior to the start of the failed transaction before continuing. So it obtains an exclusive lock on the database file. The exclusive lock prevents two or more processes from trying to rollback the same hot journal at the same time.
If the process is unable to get an exclusive lock, it backs off. It releases its shared lock and returns SQLITE_BUSY.
To Be Continue....
- rollback-0.gif 7556 bytes added by drh on 2007-Apr-08 21:25:14 UTC.
- rollback-1.gif 7463 bytes added by drh on 2007-Apr-08 21:25:26 UTC.
- rollback-2.gif 7189 bytes added by drh on 2007-Apr-08 21:25:41 UTC.
- rollback-3.gif 8243 bytes added by drh on 2007-Apr-08 21:25:56 UTC.
- rollback-4.gif 8348 bytes added by drh on 2007-Apr-08 21:26:12 UTC.
- rollback-5.gif 7301 bytes added by drh on 2007-Apr-08 21:26:27 UTC.