Class: Database
Constructors
Constructor
new Database(
dbName,options):Database
Opens a SQLite database.
Parameters
dbName
string
The path of the database. Defaults to :memory:, which
opens an in-memory database.
options
Options when opening the database.
Returns
Database
Methods
close()
close():
void
Closes the database. No further operations can be performed afterwards.
Returns
void
exec()
exec(
sql):void
Execute the given SQL statement(s).
Parameters
sql
string
The SQL statement(s) that will run.
Returns
void
loadExtension()
loadExtension(
file,entrypoint?):undefined
Load an extension from file
Parameters
file
string
location of the shared library
entrypoint?
string
entrypoint, if left empty a guess is made by sqlite
Returns
undefined
prepare()
prepare(
sql):IStatement
Create a prepared statement, to run SQL queries.
Parameters
sql
string
The SQL query that will run.
Returns
transaction()
transaction(
fn):ITransaction
Wrap the given function so it runs in a transaction. When the (returned) function is invoked, it will start a new transaction. When the function returns, the transaction will be committed. If an exception is thrown, the transaction will be rolled back.
const ins = db.prepare('INSERT INTO test (txt, int) VALUES(?, ?)');
const insMany = db.transaction(datas => {
for (const data of datas) {
ins.run(data);
}
});
insMany([
[ '1234', 1234 ],
[ '4321', 4321 ],
]);
Transaction functions can be called from inside other transaction functions. When doing so, the inner transaction becomes a savepoint. If an error is thrown inside of a nested transaction function, the nested transaction function will roll back to the state just before the savepoint. If the error is not caught in the outer transaction function, this will cause the outer transaction function to roll back as well.
Transactions also come with deferred, immediate, and exclusive versions:
insertMany(datas); // uses "BEGIN"
insertMany.deferred(datas); // uses "BEGIN DEFERRED"
insertMany.immediate(datas); // uses "BEGIN IMMEDIATE"
insertMany.exclusive(datas); // uses "BEGIN EXCLUSIVE"
NOTE: This implementation was mostly taken from better-sqlite3.
Parameters
fn
Function
The function to be wrapped in a transaction.