Skip to content

Commit

Permalink
sqlite: reset statement immediately in run()
Browse files Browse the repository at this point in the history
This commit updates StatementSync.prototype.run() to reset the
prepared statement immediately after calling sqlite3_step() to
return the correct change metadata.

Fixes: #57344
  • Loading branch information
cjihrig committed Mar 6, 2025
1 parent ded4eca commit f69726f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
10 changes: 3 additions & 7 deletions src/node_sqlite.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1866,13 +1866,9 @@ void StatementSync::Run(const FunctionCallbackInfo<Value>& args) {
return;
}

auto reset = OnScopeLeave([&]() { sqlite3_reset(stmt->statement_); });
r = sqlite3_step(stmt->statement_);
if (r != SQLITE_ROW && r != SQLITE_DONE) {
THROW_ERR_SQLITE_ERROR(env->isolate(), stmt->db_.get());
return;
}

sqlite3_step(stmt->statement_);
r = sqlite3_reset(stmt->statement_);
CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_.get(), r, SQLITE_OK, void());
Local<Object> result = Object::New(env->isolate());
sqlite3_int64 last_insert_rowid =
sqlite3_last_insert_rowid(stmt->db_->Connection());
Expand Down
19 changes: 19 additions & 0 deletions test/parallel/test-sqlite-statement-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,25 @@ suite('StatementSync.prototype.run()', () => {
errstr: 'constraint failed',
});
});

test('returns correct metadata when using RETURNING', (t) => {
const db = new DatabaseSync(':memory:');
const setup = db.exec(
'CREATE TABLE data(key INTEGER PRIMARY KEY, val INTEGER NOT NULL) STRICT;'
);
t.assert.strictEqual(setup, undefined);
const sql = 'INSERT INTO data (key, val) VALUES ($k, $v) RETURNING key';
const stmt = db.prepare(sql);
t.assert.deepStrictEqual(
stmt.run({ k: 1, v: 10 }), { changes: 1, lastInsertRowid: 1 }
);
t.assert.deepStrictEqual(
stmt.run({ k: 2, v: 20 }), { changes: 1, lastInsertRowid: 2 }
);
t.assert.deepStrictEqual(
stmt.run({ k: 3, v: 30 }), { changes: 1, lastInsertRowid: 3 }
);
});
});

suite('StatementSync.prototype.sourceSQL', () => {
Expand Down

0 comments on commit f69726f

Please sign in to comment.