mirror of
https://github.com/nodejs/node.git
synced 2026-11-21 12:59:16 -05:00
Expose SQLite's virtual table API through a new `database.createModule(name, options)` method, wrapping `sqlite3_create_module_v2()`. This enables read-only virtual tables backed by JavaScript data sources, usable either as an eponymous table (`SELECT * FROM module_name`) or via `CREATE VIRTUAL TABLE t USING module_name`. Hidden columns pass parameters using table-valued function syntax (`SELECT * FROM module_name(param1, param2)`). `options` accepts `columns`, `rows`, `directOnly`, and `useBigIntArguments`. Column types are validated against INTEGER, TEXT, REAL, BLOB, and ANY, and column names are quoted when building the `sqlite3_declare_vtab()` schema. Rebased from https://github.com/nodejs/node/pull/61544, which was opened by byteforge38 and became inactive. Changes on top of that work: - xColumn reports the value each hidden column was constrained to, rather than NULL. SQLite treats xBestIndex's `omit` as a hint, so it may recheck a constraint it already handed to xFilter; against NULL that recheck rejected every row, and `gs(1, 3) WHERE start = 1` returned no rows. - xBestIndex lowers estimatedCost as it consumes constraints. With a constant cost the planner was free to pick the unconstrained plan and recheck afterwards, so a correlated parameter such as `FROM t, gs(t.a, t.a + 1)` also returned no rows. - Violations of the iteration protocol report a SQLite error instead of calling PropagateJSError with no JavaScript exception pending. That left `.all()` returning undefined and `exec()` reporting success. - xBestIndex passes the constrained hidden-column indices to xFilter through idxStr rather than an int bitmask, which previously aliased for parameter indices at or above the width of an int. - xFilter, xNext, and xColumn take a CallbackDepthGuard. Without it close() from inside rows(), an iterator's next(), or a row getter finalized the statement that SQLite was still stepping, crashing the process. - xClose calls the iterator's return() method so generator `finally` blocks run when SQLite stops stepping early, as it does for LIMIT or a `break` out of a for...of loop. It is skipped while tearing down from ~StatementSync or ~DatabaseSync, which run from garbage collection callbacks where JavaScript cannot be executed; an abandoned generator does not run `finally` in JavaScript either. It is also skipped when an error is already pending, so that error still reaches the caller. - VirtualTableModule holds a BaseObjectWeakPtr<DatabaseSync> to match UserDefinedFunction instead of a raw pointer. - createModule() rejects being called from an authorizer callback. - Documents that values yielded by rows() follow the usual conversion rules, so a number is stored as REAL and a BigInt as INTEGER even when a column declares INTEGER, since virtual tables do not apply column affinity to the values they return. Refs: https://github.com/nodejs/node/pull/61544 Refs: https://github.com/nodejs/node/issues/63826 Fixes: https://github.com/nodejs/node/issues/61539 Co-authored-by: byteforge38 <stormcraft318@gmail.com> Signed-off-by: Trevor Burnham <trevorburnham@gmail.com> Assisted-by: Claude Opus 5 PR-URL: https://github.com/nodejs/node/pull/65787 Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
279 lines
8.0 KiB
JavaScript
279 lines
8.0 KiB
JavaScript
'use strict';
|
|
const { skipIfSQLiteMissing } = require('../common');
|
|
skipIfSQLiteMissing();
|
|
const tmpdir = require('../common/tmpdir');
|
|
const { join } = require('node:path');
|
|
const { backup, DatabaseSync } = require('node:sqlite');
|
|
const { suite, test } = require('node:test');
|
|
|
|
tmpdir.refresh();
|
|
|
|
const invalidState = {
|
|
code: 'ERR_INVALID_STATE',
|
|
message: /database is not open/,
|
|
};
|
|
|
|
// A property getter on the options bag runs arbitrary JavaScript in the middle
|
|
// of the call, so state validated before the options were read can be stale by
|
|
// the time it is used.
|
|
suite('closing the database from an options getter', () => {
|
|
test('prepare() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.prepare('SELECT 1', {
|
|
get returnArrays() {
|
|
db.close();
|
|
return false;
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('function() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.function('fn', {
|
|
get useBigIntArguments() {
|
|
db.close();
|
|
return false;
|
|
},
|
|
}, () => 1);
|
|
}, invalidState);
|
|
});
|
|
|
|
test('function() throws when the length getter closes the database', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
const fn = () => 1;
|
|
Object.defineProperty(fn, 'length', {
|
|
configurable: true,
|
|
get() {
|
|
db.close();
|
|
return 0;
|
|
},
|
|
});
|
|
t.assert.throws(() => {
|
|
db.function('fn', fn);
|
|
}, invalidState);
|
|
});
|
|
|
|
test('aggregate() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.aggregate('agg', {
|
|
get start() {
|
|
db.close();
|
|
return 0;
|
|
},
|
|
step: (acc, value) => acc,
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('aggregate() throws when the length getter closes the database', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
const step = (acc, value) => acc;
|
|
Object.defineProperty(step, 'length', {
|
|
configurable: true,
|
|
get() {
|
|
db.close();
|
|
return 2;
|
|
},
|
|
});
|
|
t.assert.throws(() => {
|
|
db.aggregate('agg', { start: 0, step });
|
|
}, invalidState);
|
|
});
|
|
|
|
test('createModule() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.createModule('mod', {
|
|
columns: [{ name: 'value', type: 'INTEGER' }],
|
|
*rows() {
|
|
yield [1];
|
|
},
|
|
get directOnly() {
|
|
db.close();
|
|
return false;
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('createModule() throws when a column getter closes the database', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.createModule('mod', {
|
|
columns: [{
|
|
name: 'value',
|
|
get type() {
|
|
db.close();
|
|
return 'INTEGER';
|
|
},
|
|
}],
|
|
*rows() {
|
|
yield [1];
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('deserialize() throws instead of using a closed connection', (t) => {
|
|
const source = new DatabaseSync(':memory:');
|
|
source.exec('CREATE TABLE data(value TEXT)');
|
|
const image = source.serialize();
|
|
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.deserialize(image, {
|
|
get dbName() {
|
|
db.close();
|
|
return 'main';
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('createSession() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.createSession({
|
|
get db() {
|
|
db.close();
|
|
return 'main';
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('applyChangeset() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
db.exec('CREATE TABLE data(key INTEGER PRIMARY KEY)');
|
|
const session = db.createSession();
|
|
db.exec('INSERT INTO data (key) VALUES (1)');
|
|
const changeset = session.changeset();
|
|
|
|
t.assert.throws(() => {
|
|
db.applyChangeset(changeset, {
|
|
get onConflict() {
|
|
db.close();
|
|
return undefined;
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
|
|
test('backup() throws instead of using a closed connection', (t) => {
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
backup(db, join(tmpdir.path, 'getter-backup.db'), {
|
|
get rate() {
|
|
db.close();
|
|
return 1;
|
|
},
|
|
});
|
|
}, invalidState);
|
|
});
|
|
});
|
|
|
|
// The state check runs before the options bag is read, so a call that is
|
|
// already doomed must not execute any of the caller's getters.
|
|
test('options getters do not run on an already-closed database', (t) => {
|
|
const source = new DatabaseSync(':memory:');
|
|
source.exec('CREATE TABLE data(key INTEGER PRIMARY KEY)');
|
|
const image = source.serialize();
|
|
const session = source.createSession();
|
|
source.exec('INSERT INTO data (key) VALUES (1)');
|
|
const changeset = session.changeset();
|
|
|
|
const cases = {
|
|
prepare: (db, options) => db.prepare('SELECT 1', options),
|
|
function: (db, options) => db.function('fn', options, () => 1),
|
|
aggregate: (db, options) => db.aggregate('agg', options),
|
|
deserialize: (db, options) => db.deserialize(image, options),
|
|
createSession: (db, options) => db.createSession(options),
|
|
applyChangeset: (db, options) => db.applyChangeset(changeset, options),
|
|
backup: (db, options) =>
|
|
backup(db, join(tmpdir.path, 'closed-backup.db'), options),
|
|
};
|
|
|
|
// The property each method reads first, and a valid value for it, so that a
|
|
// getter which does run leaves the "did not run" assertion as the failure
|
|
// rather than a type error from the returned value.
|
|
const probes = {
|
|
prepare: ['returnArrays', false],
|
|
function: ['useBigIntArguments', false],
|
|
aggregate: ['start', 0],
|
|
deserialize: ['dbName', 'main'],
|
|
createSession: ['db', 'main'],
|
|
applyChangeset: ['onConflict', undefined],
|
|
backup: ['rate', 1],
|
|
};
|
|
|
|
for (const [name, invoke] of Object.entries(cases)) {
|
|
const db = new DatabaseSync(':memory:');
|
|
db.close();
|
|
|
|
const [key, value] = probes[name];
|
|
let ran = false;
|
|
const options = {
|
|
get [key]() {
|
|
ran = true;
|
|
return value;
|
|
},
|
|
};
|
|
|
|
t.assert.throws(() => invoke(db, options), invalidState, name);
|
|
t.assert.strictEqual(ran, false, `${name} ran an options getter`);
|
|
}
|
|
});
|
|
|
|
suite('resizing a deserialize() buffer from an options getter', () => {
|
|
test('throws rather than handing uninitialized memory to SQLite', (t) => {
|
|
const source = new DatabaseSync(':memory:');
|
|
source.exec('CREATE TABLE data(value TEXT)');
|
|
source.prepare('INSERT INTO data (value) VALUES (?)').run('hello');
|
|
const image = source.serialize();
|
|
|
|
const buffer = new ArrayBuffer(image.byteLength, {
|
|
maxByteLength: image.byteLength,
|
|
});
|
|
new Uint8Array(buffer).set(image);
|
|
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.deserialize(new Uint8Array(buffer), {
|
|
get dbName() {
|
|
buffer.resize(1024);
|
|
return 'main';
|
|
},
|
|
});
|
|
}, {
|
|
code: 'ERR_INVALID_STATE',
|
|
message: /"buffer" argument was resized/,
|
|
});
|
|
});
|
|
|
|
test('throws when the buffer is detached', (t) => {
|
|
const source = new DatabaseSync(':memory:');
|
|
source.exec('CREATE TABLE data(value TEXT)');
|
|
const image = source.serialize();
|
|
|
|
const buffer = new ArrayBuffer(image.byteLength);
|
|
new Uint8Array(buffer).set(image);
|
|
|
|
const db = new DatabaseSync(':memory:');
|
|
t.assert.throws(() => {
|
|
db.deserialize(new Uint8Array(buffer), {
|
|
get dbName() {
|
|
structuredClone(buffer, { transfer: [buffer] });
|
|
return 'main';
|
|
},
|
|
});
|
|
}, {
|
|
code: 'ERR_INVALID_STATE',
|
|
message: /"buffer" argument was resized/,
|
|
});
|
|
});
|
|
});
|