Skip to content
Closed
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
18 changes: 18 additions & 0 deletions packages/bun-types/sqlite.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,15 @@ declare module "bun:sqlite" {
*/
loadExtension(extension: string, entryPoint?: string): void;

/**
* Interrupt any active operation on this database connection.
*
* Internally, this calls `sqlite3_interrupt`. If a query is currently
* running, its next `sqlite3_step` returns `SQLITE_INTERRUPT` and Bun
* throws a {@link SQLiteError}.
*/
interrupt(): void;

/**
* Change the dynamic library path to SQLite
*
Expand Down Expand Up @@ -878,6 +887,15 @@ declare module "bun:sqlite" {
*/
finalize(): void;

/**
* Interrupt any active operation on the database connection that owns this
* statement.
*
* This has the same effect as calling {@link Database.interrupt} on the
* statement's database.
*/
interrupt(): void;

/**
* Calls {@link finalize} if it wasn't already called.
*/
Expand Down
2 changes: 1 addition & 1 deletion src/codegen/bake-codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ async function run() {
side: JSON.stringify(side),
IS_ERROR_RUNTIME: String(file === "error"),
IS_BUN_DEVELOPMENT: String(!!debug),
OVERLAY_CSS: css("../runtime/bake/client/overlay.css", !!debug),
OVERLAY_CSS: JSON.stringify(css("../runtime/bake/client/overlay.css", !!debug)),
},
minify: {
syntax: !debug,
Expand Down
11 changes: 11 additions & 0 deletions src/js/bun/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ interface CppSQLStatement {
values: (...args: TODO[]) => TODO;
raw: (...args: TODO[]) => TODO;
finalize: (...args: TODO[]) => TODO;
interrupt: () => void;
toString: (...args: TODO[]) => TODO;
columns: string[];
columnsCount: number;
Expand All @@ -121,6 +122,7 @@ interface CppSQL {
deserialize(serialized: NodeJS.TypedArray | ArrayBufferLike, openFlags: number, deserializeFlags: number): TODO;
fcntl(handle: TODO, ...args: TODO[]): TODO;
close(handle: TODO, throwOnError: boolean): void;
interrupt(handle: TODO): void;
setCustomSQLite(path: string): void;
}

Expand Down Expand Up @@ -329,6 +331,10 @@ class Statement {
return this.#raw.finalize(...args);
}

interrupt() {
return this.#raw.interrupt();
}

*[Symbol.iterator]() {
yield* this.#iterateNoArgs();
}
Expand Down Expand Up @@ -519,6 +525,11 @@ class Database implements SqliteTypes.Database {
this.#hasClosed = true;
return SQL.close(this.#handle, throwOnError);
}

interrupt() {
return SQL.interrupt(this.#handle);
}

clearQueryCache() {
for (let item of this.#cachedQueriesValues) {
item?.finalize?.();
Expand Down
56 changes: 56 additions & 0 deletions src/jsc/bindings/sqlite/JSSQLStatement.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,10 @@ JSC_DECLARE_CUSTOM_GETTER(jsSqlStatementGetColumnCount);

JSC_DECLARE_HOST_FUNCTION(jsSQLStatementSerialize);
JSC_DECLARE_HOST_FUNCTION(jsSQLStatementDeserialize);
JSC_DECLARE_HOST_FUNCTION(jsSQLStatementInterruptFunction);

JSC_DECLARE_HOST_FUNCTION(jsSQLStatementSetPrototypeFunction);
JSC_DECLARE_HOST_FUNCTION(jsSQLStatementInterruptStatementFunction);
JSC_DECLARE_HOST_FUNCTION(jsSQLStatementFunctionFinalize);
JSC_DECLARE_HOST_FUNCTION(jsSQLStatementToStringFunction);

Expand Down Expand Up @@ -612,6 +614,7 @@ static const HashTableValue JSSQLStatementPrototypeTableValues[] = {
{ "values"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementExecuteStatementFunctionRows, 1 } },
{ "raw"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementExecuteStatementFunctionRawRows, 1 } },
{ "finalize"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementFunctionFinalize, 0 } },
{ "interrupt"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementInterruptStatementFunction, 0 } },
{ "toString"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementToStringFunction, 0 } },
{ "columns"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor), NoIntrinsic, { HashTableValue::GetterSetterType, jsSqlStatementGetColumnNames, 0 } },
{ "columnsCount"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor), NoIntrinsic, { HashTableValue::GetterSetterType, jsSqlStatementGetColumnCount, 0 } },
Expand Down Expand Up @@ -1849,6 +1852,40 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementFcntlFunction, (JSC::JSGlobalObject * lex
return JSValue::encode(jsNumber(statusCode));
}

JSC_DEFINE_HOST_FUNCTION(jsSQLStatementInterruptFunction, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto scope = DECLARE_THROW_SCOPE(vm);

JSValue thisValue = callFrame->thisValue();
JSSQLStatementConstructor* thisObject = dynamicDowncast<JSSQLStatementConstructor>(thisValue.getObject());
if (!thisObject) [[unlikely]] {
throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, "Expected SQLStatement"_s));
return {};
}

