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
4 changes: 4 additions & 0 deletions doc/api/sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,10 @@ added:
attempt is made to apply any changes to the table.
Otherwise, if the return value is truthy or no `filter` callback is provided,
all changes related to the table are attempted.
When an error is thrown in the `filter` callback, applying the changeset is
aborted, any changes already applied by this call are rolled back, and the
error is rethrown. Changes made before the call, including those in a
transaction that is still open, are kept.
* `onConflict` {Function} A function that determines how to handle conflicts. The function receives one argument,
which can be one of the following values:

Expand Down
42 changes: 42 additions & 0 deletions src/node_sqlite.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3211,7 +3211,22 @@ void Database::ApplyChangeset(const FunctionCallbackInfo<Value>& args) {
std::memcpy(changeset->Data(), buf.data(), buf.length());
}

// A filter callback that throws can only make SQLite skip the remaining
// tables (xFilter cannot abort the apply), so tables accepted before the
// exception would stay applied. Wrap the apply in a savepoint so it can be
// undone in that case. A savepoint, rather than a transaction, leaves any
// transaction the caller already has open, and its earlier writes, intact.
int r;
const bool use_savepoint = static_cast<bool>(context.filterCallback);
if (use_savepoint) {
r = sqlite3_exec(db->connection_.get(),
"SAVEPOINT node_sqlite_apply_changeset",
nullptr,
nullptr,
nullptr);
CHECK_ERROR_OR_THROW(env->isolate(), db, r, SQLITE_OK, void());
}

{
CallbackDepthGuard guard(db);
r = sqlite3changeset_apply(
Expand All @@ -3223,6 +3238,33 @@ void Database::ApplyChangeset(const FunctionCallbackInfo<Value>& args) {
xConflict,
static_cast<void*>(&context));
}
if (use_savepoint) {
// Mirrors how sqlite3changeset_apply() handles its own savepoint.
int release_r = SQLITE_ERROR;
if (!filterCallbackFailed) {
release_r = sqlite3_exec(db->connection_.get(),
"RELEASE node_sqlite_apply_changeset",
nullptr,
nullptr,
nullptr);
}
if (release_r != SQLITE_OK) {
sqlite3_exec(db->connection_.get(),
"ROLLBACK TO node_sqlite_apply_changeset",
nullptr,
nullptr,
nullptr);
sqlite3_exec(db->connection_.get(),
"RELEASE node_sqlite_apply_changeset",
nullptr,
nullptr,
nullptr);
}
// The exception thrown by the filter callback is still pending and is
// propagated to JavaScript.
if (filterCallbackFailed) return;
if (r == SQLITE_OK) r = release_r;
}
if (r == SQLITE_OK) {
args.GetReturnValue().Set(true);
return;
Expand Down
62 changes: 62 additions & 0 deletions test/parallel/test-sqlite-session.js
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,68 @@ test('filter handler throws', (t) => {
});
});

suite('filter handler throws after accepting a table', () => {
const createTableSql = `
CREATE TABLE a(id INTEGER PRIMARY KEY, v);
CREATE TABLE b(id INTEGER PRIMARY KEY, v);
CREATE TABLE marker(id INTEGER);
`;

function prepare() {
const source = new Database(':memory:');
const target = new Database(':memory:');
source.exec(createTableSql);
target.exec(createTableSql);
const session = source.createSession();
source.exec("INSERT INTO a VALUES (1, 'x'); INSERT INTO b VALUES (1, 'y')");
return { target, changeset: session.changeset() };
}

function count(db, table) {
return db.prepare(`SELECT count(*) AS n FROM ${table}`).get().n;
}

const filterError = new Error('filter failed for b');
const filter = (table) => {
if (table === 'b') throw filterError;
return true;
};

test('rolls back the tables applied before the exception', (t) => {
const { target, changeset } = prepare();
t.assert.throws(() => target.applyChangeset(changeset, { filter }),
(err) => err === filterError);
t.assert.strictEqual(count(target, 'a'), 0);
t.assert.strictEqual(count(target, 'b'), 0);
t.assert.strictEqual(target.isTransaction, false);
});

test('keeps an open outer transaction and its earlier writes', (t) => {
const { target, changeset } = prepare();
target.exec('BEGIN; INSERT INTO marker VALUES (7)');
t.assert.throws(() => target.applyChangeset(changeset, { filter }),
(err) => err === filterError);
t.assert.strictEqual(target.isTransaction, true);
t.assert.strictEqual(count(target, 'a'), 0);
t.assert.strictEqual(count(target, 'b'), 0);
t.assert.strictEqual(count(target, 'marker'), 1);
target.exec('INSERT INTO marker VALUES (8); COMMIT');
t.assert.strictEqual(count(target, 'marker'), 2);
});

test('a filter that does not throw leaves the outer transaction open',
(t) => {
const { target, changeset } = prepare();
target.exec('BEGIN');
t.assert.strictEqual(
target.applyChangeset(changeset, { filter: () => true }), true);
t.assert.strictEqual(target.isTransaction, true);
target.exec('ROLLBACK');
t.assert.strictEqual(count(target, 'a'), 0);
t.assert.strictEqual(count(target, 'b'), 0);
});
});

test('database.applyChangeset() - changeset detached by filter', (t) => {
const database1 = new Database(':memory:');
const database2 = new Database(':memory:');
Expand Down