Adds transactions support to node-sqlite3.
Node-sqlite3 is a great way how to access a SQLite database but id doesn't provide support for transactions yet. The underlying SQLite database can handle transactions easily so you can still do:
This works fine until you add an async operation between
COMMIT. The problem is that node-sqlite3 uses single connection to the database and thus queries from other places can end up intermixing with each other messing up the transactions.
Sqlite3-transactions solves this problem by transparently locking the database while in a transaction. If database is locked all queries which don't belong to the transaction are queued and executed after the transaction is finished. As a bonus you got a clean nice API for transactions.
npm install sqlite3npm install sqlite3-transactions
var sqlite3 =TransactionDatabase = TransactionDatabase;// Wrap sqlite3 databasevar db ="test.sqlite" sqlite3OPEN_READWRITE | sqlite3OPEN_CREATE;// Use db as normal sqlite3.Database object.db;// Begin a transaction.db
I haven't mentioned one feature in the example - on
error event automatic
rollback() is performed on the current transaction.
Call this method to start a transaction. The database is locked and all queries are queued until the transaction is over.
callback receives two parameters
transaction to perform operations directly with database. You must call
transaction.rollback() to finish the transaction and unlock the database. You don't have to
rollback() in the case:
errorpassed to the callback.
errorevent during the transaction.
Commits the transaction. The
callback(error) is called after the transaction is committed. If
error is set then the commit failed for some reason and rollback was performed instead.
Queued operations are executed after the actual commit but before the
callback. This helps to prevent starvation.
Rolls back the transaction. The
callback(error)is called after the operation is completed.
Remember to call
rollback() on each transaction otherwise you lock your DB forever.
sqlite3-transactions is in very early stage of development. Please help me test it.