Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions doc/api/sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,120 @@ changes:
Compiles a SQL statement into a [prepared statement][]. This method is a wrapper
around [`sqlite3_prepare_v3()`][].

### `database.transaction(fn[, options])`

<!-- YAML
added: REPLACEME
-->

* `fn` {Function} The function to run inside the transaction. It is called
synchronously with no arguments.
* `options` {Object} Optional configuration for the transaction.
* `mode` {string} The type of transaction to start. Must be one of
`'deferred'`, `'immediate'`, or `'exclusive'`. This option is ignored if a
transaction is already active. **Default:** `'deferred'`.
* Returns: {any} The value returned by `fn`.

Runs `fn` inside a transaction. The transaction is started with [`BEGIN`][]
before `fn` is called and is committed when `fn` returns. If `fn` throws, the
transaction is rolled back and the error is rethrown. If the commit fails, the
transaction is rolled back and the error is thrown.

If a transaction is already active, including one started by executing `BEGIN`
directly, a [`SAVEPOINT`][] is used instead. This allows calls to
`database.transaction()` to be nested. If a nested `fn` throws, only the changes
made by that call are undone, and the enclosing transaction can still be
committed if the error is handled.

`fn` must be synchronous. If it returns a `Promise`, the transaction is rolled
back and an [`ERR_INVALID_RETURN_VALUE`][] error is thrown.

If `fn` ends the transaction itself, for example by executing `COMMIT` or
`ROLLBACK`, this method does not commit or roll back when `fn` returns.

The statements this method executes to manage the transaction are subject to
the authorizer callback set with [`database.setAuthorizer()`][]. They are also
published to the [`'sqlite.db.query'`][] channel, except for the rollback that
follows an error.

```mjs
import { Database } from 'node:sqlite';

const db = new Database(':memory:');
db.exec('CREATE TABLE accounts(id INTEGER PRIMARY KEY, balance INTEGER)');
db.exec('INSERT INTO accounts VALUES (1, 100), (2, 0)');

using withdraw = db.prepare(
'UPDATE accounts SET balance = balance - ? WHERE id = ?');
using deposit = db.prepare(
'UPDATE accounts SET balance = balance + ? WHERE id = ?');
using balances = db.prepare('SELECT balance FROM accounts ORDER BY id');

function transfer(amount, from, to) {
return db.transaction(() => {
withdraw.run(amount, from);
deposit.run(amount, to);
return amount;
}, { mode: 'immediate' });
}

console.log(transfer(40, 1, 2));
// Prints: 40
console.log(balances.all());
// Prints: [ { balance: 60 }, { balance: 40 } ]

try {
db.transaction(() => {
withdraw.run(10, 1);
throw new Error('Transfer cancelled');
});
} catch (err) {
console.log(err.message);
// Prints: Transfer cancelled
}
console.log(balances.all());
// Prints: [ { balance: 60 }, { balance: 40 } ]
```

```cjs
const { Database } = require('node:sqlite');

const db = new Database(':memory:');
db.exec('CREATE TABLE accounts(id INTEGER PRIMARY KEY, balance INTEGER)');
db.exec('INSERT INTO accounts VALUES (1, 100), (2, 0)');

using withdraw = db.prepare(
'UPDATE accounts SET balance = balance - ? WHERE id = ?');
using deposit = db.prepare(
'UPDATE accounts SET balance = balance + ? WHERE id = ?');
using balances = db.prepare('SELECT balance FROM accounts ORDER BY id');

function transfer(amount, from, to) {
return db.transaction(() => {
withdraw.run(amount, from);
deposit.run(amount, to);
return amount;
}, { mode: 'immediate' });
}

console.log(transfer(40, 1, 2));
// Prints: 40
console.log(balances.all());
// Prints: [ { balance: 60 }, { balance: 40 } ]

try {
db.transaction(() => {
withdraw.run(10, 1);
throw new Error('Transfer cancelled');
});
} catch (err) {
console.log(err.message);
// Prints: Transfer cancelled
}
console.log(balances.all());
// Prints: [ { balance: 60 }, { balance: 40 } ]
```

### `database.createTagStore([maxSize])`