JSC::JSValue dbNumber = callFrame->argument(0);
if (!dbNumber.isNumber()) {
throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, "Invalid database handle"_s));
return {};
}

int32_t handle = dbNumber.toInt32(lexicalGlobalObject);
if (handle < 0 || handle >= databases().size()) [[unlikely]] {
throwException(lexicalGlobalObject, scope, createRangeError(lexicalGlobalObject, "Invalid database handle"_s));
return {};
}

sqlite3* db = databases()[handle]->db;
if (!db) [[unlikely]] {
throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, "Database has closed"_s));
return {};
}

sqlite3_interrupt(db);
RELEASE_AND_RETURN(scope, JSValue::encode(jsUndefined()));
}

/* Hash table for constructor */
static const HashTableValue JSSQLStatementConstructorTableValues[] = {
{ "open"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementOpenStatementFunction, 2 } },
Expand All @@ -1857,6 +1894,7 @@ static const HashTableValue JSSQLStatementConstructorTableValues[] = {
{ "run"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementExecuteFunction, 3 } },
{ "isInTransaction"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementIsInTransactionFunction, 1 } },
{ "loadExtension"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementLoadExtensionFunction, 2 } },
{ "interrupt"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementInterruptFunction, 1 } },
{ "setCustomSQLite"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementSetCustomSQLite, 1 } },
{ "serialize"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementSerialize, 1 } },
{ "deserialize"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsSQLStatementDeserialize, 2 } },
Expand Down Expand Up @@ -2714,6 +2752,24 @@ JSC_DEFINE_CUSTOM_SETTER(jsSqlStatementSetSafeIntegers, (JSGlobalObject * lexica
return true;
}

JSC_DEFINE_HOST_FUNCTION(jsSQLStatementInterruptStatementFunction, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
JSSQLStatement* castedThis = dynamicDowncast<JSSQLStatement>(callFrame->thisValue());
auto scope = DECLARE_THROW_SCOPE(vm);
CHECK_THIS
CHECK_PREPARED

sqlite3* db = castedThis->version_db->db;
if (!db) [[unlikely]] {
throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, "Database has closed"_s));
return {};
}

sqlite3_interrupt(db);
RELEASE_AND_RETURN(scope, JSValue::encode(jsUndefined()));
}

JSC_DEFINE_HOST_FUNCTION(jsSQLStatementFunctionFinalize, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
Expand Down
8 changes: 8 additions & 0 deletions src/jsc/bindings/sqlite/lazy_sqlite3.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ typedef int (*lazy_sqlite3_close_v2_type)(sqlite3*);
typedef int (*lazy_sqlite3_close_type)(sqlite3*);
typedef int (*lazy_sqlite3_file_control_type)(sqlite3*, const char* zDbName, int op, void* pArg);
typedef int (*lazy_sqlite3_extended_result_codes_type)(sqlite3*, int onoff);
typedef void (*lazy_sqlite3_interrupt_type)(sqlite3*);
typedef const void* (*lazy_sqlite3_column_blob_type)(sqlite3_stmt*, int iCol);
typedef double (*lazy_sqlite3_column_double_type)(sqlite3_stmt*, int iCol);
typedef int (*lazy_sqlite3_column_int_type)(sqlite3_stmt*, int iCol);
Expand Down Expand Up @@ -141,6 +142,7 @@ static lazy_sqlite3_stmt_busy_type lazy_sqlite3_stmt_busy;
static lazy_sqlite3_compileoption_used_type lazy_sqlite3_compileoption_used;
static lazy_sqlite3_config_type lazy_sqlite3_config;
static lazy_sqlite3_extended_result_codes_type lazy_sqlite3_extended_result_codes;
static lazy_sqlite3_interrupt_type lazy_sqlite3_interrupt;
static lazy_sqlite3_extended_errcode_type lazy_sqlite3_extended_errcode;
static lazy_sqlite3_error_offset_type lazy_sqlite3_error_offset;
static lazy_sqlite3_memory_used_type lazy_sqlite3_memory_used;
Expand Down Expand Up @@ -193,6 +195,7 @@ static lazy_sqlite3_last_insert_rowid_type lazy_sqlite3_last_insert_rowid;
#define sqlite3_compileoption_used lazy_sqlite3_compileoption_used
#define sqlite3_config lazy_sqlite3_config
#define sqlite3_extended_result_codes lazy_sqlite3_extended_result_codes
#define sqlite3_interrupt lazy_sqlite3_interrupt
#define sqlite3_extended_errcode lazy_sqlite3_extended_errcode
#define sqlite3_error_offset lazy_sqlite3_error_offset
#define sqlite3_memory_used lazy_sqlite3_memory_used
Expand Down Expand Up @@ -279,6 +282,7 @@ static int lazyLoadSQLite()
lazy_sqlite3_compileoption_used = (lazy_sqlite3_compileoption_used_type)dlsym(sqlite3_handle, "sqlite3_compileoption_used");
lazy_sqlite3_config = (lazy_sqlite3_config_type)dlsym(sqlite3_handle, "sqlite3_config");
lazy_sqlite3_extended_result_codes = (lazy_sqlite3_extended_result_codes_type)dlsym(sqlite3_handle, "sqlite3_extended_result_codes");
lazy_sqlite3_interrupt = (lazy_sqlite3_interrupt_type)dlsym(sqlite3_handle, "sqlite3_interrupt");
lazy_sqlite3_extended_errcode = (lazy_sqlite3_extended_errcode_type)dlsym(sqlite3_handle, "sqlite3_extended_errcode");
lazy_sqlite3_error_offset = (lazy_sqlite3_error_offset_type)dlsym(sqlite3_handle, "sqlite3_error_offset");
lazy_sqlite3_memory_used = (lazy_sqlite3_memory_used_type)dlsym(sqlite3_handle, "sqlite3_memory_used");
Expand All @@ -292,6 +296,10 @@ static int lazyLoadSQLite()
};
}