<!-- YAML
Expand Down Expand Up @@ -2171,8 +2285,11 @@ callback function to indicate what type of operation is being authorized.
[Writing numbers and BigInts]: #writing-numbers-and-bigints
[`'sqlite.db.query'`]: diagnostics_channel.md#event-sqlitedbquery
[`ATTACH DATABASE`]: https://www.sqlite.org/lang_attach.html
[`BEGIN`]: https://www.sqlite.org/lang_transaction.html
[`ERR_INVALID_RETURN_VALUE`]: errors.md#err_invalid_return_value
[`ERR_INVALID_STATE`]: errors.md#err_invalid_state
[`PRAGMA foreign_keys`]: https://www.sqlite.org/pragma.html#pragma_foreign_keys
[`SAVEPOINT`]: https://www.sqlite.org/lang_savepoint.html
[`SQLITE_DBCONFIG_DEFENSIVE`]: https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigdefensive
[`SQLITE_DETERMINISTIC`]: https://www.sqlite.org/c3ref/c_deterministic.html
[`SQLITE_DIRECTONLY`]: https://www.sqlite.org/c3ref/c_deterministic.html
Expand Down
1 change: 1 addition & 0 deletions src/node_errors.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ void OOMErrorHandler(const char* location, const v8::OOMDetails& details);
V(ERR_INVALID_PACKAGE_CONFIG, Error) \
V(ERR_INVALID_OBJECT_DEFINE_PROPERTY, TypeError) \
V(ERR_INVALID_MODULE, Error) \
V(ERR_INVALID_RETURN_VALUE, TypeError) \
V(ERR_INVALID_STATE, Error) \
V(ERR_INVALID_THIS, TypeError) \
V(ERR_INVALID_URL, TypeError) \
Expand Down
122 changes: 122 additions & 0 deletions src/node_sqlite.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2329,6 +2329,127 @@ void Database::Exec(const FunctionCallbackInfo<Value>& args) {
CHECK_ERROR_OR_THROW(env->isolate(), db, r, SQLITE_OK, void());
}

// SQLite resolves savepoint names newest-first, so one name covers any depth.
static constexpr char kTransactionSavepointSql[] =
"SAVEPOINT node_sqlite_transaction";
static constexpr char kTransactionReleaseSql[] =
"RELEASE node_sqlite_transaction";
static constexpr char kTransactionRollbackToSql[] =
"ROLLBACK TO node_sqlite_transaction; RELEASE node_sqlite_transaction";

static bool InTransaction(Database* db) {
return sqlite3_get_autocommit(db->Connection()) == 0;
}

static int ExecTransactionSql(Database* db, const char* sql) {
return sqlite3_exec(db->Connection(), sql, nullptr, nullptr, nullptr);
}

// Returns the BEGIN statement for options.mode, or nullptr after throwing.
static const char* ReadTransactionBeginSql(Environment* env,
Local<Value> options) {
std::string mode = "deferred";
if (!options->IsUndefined()) {
if (!options->IsObject()) {
THROW_ERR_INVALID_ARG_TYPE(env->isolate(),
"The \"options\" argument must be an object.");
return nullptr;
}
if (!ReadOptionalString(env, options.As<Object>(), "mode", &mode)) {
return nullptr;
}
}

if (mode == "deferred") return "BEGIN DEFERRED";
if (mode == "immediate") return "BEGIN IMMEDIATE";
if (mode == "exclusive") return "BEGIN EXCLUSIVE";
THROW_ERR_INVALID_ARG_VALUE(
env->isolate(),
"The \"options.mode\" argument must be one of 'deferred', 'immediate', "
"or 'exclusive'.");
return nullptr;
}

// Calls fn and commits. Returns an empty handle with an exception pending on
// failure, leaving any rollback to the caller.
static MaybeLocal<Value> CallAndCommit(Environment* env,
Database* db,
Local<Function> fn,
bool nested) {
Isolate* isolate = env->isolate();
Local<Value> result;
if (!fn->Call(env->context(), Undefined(isolate), 0, nullptr)
.ToLocal(&result)) {
return {};
}

if (result->IsPromise()) {
THROW_ERR_INVALID_RETURN_VALUE(
isolate,
"Expected a non-Promise value to be returned from the \"fn\" function "
"but got an instance of Promise.");
return {};
}

if (!db->IsOpen()) {
THROW_ERR_INVALID_STATE(env, "database is not open");
return {};
}

// fn may have ended the transaction itself.
if (InTransaction(db)) {
int r = ExecTransactionSql(db, nested ? kTransactionReleaseSql : "COMMIT");
CHECK_ERROR_OR_THROW(isolate, db, r, SQLITE_OK, MaybeLocal<Value>());
}

return result;
}

void Database::Transaction(const FunctionCallbackInfo<Value>& args) {
Database* db;
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);