if (!lazy_sqlite3_interrupt) {
return -1;
}

if (!lazy_sqlite3_extended_errcode) {
lazy_sqlite3_extended_errcode = [](sqlite3*) -> int {
return 0;
Expand Down
47 changes: 47 additions & 0 deletions test/js/bun/sqlite/sqlite.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,53 @@ it("Database.open", () => {
new Database().close();
});

it("Database.interrupt interrupts an active iterator", () => {
const db = new Database(":memory:");
const iterator = db
.query(
"WITH RECURSIVE counter(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM counter WHERE value < 100000) SELECT value FROM counter",
)
.iterate();

expect(iterator.next().value).toEqual({ value: 1 });

db.interrupt();

try {
iterator.next();
throw new Error("Expected query to be interrupted");
} catch (error) {
expect(error).toBeInstanceOf(SQLiteError);
expect(error.code).toBe("SQLITE_INTERRUPT");
expect(error.errno).toBe(9);
Comment on lines +319 to +320

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Prefer asserting error.code only for SQLite error identity.

Line 320 and Line 343 hard-code errno (9), which is a magic-number assertion and less stable than error.code === "SQLITE_INTERRUPT".

♻️ Proposed fix
-    expect(error.errno).toBe(9);
@@
-    expect(error.errno).toBe(9);

Based on learnings: use string error.code checks for SQLite errors instead of numeric errno values.

Also applies to: 342-343

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/js/bun/sqlite/sqlite.test.js` around lines 319 - 320, Remove the brittle
numeric errno assertions and rely only on the SQLite string error code: delete
the expect(error.errno).toBe(9) assertions in the failing tests and keep/assert
only expect(error.code).toBe("SQLITE_INTERRUPT") (the tests that reference the
error variable and its code); ensure any duplicate errno checks (e.g., the
second occurrence near the later test that also asserts error.errno) are removed
so the tests assert error identity via error.code only.

}

expect(db.query("SELECT 1 AS value").get()).toEqual({ value: 1 });
});

it("Statement.interrupt interrupts an active iterator", () => {
const db = new Database(":memory:");
const stmt = db.query(
"WITH RECURSIVE counter(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM counter WHERE value < 100000) SELECT value FROM counter",
);
const iterator = stmt.iterate();

expect(iterator.next().value).toEqual({ value: 1 });

stmt.interrupt();

try {
iterator.next();
throw new Error("Expected query to be interrupted");
} catch (error) {
expect(error).toBeInstanceOf(SQLiteError);
expect(error.code).toBe("SQLITE_INTERRUPT");
expect(error.errno).toBe(9);
}

expect(db.query("SELECT 1 AS value").get()).toEqual({ value: 1 });
});

it("upsert cross-process, see #1366", () => {
const dir = realpathSync(tmpdir()) + "/";
const { exitCode } = spawnSync([bunExe(), import.meta.dir + "/sqlite-cross-process.js"], {
Expand Down
Loading