if (!args[0]->IsFunction()) {
THROW_ERR_INVALID_ARG_TYPE(isolate,
"The \"fn\" argument must be a function.");
return;
}

const char* begin_sql = ReadTransactionBeginSql(env, args[1]);
if (begin_sql == nullptr) return;

// An options getter may have closed the database or begun a transaction.
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
const bool nested = InTransaction(db);

// fn may drop every other reference to the database.
BaseObjectPtr<Database> guard(db);

int r = ExecTransactionSql(db, nested ? kTransactionSavepointSql : begin_sql);
CHECK_ERROR_OR_THROW(isolate, db, r, SQLITE_OK, void());

TryCatch try_catch(isolate);
Local<Value> result;
if (CallAndCommit(env, db, args[0].As<Function>(), nested).ToLocal(&result)) {
args.GetReturnValue().Set(result);
return;
}

// Best effort: a failed rollback must not replace the caught exception.
if (db->IsOpen() && InTransaction(db)) {
TryCatch rollback_try_catch(isolate);
USE(ExecTransactionSql(db,
nested ? kTransactionRollbackToSql : "ROLLBACK"));
db->SetIgnoreNextSQLiteError(false);
}

if (try_catch.HasCaught()) try_catch.ReThrow();
}

void Database::CustomFunction(const FunctionCallbackInfo<Value>& args) {
Database* db;
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
Expand Down Expand Up @@ -5159,6 +5280,7 @@ static void Initialize(Local<Object> target,
SetProtoDispose(isolate, db_tmpl, Database::Dispose);
SetProtoMethod(isolate, db_tmpl, "prepare", Database::Prepare);
SetProtoMethod(isolate, db_tmpl, "exec", Database::Exec);
SetProtoMethod(isolate, db_tmpl, "transaction", Database::Transaction);
SetProtoMethod(isolate, db_tmpl, "function", Database::CustomFunction);
SetProtoMethod(
isolate, db_tmpl, "createTagStore", Database::CreateTagStore);
Expand Down
1 change: 1 addition & 0 deletions src/node_sqlite.h
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ class Database : public BaseObject {
static void Dispose(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Prepare(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Exec(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Transaction(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CreateTagStore(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Location(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CustomFunction(const v8::FunctionCallbackInfo<v8::Value>& args);
Expand Down
1 change: 1 addition & 0 deletions test/parallel/test-sqlite-authz.js
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ suite('authorizer callback reentrancy', () => {
const cases = {
prepare: () => db.prepare('SELECT 1'),
exec: () => db.exec('SELECT 1'),
transaction: () => db.transaction(() => {}),
setAuthorizer: () => db.setAuthorizer(null),
createSession: () => db.createSession(),
applyChangeset: () => db.applyChangeset(new Uint8Array([1])),
Expand Down
44 changes: 44 additions & 0 deletions test/parallel/test-sqlite-diagnostic-channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,50 @@ suite('sqlite.db.query diagnostics channel', () => {
]);
});

it('subscriber receives the statements run by transaction()', (t) => {
let calls = [];
using db = new Database(':memory:');

const handler = (msg) => calls.push(msg.sql);
dc.subscribe('sqlite.db.query', handler);
t.after(() => dc.unsubscribe('sqlite.db.query', handler));

db.exec('CREATE TABLE t (x INTEGER)');
calls = []; // reset after setup

db.transaction(() => {
db.exec('INSERT INTO t VALUES (1)');
db.transaction(() => {});
}, { mode: 'immediate' });

assert.deepStrictEqual(calls, [
'BEGIN IMMEDIATE',
'INSERT INTO t VALUES (1)',
'SAVEPOINT node_sqlite_transaction',
'RELEASE node_sqlite_transaction',
'COMMIT',
]);
});

it('transaction() rethrows the error from fn with a subscriber', (t) => {
using db = new Database(':memory:');

const handler = () => {};
dc.subscribe('sqlite.db.query', handler);
t.after(() => dc.unsubscribe('sqlite.db.query', handler));

db.exec('CREATE TABLE t (x INTEGER)');
const err = new Error('boom');
assert.throws(() => {
db.transaction(() => {
db.exec('INSERT INTO t VALUES (1)');
throw err;
});
}, (thrown) => thrown === err);
assert.strictEqual(db.isTransaction, false);
assert.deepStrictEqual(db.prepare('SELECT x FROM t').all(), []);
});

it('does not replace an exception that is already pending', (t) => {
using db = new Database(':memory:');
let calls = 0;
Expand Down
Loading
Loading