From 500e38e4b5190508df517e1e4fd48ef054084106 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 21:53:59 -0800 Subject: [PATCH 01/17] ADFA-7081: Add sqlite-js, SQL functions written in JavaScript for sqlite3 sqlite-js packages sqliteai/sqlite-js 1.3.7, a SQLite loadable extension for scalar, aggregate, window and collation functions written in JavaScript, with quickjs-ng 0.12.1 built in. It installs $PREFIX/lib/sqlite-js.so, loaded with `.load sqlite-js`, plus a README and acceptance tests. Six patches, each to be sent upstream, fix what 1.3.7 gets wrong: - 0001: sqlite3_interrupt() (Ctrl-C in sqlite3) stops running JavaScript. Before, `while (true) {}` hung the shell. - 0002: a 64 MB memory limit per connection, and js_set_memory_limit(). Before, code that kept allocating took all the memory there was. - 0003: js_eval() and the other functions that run code, read files or change the runtime are SQLITE_DIRECTONLY, so a database's views and triggers cannot call them even with trusted_schema on. - 0004: an ArrayBuffer or typed array result is a BLOB. Before, it was NULL, so no BLOB could pass through a function. - 0005: a whole-number result in the safe-integer range is an INTEGER. Before, an INTEGER outside the 32-bit range came back as a REAL. - 0006: an exception in an aggregate step or window inverse function is an SQL error. Before, it was ignored and the result silently wrong. Each adds a test to upstream's test/main.c, which fails without it. build.sh exports only the entry points (sqlite-js.map), since SQLite opens extensions with RTLD_GLOBAL, and adds sqlite3_sqlitejs_init, the name SQLite derives from the file name, as an alias of upstream's sqlite3_js_init. It compiles against Termux's SQLite headers, putting the copies bundled in libs/ last with -idirafter, and collects QuickJS's MIT license, which is only in source comments, into LICENSE.quickjs. QuickJS's std and os modules stay: JavaScript cannot reach them, since nothing runs its job queue, so import() never completes. A test checks that it stays so. Tests: upstream's test/main.c passes 12 of 12, and its six new tests fail on 1.3.7. tests/run-tests.sh passes 73 of 73 on x86_64 Linux with sqlite3 3.46.1, and 25 fail against unpatched 1.3.7; it runs the README's sql examples as written. The recipe's steps run outside Docker on the host and with the NDK r29 toolchain at API 24 for aarch64 and arm: six patches apply, only the two entry points are exported, and the libraries need only libc, libm and libdl. Termux's linter passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- README.md | 1 + packages.sh | 4 + ...t-when-the-connection-is-interrupted.patch | 169 ++++++ ...the-memory-of-the-JavaScript-runtime.patch | 190 ++++++ ...ions-that-run-code-out-of-the-schema.patch | 138 +++++ ...rayBuffers-and-typed-arrays-as-BLOBs.patch | 207 +++++++ ...005-Return-whole-numbers-as-INTEGERs.patch | 161 ++++++ ...s-thrown-by-aggregate-and-window-ste.patch | 93 +++ packages/sqlite-js/README.md | 209 +++++++ packages/sqlite-js/build.sh | 63 ++ packages/sqlite-js/sqlite-js.map | 12 + packages/sqlite-js/tests/run-tests.sh | 542 ++++++++++++++++++ 12 files changed, 1789 insertions(+) create mode 100644 packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch create mode 100644 packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch create mode 100644 packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch create mode 100644 packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch create mode 100644 packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch create mode 100644 packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch create mode 100644 packages/sqlite-js/README.md create mode 100644 packages/sqlite-js/build.sh create mode 100644 packages/sqlite-js/sqlite-js.map create mode 100644 packages/sqlite-js/tests/run-tests.sh diff --git a/README.md b/README.md index 50cdb8b..1f9dee5 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Packages that are not in `termux-packages` live in `packages//`, laid out | Package | What it is | |---------|------------| | `sqlite-brotli` | SQLite extension adding `encodeBrotli()` and `decodeBrotli()`. See [its README](packages/sqlite-brotli/README.md). | +| `sqlite-js` | SQLite extension for SQL functions written in JavaScript: [sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) with our patches. See [its README](packages/sqlite-js/README.md). | The key specified with the `-s` option is the **public key** (**NOT** the private key!), which can be generated using : diff --git a/packages.sh b/packages.sh index bcc8bf7..eef4183 100644 --- a/packages.sh +++ b/packages.sh @@ -99,4 +99,8 @@ COTG_PACKAGES+=( # Brotli functions for the sqlite3 shell, used to maintain # documentation.db (ADFA-6635). Built from packages/sqlite-brotli. "sqlite-brotli" + + # SQL functions written in JavaScript for the sqlite3 shell + # (ADFA-7081). Built from packages/sqlite-js. + "sqlite-js" ) diff --git a/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch b/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch new file mode 100644 index 0000000..ec319c8 --- /dev/null +++ b/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch @@ -0,0 +1,169 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 20:56:10 -0800 +Subject: [PATCH 1/6] Stop JavaScript when the connection is interrupted + +JavaScript runs inside the SQL statement that calls it, but QuickJS had +no interrupt handler, so sqlite3_interrupt() could not stop code that +never returns to SQLite. `SELECT js_eval('while (true) {}')` hung the +sqlite3 shell, where Ctrl-C calls sqlite3_interrupt(), and an app could +not cancel the query. + +Install a QuickJS interrupt handler that reports the connection's +sqlite3_is_interrupted(). QuickJS then stops the code with an +uncatchable "interrupted" error, and the statement fails as interrupted. +sqlite3_is_interrupted() is new in SQLite 3.41.0, so the handler is only +installed when the library is at least that version. + +Add an Interrupt test that interrupts endless loops in js_eval() and in a +scalar function from another thread, and checks that the connection +still works afterwards. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 4 +++ + src/sqlitejs.c | 15 ++++++++++- + test/main.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 85 insertions(+), 1 deletion(-) + +diff --git a/README.md b/README.md +index e389272..45bf583 100644 +--- a/README.md ++++ b/README.md +@@ -410,6 +410,10 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB + ``` + ++### Interrupting JavaScript ++ ++JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. ++ + ## Examples + + ### Example 1: String Manipulation +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 024a2f8..524581e 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -187,6 +187,15 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + + // MARK: - Initializer - + ++// QuickJS calls this from time to time while it runs code. A non-zero result stops the code ++// with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, ++// a cancelled query in an app) also stops JavaScript that never returns to SQLite. ++static int js_interrupt_handler (JSRuntime *rt, void *opaque) { ++ UNUSED(rt); ++ globaljs_context *js = (globaljs_context *)opaque; ++ return (js->db != NULL) && sqlite3_is_interrupted(js->db); ++} ++ + static globaljs_context *globaljs_init (sqlite3 *db) { + JSRuntime *rt = NULL; + JSContext *ctx = NULL; +@@ -200,7 +209,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + + //JS_SetMemoryLimit(rt, 80 * 1024); + //JS_SetMaxStackSize(rt, 10 * 1024); +- ++ ++ // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry ++ // in its sqlite3_api_routines, so JavaScript cannot be interrupted there ++ if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); ++ + js_std_init_handlers(rt); + JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); + +diff --git a/test/main.c b/test/main.c +index d0ed2e7..0f8da0c 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + + #define DB_PATH "js_functions.sqlite" + #define VERBOSE 1 +@@ -488,6 +489,71 @@ abort_test: + return rc; + } + ++// MARK: - Interrupt - ++ ++int test_open (sqlite3 **db) { ++ int rc = sqlite3_open(":memory:", db); ++ if (rc != SQLITE_OK) return rc; ++ ++ #if JS_LOAD_EMBEDDED ++ return sqlite3_js_init(*db, NULL, NULL); ++ #else ++ rc = sqlite3_enable_load_extension(*db, 1); ++ if (rc != SQLITE_OK) return rc; ++ return db_exec(*db, "SELECT load_extension('./dist/js');"); ++ #endif ++} ++ ++void *test_interrupt_worker (void *ptr) { ++ // give the statement time to start running JavaScript ++ usleep(200 * 1000); ++ sqlite3_interrupt((sqlite3 *)ptr); ++ return NULL; ++} ++ ++// Runs sql, which never ends unless it is interrupted, and interrupts it from another thread. ++// The statement must fail as interrupted, and the connection must stay usable. ++int test_interrupt_sql (sqlite3 *db, const char *sql) { ++ pthread_t thread; ++ if (pthread_create(&thread, NULL, test_interrupt_worker, (void *)db) != 0) return SQLITE_ERROR; ++ int rc = sqlite3_exec(db, sql, NULL, NULL, NULL); ++ pthread_join(thread, NULL); ++ ++ if (rc == SQLITE_OK || strstr(sqlite3_errmsg(db), "interrupted") == NULL) { ++ printf("FAIL: %s\n Expected: interrupted, Got: %d %s\n", sql, rc, sqlite3_errmsg(db)); ++ return SQLITE_ERROR; ++ } ++ return check_query(db, "SELECT js_eval('1+1');", "2"); ++} ++ ++int test_interrupt (void) { ++ sqlite3 *db = NULL; ++ ++ // if the code cannot be interrupted, end the test program instead of hanging forever ++ alarm(30); ++ ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = test_interrupt_sql(db, "SELECT js_eval('while (true) {}');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "SELECT js_create_scalar('forever', '(function(args){ for (;;) {} })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = test_interrupt_sql(db, "SELECT forever();"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // JavaScript catch blocks cannot keep running code alive ++ rc = test_interrupt_sql(db, "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ alarm(0); ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -504,6 +570,7 @@ int main (void) { + result += test_report("Serialization 2", test_serialization(DB_PATH, false, 2)); // update functions previously registered in the js_functions table + result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations + result += test_report("Thread", test_thread()); ++ result += test_report("Interrupt", test_interrupt()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch new file mode 100644 index 0000000..ad5cafe --- /dev/null +++ b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch @@ -0,0 +1,190 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 20:58:13 -0800 +Subject: [PATCH 2/6] Limit the memory of the JavaScript runtime + +The JavaScript runtime had no memory limit (the JS_SetMemoryLimit call +was commented out), so code that keeps allocating took all the memory of +the process. On a phone that ends with the operating system killing the +process, which in an app takes the app down with it. + +Set a default limit of 64 MB per connection, which SQLITE_JS_DEFAULT_ +MEMORY_LIMIT changes at build time, and add js_set_memory_limit(bytes) +to change it at run time; 0 means no limit, as in JS_SetMemoryLimit(). +Code that needs more fails with an "out of memory" error, and the +connection stays usable. A QuickJS context takes about 54 KB, so the +default leaves room for over a thousand aggregate contexts at once. + +Add a Memory limit test: allocations under and over the default, code +that never stops allocating, raising, removing and lowering the limit, +and invalid arguments. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 9 ++++++++ + src/sqlitejs.c | 30 +++++++++++++++++++++---- + test/main.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 96 insertions(+), 4 deletions(-) + +diff --git a/README.md b/README.md +index 45bf583..52efd7b 100644 +--- a/README.md ++++ b/README.md +@@ -410,6 +410,15 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB + ``` + ++### js_set_memory_limit ++ ++Sets the most memory, in bytes, that JavaScript may allocate on this connection; 0 means no limit. The default is 64 MB (64 × 1024 × 1024 bytes); build with `-DSQLITE_JS_DEFAULT_MEMORY_LIMIT=bytes` to change it. Code that needs more fails with an "out of memory" error, and the connection stays usable. ++ ++```sql ++SELECT js_set_memory_limit(268435456); -- Allow 256 MB ++SELECT js_set_memory_limit(0); -- No limit ++``` ++ + ### Interrupting JavaScript + + JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 524581e..558744f 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -187,6 +187,14 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + + // MARK: - Initializer - + ++// The most memory, in bytes, the JavaScript runtime of a connection may allocate until ++// js_set_memory_limit() changes it; 0 means no limit. Without a limit, code that keeps ++// allocating takes all the memory of the process, which on a phone ends with the operating ++// system killing it. 64 MB is room for over a thousand aggregate contexts (about 54 KB each). ++#ifndef SQLITE_JS_DEFAULT_MEMORY_LIMIT ++#define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) ++#endif ++ + // QuickJS calls this from time to time while it runs code. A non-zero result stops the code + // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, + // a cancelled query in an app) also stops JavaScript that never returns to SQLite. +@@ -207,7 +215,7 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + rt = JS_NewRuntime(); + if (!rt) goto abort_init; + +- //JS_SetMemoryLimit(rt, 80 * 1024); ++ JS_SetMemoryLimit(rt, SQLITE_JS_DEFAULT_MEMORY_LIMIT); + //JS_SetMaxStackSize(rt, 10 * 1024); + + // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry +@@ -1305,6 +1313,20 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + JS_SetMaxStackSize(js->runtime, stack_size); + } + ++void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { ++ UNUSED(argc); ++ globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); ++ ++ if ((sqlite3_value_type(argv[0]) != SQLITE_INTEGER) || (sqlite3_value_int64(argv[0]) < 0)) { ++ sqlite3_result_error(context, "The memory limit must be an integer number of bytes, or 0 for no limit", -1); ++ return; ++ } ++ ++ // a limit beyond the address space (on a 32-bit system) can never be reached, so it is no limit ++ sqlite3_uint64 limit = (sqlite3_uint64)sqlite3_value_int64(argv[0]); ++ JS_SetMemoryLimit(js->runtime, (limit > SIZE_MAX) ? 0 : (size_t)limit); ++} ++ + // MARK: - + + const char *sqlitejs_version (void) { +@@ -1325,9 +1347,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r + globaljs_context *js = globaljs_init(db); + if (!js) return SQLITE_NOMEM; + +- const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size"}; +- const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size}; +- int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1}; ++ const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; ++ const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; ++ int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; + + size_t f_count = sizeof(f_name) / sizeof(const char *); + for (size_t i=0; i x * 2).join()');", "2,4,6"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a higher limit, then no limit ++ rc = db_exec(db, "SELECT js_set_memory_limit(256 * 1024 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');", "134217728"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_set_memory_limit(0);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');", "134217728"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a lower limit ++ rc = db_exec(db, "SELECT js_set_memory_limit(8 * 1024 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');", "out of memory"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // only a non-negative integer is a limit ++ const char *invalid[] = {"-1", "1.5", "'1000000'", "NULL", "x'00'"}; ++ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { ++ char sql[128]; ++ snprintf(sql, sizeof(sql), "SELECT js_set_memory_limit(%s);", invalid[i]); ++ rc = check_error(db, sql, "The memory limit must be an integer number of bytes"); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -571,6 +631,7 @@ int main (void) { + result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); ++ result += test_report("Memory limit", test_memory_limit()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch b/packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch new file mode 100644 index 0000000..4925c23 --- /dev/null +++ b/packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch @@ -0,0 +1,138 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 20:59:46 -0800 +Subject: [PATCH 3/6] Keep the functions that run code out of the schema + +js_eval(), js_create_*(), js_load_text(), js_load_blob(), js_init_table() +and the js_set_* functions were registered without SQLITE_DIRECTONLY, so +a view, trigger, CHECK constraint or generated column could call them. +With PRAGMA trusted_schema ON, the default of the SQLite library (the +sqlite3 shell turns it off), a database from an untrusted source could +run JavaScript or read files just by being queried: +`CREATE VIEW v AS SELECT js_eval('...')`. + +Register every function but js_version() with SQLITE_DIRECTONLY, so only +top-level SQL can call them. The functions created with js_create_* are +unchanged, so they still work in views, triggers and indexes. + +Add a Direct only test: with trusted_schema ON, a view, a trigger and a +generated column cannot call js_eval() or js_load_text(), a top-level +statement can, and a view can still use js_version() and a function made +with js_create_scalar(). + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 6 ++++++ + src/sqlitejs.c | 10 ++++++++-- + test/main.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 63 insertions(+), 2 deletions(-) + +diff --git a/README.md b/README.md +index 52efd7b..ff51b2f 100644 +--- a/README.md ++++ b/README.md +@@ -419,6 +419,12 @@ SELECT js_set_memory_limit(268435456); -- Allow 256 MB + SELECT js_set_memory_limit(0); -- No limit + ``` + ++### Using the functions from the schema ++ ++Every function above but `js_version` runs JavaScript, reads files or changes the JavaScript runtime, so it is registered with `SQLITE_DIRECTONLY`: only top-level SQL can call it, never a view, trigger, CHECK constraint, generated column or index. That way a database from an untrusted source cannot run JavaScript just by being queried. The functions you create with `js_create_scalar`, `js_create_aggregate`, `js_create_window` and `js_create_collation` are not restricted. ++ ++A database can still store JavaScript in its `js_functions` table, and `js_init_table(1)` runs it. Call it only on databases you trust. ++ + ### Interrupting JavaScript + + JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 558744f..5765567 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -1350,11 +1350,17 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r + const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; + const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; + int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; +- ++ ++ // Every function but js_version runs JavaScript, reads files or changes the JavaScript ++ // runtime. SQLITE_DIRECTONLY keeps them out of the schema (views, triggers, CHECK ++ // constraints, generated columns, indexes), so that a database from an untrusted source ++ // cannot run JavaScript just by being queried, whatever PRAGMA trusted_schema says. ++ int f_flags[] = {0, 0, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY}; ++ + size_t f_count = sizeof(f_name) / sizeof(const char *); + for (size_t i=0; iref_count++; +- int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); ++ int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8 | f_flags[i], (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); + if (rc != SQLITE_OK) { + if (pzErrMsg) *pzErrMsg = sqlite3_mprintf("Error creating function %s: %s", f_name[i], sqlite3_errmsg(db)); + // sqlite3_create_function_v2 always invokes the xDestroy callback when it fails, +diff --git a/test/main.c b/test/main.c +index c9aab4d..f8e7f78 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -614,6 +614,54 @@ abort_test: + return rc; + } + ++// MARK: - Direct only - ++ ++int test_direct_only (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // trusted_schema ON lets the schema use any function that is not SQLITE_DIRECTONLY ++ rc = db_exec(db, "PRAGMA trusted_schema = ON; CREATE TABLE t (a); CREATE TABLE log (msg);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a view, a trigger and a generated column cannot run JavaScript or read files ++ // (SQLite reports these either when the schema is created or when it is used) ++ sqlite3_exec(db, "CREATE VIEW v_eval AS SELECT js_eval('6 * 7') AS x;", NULL, NULL, NULL); ++ rc = check_error(db, "SELECT x FROM v_eval;", "unsafe use of js_eval()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "CREATE VIEW v_load AS SELECT js_load_text('/etc/hosts') AS x;", NULL, NULL, NULL); ++ rc = check_error(db, "SELECT x FROM v_load;", "unsafe use of js_load_text()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "CREATE TRIGGER t_insert AFTER INSERT ON t BEGIN INSERT INTO log VALUES (js_eval('\"trigger ran\"')); END;", NULL, NULL, NULL); ++ rc = check_error(db, "INSERT INTO t VALUES (1);", "unsafe use of js_eval()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT count(*) FROM log;", "0"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "DROP TRIGGER IF EXISTS t_insert;", NULL, NULL, NULL); ++ if (sqlite3_exec(db, "CREATE TABLE g (a, b AS (js_eval('1')));", NULL, NULL, NULL) == SQLITE_OK) { ++ rc = check_error(db, "INSERT INTO g (a) VALUES (1);", "unsafe use of js_eval()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++ // a top-level statement can still use them ++ rc = check_query(db, "SELECT js_eval('6 * 7');", "42"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // and the schema can still use js_version() and the functions created with js_create_* ++ rc = db_exec(db, "SELECT js_create_scalar('twice', '(function(args){ return args[0] * 2; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "CREATE VIEW v_ok AS SELECT js_version() IS NOT NULL AS has_version, twice(21) AS answer;"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query_v2(db, "SELECT has_version, answer FROM v_ok;", (const char*[]){"1", "42"}, 2); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -632,6 +680,7 @@ int main (void) { + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); ++ result += test_report("Direct only", test_direct_only()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch new file mode 100644 index 0000000..bb218f0 --- /dev/null +++ b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch @@ -0,0 +1,207 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 21:01:52 -0800 +Subject: [PATCH 4/6] Return ArrayBuffers and typed arrays as BLOBs + +A BLOB argument reaches JavaScript as an ArrayBuffer, but a function +that returned an ArrayBuffer, or a typed array such as Uint8Array, gave +NULL: js_value_to_sqlite() turned every object into NULL. So no function +could return binary data, and `identity(x'00ff')` with +`(function(args){ return args[0]; })` returned NULL. db.exec() bound an +ArrayBuffer but not a typed array, and bound an empty ArrayBuffer as +NULL. + +Add js_get_bytes(), which gets the bytes of an ArrayBuffer or of the part +of a buffer that a typed array views, and use it for function results and +for db.exec() parameters. An empty buffer is an empty BLOB. Returning a +detached buffer is an error; binding one still binds NULL, as before. +Document how values convert in both directions in the README. + +Add a Blobs test: BLOBs round-trip through a function, typed arrays, +subarrays and ArrayBuffers made in JavaScript become BLOBs, a function +can build a BLOB from a BLOB, a detached buffer is an error, and +db.exec() binds typed arrays and empty buffers as BLOBs. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 13 ++++++++++ + src/sqlitejs.c | 64 ++++++++++++++++++++++++++++++++++++++++++++------ + test/main.c | 38 ++++++++++++++++++++++++++++++ + 3 files changed, 108 insertions(+), 7 deletions(-) + +diff --git a/README.md b/README.md +index ff51b2f..99abfb9 100644 +--- a/README.md ++++ b/README.md +@@ -176,6 +176,19 @@ SQLite-JS provides several ways to extend SQLite functionality with JavaScript: + | Collation Sequences | Define custom sort orders for text values | + | JavaScript Evaluation | Directly evaluate JavaScript code within SQLite | + ++### Values ++ ++SQL values reach JavaScript as follows: ++ ++| SQL | JavaScript | ++|-----|------------| ++| NULL | `null` | ++| INTEGER, REAL | number | ++| TEXT | string | ++| BLOB | `ArrayBuffer` | ++ ++A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number in the 32-bit range and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. ++ + ## Scalar Functions + + Scalar functions process one row at a time and return a single value. They are useful for data transformation, calculations, text manipulation, etc. +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 5765567..2c11877 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -366,6 +366,38 @@ static void functionjs_free (functionjs_context *fctx) { + + // MARK: - Utils - + ++// Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such ++// as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an ++// ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be ++// NULL when *psize is 0), 0 if it is not, and -1 with a pending JavaScript exception if its ++// buffer is detached or the typed array is out of its bounds. ++static int js_get_bytes (JSContext *ctx, JSValueConst value, const uint8_t **pbytes, size_t *psize) { ++ *pbytes = NULL; ++ *psize = 0; ++ ++ if (JS_IsArrayBuffer(value)) { ++ uint8_t *buf = JS_GetArrayBuffer(ctx, psize, value); ++ if (!buf && JS_HasException(ctx)) return -1; ++ *pbytes = buf; ++ return 1; ++ } ++ ++ if (JS_GetTypedArrayType(value) >= 0) { ++ size_t offset = 0, length = 0, size = 0; ++ JSValue buffer = JS_GetTypedArrayBuffer(ctx, value, &offset, &length, NULL); ++ if (JS_IsException(buffer)) return -1; ++ uint8_t *buf = JS_GetArrayBuffer(ctx, &size, buffer); ++ // the typed array keeps its buffer alive, so buf stays valid ++ JS_FreeValue(ctx, buffer); ++ if (!buf && JS_HasException(ctx)) return -1; ++ *pbytes = (buf) ? buf + offset : NULL; ++ *psize = length; ++ return 1; ++ } ++ ++ return 0; ++} ++ + static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueConst val) { + if (JS_IsNull(val) || JS_IsUndefined(val)) { + return sqlite3_bind_null(vm, index); +@@ -400,14 +432,18 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo + JS_FreeCString(ctx, str); + return rc; + } +- if (JS_IsArrayBuffer(val)) { +- size_t size = 0; +- uint8_t *buf = JS_GetArrayBuffer(ctx, &size, val); +- if (buf) { +- return sqlite3_bind_blob(vm, index, buf, (int)size, SQLITE_TRANSIENT); +- } ++ const uint8_t *bytes = NULL; ++ size_t size = 0; ++ int is_blob = js_get_bytes(ctx, val, &bytes, &size); ++ if (is_blob < 0) { ++ // a detached buffer has no bytes to bind, so it binds NULL ++ JS_FreeValue(ctx, JS_GetException(ctx)); + return sqlite3_bind_null(vm, index); + } ++ if (is_blob) { ++ if (size == 0) return sqlite3_bind_zeroblob(vm, index, 0); ++ return sqlite3_bind_blob64(vm, index, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); ++ } + return sqlite3_bind_null(vm, index); + } + +@@ -636,11 +672,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + return; + } + ++ // handle ArrayBuffer and typed arrays, the forms a BLOB takes in JavaScript ++ const uint8_t *bytes = NULL; ++ size_t size = 0; ++ int is_blob = js_get_bytes(js_ctx, value, &bytes, &size); ++ if (is_blob < 0) { ++ js_error_to_sqlite(context, js_ctx, JS_EXCEPTION, NULL); ++ return; ++ } ++ if (is_blob) { ++ if (size == 0) sqlite3_result_zeroblob(context, 0); ++ else sqlite3_result_blob64(context, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); ++ return; ++ } ++ + if (JS_IsObject(value)) { + sqlite3_result_null(context); + return; + } +- ++ + // fallback for unsupported types + sqlite3_result_error(context, "Unsupported JS value type", -1); + } +diff --git a/test/main.c b/test/main.c +index f8e7f78..49aa6a1 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -662,6 +662,43 @@ abort_test: + return rc; + } + ++// MARK: - Blobs - ++ ++int test_blobs (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a BLOB arrives as an ArrayBuffer and goes back as the same BLOB ++ rc = db_exec(db, "SELECT js_create_scalar('identity', '(function(args){ return args[0]; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query_v2(db, "SELECT quote(identity(x'00ff10')), quote(identity(x'')), typeof(identity(zeroblob(3)));", (const char*[]){"X'00FF10'", "X''", "blob"}, 3); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // ArrayBuffers and typed arrays made in JavaScript, including a view of part of a buffer ++ rc = check_query_v2(db, "SELECT quote(js_eval('new Uint8Array([1, 2, 3])')), quote(js_eval('new Uint8Array([1, 2, 3, 4, 5]).subarray(1, 3)')), quote(js_eval('new Uint8Array([7, 8]).buffer')), quote(js_eval('new ArrayBuffer(0)'));", (const char*[]){"X'010203'", "X'0203'", "X'0708'", "X''"}, 4); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a function that makes a BLOB from a BLOB ++ rc = db_exec(db, "SELECT js_create_scalar('reverse_bytes', '(function(args){ return new Uint8Array(args[0]).reverse(); })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT quote(reverse_bytes(x'010203'));", "X'030201'"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a detached buffer has no bytes, so returning it is an error ++ rc = check_error(db, "SELECT js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); return b; })()');", "detached"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // db.exec() binds them as BLOBs too ++ rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT quote(?), quote(?)\", new Uint8Array([1, 2]), new ArrayBuffer(0)); rs.next(); return rs.get(0) + \" \" + rs.get(1); })()');", "X'0102' X''"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -681,6 +718,7 @@ int main (void) { + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); + result += test_report("Direct only", test_direct_only()); ++ result += test_report("Blobs", test_blobs()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch new file mode 100644 index 0000000..dcfd67f --- /dev/null +++ b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch @@ -0,0 +1,161 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 21:03:54 -0800 +Subject: [PATCH 5/6] Return whole numbers as INTEGERs + +QuickJS keeps the small whole numbers it can as 32-bit integers, and any +other number as a double, which went back to SQL as a REAL. So an INTEGER +outside the 32-bit range changed type on its way through a function: +`identity(2147483648)` returned 2147483648.0. The result of arithmetic +did too: js_eval('2 + 3') returned the INTEGER 5 but js_eval('2.5 * 2') +the REAL 5.0, and a JavaScript sum of large integers was a REAL. + +Return a number that is a whole number from -(2^53 - 1) to 2^53 - 1 +(Number.isSafeInteger), which a double holds exactly, as an INTEGER, and +any other number as a REAL, for function results and db.exec() +parameters alike. JavaScript cannot tell 3.0 from 3, so a REAL that holds +a whole number now comes back as an INTEGER; the README says so, and how +to pass an INTEGER beyond 2^53 - 1 without losing precision. + +Add a Numbers test: integers in and beyond the 32-bit range round-trip +as INTEGERs, other REALs stay REAL, integers beyond 2^53 - 1 are REALs, +arithmetic results, an aggregate result past the 32-bit range, and +db.exec() parameters. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 4 +++- + src/sqlitejs.c | 19 ++++++++++++++++++- + test/main.c | 43 +++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 64 insertions(+), 2 deletions(-) + +diff --git a/README.md b/README.md +index 99abfb9..d2cf41b 100644 +--- a/README.md ++++ b/README.md +@@ -187,7 +187,9 @@ SQL values reach JavaScript as follows: + | TEXT | string | + | BLOB | `ArrayBuffer` | + +-A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number in the 32-bit range and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. ++A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number from -(2^53 - 1) to 2^53 - 1 (`Number.isSafeInteger`) and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. ++ ++JavaScript has a single number type, a double. So a REAL that holds a whole number, such as 3.0, comes back as the INTEGER 3, and an INTEGER beyond ±(2^53 - 1) loses precision in JavaScript: pass it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. + + ## Scalar Functions + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 2c11877..45d315b 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + #include "sqlitejs.h" + #include "quickjs.h" + #include "quickjs-libc.h" +@@ -366,6 +367,18 @@ static void functionjs_free (functionjs_context *fctx) { + + // MARK: - Utils - + ++// A JavaScript number is a double. QuickJS keeps the small whole numbers it can as 32-bit ++// integers, but an INTEGER outside that range, or the result of arithmetic such as 2.5 * 2, ++// is a double too. A whole number that a double holds exactly, from -(2^53 - 1) to 2^53 - 1 ++// (Number.isSafeInteger), goes back to SQL as an INTEGER; any other number is a REAL. ++static bool js_number_to_int64 (double num, sqlite3_int64 *out) { ++ const double max_safe_integer = 9007199254740991.0; ++ // NaN fails both comparisons ++ if (!(num >= -max_safe_integer && num <= max_safe_integer) || (num != floor(num))) return false; ++ *out = (sqlite3_int64)num; ++ return true; ++} ++ + // Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such + // as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an + // ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be +@@ -410,7 +423,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo + return sqlite3_bind_int(vm, index, num); + } else { + double num; ++ sqlite3_int64 inum; + JS_ToFloat64(ctx, &num, val); ++ if (js_number_to_int64(num, &inum)) return sqlite3_bind_int64(vm, index, inum); + return sqlite3_bind_double(vm, index, num); + } + } +@@ -636,8 +651,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + sqlite3_result_int(context, num); + } else { + double num; ++ sqlite3_int64 inum; + JS_ToFloat64(js_ctx, &num, value); +- sqlite3_result_double(context, num); ++ if (js_number_to_int64(num, &inum)) sqlite3_result_int64(context, inum); ++ else sqlite3_result_double(context, num); + } + return; + } +diff --git a/test/main.c b/test/main.c +index 49aa6a1..28211e9 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -699,6 +699,48 @@ abort_test: + return rc; + } + ++// MARK: - Numbers - ++ ++int test_numbers (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "SELECT js_create_scalar('identity', '(function(args){ return args[0]; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // integers keep their type and value through JavaScript, beyond the 32-bit range too ++ rc = check_query(db, "WITH v(x) AS (VALUES (0), (42), (-7), (2147483647), (2147483648), (-2147483649), (9007199254740991), (-9007199254740991)) SELECT group_concat(typeof(identity(x)) || ' ' || (identity(x) = x), ',') FROM v;", "integer 1,integer 1,integer 1,integer 1,integer 1,integer 1,integer 1,integer 1"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // REALs that are not whole numbers stay REAL; a whole number is an INTEGER, as JavaScript cannot tell 3.0 from 3 ++ rc = check_query_v2(db, "SELECT quote(identity(3.5)), quote(identity(-0.25)), quote(identity(1e300)), quote(identity(3.0));", (const char*[]){"3.5", "-0.25", "1.0e+300", "3"}, 4); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // beyond 2^53 - 1 a double cannot hold every integer, so the result is a REAL ++ rc = check_query(db, "SELECT typeof(identity(9007199254740993));", "real"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // results of arithmetic ++ rc = check_query_v2(db, "SELECT quote(js_eval('2.5 * 2')), quote(js_eval('1e10')), typeof(js_eval('0.1 + 0.2')), typeof(js_eval('NaN'));", (const char*[]){"5", "10000000000", "real", "null"}, 4); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // an aggregate whose result is past the 32-bit range ++ rc = db_exec(db, "SELECT js_create_aggregate('js_sum', 'total = 0;', '(function(args){ total += args[0]; })', '(function(){ return total; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "WITH v(x) AS (VALUES (3000000000), (1)) SELECT typeof(js_sum(x)) || ' ' || js_sum(x) FROM v;", "integer 3000000001"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // db.exec() binds numbers the same way ++ rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT typeof(?), typeof(?), typeof(?)\", 2147483648, 2.5 * 2, 2.5); rs.next(); return [rs.get(0), rs.get(1), rs.get(2)].join(); })()');", "integer,integer,real"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -719,6 +761,7 @@ int main (void) { + result += test_report("Memory limit", test_memory_limit()); + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); ++ result += test_report("Numbers", test_numbers()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch new file mode 100644 index 0000000..352ad41 --- /dev/null +++ b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch @@ -0,0 +1,93 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 21:16:06 -0800 +Subject: [PATCH 6/6] Report exceptions thrown by aggregate and window steps + +js_execute_common() turned the result of a function into an SQL result +only when the caller wanted the value. The step function of an aggregate +or window function, and the inverse function of a window function, +return nothing, so their result was dropped, and with it any exception +they threw: the aggregate went on as if the row had been added or +removed. A step that threw, or ran out of memory, gave a wrong result +with no error. + +Report an exception thrown by a step or inverse function as an SQL error. +Reported from xStep or xInverse, it makes SQLite abort the statement, +which still calls xFinal, so the aggregate context is released as before. + +Add an Aggregate errors test: an exception in an aggregate step and in a +window inverse function each fail the statement with its message, and the +connection stays usable. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + src/sqlitejs.c | 3 +++ + test/main.c | 33 +++++++++++++++++++++++++++++++++ + 2 files changed, 36 insertions(+) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 45d315b..7aaaaa2 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -866,6 +866,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, + JS_FreeValue(js_context, args); + + if (return_value) js_value_to_sqlite(context, js_context, result); ++ // step and inverse functions return nothing, but an exception they throw is still an error: ++ // reported from xStep or xInverse, it makes SQLite abort the statement ++ else if (JS_IsException(result)) js_error_to_sqlite(context, js_context, result, NULL); + JS_FreeValue(js_context, result); + } + +diff --git a/test/main.c b/test/main.c +index 28211e9..f278cc9 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -741,6 +741,38 @@ abort_test: + return rc; + } + ++// MARK: - Aggregate errors - ++ ++int test_aggregate_errors (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "CREATE TABLE t (x); INSERT INTO t VALUES (1), (2), (3);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // an exception thrown by an aggregate's step function fails the statement ++ rc = db_exec(db, "SELECT js_create_aggregate('step_fails', 'n = 0;', '(function(args){ if (args[0] == 2) throw new Error(\"step boom\"); n++; })', '(function(){ return n; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT step_fails(x) FROM t;", "step boom"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // so does one thrown by a window function's inverse function ++ rc = db_exec(db, "SELECT js_create_window('inverse_fails', 'total = 0;', '(function(args){ total += args[0]; })', '(function(){ return total; })', '(function(){ return total; })', '(function(args){ throw new Error(\"inverse boom\"); })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT inverse_fails(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM t;", "inverse boom"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // and the connection stays usable ++ rc = check_query(db, "SELECT js_eval('[1, 2, 3].join()');", "1,2,3"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -762,6 +794,7 @@ int main (void) { + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); ++ result += test_report("Aggregate errors", test_aggregate_errors()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md new file mode 100644 index 0000000..2efca87 --- /dev/null +++ b/packages/sqlite-js/README.md @@ -0,0 +1,209 @@ +# sqlite-js + +A SQLite loadable extension for writing SQL functions in JavaScript: scalar +functions, aggregates, window functions and collations (ADFA-7081). It is +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.3.7 with six +changes of ours, listed [below](#changes-in-this-build). The JavaScript engine, +[quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. + +## Load it + +```text +$ sqlite3 my.db +sqlite> .load sqlite-js +``` + +If `.load sqlite-js` reports that it cannot find the file, give the full path, +which `echo $PREFIX/lib/sqlite-js` prints. (`.load` does not expand `$PREFIX` +itself.) + +Load it in the sessions that need it, rather than in `~/.sqliterc`, so that +running a database's stored JavaScript stays a deliberate step: see +[Databases from other people](#databases-from-other-people). + +## Examples + +A scalar function returns one value per row. Its code is a function that gets +the SQL arguments as an array: + +```sql +SELECT js_create_scalar('slugify', '(function (args) { + return args[0].toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); +})'); +SELECT slugify('Hello, World!'); -- hello-world +``` + +An aggregate takes code to run before the first row, a function to call for +each row, and a function that returns the result: + +```sql +SELECT js_create_aggregate('median', + 'values = [];', + '(function (args) { values.push(args[0]); })', + '(function () { + values.sort((a, b) => a - b); + const m = values.length >> 1; + return values.length % 2 ? values[m] : (values[m - 1] + values[m]) / 2; + })'); +WITH v(x) AS (VALUES (3), (1), (4), (1), (5)) +SELECT median(x) FROM v; -- 3 +``` + +A window function also takes a function that returns the current result and +one that removes a row that leaves the window: + +```sql +SELECT js_create_window('moving_sum', + 'total = 0;', + '(function (args) { total += args[0]; })', + '(function () { return total; })', + '(function () { return total; })', + '(function (args) { total -= args[0]; })'); +WITH v(x) AS (VALUES (1), (2), (3), (4)) +SELECT group_concat(s, ' ') FROM ( + SELECT moving_sum(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS s + FROM v); -- 1 3 5 7 +``` + +A collation compares two strings, like a JavaScript sort comparator: + +```sql +SELECT js_create_collation('by_length', '(function (a, b) { + return a.length - b.length || a.localeCompare(b); +})'); +WITH v(s) AS (VALUES ('ccc'), ('a'), ('bb')) +SELECT group_concat(s, ' ') FROM (SELECT s FROM v ORDER BY s COLLATE by_length); -- a bb ccc +``` + +`js_eval` runs code and returns its value. In JavaScript, `db.exec` runs SQL +on the same database, with `?` parameters: + +```sql +SELECT js_eval('[1, 2, 3].map(x => x * x).join(" ")'); -- 1 4 9 +SELECT js_eval('(function () { + const rows = db.exec("SELECT ? * 2 AS doubled", 21); + rows.next(); + return rows.get(0); +})()'); -- 42 +``` + +## Functions + +| Function | What it does | +|----------|--------------| +| `js_create_scalar(name, code)` | Creates a scalar function. | +| `js_create_aggregate(name, init, step, final)` | Creates an aggregate. `init` is code; `step` and `final` are functions. | +| `js_create_window(name, init, step, final, value, inverse)` | Creates a window function. | +| `js_create_collation(name, code)` | Creates a collation. | +| `js_eval(code)` | Runs code; returns the value of its last expression. | +| `js_init_table()` | Creates the `js_functions` table. From then on, `js_create_*` also stores each function there. | +| `js_init_table(1)` | Also creates every function stored in `js_functions`. | +| `js_load_text(path)`, `js_load_blob(path)` | Return a file's contents as TEXT or as a BLOB. | +| `js_set_memory_limit(bytes)` | Sets the memory JavaScript may use on this connection; 0 means no limit. | +| `js_set_max_stack_size(bytes)` | Sets JavaScript's stack limit. Leave it above 0: 0 turns the check off, and deep recursion then crashes `sqlite3`. | +| `js_version()`, `js_version(1)` | The sqlite-js version, or with an argument, the quickjs-ng version. | + +The functions you create last for the session. To keep them, call +`js_init_table()` before creating them, then `js_init_table(1)` in a later +session. A function cannot be redefined in the session that created it; use a +new session. + +All but `js_version` work only in top-level SQL, not in views, triggers, CHECK +constraints, generated columns or indexes. The functions you create have no +such restriction of their own, but `sqlite3` turns `trusted_schema` off, which +keeps them out of a database's views and triggers as well (TEMP ones excepted); run +`PRAGMA trusted_schema = ON;` in a session to use them there. The collations +you create work in table and index definitions either way. + +## Values + +SQL values reach JavaScript as follows: + +| SQL | JavaScript | +|-----|------------| +| NULL | `null` | +| INTEGER, REAL | number | +| TEXT | string | +| BLOB | `ArrayBuffer` | + +A result goes back to SQL as follows: `null` and `undefined` become NULL, a +boolean an INTEGER (1 or 0), a whole number from -(2^53 - 1) to 2^53 - 1 an +INTEGER and any other number a REAL, a BigInt an INTEGER, a string TEXT, and an +`ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects +become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters +of `db.exec` convert the same way. + +JavaScript has a single number type, a double. So a REAL that holds a whole +number, such as 3.0, comes back as the INTEGER 3, and an INTEGER beyond +±(2^53 - 1) loses precision in JavaScript. To keep such an INTEGER exact, pass +it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. + +## JavaScript here + +- quickjs-ng runs modern JavaScript (ES2023 and later), with no browser or + Node.js APIs: no `fetch`, `require`, `setTimeout`, DOM or `process`. +- Promises never settle and `async` functions never finish, because nothing + runs JavaScript's job queue. Write synchronous code. +- JavaScript has no file, network or process functions of its own. Through + `db.exec` it can run any SQL, including `js_load_text` and the shell's + `readfile()` and `writefile()`. +- `console.log` and `print` write to `sqlite3`'s standard output, among the + query results. +- Each session has its own JavaScript globals, shared by `js_eval` and the + scalar functions and collations you create. Each running aggregate or window + function gets globals of its own, set up by its `init` code. + +## Limits + +- **Memory.** JavaScript may use 64 MB per session. Code that needs more fails + with an "out of memory" error, and the session stays usable. + `js_set_memory_limit` changes the limit; memory that globals still hold + counts against it until they are cleared. +- **Endless code.** Ctrl-C stops running JavaScript: the statement fails with + an "interrupted" error, even if the code catches exceptions, and `sqlite3` + keeps running. +- **Stack.** 1 MB by default; `js_set_max_stack_size` changes it. + +## Databases from other people + +A database can store JavaScript in its `js_functions` table, and +`js_init_table(1)` runs it with your access. Through `db.exec` it can run any +SQL: read and change every attached database and, in `sqlite3`, read and write +your files with `readfile()` and `writefile()` and load other extensions. Call +`js_init_table(1)` only on databases you trust. + +Nothing else in a database runs JavaScript on its own: views, triggers, CHECK +constraints and generated columns cannot call `js_eval` or the other +`js_*` functions (see [changes](#changes-in-this-build)), and `sqlite3` turns +`trusted_schema` off as well. + +## Changes in this build + +Six patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. + +| Patch | Change | +|-------|--------| +| `0001` | Ctrl-C and `sqlite3_interrupt()` stop running JavaScript. Upstream, endless code hangs `sqlite3`. | +| `0002` | A 64 MB memory limit, and `js_set_memory_limit`. Upstream, code that keeps allocating takes all the memory there is. | +| `0003` | `js_eval` and the other functions that run code, read files or change the runtime work only in top-level SQL. Upstream, with `trusted_schema` on, a view can call them. | +| `0004` | A result that is an `ArrayBuffer` or typed array is a BLOB. Upstream, it is NULL, so a BLOB cannot pass through a function. | +| `0005` | A whole-number result is an INTEGER. Upstream, an INTEGER outside the 32-bit range comes back as a REAL. | +| `0006` | An exception in an aggregate's or window function's step is an SQL error. Upstream, it is ignored, and the result is silently wrong. | + +The build also exports only the extension's entry points, and adds the one +SQLite derives from the file name, so that `.load sqlite-js` needs no entry +point argument. + +## Tests + +```text +$ bash $PREFIX/share/sqlite-js/run-tests.sh +``` + +They print TAP and exit 0 only if every test passes. With the `sqlite-brotli` +package installed, they also check that both extensions load together. + +## License + +sqlite-js is under the Apache License 2.0 and quickjs-ng under the MIT +License; both licenses are in `$PREFIX/share/doc/sqlite-js/`. diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh new file mode 100644 index 0000000..95964e0 --- /dev/null +++ b/packages/sqlite-js/build.sh @@ -0,0 +1,63 @@ +TERMUX_PKG_HOMEPAGE=https://github.com/sqliteai/sqlite-js +TERMUX_PKG_DESCRIPTION="SQLite extension for functions written in JavaScript" +TERMUX_PKG_LICENSE="Apache-2.0, MIT" +TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" +TERMUX_PKG_MAINTAINER="@appdevforall" +TERMUX_PKG_VERSION=1.3.7 +TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz +TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 +TERMUX_PKG_BUILD_DEPENDS="libsqlite" +TERMUX_PKG_RECOMMENDS="sqlite" +TERMUX_PKG_BUILD_IN_SRC=true +# The *.patch files are ours (ADFA-7081) and sent upstream; check each one +# against a new upstream version, and drop those upstream has merged. +TERMUX_PKG_AUTO_UPDATE=false + +termux_step_post_get_source() { + # QuickJS (quickjs-ng, amalgamated into libs/quickjs.c) is MIT-licensed, + # with the license only in the comment that heads each amalgamated file. + # Collect every copyright line, then the license text once. + { + grep -o 'Copyright (c) [^*]*' libs/quickjs.c | sed 's/[[:space:]]*$//' | sort -u + echo + awk '/Permission is hereby granted/ { on = 1 } + on { sub(/^ \* ?/, ""); print } + on && /THE SOFTWARE\.$/ { exit }' libs/quickjs.c + } >LICENSE.quickjs +} + +termux_step_make() { + # QuickJS is compiled in. The SQLite API comes from the loading process + # through sqlite3ext.h, so the extension works with any sqlite3 that can + # load it. -idirafter puts the SQLite headers bundled in libs/ after + # Termux's, which $CPPFLAGS adds with -isystem; quickjs.h is only in libs/. + # + # SQLite derives the entry point from the file name, sqlite3_sqlitejs_init + # for sqlite-js.so, but upstream names it sqlite3_js_init, so --defsym adds + # the first as an alias. sqlite-js.map exports only those two: SQLite opens + # extensions with RTLD_GLOBAL, so an exported QuickJS function or + # sqlite3_api could bind to another extension's copy. + $CC $CPPFLAGS $CFLAGS -fPIC -shared -DQJS_BUILD_LIBC -idirafter libs \ + src/sqlitejs.c libs/quickjs.c \ + -o sqlite-js.so \ + $LDFLAGS -lm \ + -Wl,--version-script="$TERMUX_PKG_BUILDER_DIR/sqlite-js.map" \ + -Wl,--defsym=sqlite3_sqlitejs_init=sqlite3_js_init + + local exports + exports=$($NM -D --defined-only sqlite-js.so | awk '{ print $3 }' | sort | tr '\n' ' ') + if [[ $exports != "sqlite3_js_init sqlite3_sqlitejs_init " ]]; then + termux_error_exit "sqlite-js.so must export only its entry points, but exports: $exports" + fi +} + +termux_step_make_install() { + # In $PREFIX/lib, where the sqlite3 shell's RUNPATH finds it, so + # `.load sqlite-js` works without a path. + install -Dm600 sqlite-js.so "$TERMUX_PREFIX/lib/sqlite-js.so" + install -Dm600 "$TERMUX_PKG_BUILDER_DIR/README.md" \ + "$TERMUX_PREFIX/share/doc/sqlite-js/README.md" + # Executable, so it runs directly as well as with bash. + install -Dm700 "$TERMUX_PKG_BUILDER_DIR/tests/run-tests.sh" \ + "$TERMUX_PREFIX/share/sqlite-js/run-tests.sh" +} diff --git a/packages/sqlite-js/sqlite-js.map b/packages/sqlite-js/sqlite-js.map new file mode 100644 index 0000000..9c41c91 --- /dev/null +++ b/packages/sqlite-js/sqlite-js.map @@ -0,0 +1,12 @@ +/* + * Linker version script for sqlite-js.so: export only the entry points. + * sqlite3_js_init is upstream's; sqlite3_sqlitejs_init is the name SQLite + * derives from the file name, added with --defsym (see build.sh). + */ +{ + global: + sqlite3_js_init; + sqlite3_sqlitejs_init; + local: + *; +}; diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh new file mode 100644 index 0000000..576d2fb --- /dev/null +++ b/packages/sqlite-js/tests/run-tests.sh @@ -0,0 +1,542 @@ +#!/usr/bin/env bash +# +# Acceptance tests for the sqlite-js extension (ADFA-7081). +# +# Runs in Code on the Go's terminal with the sqlite, sqlite-js and +# sqlite-brotli packages installed, and on a Linux host against a local build. +# +# Usage: bash run-tests.sh +# +# Environment: +# SQLITE3 the sqlite3 shell to test (default: sqlite3) +# EXT the extension, as given to .load (default: sqlite-js) +# BROTLI_EXT sqlite-brotli, as given to .load, for AC12 (default: sqlite-brotli) +# README the README whose sql examples to run (default: found next +# to this script, installed or in the source tree) +# +# Prints TAP. Exits 0 only if every test passes. AC numbers are those of the +# acceptance criteria in ADFA-7081. + +set -u + +SQLITE3=${SQLITE3:-sqlite3} +EXT=${EXT:-sqlite-js} +BROTLI_EXT=${BROTLI_EXT:-sqlite-brotli} +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) + +usage() { + sed -n '3,19s/^# \{0,1\}//p' "$0" +} + +while getopts h opt; do + case $opt in + h) + usage + exit 0 + ;; + *) + usage >&2 + exit 2 + ;; + esac +done + +# Installed, the README is in $PREFIX/share/doc/sqlite-js and this script in +# $PREFIX/share/sqlite-js; in the source tree, the README is one level up. +if [[ -z ${README:-} ]]; then + for c in "$SCRIPT_DIR/../doc/sqlite-js/README.md" "$SCRIPT_DIR/../README.md"; do + if [[ -f $c ]]; then + README=$c + break + fi + done +fi + +# Relative paths must survive the cd into the work directory. +abs_path() { + if [[ $1 == */* && $1 != /* ]]; then + printf '%s/%s' "$(cd "$(dirname "$1")" && pwd)" "$(basename "$1")" + else + printf '%s' "$1" + fi +} +EXT=$(abs_path "$EXT") +BROTLI_EXT=$(abs_path "$BROTLI_EXT") +[[ -n ${README:-} ]] && README=$(abs_path "$README") + +# As an SQL string literal. +sql_str() { + printf "'%s'" "${1//\'/\'\'}" +} + +# As a sqlite3 shell dot-command argument: in double quotes, the shell reads +# backslash escapes. +dot_arg() { + local s=${1//\\/\\\\} + printf '"%s"' "${s//\"/\\\"}" +} + +LOAD_EXT=".load $(dot_arg "$EXT")" +LOAD_BROTLI=".load $(dot_arg "$BROTLI_EXT")" + +WORK=$(mktemp -d "${TMPDIR:-/tmp}/sqlite-js-tests.XXXXXX") || exit 1 +trap 'rm -rf "$WORK"' EXIT +cd "$WORK" || exit 1 +DB=$WORK/test.db + +n=0 +failed=0 +# Microseconds; the locale may make the decimal separator a comma. +last=${EPOCHREALTIME//[!0-9]/} + +# Sets took to the seconds since the previous test finished, to spot slow +# tests on a phone. Not run in $(...): a subshell could not update last. +took= +elapsed() { + local now=${EPOCHREALTIME//[!0-9]/} tenths + tenths=$(((now - last) / 100000)) + took="$((tenths / 10)).$((tenths % 10)) s" + last=$now +} + +ok() { + n=$((n + 1)) + elapsed + echo "ok $n - $1 ($took)" +} + +not_ok() { + n=$((n + 1)) + failed=$((failed + 1)) + elapsed + echo "not ok $n - $1 ($took)" + shift + local line + for line in "$@"; do + printf '# %s\n' "${line:0:400}" + done +} + +note() { + printf '# %s\n' "$*" +} + +# Runs SQL against $DB in a new session, with the extension loaded. Every +# session starts without the functions created in earlier ones. +sql() { + "$SQLITE3" -bail -batch -noheader -cmd "$LOAD_EXT" "$DB" "$@" +} + +# The same, but going on after an error, as an interactive session does. The +# SQL goes in on standard input: sqlite3 exits at the first error in an SQL +# argument, -bail or not. +sql_nobail() { + printf '%s\n' "$@" | "$SQLITE3" -batch -noheader -cmd "$LOAD_EXT" "$DB" +} + +# expect NAME WANT SQL...: the SQL must succeed and print exactly WANT. +expect() { + local name=$1 want=$2 got rc + shift 2 + got=$(sql "$@" 2>&1) + rc=$? + if [[ $rc -eq 0 && $got == "$want" ]]; then + ok "$name" + else + not_ok "$name" "exit status $rc" "want: $want" "got: $got" + fi +} + +# expect_error NAME PATTERN SQL...: the SQL must fail with an SQL error whose +# message matches the extended regex PATTERN. The shell exits with the SQLite +# result code; 128 and up means a signal, a crash. +expect_error() { + local name=$1 pattern=$2 got rc + shift 2 + got=$(sql "$@" 2>&1) + rc=$? + if [[ $rc -ge 1 && $rc -lt 128 && $got =~ $pattern ]]; then + ok "$name" + else + not_ok "$name" "exit status $rc, want 1 to 127" "want an error matching: $pattern" "got: $got" + fi +} + +# expect_nobail NAME PATTERN SQL...: like sql_nobail, the output (errors +# included) must match the extended regex PATTERN, and the shell must not +# crash. +expect_nobail() { + local name=$1 pattern=$2 got rc + shift 2 + got=$(sql_nobail "$@" 2>&1) + rc=$? + if [[ $rc -lt 128 && $got =~ $pattern ]]; then + ok "$name" + else + not_ok "$name" "exit status $rc" "want output matching: $pattern" "got: $got" + fi +} + +# Starts the SQL in the background, sends SIGINT, as Ctrl-C does, after a +# second, and expects the statement to fail as interrupted within 5 seconds. +# sqlite3 is started directly, not through sql(), so that $! is its process. +expect_sigint_stops() { + local name=$1 pid i rc got + shift + "$SQLITE3" -bail -batch -noheader -cmd "$LOAD_EXT" "$DB" "$@" >sigint.out 2>&1 & + pid=$! + sleep 1 + kill -INT "$pid" 2>/dev/null + for ((i = 0; i < 50; i++)); do + kill -0 "$pid" 2>/dev/null || break + sleep 0.1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -KILL "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + not_ok "$name" "still running 5 s after SIGINT; killed" + return + fi + wait "$pid" + rc=$? + got=$(&1) +# Bellard's QuickJS has no version function, so sqlite-js does not build with it. +if [[ $got =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + ok "AC2: js_version(1) reports the quickjs-ng version" + note "quickjs-ng $got" +else + not_ok "AC2: js_version(1) reports the quickjs-ng version" "got: $got" +fi + +# --- AC3: scalar, aggregate, window and collation functions ------------------ +# +# First the README's examples, as written: each ```sql block runs in a session +# of its own, and its "-- result" comments are the last lines it must print. + +if [[ -n ${README:-} && -f $README ]]; then + note "README: $README" + rm -f example*.sql + awk '/^```sql$/ { n++; on = 1; next } /^```$/ { on = 0 } on { print > ("example" n ".sql") }' "$README" + examples=0 + for f in example*.sql; do + [[ -f $f ]] || continue + examples=$((examples + 1)) + want=$(grep -o -- '-- .*$' "$f" | sed 's/^-- //') + lines=$(printf '%s\n' "$want" | wc -l) + got=$(sql "$(<"$f")" 2>&1) + rc=$? + first=$(grep -m1 -o 'js_create_[a-z]*(.[a-z_]*\|js_eval' "$f") + if [[ $rc -eq 0 && -n $want && $(printf '%s\n' "$got" | tail -n "$lines") == "$want" ]]; then + ok "AC3: README example ${f//[!0-9]/} ($first...) prints what it says" + else + not_ok "AC3: README example ${f//[!0-9]/} ($first...) prints what it says" \ + "exit status $rc" "want (last lines): $want" "got: $got" + fi + done + [[ $examples -ge 5 ]] || not_ok "AC3: the README has at least 5 sql examples" "found $examples in $README" +else + not_ok "AC3: README examples" "README not found; set README" +fi + +MEDIAN="SELECT js_create_aggregate('median', 'values = [];', '(function (args) { values.push(args[0]); })', '(function () { values.sort((a, b) => a - b); const m = values.length >> 1; return values.length % 2 ? values[m] : (values[m - 1] + values[m]) / 2; })');" +expect "AC3: an aggregate keeps the state of each group apart (GROUP BY)" $'0\na|2\nb|25\nc|7' \ + "$MEDIAN" \ + "WITH v(g, x) AS (VALUES ('a', 1), ('b', 10), ('a', 3), ('c', 7), ('b', 40), ('a', 2)) + SELECT g, median(x) FROM v GROUP BY g ORDER BY g;" + +expect "AC3: two aggregates of one function in one query keep separate state" $'0\n2|20' \ + "$MEDIAN" \ + "WITH v(x, y) AS (VALUES (1, 10), (2, 20), (3, 30)) SELECT median(x), median(y) FROM v;" + +expect "AC3: a window function over partitions" $'0\na:1 a:3 a:5 b:10 b:30' \ + "SELECT js_create_window('moving_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');" \ + "WITH v(g, x) AS (VALUES ('a', 1), ('a', 2), ('a', 3), ('b', 10), ('b', 20)) + SELECT group_concat(g || ':' || s, ' ') FROM ( + SELECT g, moving_sum(x) OVER (PARTITION BY g ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS s + FROM v ORDER BY g, x);" + +expect "AC3: a collation orders a column, its index and a UNIQUE constraint" $'0\na bb ccc\n1' \ + "SELECT js_create_collation('nocase_js', '(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); })');" \ + "CREATE TEMP TABLE words (w TEXT COLLATE nocase_js UNIQUE); INSERT INTO words VALUES ('bb'), ('ccc'), ('a');" \ + "SELECT group_concat(w, ' ') FROM (SELECT w FROM words ORDER BY w);" \ + "SELECT count(*) FROM words WHERE w = 'BB';" + +expect_error "AC3: the collation's UNIQUE index rejects a duplicate that differs in case" "UNIQUE constraint failed" \ + "SELECT js_create_collation('nocase_js', '(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); })');" \ + "CREATE TEMP TABLE words (w TEXT COLLATE nocase_js UNIQUE); INSERT INTO words VALUES ('bb');" \ + "INSERT INTO words VALUES ('BB');" + +expect "AC3: scalar functions and js_eval share the session's globals" $'3\n0\n5' \ + "SELECT js_eval('globalThis.base = 3');" \ + "SELECT js_create_scalar('add_base', '(function (args) { return base + args[0]; })');" \ + "SELECT add_base(2);" + +# --- AC4: stored functions load in a new session ---------------------------- + +DB=$WORK/ac4.db +sql "SELECT js_init_table();" \ + "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 2; })');" \ + "$MEDIAN" \ + "SELECT js_create_window('moving_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');" \ + "SELECT js_create_collation('by_length', '(function (a, b) { return a.length - b.length || a.localeCompare(b); })');" \ + >/dev/null 2>&1 || not_ok "AC4: store four functions with js_init_table()" +expect "AC4: js_functions holds the four functions" "by_length|collation;median|aggregate;moving_sum|window;twice|scalar" \ + "SELECT group_concat(name || '|' || kind, ';') FROM (SELECT name, kind FROM js_functions ORDER BY name);" +expect_error "AC4: a new session does not have them before js_init_table(1)" "no such function: twice" \ + "SELECT twice(21);" +expect "AC4: js_init_table(1) in a new session creates all four" $'0\n42|2|1 3 5|a bb ccc' \ + "SELECT js_init_table(1);" \ + "WITH v(x) AS (VALUES (1), (2), (3)), w(s) AS (VALUES ('ccc'), ('a'), ('bb')) + SELECT twice(21), + (SELECT median(x) FROM v), + (SELECT group_concat(s, ' ') FROM (SELECT moving_sum(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS s FROM v)), + (SELECT group_concat(s, ' ') FROM (SELECT s FROM w ORDER BY s COLLATE by_length));" +expect_error "AC4: a function cannot be redefined in the session that created it" \ + "Function updates must be performed using a separate database connection" \ + "SELECT js_init_table(1);" \ + "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 3; })');" +expect "AC4: a new session can redefine it, and stores the new code" $'0\n63' \ + "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 3; })');" \ + "SELECT twice(21);" +DB=$WORK/test.db + +# --- AC5: JavaScript errors are SQL errors ----------------------------------- + +expect_error "AC5: an exception thrown by js_eval is an SQL error with its message" "boom" \ + "SELECT js_eval('throw new Error(\"boom\")');" +expect_error "AC5: a reference to an undefined name is an SQL error" "undefined_name is not defined" \ + "SELECT js_eval('undefined_name + 1');" +expect_error "AC5: a syntax error in js_eval is an SQL error" "SyntaxError|expected|unexpected" \ + "SELECT js_eval('function (');" +expect_error "AC5: an exception in a scalar function is an SQL error" "scalar boom" \ + "SELECT js_create_scalar('fails', '(function (args) { throw new Error(\"scalar boom\"); })');" \ + "SELECT fails(1);" +expect_error "AC5: an exception in an aggregate step is an SQL error" "step boom" \ + "SELECT js_create_aggregate('agg_fails', 'n = 0;', '(function (args) { throw new Error(\"step boom\"); })', '(function () { return n; })');" \ + "WITH v(x) AS (VALUES (1), (2)) SELECT agg_fails(x) FROM v;" +expect_error "AC5: an exception in a window function's inverse is an SQL error" "inverse boom" \ + "SELECT js_create_window('inverse_fails', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { throw new Error(\"inverse boom\"); })');" \ + "WITH v(x) AS (VALUES (1), (2), (3)) SELECT inverse_fails(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM v;" +expect_error "AC5: code with a syntax error does not create a function" "SyntaxError|expected|unexpected" \ + "SELECT js_create_scalar('broken', '(function (args) { return args[0] +; })');" +expect_error "AC5: code that is not a function does not create one" "must evaluate to a function" \ + "SELECT js_create_scalar('not_a_function', '42');" +expect_error "AC5: js_create_scalar with non-TEXT arguments is an SQL error" "Two parameters of type TEXT are required" \ + "SELECT js_create_scalar(1, 2);" +expect_error "AC5: js_eval with a non-TEXT argument is an SQL error" "A parameter of type TEXT is required" \ + "SELECT js_eval(NULL);" + +# --- AC6: values pass correctly in both directions ------------------------- + +IDENTITY="SELECT js_create_scalar('identity', '(function (args) { return args[0]; })');" +JSTYPE="SELECT js_create_scalar('jstype', '(function (args) { const v = args[0]; return v === null ? \"null\" : v instanceof ArrayBuffer ? \"ArrayBuffer\" : typeof v; })');" +expect "AC6: SQL values reach JavaScript with the right type and come back unchanged" \ + $'0\n0\nnull:null:1 number:integer:1 number:integer:1 number:integer:1 number:integer:1 number:integer:1 number:integer:1 number:real:1 number:real:1 number:real:1 string:text:1 string:text:1 string:text:1 ArrayBuffer:blob:1 ArrayBuffer:blob:1 ArrayBuffer:blob:1' \ + "$IDENTITY" "$JSTYPE" \ + "WITH v(x) AS (VALUES (NULL), (0), (42), (-7), (2147483648), (-2147483649), (9007199254740991), (3.5), (-0.25), (1e300), + ('plain'), ('Grüße aus Zürich — 世界 ✓ 😀'), (''), (x'00ff10'), (x''), (randomblob(100000))) + SELECT group_concat(jstype(x) || ':' || typeof(identity(x)) || ':' || (identity(x) IS x), ' ') FROM v;" +expect "AC6: JavaScript results reach SQL with the right type" \ + "1|0|4611686018427387904|X'010203'|X'0203'|X'0708'|NULL|{\"a\":1}|NULL|5|real" \ + "SELECT quote(js_eval('true')), quote(js_eval('false')), quote(js_eval('2n ** 62n')), + quote(js_eval('new Uint8Array([1, 2, 3])')), quote(js_eval('new Uint8Array([1, 2, 3]).subarray(1)')), + quote(js_eval('new Uint8Array([7, 8]).buffer')), quote(js_eval('({a: 1})')), + js_eval('JSON.stringify({a: 1})'), quote(js_eval('undefined')), quote(js_eval('2.5 * 2')), + typeof(js_eval('0.1 + 0.2'));" +expect "AC6: a function can make a BLOB from a BLOB" $'0\nX\'030201\'' \ + "SELECT js_create_scalar('reverse_bytes', '(function (args) { return new Uint8Array(args[0]).reverse(); })');" \ + "SELECT quote(reverse_bytes(x'010203'));" +expect "AC6: text passes byte for byte, non-ASCII included" $'0\n0\n1|1|1' \ + "$IDENTITY" \ + "SELECT js_create_scalar('js_length', '(function (args) { return args[0].length; })');" \ + "SELECT identity('Grüße 世界 😀') = 'Grüße 世界 😀', js_length('Grüße 世界') = 8, length(identity('😀')) = 1;" +expect "AC6: as documented, a whole REAL comes back as an INTEGER, and an INTEGER beyond 2^53 - 1 as a REAL" $'0\n3|real' \ + "$IDENTITY" "SELECT quote(identity(3.0)), typeof(identity(9007199254740993));" +expect "AC6: as documented, an INTEGER passed as TEXT keeps every digit with BigInt" $'0\n9223372036854775807' \ + "SELECT js_create_scalar('big_next', '(function (args) { return BigInt(args[0]) + 1n; })');" \ + "SELECT big_next(CAST(9223372036854775806 AS TEXT));" +expect "AC6: db.exec passes parameters and returns rows with the same conversions" \ + "integer,real,text,blob,null|X'0102'" \ + "SELECT js_eval('(function () { + const r = db.exec(\"SELECT typeof(?), typeof(?), typeof(?), typeof(?), typeof(?)\", 2147483648, 2.5, \"x\", new Uint8Array([1]), null); + r.next(); + return [0, 1, 2, 3, 4].map(i => r.get(i)).join(); + })()'), quote(js_eval('(function () { const r = db.exec(\"SELECT x''0102''\"); r.next(); return r.get(0); })()'));" +printf 'line one\nline two ✓\n' >loadme.txt +expect "js_load_text and js_load_blob read a file" "line one|X'6C696E65206F6E650A6C696E652074776F20E29C930A'" \ + "SELECT substr(js_load_text($(sql_str "$WORK/loadme.txt")), 1, 8), quote(js_load_blob($(sql_str "$WORK/loadme.txt")));" + +# --- AC7: the crash cases fixed in 1.3.6 are SQL errors ---------------------- + +DB=$WORK/ac7.db +JS_FUNCTIONS="CREATE TABLE js_functions (name TEXT PRIMARY KEY COLLATE NOCASE, kind TEXT NOT NULL, init_code TEXT, step_code TEXT, final_code TEXT, value_code TEXT, inverse_code TEXT);" +rm -f "$DB" +expect_error "AC7: a stored scalar with NULL step_code is an SQL error, not a crash" "step code is required" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind) VALUES ('no_code', 'scalar');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: a stored aggregate with NULL final_code is an SQL error, not a crash" "final code is required" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind, step_code) VALUES ('no_final', 'aggregate', '(function (args) {})');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: a stored function of an unknown kind is an SQL error" "Unsupported function kind" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind, step_code) VALUES ('odd', 'procedure', '(function (args) {})');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: a js_functions table with other columns is an SQL error, not a crash" "no such column" \ + "CREATE TABLE js_functions (name TEXT, kind TEXT);" "INSERT INTO js_functions VALUES ('f', 'scalar');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: stored code that is not a function is an SQL error" "must evaluate to a function" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind, step_code) VALUES ('not_fn', 'scalar', '42');" "SELECT js_init_table(1);" +DB=$WORK/test.db + +# --- AC8: Ctrl-C stops runaway JavaScript ----------------------------------- + +expect_sigint_stops "AC8: SIGINT (Ctrl-C) stops while (true) {} in js_eval" \ + "SELECT js_eval('while (true) {}');" +expect_sigint_stops "AC8: SIGINT stops an endless scalar function" \ + "SELECT js_create_scalar('forever', '(function (args) { for (;;) {} })');" "SELECT forever(1);" +expect_sigint_stops "AC8: SIGINT stops code that catches every exception" \ + "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');" + +# In batch mode the shell exits after an interrupt, whatever stopped; only an +# interactive session goes on. script(1) runs one on a pseudo-terminal, where +# the byte 0x03 is Ctrl-C. +if command -v script >/dev/null 2>&1; then + cmd=$(printf '%q ' "$SQLITE3" -noheader -cmd "$LOAD_EXT" "$DB") + got=$({ + sleep 1 + printf '%s\n' "SELECT js_eval('while (true) {}');" + sleep 2 + printf '\003' + sleep 1 + printf '%s\n' "SELECT 'still' || ' alive';" + sleep 1 + printf '.quit\n' + } | timeout 30 script -q -c "$cmd" /dev/null 2>&1 | tr -d '\r') + if [[ $got == *interrupted* && $got == *"still alive"* ]]; then + ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" + else + not_ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" "got: $got" + fi +else + not_ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" \ + "needs script(1); install util-linux" +fi + +# --- AC9: the memory limit ------------------------------------------------------ + +expect "AC9: the default limit allows 16 MB" "16777216" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" +expect_error "AC9: the default limit (64 MB) refuses 128 MB" "out of memory" \ + "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');" +expect_nobail "AC9: code that never stops allocating fails at the limit, and the session stays usable" \ + "out of memory.*"$'\n'"1,2,3$" \ + "SELECT js_eval('(function () { const a = []; for (;;) a.push(new Array(100000).fill(1)); })()');" \ + "SELECT js_eval('[1, 2, 3].join()');" +expect_nobail "AC9: memory held by a global counts until the global is cleared" \ + "out of memory.*"$'\n'"16777216$" \ + "SELECT js_eval('globalThis.keep = new ArrayBuffer(60 * 1024 * 1024); 0');" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" \ + "SELECT js_eval('keep = null; new ArrayBuffer(16 * 1024 * 1024).byteLength');" +# js_set_memory_limit returns NULL, which prints as an empty line. +expect "AC9: js_set_memory_limit raises the limit" $'\n134217728' \ + "SELECT js_set_memory_limit(256 * 1024 * 1024);" \ + "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');" +expect_error "AC9: js_set_memory_limit lowers the limit" "out of memory" \ + "SELECT js_set_memory_limit(8 * 1024 * 1024);" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" +for bad in -1 1.5 "'64'" NULL; do + expect_error "AC9: js_set_memory_limit($bad) is an SQL error" "The memory limit must be an integer number of bytes" \ + "SELECT js_set_memory_limit($bad);" +done + +# --- AC10: a database cannot run JavaScript from its schema ---------------------- + +# The database is made without the extension, as someone else's would be. +rm -f untrusted.db +"$SQLITE3" -bail -batch untrusted.db " +CREATE TABLE t (a); +CREATE TABLE log (msg); +CREATE VIEW v_eval AS SELECT js_eval('6 * 7') AS x; +CREATE VIEW v_load AS SELECT js_load_text('/proc/self/status') AS x; +CREATE VIEW v_init AS SELECT js_init_table(1) AS x; +CREATE TRIGGER t_insert AFTER INSERT ON t BEGIN INSERT INTO log VALUES (js_eval('\"trigger ran\"')); END; +" || not_ok "AC10: create a database with JavaScript in its schema" +DB=$WORK/untrusted.db +for trusted in "sqlite3's default" ON; do + if [[ $trusted == ON ]]; then pragma="PRAGMA trusted_schema = ON;"; else pragma="SELECT 1 WHERE 0;"; fi + for view_function in v_eval:js_eval v_load:js_load_text v_init:js_init_table; do + expect_error "AC10: a view cannot call ${view_function#*:} (trusted_schema $trusted)" "unsafe use of ${view_function#*:}" \ + "$pragma" "SELECT x FROM ${view_function%%:*};" + done + expect_error "AC10: a trigger cannot call js_eval (trusted_schema $trusted)" "unsafe use of js_eval" \ + "$pragma" "INSERT INTO t VALUES (1);" +done +expect "AC10: so the trigger never ran" "0" "SELECT count(*) FROM log;" +# The view is in the database file: SQLite trusts the TEMP schema, which only +# the session itself can fill. +DB=$WORK/views.db +"$SQLITE3" -bail -batch "$DB" "CREATE VIEW v_twice AS SELECT twice(21) AS x;" || + not_ok "AC10: create a view that uses a function made with js_create_scalar" +TWICE="SELECT js_create_scalar('twice', '(function (args) { return args[0] * 2; })');" +expect "AC10: with trusted_schema ON, a view can use a function made with js_create_scalar" $'0\n42' \ + "PRAGMA trusted_schema = ON;" "$TWICE" "SELECT x FROM v_twice;" +expect_error "AC10: with sqlite3's default (trusted_schema off), it cannot" "unsafe use of twice" \ + "$TWICE" "SELECT x FROM v_twice;" +DB=$WORK/test.db + +# --- AC11: no file or process access through the std or os modules ------------ + +expect "AC11: std, os and bjson are not globals; neither are require or process" "undefined undefined undefined undefined undefined" \ + "SELECT js_eval('[typeof std, typeof os, typeof bjson, typeof require, typeof process].join(\" \")');" +expect "AC11: import(\"os\") never completes" $'1\npending' \ + "SELECT js_eval('globalThis.r = \"pending\"; import(\"os\").then(m => { r = \"loaded: \" + typeof m.exec; }, e => { r = \"rejected\"; }); 1');" \ + "SELECT js_eval('r');" +printf 'globalThis.moduleRan = true;\nexport const x = 1;\n' >module.mjs +expect "AC11: import() of a module file never runs it" $'1\nfalse' \ + "SELECT js_eval('import(\"./module.mjs\"); 1');" "SELECT js_eval('String(globalThis.moduleRan === true)');" + +# --- AC12: sqlite-js and sqlite-brotli load together --------------------------- + +if "$SQLITE3" -bail -batch :memory: "$LOAD_BROTLI" "SELECT 1;" >/dev/null 2>&1; then + BOTH="SELECT CAST(decodeBrotli(encodeBrotli(js_eval('\"ab\".repeat(5000)'))) AS TEXT) = js_eval('\"ab\".repeat(5000)'), + js_eval('(function () { const r = db.exec(\"SELECT length(decodeBrotli(encodeBrotli(?)))\", \"hello\"); r.next(); return r.get(0); })()');" + expect "AC12: sqlite-js, then sqlite-brotli: both work in one session" "1|5" "$LOAD_BROTLI" "$BOTH" + got=$("$SQLITE3" -bail -batch -noheader -cmd "$LOAD_BROTLI" -cmd "$LOAD_EXT" "$DB" "$BOTH" 2>&1) + if [[ $got == "1|5" ]]; then + ok "AC12: sqlite-brotli, then sqlite-js: both work in one session" + else + not_ok "AC12: sqlite-brotli, then sqlite-js: both work in one session" "got: $got" + fi +else + not_ok "AC12: sqlite-js and sqlite-brotli load together" \ + "cannot load $BROTLI_EXT; install the sqlite-brotli package or set BROTLI_EXT" +fi + +echo "1..$n" +if [[ $failed -ne 0 ]]; then + echo "# FAILED $failed of $n" + exit 1 +fi +echo "# passed all $n" From 79f857614258356b1702140aeee02a335452fe88 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 22:26:54 -0800 Subject: [PATCH 02/17] ADFA-7081: Address the review of sqlite-js An independent Claude review of 500e38e found two bugs in the patches, gaps in the tests, and two older problems. The package goes to 1.3.7-1. - 0004: a typed array that tracks the length of a resizable buffer kept the length QuickJS recorded when it was made. After the buffer shrank, returning or binding the array read past the buffer: a 32 MB view of a buffer shrunk to 1 byte crashed sqlite3. The offset and length now come from the byteOffset and byteLength getters, read before the bytes, and are checked against the buffer's size. - 0002: QuickJS can crash when it runs out of memory while it creates a context, which every aggregate does, so with the new limit an aggregate run with little memory left crashed sqlite3. Contexts are now created with the limit lifted; it applies again to the code that runs in them, and is set for the connection once its own context exists. - 0003: the SQLITE_DIRECTONLY flag is computed from the function's name, not from an array that parallels the function list, which a function added later would also have to extend. - run-tests.sh: without sqlite-brotli or script(1), the tests that need them are skipped rather than failed, and the summary says so. AC9 checks each statement's output and bounds the default limit (48 MB fits, 70 MB does not); a 32 MB default passed before. AC10 checks the SQLITE_DIRECTONLY flag of every function in function_list; a missing flag on js_create_* passed before. New: typed arrays over resized buffers (AC6) and aggregates near the memory limit (AC9). - README: a collation that throws or runs out of memory compares as equal, so ORDER BY gives a wrong order without an error, as upstream intends. Not changed: QuickJS records the stack top of the thread that loads the extension, so JavaScript run on that connection from another thread fails with "Maximum call stack size exceeded". The sqlite3 shell has one thread; this matters for apps (ADFA-7082). Tests: upstream's test/main.c passes 12 of 12, also under ASan and UBSan with leak checking, and its new checks fail against the previous patches. run-tests.sh passes 77 of 77 on x86_64 Linux, also with the extension under ASan and UBSan; against the 1.3.7 build, the two new tests fail; without sqlite-brotli, 76 pass and 1 is skipped. The NDK builds for aarch64 and arm export only the entry points, and Termux's linter passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...the-memory-of-the-JavaScript-runtime.patch | 126 +++++++++++++++--- ...ions-that-run-code-out-of-the-schema.patch | 41 +++--- ...rayBuffers-and-typed-arrays-as-BLOBs.patch | 67 +++++++--- ...005-Return-whole-numbers-as-INTEGERs.patch | 14 +- ...s-thrown-by-aggregate-and-window-ste.patch | 10 +- packages/sqlite-js/README.md | 10 +- packages/sqlite-js/build.sh | 1 + packages/sqlite-js/tests/run-tests.sh | 92 ++++++++++--- 8 files changed, 275 insertions(+), 86 deletions(-) diff --git a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch index ad5cafe..72d6884 100644 --- a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch +++ b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch @@ -15,17 +15,26 @@ Code that needs more fails with an "out of memory" error, and the connection stays usable. A QuickJS context takes about 54 KB, so the default leaves room for over a thousand aggregate contexts at once. +QuickJS cannot always recover from running out of memory while it +creates a context: it can crash. So the limit is set once the +connection's context exists, and the context of each aggregate or +window function, and the trial one that js_create_aggregate() and +js_create_window() make, is created with the limit lifted; the limit +then applies again to the code that runs in it. + Add a Memory limit test: allocations under and over the default, code that never stops allocating, raising, removing and lowering the limit, -and invalid arguments. +and invalid arguments. It also creates and runs an aggregate under +small limits and with little memory left, which crashed while QuickJS +created its context under the limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- - README.md | 9 ++++++++ - src/sqlitejs.c | 30 +++++++++++++++++++++---- - test/main.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 96 insertions(+), 4 deletions(-) + README.md | 9 +++++ + src/sqlitejs.c | 53 +++++++++++++++++++++++----- + test/main.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 147 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 45bf583..52efd7b 100644 @@ -48,10 +57,18 @@ index 45bf583..52efd7b 100644 JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 524581e..558744f 100644 +index 524581e..6f00635 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -187,6 +187,14 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { +@@ -31,6 +31,7 @@ typedef struct { + sqlite3 *db; + JSClassID rowSetClassID; + int ref_count; ++ size_t memory_limit; // in bytes, 0 for none: see js_set_memory_limit() + } globaljs_context; + + typedef struct { +@@ -187,6 +188,14 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { // MARK: - Initializer - @@ -66,16 +83,49 @@ index 524581e..558744f 100644 // QuickJS calls this from time to time while it runs code. A non-zero result stops the code // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, // a cancelled query in an app) also stops JavaScript that never returns to SQLite. -@@ -207,7 +215,7 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - rt = JS_NewRuntime(); - if (!rt) goto abort_init; +@@ -228,7 +237,12 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + JS_SetContextOpaque(ctx, js); + JS_SetRuntimeOpaque(rt, js); + js_global_init(ctx, js); +- ++ ++ // set only now: QuickJS cannot always recover from running out of memory while it creates ++ // a context (see js_setup_aggregate) ++ js->memory_limit = SQLITE_JS_DEFAULT_MEMORY_LIMIT; ++ JS_SetMemoryLimit(rt, js->memory_limit); ++ + return js; -- //JS_SetMemoryLimit(rt, 80 * 1024); -+ JS_SetMemoryLimit(rt, SQLITE_JS_DEFAULT_MEMORY_LIMIT); - //JS_SetMaxStackSize(rt, 10 * 1024); - - // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry -@@ -1305,6 +1313,20 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + abort_init: +@@ -655,16 +669,22 @@ static bool js_setup_aggregate (sqlite3_context *context, globaljs_context *js, + } + + // create a separate context for testing purpose ++ // QuickJS cannot always recover from running out of memory while it creates a context: it ++ // can crash. So the context is created without the memory limit (it takes about 54 KB), ++ // which then applies again to the code that runs in it. ++ JS_SetMemoryLimit(js->runtime, 0); + JSContext *ctx = JS_NewContext(js->runtime); ++ if (ctx) { ++ // setup global object ++ JS_SetContextOpaque(ctx, js); ++ js_global_init(ctx, js); ++ } ++ JS_SetMemoryLimit(js->runtime, js->memory_limit); + if (!ctx) { + sqlite3_result_error(context, "Unable to create a JS context.", -1); + return false; + } +- +- // setup global object +- JS_SetContextOpaque(ctx, js); +- js_global_init(ctx, js); +- ++ + // init code is optional + if (init_code) { + JSValue init_result = JS_Eval(ctx, init_code, strlen(init_code), NULL, JS_EVAL_TYPE_GLOBAL); +@@ -1305,6 +1325,21 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** JS_SetMaxStackSize(js->runtime, stack_size); } @@ -90,13 +140,14 @@ index 524581e..558744f 100644 + + // a limit beyond the address space (on a 32-bit system) can never be reached, so it is no limit + sqlite3_uint64 limit = (sqlite3_uint64)sqlite3_value_int64(argv[0]); -+ JS_SetMemoryLimit(js->runtime, (limit > SIZE_MAX) ? 0 : (size_t)limit); ++ js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; ++ JS_SetMemoryLimit(js->runtime, js->memory_limit); +} + // MARK: - const char *sqlitejs_version (void) { -@@ -1325,9 +1347,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r +@@ -1325,9 +1360,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r globaljs_context *js = globaljs_init(db); if (!js) return SQLITE_NOMEM; @@ -110,10 +161,10 @@ index 524581e..558744f 100644 size_t f_count = sizeof(f_name) / sizeof(const char *); for (size_t i=0; i Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- README.md | 6 ++++++ - src/sqlitejs.c | 10 ++++++++-- - test/main.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 63 insertions(+), 2 deletions(-) + src/sqlitejs.c | 9 +++++++-- + test/main.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 52efd7b..ff51b2f 100644 @@ -46,34 +50,33 @@ index 52efd7b..ff51b2f 100644 JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 558744f..5765567 100644 +index 6f00635..6b48ef2 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -1350,11 +1350,17 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r +@@ -1363,11 +1363,16 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; - -+ -+ // Every function but js_version runs JavaScript, reads files or changes the JavaScript -+ // runtime. SQLITE_DIRECTONLY keeps them out of the schema (views, triggers, CHECK -+ // constraints, generated columns, indexes), so that a database from an untrusted source -+ // cannot run JavaScript just by being queried, whatever PRAGMA trusted_schema says. -+ int f_flags[] = {0, 0, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY, SQLITE_DIRECTONLY}; + size_t f_count = sizeof(f_name) / sizeof(const char *); for (size_t i=0; iref_count++; - int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); -+ int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8 | f_flags[i], (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); ++ // Every function but js_version runs JavaScript, reads files or changes the JavaScript ++ // runtime. SQLITE_DIRECTONLY keeps them out of the schema (views, triggers, CHECK ++ // constraints, generated columns, indexes), so that a database from an untrusted source ++ // cannot run JavaScript just by being queried, whatever PRAGMA trusted_schema says. ++ int flags = (strcmp(f_name[i], "js_version") == 0) ? 0 : SQLITE_DIRECTONLY; ++ int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8 | flags, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); if (rc != SQLITE_OK) { if (pzErrMsg) *pzErrMsg = sqlite3_mprintf("Error creating function %s: %s", f_name[i], sqlite3_errmsg(db)); // sqlite3_create_function_v2 always invokes the xDestroy callback when it fails, diff --git a/test/main.c b/test/main.c -index c9aab4d..f8e7f78 100644 +index 7855bfb..dfa3306 100644 --- a/test/main.c +++ b/test/main.c -@@ -614,6 +614,54 @@ abort_test: +@@ -647,6 +647,58 @@ abort_test: return rc; } @@ -84,6 +87,10 @@ index c9aab4d..f8e7f78 100644 + int rc = test_open(&db); + if (rc != SQLITE_OK) goto abort_test; + ++ // every function but js_version is SQLITE_DIRECTONLY (0x80000 in the flags of function_list) ++ rc = check_query_v2(db, "SELECT count(*) > 10, sum(((flags & 0x80000) != 0) != (name <> 'js_version')) FROM pragma_function_list WHERE name LIKE 'js\\_%' ESCAPE '\\';", (const char*[]){"1", "0"}, 2); ++ if (rc != SQLITE_OK) goto abort_test; ++ + // trusted_schema ON lets the schema use any function that is not SQLITE_DIRECTONLY + rc = db_exec(db, "PRAGMA trusted_schema = ON; CREATE TABLE t (a); CREATE TABLE log (msg);"); + if (rc != SQLITE_OK) goto abort_test; @@ -128,7 +135,7 @@ index c9aab4d..f8e7f78 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -632,6 +680,7 @@ int main (void) { +@@ -665,6 +717,7 @@ int main (void) { result += test_report("Thread", test_thread()); result += test_report("Interrupt", test_interrupt()); result += test_report("Memory limit", test_memory_limit()); diff --git a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch index bb218f0..377b108 100644 --- a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch +++ b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch @@ -15,20 +15,27 @@ Add js_get_bytes(), which gets the bytes of an ArrayBuffer or of the part of a buffer that a typed array views, and use it for function results and for db.exec() parameters. An empty buffer is an empty BLOB. Returning a detached buffer is an error; binding one still binds NULL, as before. +A typed array's offset and length come from its byteOffset and +byteLength getters, read before its bytes: one that tracks the length +of a resizable buffer keeps the length QuickJS recorded when it was +made, which goes stale when the buffer is resized, and reading it +after a shrink would read past the buffer. A typed array of fixed +length that its shrunken buffer no longer holds is an error. Document how values convert in both directions in the README. Add a Blobs test: BLOBs round-trip through a function, typed arrays, subarrays and ArrayBuffers made in JavaScript become BLOBs, a function can build a BLOB from a BLOB, a detached buffer is an error, and -db.exec() binds typed arrays and empty buffers as BLOBs. +db.exec() binds typed arrays and empty buffers as BLOBs. It also checks +typed arrays over resizable buffers that shrink and grow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- - README.md | 13 ++++++++++ - src/sqlitejs.c | 64 ++++++++++++++++++++++++++++++++++++++++++++------ - test/main.c | 38 ++++++++++++++++++++++++++++++ - 3 files changed, 108 insertions(+), 7 deletions(-) + README.md | 13 ++++++++ + src/sqlitejs.c | 82 +++++++++++++++++++++++++++++++++++++++++++++----- + test/main.c | 50 ++++++++++++++++++++++++++++++ + 3 files changed, 138 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ff51b2f..99abfb9 100644 @@ -55,10 +62,10 @@ index ff51b2f..99abfb9 100644 Scalar functions process one row at a time and return a single value. They are useful for data transformation, calculations, text manipulation, etc. diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 5765567..2c11877 100644 +index 6b48ef2..cb4d75d 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -366,6 +366,38 @@ static void functionjs_free (functionjs_context *fctx) { +@@ -372,6 +372,56 @@ static void functionjs_free (functionjs_context *fctx) { // MARK: - Utils - @@ -79,15 +86,33 @@ index 5765567..2c11877 100644 + } + + if (JS_GetTypedArrayType(value) >= 0) { -+ size_t offset = 0, length = 0, size = 0; -+ JSValue buffer = JS_GetTypedArrayBuffer(ctx, value, &offset, &length, NULL); ++ // The offset and length come from the byteOffset and byteLength getters: a typed array ++ // can track the length of a resizable buffer, and the length QuickJS records when the ++ // array is made goes stale when the buffer is resized. They are read before the bytes, ++ // because a getter can run JavaScript, which could resize or detach the buffer. ++ int64_t offset = 0, length = 0; ++ JSValue prop = JS_GetPropertyStr(ctx, value, "byteOffset"); ++ int rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &offset, prop); ++ JS_FreeValue(ctx, prop); ++ if (rc < 0) return -1; ++ prop = JS_GetPropertyStr(ctx, value, "byteLength"); ++ rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &length, prop); ++ JS_FreeValue(ctx, prop); ++ if (rc < 0) return -1; ++ ++ size_t size = 0; ++ JSValue buffer = JS_GetTypedArrayBuffer(ctx, value, NULL, NULL, NULL); + if (JS_IsException(buffer)) return -1; + uint8_t *buf = JS_GetArrayBuffer(ctx, &size, buffer); + // the typed array keeps its buffer alive, so buf stays valid + JS_FreeValue(ctx, buffer); + if (!buf && JS_HasException(ctx)) return -1; ++ if ((offset < 0) || (length < 0) || ((uint64_t)offset > size) || ((uint64_t)length > size - (size_t)offset)) { ++ JS_ThrowRangeError(ctx, "typed array is out of the bounds of its buffer"); ++ return -1; ++ } + *pbytes = (buf) ? buf + offset : NULL; -+ *psize = length; ++ *psize = (size_t)length; + return 1; + } + @@ -97,7 +122,7 @@ index 5765567..2c11877 100644 static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueConst val) { if (JS_IsNull(val) || JS_IsUndefined(val)) { return sqlite3_bind_null(vm, index); -@@ -400,14 +432,18 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo +@@ -406,14 +456,18 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo JS_FreeCString(ctx, str); return rc; } @@ -122,7 +147,7 @@ index 5765567..2c11877 100644 return sqlite3_bind_null(vm, index); } -@@ -636,11 +672,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV +@@ -642,11 +696,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV return; } @@ -150,10 +175,10 @@ index 5765567..2c11877 100644 sqlite3_result_error(context, "Unsupported JS value type", -1); } diff --git a/test/main.c b/test/main.c -index f8e7f78..49aa6a1 100644 +index dfa3306..b6c6a8a 100644 --- a/test/main.c +++ b/test/main.c -@@ -662,6 +662,43 @@ abort_test: +@@ -699,6 +699,55 @@ abort_test: return rc; } @@ -188,6 +213,18 @@ index f8e7f78..49aa6a1 100644 + rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT quote(?), quote(?)\", new Uint8Array([1, 2]), new ArrayBuffer(0)); rs.next(); return rs.get(0) + \" \" + rs.get(1); })()');", "X'0102' X''"); + if (rc != SQLITE_OK) goto abort_test; + ++ // a typed array that tracks the length of a resizable buffer has the buffer's current length, ++ // after the buffer shrinks (by 1 MB, so that reading the old length would read far past it) ++ // or grows ++ rc = check_query_v2(db, "SELECT quote(js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab); u.fill(7); ab.resize(2); return u; })()')), length(js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(1); return u; })()')), length(js_eval('(function () { const ab = new ArrayBuffer(4, { maxByteLength: 16 }); const u = new Uint8Array(ab, 2); ab.resize(16); return u; })()'));", (const char*[]){"X'0707'", "1", "14"}, 3); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(3); const rs = db.exec(\"SELECT length(?)\", u); rs.next(); return rs.get(0); })()');", "3"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a typed array of fixed length that a shrunken buffer no longer holds is an error ++ rc = check_error(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); return u; })()');", "detached or resized"); ++ if (rc != SQLITE_OK) goto abort_test; ++ +abort_test: + if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); + if (db) sqlite3_close(db); @@ -197,7 +234,7 @@ index f8e7f78..49aa6a1 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -681,6 +718,7 @@ int main (void) { +@@ -718,6 +767,7 @@ int main (void) { result += test_report("Interrupt", test_interrupt()); result += test_report("Memory limit", test_memory_limit()); result += test_report("Direct only", test_direct_only()); diff --git a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch index dcfd67f..5880b38 100644 --- a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch +++ b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch @@ -46,7 +46,7 @@ index 99abfb9..d2cf41b 100644 ## Scalar Functions diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 2c11877..45d315b 100644 +index cb4d75d..c56b241 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c @@ -11,6 +11,7 @@ @@ -57,7 +57,7 @@ index 2c11877..45d315b 100644 #include "sqlitejs.h" #include "quickjs.h" #include "quickjs-libc.h" -@@ -366,6 +367,18 @@ static void functionjs_free (functionjs_context *fctx) { +@@ -372,6 +373,18 @@ static void functionjs_free (functionjs_context *fctx) { // MARK: - Utils - @@ -76,7 +76,7 @@ index 2c11877..45d315b 100644 // Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such // as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an // ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be -@@ -410,7 +423,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo +@@ -434,7 +447,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo return sqlite3_bind_int(vm, index, num); } else { double num; @@ -86,7 +86,7 @@ index 2c11877..45d315b 100644 return sqlite3_bind_double(vm, index, num); } } -@@ -636,8 +651,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV +@@ -660,8 +675,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV sqlite3_result_int(context, num); } else { double num; @@ -99,10 +99,10 @@ index 2c11877..45d315b 100644 return; } diff --git a/test/main.c b/test/main.c -index 49aa6a1..28211e9 100644 +index b6c6a8a..cb2f899 100644 --- a/test/main.c +++ b/test/main.c -@@ -699,6 +699,48 @@ abort_test: +@@ -748,6 +748,48 @@ abort_test: return rc; } @@ -151,7 +151,7 @@ index 49aa6a1..28211e9 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -719,6 +761,7 @@ int main (void) { +@@ -768,6 +810,7 @@ int main (void) { result += test_report("Memory limit", test_memory_limit()); result += test_report("Direct only", test_direct_only()); result += test_report("Blobs", test_blobs()); diff --git a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch index 352ad41..0e7056d 100644 --- a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch +++ b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch @@ -27,10 +27,10 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 2 files changed, 36 insertions(+) diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 45d315b..7aaaaa2 100644 +index c56b241..790dc82 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -866,6 +866,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, +@@ -896,6 +896,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, JS_FreeValue(js_context, args); if (return_value) js_value_to_sqlite(context, js_context, result); @@ -41,10 +41,10 @@ index 45d315b..7aaaaa2 100644 } diff --git a/test/main.c b/test/main.c -index 28211e9..f278cc9 100644 +index cb2f899..0af4d22 100644 --- a/test/main.c +++ b/test/main.c -@@ -741,6 +741,38 @@ abort_test: +@@ -790,6 +790,38 @@ abort_test: return rc; } @@ -83,7 +83,7 @@ index 28211e9..f278cc9 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -762,6 +794,7 @@ int main (void) { +@@ -811,6 +843,7 @@ int main (void) { result += test_report("Direct only", test_direct_only()); result += test_report("Blobs", test_blobs()); result += test_report("Numbers", test_numbers()); diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index 2efca87..8af2d5a 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -163,6 +163,9 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. an "interrupted" error, even if the code catches exceptions, and `sqlite3` keeps running. - **Stack.** 1 MB by default; `js_set_max_stack_size` changes it. +- **Collations that fail.** A collation that throws an exception, or runs out + of memory, compares the two strings as equal. `ORDER BY` then returns a + wrong order rather than an error, so keep collation code simple. ## Databases from other people @@ -200,8 +203,11 @@ point argument. $ bash $PREFIX/share/sqlite-js/run-tests.sh ``` -They print TAP and exit 0 only if every test passes. With the `sqlite-brotli` -package installed, they also check that both extensions load together. +They print TAP and exit 0 only if every test passes. Two tests need other +packages and are skipped without them: `sqlite-brotli`, to check that both +extensions load together, and `util-linux`, whose `script` drives an +interactive `sqlite3` to check that Ctrl-C leaves it running. The last line +says how many were skipped. ## License diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 95964e0..2bd7b1f 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,6 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.3.7 +TERMUX_PKG_REVISION=1 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 TERMUX_PKG_BUILD_DEPENDS="libsqlite" diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 576d2fb..4d8b6cc 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -117,6 +117,16 @@ not_ok() { done } +# For a test that needs a tool that is not installed. TAP counts it as +# passed, so the summary at the end lists the skips. +skipped=0 +skip() { + n=$((n + 1)) + skipped=$((skipped + 1)) + elapsed + echo "ok $n - $1 # SKIP $2 ($took)" +} + note() { printf '# %s\n' "$*" } @@ -162,18 +172,21 @@ expect_error() { fi } -# expect_nobail NAME PATTERN SQL...: like sql_nobail, the output (errors -# included) must match the extended regex PATTERN, and the shell must not -# crash. +# expect_nobail NAME WANT ERROR SQL...: run as sql_nobail, the statements +# must print exactly WANT, and exactly one of them must fail, with an error +# message containing ERROR. The shell must not crash. expect_nobail() { - local name=$1 pattern=$2 got rc - shift 2 - got=$(sql_nobail "$@" 2>&1) + local name=$1 want=$2 error=$3 got err rc + local one_error=$'^[^\n]*'"$error"$'[^\n]*$' + shift 3 + got=$(sql_nobail "$@" 2>nobail.err) rc=$? - if [[ $rc -lt 128 && $got =~ $pattern ]]; then + err=$(/dev/null 2>&1; then not_ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" "got: $got" fi else - not_ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" \ - "needs script(1); install util-linux" + skip "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" \ + "needs script(1), from the util-linux package" fi # --- AC9: the memory limit ------------------------------------------------------ -expect "AC9: the default limit allows 16 MB" "16777216" \ - "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" -expect_error "AC9: the default limit (64 MB) refuses 128 MB" "out of memory" \ - "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');" +# The default limit is 64 MB: 48 MB fits beside the runtime's own use, and +# 70 MB does not. +expect "AC9: the default limit allows 48 MB" "50331648" \ + "SELECT js_eval('new ArrayBuffer(48 * 1024 * 1024).byteLength');" +expect_error "AC9: the default limit refuses 70 MB" "out of memory" \ + "SELECT js_eval('new ArrayBuffer(70 * 1024 * 1024).byteLength');" expect_nobail "AC9: code that never stops allocating fails at the limit, and the session stays usable" \ - "out of memory.*"$'\n'"1,2,3$" \ + "1,2,3" "out of memory" \ "SELECT js_eval('(function () { const a = []; for (;;) a.push(new Array(100000).fill(1)); })()');" \ "SELECT js_eval('[1, 2, 3].join()');" expect_nobail "AC9: memory held by a global counts until the global is cleared" \ - "out of memory.*"$'\n'"16777216$" \ + $'0\n16777216' "out of memory" \ "SELECT js_eval('globalThis.keep = new ArrayBuffer(60 * 1024 * 1024); 0');" \ "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" \ "SELECT js_eval('keep = null; new ArrayBuffer(16 * 1024 * 1024).byteLength');" + +# QuickJS can crash if it runs out of memory while it creates a context, which +# every aggregate needs. Aggregates under small limits, and with little memory +# left under the default one, may fail, but must not crash. +AGGREGATE="SELECT js_create_aggregate('n_rows', 'n = 0;', '(function (args) { n++; })', '(function () { return n; })'); +WITH v(x) AS (VALUES (1), (2)) SELECT n_rows(x) FROM v;" +runs=0 +crashes=() +for kb in 100 140 180 220 260 300 340 380 420; do + sql_nobail "SELECT js_set_memory_limit($kb * 1024);" "$AGGREGATE" >/dev/null 2>&1 + (($? >= 128)) && crashes+=("limit $kb KB") + runs=$((runs + 1)) +done +for kb in 0 1 2 3 4 6 8 12 16; do + sql_nobail "SELECT js_eval('globalThis.keep = []; try { for (;;) keep.push(new ArrayBuffer(1024)); } catch (e) {} keep.length -= $kb; 0');" \ + "$AGGREGATE" >/dev/null 2>&1 + (($? >= 128)) && crashes+=("$kb KB left") + runs=$((runs + 1)) +done +if [[ ${#crashes[@]} -eq 0 ]]; then + ok "AC9: aggregates near the memory limit fail cleanly, never crash ($runs runs)" +else + not_ok "AC9: aggregates near the memory limit fail cleanly, never crash ($runs runs)" "crashed: ${crashes[*]}" +fi # js_set_memory_limit returns NULL, which prints as an empty line. expect "AC9: js_set_memory_limit raises the limit" $'\n134217728' \ "SELECT js_set_memory_limit(256 * 1024 * 1024);" \ @@ -494,6 +541,9 @@ for trusted in "sqlite3's default" ON; do "$pragma" "INSERT INTO t VALUES (1);" done expect "AC10: so the trigger never ran" "0" "SELECT count(*) FROM log;" +# SQLITE_DIRECTONLY is 0x80000 in function_list's flags. +expect "AC10: every js_* function but js_version is SQLITE_DIRECTONLY" "13|0" \ + "SELECT count(*), sum(((flags & 0x80000) != 0) != (name <> 'js_version')) FROM pragma_function_list WHERE name LIKE 'js\_%' ESCAPE '\\';" # The view is in the database file: SQLite trusts the TEMP schema, which only # the session itself can fill. DB=$WORK/views.db @@ -530,8 +580,8 @@ if "$SQLITE3" -bail -batch :memory: "$LOAD_BROTLI" "SELECT 1;" >/dev/null 2>&1; not_ok "AC12: sqlite-brotli, then sqlite-js: both work in one session" "got: $got" fi else - not_ok "AC12: sqlite-js and sqlite-brotli load together" \ - "cannot load $BROTLI_EXT; install the sqlite-brotli package or set BROTLI_EXT" + skip "AC12: sqlite-js and sqlite-brotli load together" \ + "cannot load $BROTLI_EXT; install the sqlite-brotli package, or set BROTLI_EXT" fi echo "1..$n" @@ -539,4 +589,8 @@ if [[ $failed -ne 0 ]]; then echo "# FAILED $failed of $n" exit 1 fi -echo "# passed all $n" +if [[ $skipped -ne 0 ]]; then + echo "# passed all $n, but skipped $skipped: install what they name to run them" +else + echo "# passed all $n" +fi From f3c076c40f7066e80eb397294735fe1955d75591 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 11:50:41 -0800 Subject: [PATCH 03/17] ADFA-7081: sqlite-js 1.3.7-2, keep the stack size within the thread's stack Patch 0007: js_set_max_stack_size() passed its argument to QuickJS unchecked, so text (read as 0, which turns the check off) or a size larger than the thread's stack made endless recursion crash sqlite3, and the 1 MB default did the same on a thread with less stack. It now measures the calling thread's stack, keeps a 256 KB margin, refuses text, negatives and sizes beyond what the stack allows (the error names the largest size), and lowers the default when the loading thread has less. 0 still turns the check off, as upstream documents for use from several threads. run-tests.sh: AC13 checks the error cases, endless recursion at the default, just below the largest size (also through db.exec) and with a 512 KB stack. README lists the seventh patch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...ipt-stack-size-within-the-thread-s-s.patch | 272 ++++++++++++++++++ packages/sqlite-js/README.md | 11 +- packages/sqlite-js/build.sh | 2 +- packages/sqlite-js/tests/run-tests.sh | 40 +++ 4 files changed, 320 insertions(+), 5 deletions(-) create mode 100644 packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch diff --git a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch new file mode 100644 index 0000000..17f37f1 --- /dev/null +++ b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch @@ -0,0 +1,272 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Wed, 11 Nov 2026 11:47:56 -0800 +Subject: [PATCH] Keep the JavaScript stack size within the thread's stack + +QuickJS stops code that calls itself too deeply when the stack falls +below a limit it computes from the size it was given. It trusts that +size, so a size larger than the thread's stack never trips the check, +and code that calls itself without end crashes the process instead of +failing with "Maximum call stack size exceeded". + +js_set_max_stack_size() passed its argument to JS_SetMaxStackSize() +unchecked, through sqlite3_value_int(): text such as '1MB' or 'abc' +read as 1 or 0, and a size above the thread's stack, such as 16 MB on +a thread with 8 MB, crashed sqlite3 on endless recursion. The 1 MB +default could itself be too large: on a thread with 512 KB of stack, +endless recursion crashed at the default, and Windows gives a main +thread 1 MB, apps often their threads no more. + +Measure the calling thread's stack (pthread_getattr_np() on Linux and +Android, pthread_get_stackaddr_np() and pthread_get_stacksize_np() on +Apple platforms, VirtualQuery() on Windows) and keep a margin, +SQLITE_JS_STACK_MARGIN (256 KB), for the native code that runs between +two of QuickJS's checks, such as SQLite when JavaScript runs SQL +through db.exec. js_set_max_stack_size() now accepts an integer up to +what the stack allows, and reports the largest size in its error +message; elsewhere it allows up to the default. When the extension is +loaded, the default is lowered to what the loading thread's stack +allows. The stack position is read the way QuickJS reads it, because +under AddressSanitizer a local variable lives on a separate stack. + +0 still turns the check off, as the 1.3.7 changelog documents for a +connection used from several threads, and test_thread relies on. + +Add a Stack size test: endless recursion fails at the default, invalid +sizes are errors, and endless recursion, also through db.exec, fails +cleanly just below the largest size allowed and at a smaller one. It +fails without this change. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 5 ++- + src/sqlitejs.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++++-- + test/main.c | 58 ++++++++++++++++++++++++++++++++++ + 3 files changed, 144 insertions(+), 3 deletions(-) + +diff --git a/README.md b/README.md +index d2cf41b..8ef6804 100644 +--- a/README.md ++++ b/README.md +@@ -419,10 +419,13 @@ SELECT js_load_blob('/path/to/file.bin'); -- Returns file contents as a blob + + ### js_set_max_stack_size + +-Configures the maximum stack size (in bytes) for the JavaScript engine. ++Sets the most stack, in bytes, that JavaScript may use, which limits how deeply functions can call themselves; code that goes deeper fails with "Maximum call stack size exceeded". The default is 1 MB, or less when the thread that loads the extension has less stack. The size must be an integer no larger than the calling thread's stack allows, less a margin for the native code that runs between QuickJS's checks (`SQLITE_JS_STACK_MARGIN`, 256 KB); the error message gives the largest size allowed. A larger size, or text, which would read as 0, is an error, because QuickJS's check would never trip and code that calls itself without end would crash the process. ++ ++`0` turns the check off, for a connection used from several threads: the check measures from the stack of the thread that loaded the extension. With the check off, code that calls itself without end crashes the process. + + ```sql + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB ++SELECT js_set_max_stack_size(0); -- No check, for use from several threads + ``` + + ### js_set_memory_limit +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 790dc82..e5562f4 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -5,6 +5,11 @@ + // Created by Marco Bambini on 31/03/25. + // + ++// glibc declares pthread_getattr_np() (see js_stack_room) only for _GNU_SOURCE ++#if defined(__linux__) && !defined(_GNU_SOURCE) ++#define _GNU_SOURCE ++#endif ++ + #include + #include + #include +@@ -16,6 +21,15 @@ + #include "quickjs.h" + #include "quickjs-libc.h" + ++#if defined(_WIN32) ++#include ++#if defined(_MSC_VER) ++#include ++#endif ++#elif defined(__APPLE__) || defined(__linux__) ++#include ++#endif ++ + #ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 + #endif +@@ -197,6 +211,53 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + #define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) + #endif + ++// Stack, in bytes, kept free below the JavaScript stack limit for the native code that runs ++// between two of QuickJS's stack checks: QuickJS's own C functions, and SQLite when JavaScript ++// runs SQL through db.exec. ++#ifndef SQLITE_JS_STACK_MARGIN ++#define SQLITE_JS_STACK_MARGIN (256 * 1024) ++#endif ++ ++// The stack, in bytes, that the calling thread has left below this function, less the margin. ++// QuickJS trusts its stack size: one larger than the thread has never trips its check, and code ++// that calls itself without end then crashes the process. Returns false where the thread's stack ++// cannot be found. ++static bool js_stack_room (size_t *room) { ++ // where the stack is now, found the way QuickJS finds it: the address of a local variable ++ // can be elsewhere, for example on AddressSanitizer's separate stack ++#if defined(__clang__) || defined(__GNUC__) ++ uintptr_t sp = (uintptr_t)__builtin_frame_address(0); ++#elif defined(_MSC_VER) ++ uintptr_t sp = (uintptr_t)_AddressOfReturnAddress(); ++#else ++ volatile char here = 0; ++ uintptr_t sp = (uintptr_t)&here; ++#endif ++ uintptr_t low = 0; ++#if defined(_WIN32) ++ // the stack is one allocation, reserved from its lowest address ++ MEMORY_BASIC_INFORMATION mbi; ++ if (VirtualQuery((LPCVOID)sp, &mbi, sizeof(mbi)) == 0) return false; ++ low = (uintptr_t)mbi.AllocationBase; ++#elif defined(__APPLE__) ++ pthread_t self = pthread_self(); ++ low = (uintptr_t)pthread_get_stackaddr_np(self) - pthread_get_stacksize_np(self); ++#elif defined(__linux__) ++ pthread_attr_t attr; ++ void *addr = NULL; ++ size_t size = 0; ++ if (pthread_getattr_np(pthread_self(), &attr) != 0) return false; ++ int rc = pthread_attr_getstack(&attr, &addr, &size); ++ pthread_attr_destroy(&attr); ++ if (rc != 0) return false; ++ low = (uintptr_t)addr; ++#else ++ return false; ++#endif ++ *room = (sp > low + SQLITE_JS_STACK_MARGIN) ? (size_t)(sp - low - SQLITE_JS_STACK_MARGIN) : 0; ++ return true; ++} ++ + // QuickJS calls this from time to time while it runs code. A non-zero result stops the code + // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, + // a cancelled query in an app) also stops JavaScript that never returns to SQLite. +@@ -224,6 +285,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + // in its sqlite3_api_routines, so JavaScript cannot be interrupted there + if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); + ++ // the default stack size must fit in the stack of the thread that loads the extension: Windows ++ // gives a main thread 1 MB, and apps often give their threads no more ++ size_t room = 0; ++ if (js_stack_room(&room) && (room < JS_DEFAULT_STACK_SIZE)) JS_SetMaxStackSize(rt, (room > 0) ? room : 1); ++ + js_std_init_handlers(rt); + JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); + +@@ -1409,8 +1475,22 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + UNUSED(argc); + globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); + +- int stack_size = sqlite3_value_int(argv[0]); +- JS_SetMaxStackSize(js->runtime, stack_size); ++ // 0 turns QuickJS's check off, for a connection used from several threads (the check measures ++ // from the stack of the thread that loaded the extension). Text would read as 0, and a size ++ // larger than the thread's stack is no limit either: code that calls itself without end ++ // would crash the process. Where the stack cannot be measured, allow up to the default. ++ size_t most = JS_DEFAULT_STACK_SIZE; ++ js_stack_room(&most); ++ sqlite3_int64 size = sqlite3_value_int64(argv[0]); ++ if ((sqlite3_value_type(argv[0]) != SQLITE_INTEGER) || (size < 0) || ((sqlite3_uint64)size > most)) { ++ char *msg = sqlite3_mprintf("The stack size must be an integer number of bytes from 1 to %llu, which this thread's stack allows, or 0 for no check", (unsigned long long)most); ++ if (msg) sqlite3_result_error(context, msg, -1); ++ else sqlite3_result_error_nomem(context); ++ sqlite3_free(msg); ++ return; ++ } ++ ++ JS_SetMaxStackSize(js->runtime, (size_t)size); + } + + void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { +diff --git a/test/main.c b/test/main.c +index 0af4d22..7ccdcb5 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -10,6 +10,7 @@ + #include "sqlitejs.h" + #include + #include ++#include + #include + #include + +@@ -647,6 +648,62 @@ abort_test: + return rc; + } + ++// MARK: - Stack size - ++ ++int test_stack_size (void) { ++ sqlite3 *db = NULL; ++ char sql[256]; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // code that calls itself without end fails, and the connection stays usable ++ const char *recurse = "SELECT js_eval('(function f(n) { return f(n + 1); })(0)');"; ++ rc = check_error(db, recurse, "Maximum call stack size exceeded"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('1 + 1');", "2"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a size is an integer no larger than the thread's stack, or 0 for no check: text would read ++ // as 0, and a size larger than the stack never trips the check, so the code above would ++ // crash the process ++ const char *invalid[] = {"'abc'", "-1", "1.5", "'1048576'", "NULL", "x'00'", "1073741824"}; ++ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { ++ snprintf(sql, sizeof(sql), "SELECT js_set_max_stack_size(%s);", invalid[i]); ++ rc = check_error(db, sql, "The stack size must be an integer number of bytes from 1 to "); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++ // close to the largest size allowed, the code still stops, also when it calls itself ++ // through SQL, which puts SQLite's frames between QuickJS's stack checks ++ const char *most_text = strstr(sqlite3_errmsg(db), "from 1 to "); ++ long long most = most_text ? strtoll(most_text + strlen("from 1 to "), NULL, 10) : 0; ++ if (most <= 64 * 1024) { printf("FAIL: no stack size range in: %s\n", sqlite3_errmsg(db)); rc = SQLITE_ERROR; goto abort_test; } ++ snprintf(sql, sizeof(sql), "SELECT js_set_max_stack_size(%lld);", most - 4096); ++ rc = db_exec(db, sql); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, recurse, "Maximum call stack size exceeded"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_create_scalar('recurse_sql', '(function (args) { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (!rs.next()) throw new Error(\"stopped\"); return rs.get(0); })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT recurse_sql(0);", "stopped"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a smaller size ++ rc = db_exec(db, "SELECT js_set_max_stack_size(256 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, recurse, "Maximum call stack size exceeded"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // 0 is still allowed, for connections used from several threads (see test_thread) ++ rc = check_query(db, "SELECT quote(js_set_max_stack_size(0));", "NULL"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - Direct only - + + int test_direct_only (void) { +@@ -840,6 +897,7 @@ int main (void) { + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); ++ result += test_report("Stack size", test_stack_size()); + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index 8af2d5a..e7f1c5b 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -2,7 +2,7 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is -[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.3.7 with six +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.3.7 with seven changes of ours, listed [below](#changes-in-this-build). The JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. @@ -100,7 +100,7 @@ SELECT js_eval('(function () { | `js_init_table(1)` | Also creates every function stored in `js_functions`. | | `js_load_text(path)`, `js_load_blob(path)` | Return a file's contents as TEXT or as a BLOB. | | `js_set_memory_limit(bytes)` | Sets the memory JavaScript may use on this connection; 0 means no limit. | -| `js_set_max_stack_size(bytes)` | Sets JavaScript's stack limit. Leave it above 0: 0 turns the check off, and deep recursion then crashes `sqlite3`. | +| `js_set_max_stack_size(bytes)` | Sets JavaScript's stack limit, at most what the thread's stack allows (the error gives the largest size). 0 turns the check off, for use from several threads; deep recursion then crashes `sqlite3`. | | `js_version()`, `js_version(1)` | The sqlite-js version, or with an argument, the quickjs-ng version. | The functions you create last for the session. To keep them, call @@ -162,7 +162,9 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with an "interrupted" error, even if the code catches exceptions, and `sqlite3` keeps running. -- **Stack.** 1 MB by default; `js_set_max_stack_size` changes it. +- **Stack.** 1 MB by default, or less on a thread with less stack; + `js_set_max_stack_size` changes it. Code that calls itself too deeply fails + with "Maximum call stack size exceeded". - **Collations that fail.** A collation that throws an exception, or runs out of memory, compares the two strings as equal. `ORDER BY` then returns a wrong order rather than an error, so keep collation code simple. @@ -182,7 +184,7 @@ constraints and generated columns cannot call `js_eval` or the other ## Changes in this build -Six patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. +Seven patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. | Patch | Change | |-------|--------| @@ -192,6 +194,7 @@ Six patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. | `0004` | A result that is an `ArrayBuffer` or typed array is a BLOB. Upstream, it is NULL, so a BLOB cannot pass through a function. | | `0005` | A whole-number result is an INTEGER. Upstream, an INTEGER outside the 32-bit range comes back as a REAL. | | `0006` | An exception in an aggregate's or window function's step is an SQL error. Upstream, it is ignored, and the result is silently wrong. | +| `0007` | The JavaScript stack size stays within the thread's stack: `js_set_max_stack_size` refuses text and larger sizes, and the default shrinks on a small stack. Upstream, those make endless recursion crash `sqlite3`. | The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 2bd7b1f..2589b63 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,7 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.3.7 -TERMUX_PKG_REVISION=1 +TERMUX_PKG_REVISION=2 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 TERMUX_PKG_BUILD_DEPENDS="libsqlite" diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 4d8b6cc..7ef883e 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -584,6 +584,46 @@ else "cannot load $BROTLI_EXT; install the sqlite-brotli package, or set BROTLI_EXT" fi +# --- AC13: the stack size stays within the thread's stack --------------------- + +# QuickJS trusts its stack size: a size larger than the thread's stack, or 0, +# never trips its check, and code that calls itself without end crashes. +RECURSE="SELECT js_eval('(function f(n) { return f(n + 1); })(0)');" +expect_error "AC13: endless recursion fails at the default size" \ + "Maximum call stack size exceeded" "$RECURSE" +for size in "'abc'" -1 1.5 "'1048576'" 1073741824; do + expect_error "AC13: js_set_max_stack_size($size) is an error" \ + "The stack size must be an integer number of bytes from 1 to [0-9]+" \ + "SELECT js_set_max_stack_size($size);" +done +expect "AC13: js_set_max_stack_size(0) turns the check off, for use from several threads" "NULL" \ + "SELECT quote(js_set_max_stack_size(0));" + +# Close to the largest size allowed (each process has its own, since the stack +# starts at a slightly different place), recursion still fails cleanly, also +# through db.exec, which puts SQLite's frames between QuickJS's checks. +most=$(sql "SELECT js_set_max_stack_size(1073741824);" 2>&1 | sed -n 's/.*from 1 to \([0-9]*\).*/\1/p') +if [[ $most =~ ^[0-9]+$ ]] && ((most > 128 * 1024)); then + near=$((most - 64 * 1024)) + expect_error "AC13: endless recursion fails just below the largest size" \ + "Maximum call stack size exceeded" "SELECT js_set_max_stack_size($near);" "$RECURSE" + expect_error "AC13: endless recursion through db.exec fails just below the largest size" "stopped" \ + "SELECT js_set_max_stack_size($near);" \ + "SELECT js_create_scalar('recurse_sql', '(function (args) { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (!rs.next()) throw new Error(\"stopped\"); return rs.get(0); })');" \ + "SELECT recurse_sql(0);" +else + not_ok "AC13: the error names the largest size" "got: $most" +fi + +# On a thread with less stack than the 1 MB default, the default shrinks. +got=$(ulimit -s 512 && sql "$RECURSE" 2>&1) +rc=$? +if [[ $rc -ge 1 && $rc -lt 128 && $got =~ "Maximum call stack size exceeded" ]]; then + ok "AC13: with 512 KB of stack, endless recursion fails at the default size" +else + not_ok "AC13: with 512 KB of stack, endless recursion fails at the default size" "exit status $rc" "got: $got" +fi + echo "1..$n" if [[ $failed -ne 0 ]]; then echo "# FAILED $failed of $n" From f8a7661bead76943af70eccfb6b56c3648ef3918 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:26:22 -0800 Subject: [PATCH 04/17] ADFA-7081: sqlite-js 1.3.7-3, report SQL errors from db.exec Patch 0008 (F20): db.exec's result set treated any sqlite3_step() result but SQLITE_ROW as the end of the rows, so an error while the statement ran was dropped: next() returned false and toArray() the rows before the error, and a failed write looked like success. Both now throw the connection's error message; the end of the rows is still false. The README documents db.exec, including that a statement runs only when next() or toArray() steps it (F21). Patch 0007: its SQL-recursion test catches the deeper call's error itself, so it passes with or without 0008 (only the test changed). run-tests.sh: new AC14 for the error cases; AC13's recursion through db.exec likewise. 91 tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...ipt-stack-size-within-the-thread-s-s.patch | 6 +- ...-SQL-errors-from-db.exec-result-sets.patch | 158 ++++++++++++++++++ packages/sqlite-js/README.md | 10 +- packages/sqlite-js/build.sh | 2 +- packages/sqlite-js/tests/run-tests.sh | 18 +- 5 files changed, 187 insertions(+), 7 deletions(-) create mode 100644 packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch diff --git a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch index 17f37f1..7d6c5e2 100644 --- a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch +++ b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 11:47:56 -0800 -Subject: [PATCH] Keep the JavaScript stack size within the thread's stack +Subject: [PATCH 7/8] Keep the JavaScript stack size within the thread's stack QuickJS stops code that calls itself too deeply when the stack falls below a limit it computes from the size it was given. It trusts that @@ -188,7 +188,7 @@ index 790dc82..e5562f4 100644 void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { diff --git a/test/main.c b/test/main.c -index 0af4d22..7ccdcb5 100644 +index 0af4d22..ff1c0e7 100644 --- a/test/main.c +++ b/test/main.c @@ -10,6 +10,7 @@ @@ -238,7 +238,7 @@ index 0af4d22..7ccdcb5 100644 + if (rc != SQLITE_OK) goto abort_test; + rc = check_error(db, recurse, "Maximum call stack size exceeded"); + if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_create_scalar('recurse_sql', '(function (args) { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (!rs.next()) throw new Error(\"stopped\"); return rs.get(0); })');"); ++ rc = db_exec(db, "SELECT js_create_scalar('recurse_sql', '(function (args) { try { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (rs.next()) return rs.get(0); } catch (e) {} throw new Error(\"stopped\"); })');"); + if (rc != SQLITE_OK) goto abort_test; + rc = check_error(db, "SELECT recurse_sql(0);", "stopped"); + if (rc != SQLITE_OK) goto abort_test; diff --git a/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch b/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch new file mode 100644 index 0000000..549a1c7 --- /dev/null +++ b/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch @@ -0,0 +1,158 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Wed, 11 Nov 2026 12:24:04 -0800 +Subject: [PATCH 8/8] Report SQL errors from db.exec result sets + +db.exec() prepares a statement and returns a result set; the statement +runs as next() or toArray() steps it. Both treated any sqlite3_step() +result other than SQLITE_ROW as the end of the rows, so an error while +the statement runs was dropped: next() returned false, as at the end of +the rows, and toArray() returned the rows read before the error. A +failed UNIQUE constraint on an INSERT, or an integer overflow, looked +like success, and JavaScript that writes through db.exec() could not +tell. An error found when the statement is prepared, such as an unknown +function, was already thrown by db.exec(). + +Throw an InternalError with the connection's error message when +sqlite3_step() returns neither SQLITE_ROW nor SQLITE_DONE, from next() +and from toArray(). The statement is finalized as before. The end of +the rows is still false. The README now documents db.exec(), including +that a statement runs only when next() or toArray() steps it. + +Add an Exec errors test: a failed constraint and an overflow throw from +next(), an overflow on the second row throws from toArray(), JavaScript +can catch the error, and the end of the rows and a successful INSERT +are unchanged. It fails without this change. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 12 ++++++++++++ + src/sqlitejs.c | 19 +++++++++++++++---- + test/main.c | 35 +++++++++++++++++++++++++++++++++++ + 3 files changed, 62 insertions(+), 4 deletions(-) + +diff --git a/README.md b/README.md +index 8ef6804..abec56b 100644 +--- a/README.md ++++ b/README.md +@@ -397,6 +397,18 @@ SELECT js_eval('Math.PI * Math.pow(5, 2)'); + SELECT js_eval('new Date(1629381600000).toLocaleDateString()'); + ``` + ++### Running SQL from JavaScript ++ ++JavaScript can run SQL on the same connection through the global `db` object. `db.exec(sql, ...parameters)` prepares one statement, binds the parameters to its `?` placeholders, and returns a result set. The statement runs as you step through it: `next()` moves to the next row and returns `true`, or `false` after the last; `get(i)` and `name(i)` give a column's value and name; `columnCount` is the number of columns; and `toArray()` returns the remaining rows as arrays. A statement that returns no rows, such as an `INSERT`, also runs only when you call `next()` or `toArray()`. ++ ++An error while the statement runs, such as a failed constraint, is thrown from `next()` or `toArray()`, as an error in the SQL itself is thrown from `db.exec()`. ++ ++```sql ++CREATE TABLE t(a UNIQUE); ++SELECT js_eval('db.exec("INSERT INTO t VALUES (?)", 1).next()'); -- 0: the row is inserted, and next() is false, as there are no rows ++SELECT js_eval('(function () { try { db.exec("INSERT INTO t VALUES (?)", 1).next(); } catch (e) { return e.message; } })()'); -- UNIQUE constraint failed: t.a ++``` ++ + ## Utility Functions + + ### js_version +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index e5562f4..8f6e3a9 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -115,11 +115,16 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J + if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); + + if (!rs->vm) return JS_FALSE; +- if (sqlite3_step(rs->vm) == SQLITE_ROW) return JS_TRUE; ++ int rc = sqlite3_step(rs->vm); ++ if (rc == SQLITE_ROW) return JS_TRUE; + ++ // an error while the statement runs (a constraint, an overflow, an interrupt) is an ++ // exception, as an error while it is prepared is in js_sqlite_exec; only the end of the ++ // rows is false ++ JSValue result = (rc == SQLITE_DONE) ? JS_FALSE : JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); + sqlite3_finalize(rs->vm); + rs->vm = NULL; +- return JS_FALSE; ++ return result; + } + + static JSValue js_rowset_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { +@@ -168,8 +173,9 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg + + int ncols = rs->ncols; + int nrows = 0; ++ int rc; + while (true) { +- int rc = sqlite3_step(rs->vm); ++ rc = sqlite3_step(rs->vm); + if (rc != SQLITE_ROW) break; + + JSValue row = JS_NewArray(ctx); +@@ -186,7 +192,12 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg + + JS_SetPropertyUint32(ctx, result, nrows++, row); + } +- ++ ++ // as in js_rowset_next: an error is an exception, not a shorter array ++ if (rc != SQLITE_DONE) { ++ JS_FreeValue(ctx, result); ++ result = JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); ++ } + sqlite3_finalize(rs->vm); + rs->vm = NULL; + return result; +diff --git a/test/main.c b/test/main.c +index ff1c0e7..3b562dd 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -881,6 +881,40 @@ abort_test: + + // MARK: - + ++// MARK: - Exec errors - ++ ++int test_exec_errors (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "CREATE TABLE u(a UNIQUE); INSERT INTO u VALUES (1);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // an error while the statement runs is an exception, from next() and from toArray() ++ rc = check_error(db, "SELECT js_eval('db.exec(\"INSERT INTO u VALUES (1)\").next()');", "UNIQUE constraint failed"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('db.exec(\"SELECT abs(-9223372036854775808)\").next()');", "integer overflow"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('db.exec(\"SELECT 1 UNION ALL SELECT abs(-9223372036854775808) UNION ALL SELECT 3\").toArray()');", "integer overflow"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // JavaScript can catch it ++ rc = check_query(db, "SELECT js_eval('(function () { try { db.exec(\"INSERT INTO u VALUES (1)\").next(); return \"no error\"; } catch (e) { return e.message; } })()');", "UNIQUE constraint failed: u.a"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // the end of the rows is still false, and a statement that succeeds still runs ++ rc = check_query(db, "SELECT js_eval('[db.exec(\"SELECT 1 WHERE 0\").next(), db.exec(\"INSERT INTO u VALUES (2)\").next(), JSON.stringify(db.exec(\"SELECT a FROM u ORDER BY a\").toArray())].join(\" \")');", "false false [[1],[2]]"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ ++// MARK: - ++ + int test_report(const char *description, int rc){ + printf("%s%-30s %s\n", VERBOSE ? "********** " : "", description, (rc == SQLITE_OK) ? "OK" : "FAILED"); + return (rc == SQLITE_OK) ? 0 : 1; +@@ -902,6 +936,7 @@ int main (void) { + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); + result += test_report("Aggregate errors", test_aggregate_errors()); ++ result += test_report("Exec errors", test_exec_errors()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index e7f1c5b..979cb1c 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -2,7 +2,7 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is -[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.3.7 with seven +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.3.7 with eight changes of ours, listed [below](#changes-in-this-build). The JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. @@ -87,6 +87,11 @@ SELECT js_eval('(function () { })()'); -- 42 ``` +`db.exec` returns a result set, and the statement runs as `next()` or +`toArray()` steps it, so call `next()` once to run an `INSERT` or another +statement that returns no rows. An SQL error, while the statement is prepared +or while it runs, is a JavaScript exception. + ## Functions | Function | What it does | @@ -184,7 +189,7 @@ constraints and generated columns cannot call `js_eval` or the other ## Changes in this build -Seven patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. +Eight patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. | Patch | Change | |-------|--------| @@ -195,6 +200,7 @@ Seven patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. | `0005` | A whole-number result is an INTEGER. Upstream, an INTEGER outside the 32-bit range comes back as a REAL. | | `0006` | An exception in an aggregate's or window function's step is an SQL error. Upstream, it is ignored, and the result is silently wrong. | | `0007` | The JavaScript stack size stays within the thread's stack: `js_set_max_stack_size` refuses text and larger sizes, and the default shrinks on a small stack. Upstream, those make endless recursion crash `sqlite3`. | +| `0008` | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. Upstream, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 2589b63..49fbfe3 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,7 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.3.7 -TERMUX_PKG_REVISION=2 +TERMUX_PKG_REVISION=3 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 TERMUX_PKG_BUILD_DEPENDS="libsqlite" diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 7ef883e..61f8505 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -609,7 +609,7 @@ if [[ $most =~ ^[0-9]+$ ]] && ((most > 128 * 1024)); then "Maximum call stack size exceeded" "SELECT js_set_max_stack_size($near);" "$RECURSE" expect_error "AC13: endless recursion through db.exec fails just below the largest size" "stopped" \ "SELECT js_set_max_stack_size($near);" \ - "SELECT js_create_scalar('recurse_sql', '(function (args) { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (!rs.next()) throw new Error(\"stopped\"); return rs.get(0); })');" \ + "SELECT js_create_scalar('recurse_sql', '(function (args) { try { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (rs.next()) return rs.get(0); } catch (e) {} throw new Error(\"stopped\"); })');" \ "SELECT recurse_sql(0);" else not_ok "AC13: the error names the largest size" "got: $most" @@ -624,6 +624,22 @@ else not_ok "AC13: with 512 KB of stack, endless recursion fails at the default size" "exit status $rc" "got: $got" fi +# --- AC14: SQL errors in db.exec are exceptions --------------------------------- + +# The statement runs as next() or toArray() steps it; an error while it runs +# must not look like the end of the rows. +EXEC_SETUP="CREATE TABLE IF NOT EXISTS ac14(a UNIQUE); INSERT OR IGNORE INTO ac14 VALUES (1);" +expect_error "AC14: a failed constraint throws from next()" "UNIQUE constraint failed" \ + "$EXEC_SETUP" "SELECT js_eval('db.exec(\"INSERT INTO ac14 VALUES (1)\").next()');" +expect_error "AC14: an overflow on the second row throws from toArray()" "integer overflow" \ + "SELECT js_eval('db.exec(\"SELECT 1 UNION ALL SELECT abs(-9223372036854775808)\").toArray()');" +expect "AC14: JavaScript can catch the error" "UNIQUE constraint failed: ac14.a" \ + "$EXEC_SETUP" "SELECT js_eval('(function () { try { db.exec(\"INSERT INTO ac14 VALUES (1)\").next(); return \"no error\"; } catch (e) { return e.message; } })()');" +expect "AC14: a statement runs only when stepped, and the end of the rows is false" $'0\nfalse false\n1,2' \ + "$EXEC_SETUP" "SELECT js_eval('db.exec(\"INSERT INTO ac14 VALUES (3)\"); 0');" \ + "SELECT js_eval('[db.exec(\"SELECT 1 WHERE 0\").next(), db.exec(\"INSERT INTO ac14 VALUES (2)\").next()].join(\" \")');" \ + "SELECT group_concat(a) FROM (SELECT a FROM ac14 ORDER BY a);" + echo "1..$n" if [[ $failed -ne 0 ]]; then echo "# FAILED $failed of $n" From 6a10187f19e5cea4b4fcce19224582ff756de5dd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 15:00:59 -0800 Subject: [PATCH 05/17] ADFA-7081: sqlite-js 1.3.7-4, keep run-tests.sh from leaving runaway processes The interactive Ctrl-C test ran js_eval('while (true) {}') under timeout 30 script(1). Against a build where Ctrl-C does not stop JavaScript, such as unpatched 1.3.7, timeout stopped script but not the sqlite3 it ran, which kept a CPU core busy until killed; three were found after 17 hours on a development machine. Each runaway loop in the AC8 tests now gives up after 20 s, and the interactive test must finish within 15 s, since the shell also reports "interrupted" when a loop ends by itself. The AC9 allocation loops stop at about 4 times the 64 MB default, so a build without the limit fails the test instead of exhausting the device's memory. timeout also kills script if it ignores SIGTERM. Tested on x86_64 Linux: the 1.3.7-3 build passes 91 of 91. Unpatched 1.3.7 fails 39, including the four Ctrl-C tests and the allocation-loop test, and leaves no process or test directory behind. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/build.sh | 2 +- packages/sqlite-js/tests/run-tests.sh | 39 +++++++++++++++++---------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 49fbfe3..1a5ba50 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,7 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.3.7 -TERMUX_PKG_REVISION=3 +TERMUX_PKG_REVISION=4 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 TERMUX_PKG_BUILD_DEPENDS="libsqlite" diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 61f8505..69ef734 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -433,35 +433,44 @@ DB=$WORK/test.db # --- AC8: Ctrl-C stops runaway JavaScript ----------------------------------- -expect_sigint_stops "AC8: SIGINT (Ctrl-C) stops while (true) {} in js_eval" \ - "SELECT js_eval('while (true) {}');" -expect_sigint_stops "AC8: SIGINT stops an endless scalar function" \ - "SELECT js_create_scalar('forever', '(function (args) { for (;;) {} })');" "SELECT forever(1);" +# Each runaway loop gives up after 20 s, long after the tests expect Ctrl-C to +# have stopped it, so that a build where Ctrl-C does nothing leaves no sqlite3 +# behind: timeout(1) below can stop script(1), but not the sqlite3 it runs. +RUNAWAY='for (const end = Date.now() + 20000; Date.now() < end;) {}' +expect_sigint_stops "AC8: SIGINT (Ctrl-C) stops a runaway loop in js_eval" \ + "SELECT js_eval('$RUNAWAY');" +expect_sigint_stops "AC8: SIGINT stops a runaway scalar function" \ + "SELECT js_create_scalar('forever', '(function (args) { $RUNAWAY })');" "SELECT forever(1);" expect_sigint_stops "AC8: SIGINT stops code that catches every exception" \ - "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');" + "SELECT js_eval('for (const end = Date.now() + 20000; Date.now() < end;) { try { while (Date.now() < end) {} } catch (e) {} }');" # In batch mode the shell exits after an interrupt, whatever stopped; only an # interactive session goes on. script(1) runs one on a pseudo-terminal, where # the byte 0x03 is Ctrl-C. if command -v script >/dev/null 2>&1; then cmd=$(printf '%q ' "$SQLITE3" -noheader -cmd "$LOAD_EXT" "$DB") + # The shell also reports "interrupted" once the loop ends by itself, so the + # session must end well before the loop's 20 s are up: about 5 s if Ctrl-C works. + started=$SECONDS got=$({ sleep 1 - printf '%s\n' "SELECT js_eval('while (true) {}');" + printf '%s\n' "SELECT js_eval('$RUNAWAY');" sleep 2 printf '\003' sleep 1 printf '%s\n' "SELECT 'still' || ' alive';" sleep 1 printf '.quit\n' - } | timeout 30 script -q -c "$cmd" /dev/null 2>&1 | tr -d '\r') - if [[ $got == *interrupted* && $got == *"still alive"* ]]; then - ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" + } | timeout -k 5 30 script -q -c "$cmd" /dev/null 2>&1 | tr -d '\r') + seconds=$((SECONDS - started)) + if [[ $got == *interrupted* && $got == *"still alive"* && $seconds -lt 15 ]]; then + ok "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" else - not_ok "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" "got: $got" + not_ok "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ + "took $seconds s, want under 15" "got: $got" fi else - skip "AC8: in an interactive session, Ctrl-C stops while (true) {} and sqlite3 keeps running" \ + skip "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ "needs script(1), from the util-linux package" fi @@ -473,9 +482,11 @@ expect "AC9: the default limit allows 48 MB" "50331648" \ "SELECT js_eval('new ArrayBuffer(48 * 1024 * 1024).byteLength');" expect_error "AC9: the default limit refuses 70 MB" "out of memory" \ "SELECT js_eval('new ArrayBuffer(70 * 1024 * 1024).byteLength');" -expect_nobail "AC9: code that never stops allocating fails at the limit, and the session stays usable" \ +# The allocation loops stop at about 4 times the 64 MB default, so that a build +# without the limit fails the test rather than exhausting the device's memory. +expect_nobail "AC9: code that keeps allocating fails at the limit, and the session stays usable" \ "1,2,3" "out of memory" \ - "SELECT js_eval('(function () { const a = []; for (;;) a.push(new Array(100000).fill(1)); })()');" \ + "SELECT js_eval('(function () { const a = []; for (let i = 0; i < 160; i++) a.push(new Array(100000).fill(1)); })()');" \ "SELECT js_eval('[1, 2, 3].join()');" expect_nobail "AC9: memory held by a global counts until the global is cleared" \ $'0\n16777216' "out of memory" \ @@ -496,7 +507,7 @@ for kb in 100 140 180 220 260 300 340 380 420; do runs=$((runs + 1)) done for kb in 0 1 2 3 4 6 8 12 16; do - sql_nobail "SELECT js_eval('globalThis.keep = []; try { for (;;) keep.push(new ArrayBuffer(1024)); } catch (e) {} keep.length -= $kb; 0');" \ + sql_nobail "SELECT js_eval('globalThis.keep = []; try { for (let i = 0; i < 262144; i++) keep.push(new ArrayBuffer(1024)); } catch (e) {} keep.length -= $kb; 0');" \ "$AGGREGATE" >/dev/null 2>&1 (($? >= 128)) && crashes+=("$kb KB left") runs=$((runs + 1)) From 564c003f865689792420b6fdbe623485493aa020 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 18:36:09 -0800 Subject: [PATCH 06/17] ADFA-7081: sqlite-js 1.3.7-5, fix what the independent review found From the independent review of PR #6: - 0002: QuickJS sets its garbage-collection threshold to 1.5 times the memory in use. Past two thirds of the limit, that is beyond the limit, so garbage filled it and code that fits failed. The threshold is now kept between the memory in use and the limit. - 0002: running out of memory through small allocations leaves no room for QuickJS's error, so QuickJS throws null. That now reports "out of memory" instead of "Unknown JavaScript exception". - 0004: db.exec throws for a buffer it cannot read (detached, or a typed array out of its buffer's bounds) instead of binding NULL. - 0004, from CodeRabbit on CodeOnTheGo #2244: a typed array's offset and length are read through getters taken when the runtime is made, so properties a script defines over them cannot change which bytes are read. - 0003 and the README: TEMP views and triggers can call the js_* functions, since SQLite trusts the TEMP schema. Patches 0001-0008 are regenerated from the work repo. Only 0002, 0003 and 0004 change in substance. The others change in their headers, hunk line numbers and index lines. run-tests.sh adds six checks, for 97 in all: - garbage is collected with 48 of 64 MB held; - an aggregate over 300 groups runs with 48 of 64 MB held; - small allocations run out with "out of memory"; - db.exec throws for buffers it cannot bind; - shadowed typed-array properties are ignored; - a TEMP view can call js_eval. On a host build, 97 of 97 pass, and 1.3.7-4 fails the five that test the fixes. Upstream test/main.c passes 14 of 14 under ASan and UBSan with leak checking, and each new test there fails without its fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...t-when-the-connection-is-interrupted.patch | 2 +- ...the-memory-of-the-JavaScript-runtime.patch | 232 ++++++++++++++++-- ...ions-that-run-code-out-of-the-schema.patch | 20 +- ...rayBuffers-and-typed-arrays-as-BLOBs.patch | 147 ++++++++--- ...005-Return-whole-numbers-as-INTEGERs.patch | 24 +- ...s-thrown-by-aggregate-and-window-ste.patch | 12 +- ...ipt-stack-size-within-the-thread-s-s.patch | 24 +- ...-SQL-errors-from-db.exec-result-sets.patch | 16 +- packages/sqlite-js/README.md | 12 +- packages/sqlite-js/build.sh | 2 +- packages/sqlite-js/tests/run-tests.sh | 26 ++ 11 files changed, 416 insertions(+), 101 deletions(-) diff --git a/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch b/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch index ec319c8..1d976a2 100644 --- a/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch +++ b/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 20:56:10 -0800 -Subject: [PATCH 1/6] Stop JavaScript when the connection is interrupted +Subject: [PATCH 1/8] Stop JavaScript when the connection is interrupted JavaScript runs inside the SQL statement that calls it, but QuickJS had no interrupt handler, so sqlite3_interrupt() could not stop code that diff --git a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch index 72d6884..850f36f 100644 --- a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch +++ b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 20:58:13 -0800 -Subject: [PATCH 2/6] Limit the memory of the JavaScript runtime +Subject: [PATCH 2/8] Limit the memory of the JavaScript runtime The JavaScript runtime had no memory limit (the JS_SetMemoryLimit call was commented out), so code that keeps allocating took all the memory of @@ -22,22 +22,41 @@ window function, and the trial one that js_create_aggregate() and js_create_window() make, is created with the limit lifted; the limit then applies again to the code that runs in it. +QuickJS collects cyclic garbage only when its memory use passes a +threshold, which it resets after each collection to 1.5 times the +memory still in use. With more than two thirds of the limit in use the +threshold was past the limit, so garbage filled the rest and code that +fits failed. The interrupt handler, js_set_memory_limit() and each +aggregate's setup now lower it, after a collection, to halfway between +the memory in use and the limit. + +When the limit leaves no room even for the "out of memory" error, +QuickJS throws null, which reported "Unknown JavaScript exception". The +runtime now allocates through functions that count its memory as QuickJS +does, and a null exception after the memory in use reached the limit +reports "out of memory". JavaScript that catches it still receives null; +the README says so. + Add a Memory limit test: allocations under and over the default, code that never stops allocating, raising, removing and lowering the limit, and invalid arguments. It also creates and runs an aggregate under small limits and with little memory left, which crashed while QuickJS -created its context under the limit. +created its context under the limit. With 12 of 16 MB held, code that +makes many times the free memory in cyclic garbage runs, and so does an +aggregate over 300 groups; running out of memory through small +allocations reports "out of memory". Both fail without the collection +and reporting changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- - README.md | 9 +++++ - src/sqlitejs.c | 53 +++++++++++++++++++++++----- - test/main.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 147 insertions(+), 9 deletions(-) + README.md | 9 +++ + src/sqlitejs.c | 163 ++++++++++++++++++++++++++++++++++++++++++++++--- + test/main.c | 115 ++++++++++++++++++++++++++++++++++ + 3 files changed, 277 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md -index 45bf583..52efd7b 100644 +index 45bf583..d88b539 100644 --- a/README.md +++ b/README.md @@ -410,6 +410,15 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. @@ -46,7 +65,7 @@ index 45bf583..52efd7b 100644 +### js_set_memory_limit + -+Sets the most memory, in bytes, that JavaScript may allocate on this connection; 0 means no limit. The default is 64 MB (64 × 1024 × 1024 bytes); build with `-DSQLITE_JS_DEFAULT_MEMORY_LIMIT=bytes` to change it. Code that needs more fails with an "out of memory" error, and the connection stays usable. ++Sets the most memory, in bytes, that JavaScript may allocate on this connection; 0 means no limit. The default is 64 MB (64 × 1024 × 1024 bytes); build with `-DSQLITE_JS_DEFAULT_MEMORY_LIMIT=bytes` to change it. Code that needs more fails with an "out of memory" error, and the connection stays usable. JavaScript that catches the error receives `null` instead when the limit leaves no room even for the error. + +```sql +SELECT js_set_memory_limit(268435456); -- Allow 256 MB @@ -57,18 +76,33 @@ index 45bf583..52efd7b 100644 JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 524581e..6f00635 100644 +index 524581e..1ba634e 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -31,6 +31,7 @@ typedef struct { +@@ -11,6 +11,11 @@ + #include + #include + #include ++#if defined(__APPLE__) ++#include ++#elif defined(_WIN32) || defined(__linux__) || defined(__ANDROID__) || defined(__GLIBC__) ++#include ++#endif + #include "sqlitejs.h" + #include "quickjs.h" + #include "quickjs-libc.h" +@@ -31,6 +36,10 @@ typedef struct { sqlite3 *db; JSClassID rowSetClassID; int ref_count; + size_t memory_limit; // in bytes, 0 for none: see js_set_memory_limit() ++ size_t gc_threshold; // QuickJS's GC threshold when last checked: see js_keep_gc_below_limit() ++ size_t mem_used; // memory the runtime has allocated: see js_mem_malloc() ++ size_t mem_peak; // the most in use since the last result or error } globaljs_context; typedef struct { -@@ -187,6 +188,14 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { +@@ -187,15 +196,107 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { // MARK: - Initializer - @@ -79,11 +113,113 @@ index 524581e..6f00635 100644 +#ifndef SQLITE_JS_DEFAULT_MEMORY_LIMIT +#define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) +#endif ++ ++// QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets ++// after each collection to 1.5 times the memory still in use. With more than two thirds of the ++// memory limit in use, that is beyond the limit: garbage would fill the rest, and code that fits ++// in the limit would fail. So the threshold is lowered to halfway between the memory in use and ++// the limit. Called often, so it does nothing until a collection has changed the threshold. ++static void js_keep_gc_below_limit (globaljs_context *js) { ++ size_t threshold = JS_GetGCThreshold(js->runtime); ++ if (threshold == js->gc_threshold) return; ++ size_t limit = js->memory_limit; ++ if ((limit > 0) && (threshold > limit - limit / 4)) { ++ size_t used = threshold / 3 * 2; ++ if (used > limit) used = limit; ++ threshold = used + (limit - used) / 2; ++ JS_SetGCThreshold(js->runtime, threshold); ++ } ++ js->gc_threshold = threshold; ++} + // QuickJS calls this from time to time while it runs code. A non-zero result stops the code // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, // a cancelled query in an app) also stops JavaScript that never returns to SQLite. -@@ -228,7 +237,12 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + static int js_interrupt_handler (JSRuntime *rt, void *opaque) { + UNUSED(rt); + globaljs_context *js = (globaljs_context *)opaque; ++ js_keep_gc_below_limit(js); + return (js->db != NULL) && sqlite3_is_interrupted(js->db); + } + ++// The runtime's allocator: the system's, as QuickJS's default is, counting the memory in use the ++// way QuickJS counts it against the memory limit, and the most in use since the last result or ++// error (see js_reached_memory_limit). QuickJS refuses an allocation over the limit before it ++// gets here. ++#if defined(__APPLE__) ++#define js_mem_usable_size(ptr) malloc_size(ptr) ++#define JS_MEM_OVERHEAD 0 ++#elif defined(_WIN32) ++#define js_mem_usable_size(ptr) _msize((void *)(ptr)) ++#define JS_MEM_OVERHEAD 8 ++#elif defined(__linux__) || defined(__ANDROID__) || defined(__GLIBC__) ++#define js_mem_usable_size(ptr) malloc_usable_size((void *)(ptr)) ++#define JS_MEM_OVERHEAD 8 ++#else ++#define js_mem_usable_size(ptr) ((size_t)0) ++#define JS_MEM_OVERHEAD 0 ++#endif ++ ++static void js_mem_add (globaljs_context *js, void *ptr) { ++ if (!ptr) return; ++ js->mem_used += js_mem_usable_size(ptr) + JS_MEM_OVERHEAD; ++ if (js->mem_used > js->mem_peak) js->mem_peak = js->mem_used; ++} ++ ++static void js_mem_sub (globaljs_context *js, void *ptr) { ++ if (ptr) js->mem_used -= js_mem_usable_size(ptr) + JS_MEM_OVERHEAD; ++} ++ ++static void *js_mem_calloc (void *opaque, size_t count, size_t size) { ++ void *ptr = calloc(count, size); ++ js_mem_add((globaljs_context *)opaque, ptr); ++ return ptr; ++} ++ ++static void *js_mem_malloc (void *opaque, size_t size) { ++ void *ptr = malloc(size); ++ js_mem_add((globaljs_context *)opaque, ptr); ++ return ptr; ++} ++ ++static void js_mem_free (void *opaque, void *ptr) { ++ js_mem_sub((globaljs_context *)opaque, ptr); ++ free(ptr); ++} ++ ++static void *js_mem_realloc (void *opaque, void *ptr, size_t size) { ++ globaljs_context *js = (globaljs_context *)opaque; ++ size_t old = (ptr) ? js_mem_usable_size(ptr) + JS_MEM_OVERHEAD : 0; ++ void *new_ptr = realloc(ptr, size); ++ if (!new_ptr && size) return NULL; // the old block is unchanged ++ js->mem_used -= old; ++ js_mem_add(js, new_ptr); ++ return new_ptr; ++} ++ ++static size_t js_mem_size (const void *ptr) { ++ return js_mem_usable_size(ptr); ++} ++ ++static const JSMallocFunctions js_mem_funcs = {js_mem_calloc, js_mem_malloc, js_mem_free, js_mem_realloc, js_mem_size}; ++ ++static void js_mem_reset_peak (globaljs_context *js) { ++ if (js) js->mem_peak = js->mem_used; ++} ++ + static globaljs_context *globaljs_init (sqlite3 *db) { + JSRuntime *rt = NULL; + JSContext *ctx = NULL; +@@ -204,7 +305,7 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + if (!js) return NULL; + memset(js, 0, sizeof(globaljs_context)); + +- rt = JS_NewRuntime(); ++ rt = JS_NewRuntime2(&js_mem_funcs, js); + if (!rt) goto abort_init; + + //JS_SetMemoryLimit(rt, 80 * 1024); +@@ -228,7 +329,12 @@ static globaljs_context *globaljs_init (sqlite3 *db) { JS_SetContextOpaque(ctx, js); JS_SetRuntimeOpaque(rt, js); js_global_init(ctx, js); @@ -97,10 +233,46 @@ index 524581e..6f00635 100644 return js; abort_init: -@@ -655,16 +669,22 @@ static bool js_setup_aggregate (sqlite3_context *context, globaljs_context *js, +@@ -543,6 +649,12 @@ static void js_dump_globals (JSContext *ctx) { + } + #endif + ++// True if JavaScript reached its memory limit since the last result or error. QuickJS then may ++// have had no memory left to make its "out of memory" error, and have thrown null instead. ++static bool js_reached_memory_limit (globaljs_context *js) { ++ return js && (js->memory_limit > 0) && (js->mem_peak + 64 * 1024 >= js->memory_limit); ++} ++ + static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSValue value, const char *default_error) { + if (!default_error) default_error = "Unknown JavaScript exception"; + const char *err_msg = NULL; +@@ -558,8 +670,11 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + JS_FreeValue(js_ctx, message); + } else if (JS_IsString(exception)) { + err_msg = JS_ToCString(js_ctx, exception); ++ } else if (JS_IsNull(exception) && js_reached_memory_limit(JS_GetContextOpaque(js_ctx))) { ++ default_error = "out of memory"; + } + } ++ js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); + + // set a default error message and code + sqlite3_result_error(context, (err_msg) ? err_msg : default_error, -1); +@@ -576,6 +691,7 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + js_error_to_sqlite(context, js_ctx, value, NULL); + return; + } ++ js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); + + // check for null or undefined + if (JS_IsNull(value) || JS_IsUndefined(value)) { +@@ -655,16 +771,26 @@ static bool js_setup_aggregate (sqlite3_context *context, globaljs_context *js, } // create a separate context for testing purpose ++ // Each finished aggregate leaves its context behind as cyclic garbage, so the collector must ++ // be able to run before the limit is reached. ++ js_keep_gc_below_limit(js); + // QuickJS cannot always recover from running out of memory while it creates a context: it + // can crash. So the context is created without the memory limit (it takes about 54 KB), + // which then applies again to the code that runs in it. @@ -112,6 +284,7 @@ index 524581e..6f00635 100644 + js_global_init(ctx, js); + } + JS_SetMemoryLimit(js->runtime, js->memory_limit); ++ js_mem_reset_peak(js); if (!ctx) { sqlite3_result_error(context, "Unable to create a JS context.", -1); return false; @@ -125,7 +298,7 @@ index 524581e..6f00635 100644 // init code is optional if (init_code) { JSValue init_result = JS_Eval(ctx, init_code, strlen(init_code), NULL, JS_EVAL_TYPE_GLOBAL); -@@ -1305,6 +1325,21 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** +@@ -1305,6 +1431,23 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** JS_SetMaxStackSize(js->runtime, stack_size); } @@ -142,12 +315,14 @@ index 524581e..6f00635 100644 + sqlite3_uint64 limit = (sqlite3_uint64)sqlite3_value_int64(argv[0]); + js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; + JS_SetMemoryLimit(js->runtime, js->memory_limit); ++ js->gc_threshold = 0; // check the GC threshold against the new limit ++ js_keep_gc_below_limit(js); +} + // MARK: - const char *sqlitejs_version (void) { -@@ -1325,9 +1360,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r +@@ -1325,9 +1468,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r globaljs_context *js = globaljs_init(db); if (!js) return SQLITE_NOMEM; @@ -161,10 +336,10 @@ index 524581e..6f00635 100644 size_t f_count = sizeof(f_name) / sizeof(const char *); for (size_t i=0; i Date: Tue, 10 Nov 2026 20:59:46 -0800 -Subject: [PATCH 3/6] Keep the functions that run code out of the schema +Subject: [PATCH 3/8] Keep the functions that run code out of the schema js_eval(), js_create_*(), js_load_text(), js_load_blob(), js_init_table() and the js_set_* functions were registered without SQLITE_DIRECTONLY, so @@ -12,7 +12,9 @@ run JavaScript or read files just by being queried: `CREATE VIEW v AS SELECT js_eval('...')`. Register every function but js_version() with SQLITE_DIRECTONLY, so only -top-level SQL can call them. The functions created with js_create_* are +top-level SQL can call them. TEMP views and triggers still can: SQLite +trusts them, since only the connection itself can make them, and the +README says so. The functions created with js_create_* are unchanged, so they still work in views, triggers and indexes. The flag is computed from the function's name rather than from a table that parallels the function list, so a function added later gets it without @@ -33,7 +35,7 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md -index 52efd7b..ff51b2f 100644 +index d88b539..bcbb7f0 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,12 @@ SELECT js_set_memory_limit(268435456); -- Allow 256 MB @@ -42,7 +44,7 @@ index 52efd7b..ff51b2f 100644 +### Using the functions from the schema + -+Every function above but `js_version` runs JavaScript, reads files or changes the JavaScript runtime, so it is registered with `SQLITE_DIRECTONLY`: only top-level SQL can call it, never a view, trigger, CHECK constraint, generated column or index. That way a database from an untrusted source cannot run JavaScript just by being queried. The functions you create with `js_create_scalar`, `js_create_aggregate`, `js_create_window` and `js_create_collation` are not restricted. ++Every function above but `js_version` runs JavaScript, reads files or changes the JavaScript runtime, so it is registered with `SQLITE_DIRECTONLY`: only top-level SQL can call it, never a view, trigger, CHECK constraint, generated column or index stored in the database. (TEMP views and triggers can call it: SQLite trusts them, since only the connection itself can make them.) That way a database from an untrusted source cannot run JavaScript just by being queried. The functions you create with `js_create_scalar`, `js_create_aggregate`, `js_create_window` and `js_create_collation` are not restricted. + +A database can still store JavaScript in its `js_functions` table, and `js_init_table(1)` runs it. Call it only on databases you trust. + @@ -50,10 +52,10 @@ index 52efd7b..ff51b2f 100644 JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 6f00635..6b48ef2 100644 +index 1ba634e..8a48d92 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -1363,11 +1363,16 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r +@@ -1471,11 +1471,16 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; @@ -73,10 +75,10 @@ index 6f00635..6b48ef2 100644 if (pzErrMsg) *pzErrMsg = sqlite3_mprintf("Error creating function %s: %s", f_name[i], sqlite3_errmsg(db)); // sqlite3_create_function_v2 always invokes the xDestroy callback when it fails, diff --git a/test/main.c b/test/main.c -index 7855bfb..dfa3306 100644 +index 4adeb82..c13e043 100644 --- a/test/main.c +++ b/test/main.c -@@ -647,6 +647,58 @@ abort_test: +@@ -668,6 +668,58 @@ abort_test: return rc; } @@ -135,7 +137,7 @@ index 7855bfb..dfa3306 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -665,6 +717,7 @@ int main (void) { +@@ -686,6 +738,7 @@ int main (void) { result += test_report("Thread", test_thread()); result += test_report("Interrupt", test_interrupt()); result += test_report("Memory limit", test_memory_limit()); diff --git a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch index 377b108..2aa28ba 100644 --- a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch +++ b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 21:01:52 -0800 -Subject: [PATCH 4/6] Return ArrayBuffers and typed arrays as BLOBs +Subject: [PATCH 4/8] Return ArrayBuffers and typed arrays as BLOBs A BLOB argument reaches JavaScript as an ArrayBuffer, but a function that returned an ArrayBuffer, or a typed array such as Uint8Array, gave @@ -13,10 +13,14 @@ NULL. Add js_get_bytes(), which gets the bytes of an ArrayBuffer or of the part of a buffer that a typed array views, and use it for function results and -for db.exec() parameters. An empty buffer is an empty BLOB. Returning a -detached buffer is an error; binding one still binds NULL, as before. -A typed array's offset and length come from its byteOffset and -byteLength getters, read before its bytes: one that tracks the length +for db.exec() parameters. An empty buffer is an empty BLOB. Returning or +binding a detached buffer, or a typed array out of its buffer's bounds, +is an error: db.exec() throws it rather than binding NULL, which would +make a failed write look like a success. A typed array's offset and +length come from the byteOffset and byteLength getters of +%TypedArray%.prototype, taken when the runtime is made, so a script that +shadows or redefines them cannot change which bytes are read. They are +read before its bytes: one that tracks the length of a resizable buffer keeps the length QuickJS recorded when it was made, which goes stale when the buffer is resized, and reading it after a shrink would read past the buffer. A typed array of fixed @@ -26,19 +30,21 @@ Document how values convert in both directions in the README. Add a Blobs test: BLOBs round-trip through a function, typed arrays, subarrays and ArrayBuffers made in JavaScript become BLOBs, a function can build a BLOB from a BLOB, a detached buffer is an error, and -db.exec() binds typed arrays and empty buffers as BLOBs. It also checks -typed arrays over resizable buffers that shrink and grow. +db.exec() binds typed arrays and empty buffers as BLOBs and throws for a +buffer it cannot read. It also checks typed arrays over resizable +buffers that shrink and grow, and typed arrays whose byteOffset and +byteLength are shadowed or redefined. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- - README.md | 13 ++++++++ - src/sqlitejs.c | 82 +++++++++++++++++++++++++++++++++++++++++++++----- - test/main.c | 50 ++++++++++++++++++++++++++++++ - 3 files changed, 138 insertions(+), 7 deletions(-) + README.md | 13 ++++++ + src/sqlitejs.c | 113 ++++++++++++++++++++++++++++++++++++++++++++----- + test/main.c | 60 ++++++++++++++++++++++++++ + 3 files changed, 176 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md -index ff51b2f..99abfb9 100644 +index bcbb7f0..074735a 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,19 @@ SQLite-JS provides several ways to extend SQLite functionality with JavaScript: @@ -62,10 +68,69 @@ index ff51b2f..99abfb9 100644 Scalar functions process one row at a time and return a single value. They are useful for data transformation, calculations, text manipulation, etc. diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 6b48ef2..cb4d75d 100644 +index 8a48d92..8c614fb 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -372,6 +372,56 @@ static void functionjs_free (functionjs_context *fctx) { +@@ -40,6 +40,8 @@ typedef struct { + size_t gc_threshold; // QuickJS's GC threshold when last checked: see js_keep_gc_below_limit() + size_t mem_used; // memory the runtime has allocated: see js_mem_malloc() + size_t mem_peak; // the most in use since the last result or error ++ JSValue typed_array_byte_offset; // the getters of every typed array's own ++ JSValue typed_array_byte_length; // offset and length: see js_get_bytes() + } globaljs_context; + + typedef struct { +@@ -304,6 +306,8 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + globaljs_context *js = (globaljs_context *)sqlite3_malloc(sizeof(globaljs_context)); + if (!js) return NULL; + memset(js, 0, sizeof(globaljs_context)); ++ js->typed_array_byte_offset = JS_UNDEFINED; ++ js->typed_array_byte_length = JS_UNDEFINED; + + rt = JS_NewRuntime2(&js_mem_funcs, js); + if (!rt) goto abort_init; +@@ -330,6 +334,14 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + JS_SetRuntimeOpaque(rt, js); + js_global_init(ctx, js); + ++ // taken before any other code runs: a script can shadow or redefine a typed array's ++ // byteOffset and byteLength, but these are its own ++ static const char offset_getter[] = "Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteOffset').get"; ++ static const char length_getter[] = "Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteLength').get"; ++ js->typed_array_byte_offset = JS_Eval(ctx, offset_getter, sizeof(offset_getter) - 1, "", JS_EVAL_TYPE_GLOBAL); ++ js->typed_array_byte_length = JS_Eval(ctx, length_getter, sizeof(length_getter) - 1, "", JS_EVAL_TYPE_GLOBAL); ++ if (!JS_IsFunction(ctx, js->typed_array_byte_offset) || !JS_IsFunction(ctx, js->typed_array_byte_length)) goto abort_init; ++ + // set only now: QuickJS cannot always recover from running out of memory while it creates + // a context (see js_setup_aggregate) + js->memory_limit = SQLITE_JS_DEFAULT_MEMORY_LIMIT; +@@ -338,7 +350,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + return js; + + abort_init: +- if (ctx) JS_FreeContext(ctx); ++ if (ctx) { ++ JS_FreeValue(ctx, js->typed_array_byte_offset); ++ JS_FreeValue(ctx, js->typed_array_byte_length); ++ JS_FreeContext(ctx); ++ } + if (rt) { + js_std_free_handlers(rt); + JS_FreeRuntime(rt); +@@ -352,7 +368,11 @@ static void globaljs_free (globaljs_context *js) { + + // order matters + if (js->runtime) js_std_free_handlers(js->runtime); +- if (js->context) JS_FreeContext(js->context); ++ if (js->context) { ++ JS_FreeValue(js->context, js->typed_array_byte_offset); ++ JS_FreeValue(js->context, js->typed_array_byte_length); ++ JS_FreeContext(js->context); ++ } + if (js->runtime) JS_FreeRuntime(js->runtime); + sqlite3_free(js); + } +@@ -464,6 +484,58 @@ static void functionjs_free (functionjs_context *fctx) { // MARK: - Utils - @@ -88,14 +153,16 @@ index 6b48ef2..cb4d75d 100644 + if (JS_GetTypedArrayType(value) >= 0) { + // The offset and length come from the byteOffset and byteLength getters: a typed array + // can track the length of a resizable buffer, and the length QuickJS records when the -+ // array is made goes stale when the buffer is resized. They are read before the bytes, -+ // because a getter can run JavaScript, which could resize or detach the buffer. ++ // array is made goes stale when the buffer is resized. They are the getters taken when ++ // the runtime was made (see globaljs_init), not the properties, which a script can ++ // shadow, so they run no JavaScript. ++ globaljs_context *js = (globaljs_context *)JS_GetContextOpaque(ctx); + int64_t offset = 0, length = 0; -+ JSValue prop = JS_GetPropertyStr(ctx, value, "byteOffset"); ++ JSValue prop = JS_Call(ctx, js->typed_array_byte_offset, value, 0, NULL); + int rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &offset, prop); + JS_FreeValue(ctx, prop); + if (rc < 0) return -1; -+ prop = JS_GetPropertyStr(ctx, value, "byteLength"); ++ prop = JS_Call(ctx, js->typed_array_byte_length, value, 0, NULL); + rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &length, prop); + JS_FreeValue(ctx, prop); + if (rc < 0) return -1; @@ -122,7 +189,7 @@ index 6b48ef2..cb4d75d 100644 static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueConst val) { if (JS_IsNull(val) || JS_IsUndefined(val)) { return sqlite3_bind_null(vm, index); -@@ -406,14 +456,18 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo +@@ -498,13 +570,15 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo JS_FreeCString(ctx, str); return rc; } @@ -132,22 +199,32 @@ index 6b48ef2..cb4d75d 100644 - if (buf) { - return sqlite3_bind_blob(vm, index, buf, (int)size, SQLITE_TRANSIENT); - } +- return sqlite3_bind_null(vm, index); + const uint8_t *bytes = NULL; + size_t size = 0; + int is_blob = js_get_bytes(ctx, val, &bytes, &size); -+ if (is_blob < 0) { -+ // a detached buffer has no bytes to bind, so it binds NULL -+ JS_FreeValue(ctx, JS_GetException(ctx)); - return sqlite3_bind_null(vm, index); - } ++ // a buffer whose bytes cannot be read (detached, or a view out of its bounds) is an error, as ++ // returning it from a function is: the JavaScript exception stays pending for js_sqlite_exec ++ if (is_blob < 0) return SQLITE_ERROR; + if (is_blob) { + if (size == 0) return sqlite3_bind_zeroblob(vm, index, 0); + return sqlite3_bind_blob64(vm, index, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); -+ } + } return sqlite3_bind_null(vm, index); } - -@@ -642,11 +696,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV +@@ -524,6 +598,11 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int + for (int i = 0; i < nbind; ++i) { + // argv[0] is the first binding argument (SQL string already consumed by caller) + rc = js_bind_value(ctx, vm, i + 1, argv[i + 1]); ++ if ((rc != SQLITE_OK) && JS_HasException(ctx)) { ++ // a JavaScript error, such as a buffer that cannot be read: throw it as it is ++ sqlite3_finalize(vm); ++ return JS_EXCEPTION; ++ } + if (rc != SQLITE_OK) goto abort_with_dberror; + } + } +@@ -744,11 +823,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV return; } @@ -175,10 +252,10 @@ index 6b48ef2..cb4d75d 100644 sqlite3_result_error(context, "Unsupported JS value type", -1); } diff --git a/test/main.c b/test/main.c -index dfa3306..b6c6a8a 100644 +index c13e043..461637a 100644 --- a/test/main.c +++ b/test/main.c -@@ -699,6 +699,55 @@ abort_test: +@@ -720,6 +720,65 @@ abort_test: return rc; } @@ -225,6 +302,16 @@ index dfa3306..b6c6a8a 100644 + rc = check_error(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); return u; })()');", "detached or resized"); + if (rc != SQLITE_OK) goto abort_test; + ++ // db.exec() throws for a buffer it cannot read, as returning it fails, instead of binding NULL ++ rc = check_query_v2(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); try { db.exec(\"SELECT ?\", u); return \"bound\"; } catch (e) { return e.message; } })()'), js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); try { db.exec(\"SELECT ?\", b); return \"bound\"; } catch (e) { return \"thrown\"; } })()');", (const char*[]){"ArrayBuffer is detached or resized", "thrown"}, 2); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a view's own offset and length count, not properties a script defines over them ++ rc = check_query_v2(db, "SELECT quote(js_eval('(function () { const u = new Uint8Array([1, 2, 3]).subarray(1, 2); Object.defineProperty(u, \"byteOffset\", { value: 0 }); Object.defineProperty(u, \"byteLength\", { value: 3 }); return u; })()')), js_eval('(function () { const u = new Uint8Array([1, 2, 3]).subarray(1, 2); Object.defineProperty(u, \"byteOffset\", { value: 0 }); const rs = db.exec(\"SELECT quote(?)\", u); rs.next(); return rs.get(0); })()');", (const char*[]){"X'02'", "X'02'"}, 2); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT quote(js_eval('(function () { Object.defineProperty(Object.getPrototypeOf(Uint8Array.prototype), \"byteOffset\", { get() { return 0; } }); return new Uint8Array([1, 2, 3]).subarray(2); })()'));", "X'03'"); ++ if (rc != SQLITE_OK) goto abort_test; ++ +abort_test: + if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); + if (db) sqlite3_close(db); @@ -234,7 +321,7 @@ index dfa3306..b6c6a8a 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -718,6 +767,7 @@ int main (void) { +@@ -739,6 +798,7 @@ int main (void) { result += test_report("Interrupt", test_interrupt()); result += test_report("Memory limit", test_memory_limit()); result += test_report("Direct only", test_direct_only()); diff --git a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch index 5880b38..b3e89dc 100644 --- a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch +++ b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 21:03:54 -0800 -Subject: [PATCH 5/6] Return whole numbers as INTEGERs +Subject: [PATCH 5/8] Return whole numbers as INTEGERs QuickJS keeps the small whole numbers it can as 32-bit integers, and any other number as a double, which went back to SQL as a REAL. So an INTEGER @@ -31,7 +31,7 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md -index 99abfb9..d2cf41b 100644 +index 074735a..3215216 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,9 @@ SQL values reach JavaScript as follows: @@ -46,7 +46,7 @@ index 99abfb9..d2cf41b 100644 ## Scalar Functions diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index cb4d75d..c56b241 100644 +index 8c614fb..2802421 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c @@ -11,6 +11,7 @@ @@ -54,10 +54,10 @@ index cb4d75d..c56b241 100644 #include #include +#include - #include "sqlitejs.h" - #include "quickjs.h" - #include "quickjs-libc.h" -@@ -372,6 +373,18 @@ static void functionjs_free (functionjs_context *fctx) { + #if defined(__APPLE__) + #include + #elif defined(_WIN32) || defined(__linux__) || defined(__ANDROID__) || defined(__GLIBC__) +@@ -484,6 +485,18 @@ static void functionjs_free (functionjs_context *fctx) { // MARK: - Utils - @@ -76,7 +76,7 @@ index cb4d75d..c56b241 100644 // Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such // as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an // ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be -@@ -434,7 +447,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo +@@ -548,7 +561,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo return sqlite3_bind_int(vm, index, num); } else { double num; @@ -86,7 +86,7 @@ index cb4d75d..c56b241 100644 return sqlite3_bind_double(vm, index, num); } } -@@ -660,8 +675,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV +@@ -787,8 +802,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV sqlite3_result_int(context, num); } else { double num; @@ -99,10 +99,10 @@ index cb4d75d..c56b241 100644 return; } diff --git a/test/main.c b/test/main.c -index b6c6a8a..cb2f899 100644 +index 461637a..2c66aa7 100644 --- a/test/main.c +++ b/test/main.c -@@ -748,6 +748,48 @@ abort_test: +@@ -779,6 +779,48 @@ abort_test: return rc; } @@ -151,7 +151,7 @@ index b6c6a8a..cb2f899 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -768,6 +810,7 @@ int main (void) { +@@ -799,6 +841,7 @@ int main (void) { result += test_report("Memory limit", test_memory_limit()); result += test_report("Direct only", test_direct_only()); result += test_report("Blobs", test_blobs()); diff --git a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch index 0e7056d..50f268e 100644 --- a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch +++ b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 10 Nov 2026 21:16:06 -0800 -Subject: [PATCH 6/6] Report exceptions thrown by aggregate and window steps +Subject: [PATCH 6/8] Report exceptions thrown by aggregate and window steps js_execute_common() turned the result of a function into an SQL result only when the caller wanted the value. The step function of an aggregate @@ -27,10 +27,10 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 2 files changed, 36 insertions(+) diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index c56b241..790dc82 100644 +index 2802421..d29ec40 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -896,6 +896,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, +@@ -1027,6 +1027,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, JS_FreeValue(js_context, args); if (return_value) js_value_to_sqlite(context, js_context, result); @@ -41,10 +41,10 @@ index c56b241..790dc82 100644 } diff --git a/test/main.c b/test/main.c -index cb2f899..0af4d22 100644 +index 2c66aa7..20e34a0 100644 --- a/test/main.c +++ b/test/main.c -@@ -790,6 +790,38 @@ abort_test: +@@ -821,6 +821,38 @@ abort_test: return rc; } @@ -83,7 +83,7 @@ index cb2f899..0af4d22 100644 // MARK: - int test_report(const char *description, int rc){ -@@ -811,6 +843,7 @@ int main (void) { +@@ -842,6 +874,7 @@ int main (void) { result += test_report("Direct only", test_direct_only()); result += test_report("Blobs", test_blobs()); result += test_report("Numbers", test_numbers()); diff --git a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch index 7d6c5e2..7838dab 100644 --- a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch +++ b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch @@ -46,7 +46,7 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 3 files changed, 144 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md -index d2cf41b..8ef6804 100644 +index 3215216..a8cdea4 100644 --- a/README.md +++ b/README.md @@ -419,10 +419,13 @@ SELECT js_load_blob('/path/to/file.bin'); -- Returns file contents as a blob @@ -65,7 +65,7 @@ index d2cf41b..8ef6804 100644 ### js_set_memory_limit diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 790dc82..e5562f4 100644 +index d29ec40..126d248 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c @@ -5,6 +5,11 @@ @@ -80,7 +80,7 @@ index 790dc82..e5562f4 100644 #include #include #include -@@ -16,6 +21,15 @@ +@@ -21,6 +26,15 @@ #include "quickjs.h" #include "quickjs-libc.h" @@ -96,7 +96,7 @@ index 790dc82..e5562f4 100644 #ifndef SQLITE_CORE SQLITE_EXTENSION_INIT1 #endif -@@ -197,6 +211,53 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { +@@ -207,6 +221,53 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { #define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) #endif @@ -147,10 +147,10 @@ index 790dc82..e5562f4 100644 + return true; +} + - // QuickJS calls this from time to time while it runs code. A non-zero result stops the code - // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, - // a cancelled query in an app) also stops JavaScript that never returns to SQLite. -@@ -224,6 +285,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + // QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets + // after each collection to 1.5 times the memory still in use. With more than two thirds of the + // memory limit in use, that is beyond the limit: garbage would fill the rest, and code that fits +@@ -320,6 +381,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { // in its sqlite3_api_routines, so JavaScript cannot be interrupted there if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); @@ -162,7 +162,7 @@ index 790dc82..e5562f4 100644 js_std_init_handlers(rt); JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); -@@ -1409,8 +1475,22 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** +@@ -1540,8 +1606,22 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** UNUSED(argc); globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); @@ -188,7 +188,7 @@ index 790dc82..e5562f4 100644 void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { diff --git a/test/main.c b/test/main.c -index 0af4d22..ff1c0e7 100644 +index 20e34a0..6dbcadc 100644 --- a/test/main.c +++ b/test/main.c @@ -10,6 +10,7 @@ @@ -199,7 +199,7 @@ index 0af4d22..ff1c0e7 100644 #include #include -@@ -647,6 +648,62 @@ abort_test: +@@ -668,6 +669,62 @@ abort_test: return rc; } @@ -262,7 +262,7 @@ index 0af4d22..ff1c0e7 100644 // MARK: - Direct only - int test_direct_only (void) { -@@ -840,6 +897,7 @@ int main (void) { +@@ -871,6 +928,7 @@ int main (void) { result += test_report("Thread", test_thread()); result += test_report("Interrupt", test_interrupt()); result += test_report("Memory limit", test_memory_limit()); diff --git a/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch b/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch index 549a1c7..613f1a3 100644 --- a/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch +++ b/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch @@ -33,7 +33,7 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md -index 8ef6804..abec56b 100644 +index a8cdea4..a1fcea1 100644 --- a/README.md +++ b/README.md @@ -397,6 +397,18 @@ SELECT js_eval('Math.PI * Math.pow(5, 2)'); @@ -56,10 +56,10 @@ index 8ef6804..abec56b 100644 ### js_version diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index e5562f4..8f6e3a9 100644 +index 126d248..bd7937a 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -115,11 +115,16 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J +@@ -125,11 +125,16 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); if (!rs->vm) return JS_FALSE; @@ -78,7 +78,7 @@ index e5562f4..8f6e3a9 100644 } static JSValue js_rowset_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { -@@ -168,8 +173,9 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg +@@ -178,8 +183,9 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg int ncols = rs->ncols; int nrows = 0; @@ -89,7 +89,7 @@ index e5562f4..8f6e3a9 100644 if (rc != SQLITE_ROW) break; JSValue row = JS_NewArray(ctx); -@@ -186,7 +192,12 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg +@@ -196,7 +202,12 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg JS_SetPropertyUint32(ctx, result, nrows++, row); } @@ -104,10 +104,10 @@ index e5562f4..8f6e3a9 100644 rs->vm = NULL; return result; diff --git a/test/main.c b/test/main.c -index ff1c0e7..3b562dd 100644 +index 6dbcadc..a23b3aa 100644 --- a/test/main.c +++ b/test/main.c -@@ -881,6 +881,40 @@ abort_test: +@@ -912,6 +912,40 @@ abort_test: // MARK: - @@ -148,7 +148,7 @@ index ff1c0e7..3b562dd 100644 int test_report(const char *description, int rc){ printf("%s%-30s %s\n", VERBOSE ? "********** " : "", description, (rc == SQLITE_OK) ? "OK" : "FAILED"); return (rc == SQLITE_OK) ? 0 : 1; -@@ -902,6 +936,7 @@ int main (void) { +@@ -933,6 +967,7 @@ int main (void) { result += test_report("Blobs", test_blobs()); result += test_report("Numbers", test_numbers()); result += test_report("Aggregate errors", test_aggregate_errors()); diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index 979cb1c..4e32b84 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -114,7 +114,9 @@ session. A function cannot be redefined in the session that created it; use a new session. All but `js_version` work only in top-level SQL, not in views, triggers, CHECK -constraints, generated columns or indexes. The functions you create have no +constraints, generated columns or indexes stored in a database. (TEMP views and +triggers can call them: SQLite trusts them, since only the session can make +them.) The functions you create have no such restriction of their own, but `sqlite3` turns `trusted_schema` off, which keeps them out of a database's views and triggers as well (TEMP ones excepted); run `PRAGMA trusted_schema = ON;` in a session to use them there. The collations @@ -161,7 +163,9 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. ## Limits - **Memory.** JavaScript may use 64 MB per session. Code that needs more fails - with an "out of memory" error, and the session stays usable. + with an "out of memory" error, and the session stays usable. JavaScript that + catches the error receives `null` instead when the limit leaves no room even + for the error. `js_set_memory_limit` changes the limit; memory that globals still hold counts against it until they are cleared. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with @@ -195,8 +199,8 @@ Eight patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. |-------|--------| | `0001` | Ctrl-C and `sqlite3_interrupt()` stop running JavaScript. Upstream, endless code hangs `sqlite3`. | | `0002` | A 64 MB memory limit, and `js_set_memory_limit`. Upstream, code that keeps allocating takes all the memory there is. | -| `0003` | `js_eval` and the other functions that run code, read files or change the runtime work only in top-level SQL. Upstream, with `trusted_schema` on, a view can call them. | -| `0004` | A result that is an `ArrayBuffer` or typed array is a BLOB. Upstream, it is NULL, so a BLOB cannot pass through a function. | +| `0003` | `js_eval` and the other functions that run code, read files or change the runtime work only in top-level SQL (and TEMP views and triggers). Upstream, with `trusted_schema` on, a view can call them. | +| `0004` | A result that is an `ArrayBuffer` or typed array is a BLOB, and `db.exec` binds one as a BLOB or throws if it cannot read it. Upstream, a result is NULL, so a BLOB cannot pass through a function. | | `0005` | A whole-number result is an INTEGER. Upstream, an INTEGER outside the 32-bit range comes back as a REAL. | | `0006` | An exception in an aggregate's or window function's step is an SQL error. Upstream, it is ignored, and the result is silently wrong. | | `0007` | The JavaScript stack size stays within the thread's stack: `js_set_max_stack_size` refuses text and larger sizes, and the default shrinks on a small stack. Upstream, those make endless recursion crash `sqlite3`. | diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 1a5ba50..11e8bf5 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,7 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.3.7 -TERMUX_PKG_REVISION=4 +TERMUX_PKG_REVISION=5 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 TERMUX_PKG_BUILD_DEPENDS="libsqlite" diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 69ef734..c17d601 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -410,6 +410,12 @@ printf 'line one\nline two ✓\n' >loadme.txt expect "js_load_text and js_load_blob read a file" "line one|X'6C696E65206F6E650A6C696E652074776F20E29C930A'" \ "SELECT substr(js_load_text($(sql_str "$WORK/loadme.txt")), 1, 8), quote(js_load_blob($(sql_str "$WORK/loadme.txt")));" +expect "AC6: db.exec throws for a buffer it cannot read, instead of binding NULL" \ + "ArrayBuffer is detached or resized|thrown" \ + "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); try { db.exec(\"SELECT ?\", u); return \"bound\"; } catch (e) { return e.message; } })()'), js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); try { db.exec(\"SELECT ?\", b); return \"bound\"; } catch (e) { return \"thrown\"; } })()');" +expect "AC6: a typed array's own offset and length count, not properties defined over them" "X'02'" \ + "SELECT quote(js_eval('(function () { const u = new Uint8Array([1, 2, 3]).subarray(1, 2); Object.defineProperty(u, \"byteOffset\", { value: 0 }); Object.defineProperty(u, \"byteLength\", { value: 3 }); return u; })()'));" + # --- AC7: the crash cases fixed in 1.3.6 are SQL errors ---------------------- DB=$WORK/ac7.db @@ -494,6 +500,22 @@ expect_nobail "AC9: memory held by a global counts until the global is cleared" "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" \ "SELECT js_eval('keep = null; new ArrayBuffer(16 * 1024 * 1024).byteLength');" +# QuickJS collects cyclic garbage only past a threshold it sets to 1.5 times the +# memory in use, which with more than two thirds of the limit held is past the +# limit: garbage would fill the rest. +expect "AC9: garbage is still collected with 48 of 64 MB held" "50331648" \ + "SELECT js_eval('globalThis.keep = new ArrayBuffer(48 * 1024 * 1024); for (let i = 0; i < 300000; i++) { const o = {}; o.o = o; } keep.byteLength');" +expect "AC9: an aggregate over 300 groups runs with 48 of 64 MB held" $'0\n0\n300' \ + "SELECT js_eval('globalThis.keep = new ArrayBuffer(48 * 1024 * 1024); 0');" \ + "SELECT js_create_aggregate('n_rows', 'n = 0;', '(function (args) { n++; })', '(function () { return n; })');" \ + "WITH RECURSIVE g(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM g WHERE x < 300) SELECT sum(c) FROM (SELECT n_rows(x) AS c FROM g GROUP BY x);" +# Small allocations fill the limit so far that not even the error object fits. +# The loop stops at about 4 times the limit, like the ones above. +expect_nobail "AC9: running out of memory through small allocations is an \"out of memory\" error" \ + "2" "out of memory" \ + "SELECT js_eval('(function () { let h = null; for (let i = 0; i < 4000000; i++) h = { n: h }; })()');" \ + "SELECT js_eval('1 + 1');" + # QuickJS can crash if it runs out of memory while it creates a context, which # every aggregate needs. Aggregates under small limits, and with little memory # left under the default one, may fail, but must not crash. @@ -555,6 +577,10 @@ expect "AC10: so the trigger never ran" "0" "SELECT count(*) FROM log;" # SQLITE_DIRECTONLY is 0x80000 in function_list's flags. expect "AC10: every js_* function but js_version is SQLITE_DIRECTONLY" "13|0" \ "SELECT count(*), sum(((flags & 0x80000) != 0) != (name <> 'js_version')) FROM pragma_function_list WHERE name LIKE 'js\_%' ESCAPE '\\';" +# SQLite trusts the TEMP schema, which only the session itself can fill, so a +# TEMP view can call js_eval, as the README says. +expect "AC10: a TEMP view can call js_eval" "42" \ + "CREATE TEMP VIEW v_temp AS SELECT js_eval('6 * 7') AS x;" "SELECT x FROM v_temp;" # The view is in the database file: SQLite trusts the TEMP schema, which only # the session itself can fill. DB=$WORK/views.db From 428a196c3dbbe925a62f2192cc0c0b15181e1123 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 00:11:29 -0800 Subject: [PATCH 07/17] ADFA-7081: sqlite-js 1.3.7-p20261112, upstream main with our changes merged Upstream merged our eight patches (sqliteai/sqlite-js #11 to #18) and #19 on 2026-11-12, with fixes of its own. One fixes a bug in our 0002, which 1.3.7-5 has: a memory limit lowered under memory that is garbage left the session out of memory until the limit was raised again (ef06558). Build from upstream main at c8ae85a, with no patches. The version follows termux-packages' convention for a commit after a release, and dpkg sorts 1.3.7-p20261112 above 1.3.7-5. The README now lists the upstream PRs instead of patches and says what a lowered limit does. run-tests.sh gets a test for that bug: 98 of 98 pass on a host build of this package, and on 1.3.7-5 only the new test fails. The aarch64 and arm builds (emulated build.sh steps, NDK 29) export only the two entry points. ADFA-7083's page examples pass, 64 of 64. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...t-when-the-connection-is-interrupted.patch | 169 ------- ...the-memory-of-the-JavaScript-runtime.patch | 470 ------------------ ...ions-that-run-code-out-of-the-schema.patch | 147 ------ ...rayBuffers-and-typed-arrays-as-BLOBs.patch | 331 ------------ ...005-Return-whole-numbers-as-INTEGERs.patch | 161 ------ ...s-thrown-by-aggregate-and-window-ste.patch | 93 ---- ...ipt-stack-size-within-the-thread-s-s.patch | 272 ---------- ...-SQL-errors-from-db.exec-result-sets.patch | 158 ------ packages/sqlite-js/README.md | 36 +- packages/sqlite-js/build.sh | 14 +- packages/sqlite-js/tests/run-tests.sh | 9 + 11 files changed, 38 insertions(+), 1822 deletions(-) delete mode 100644 packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch delete mode 100644 packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch delete mode 100644 packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch delete mode 100644 packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch delete mode 100644 packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch delete mode 100644 packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch delete mode 100644 packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch delete mode 100644 packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch diff --git a/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch b/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch deleted file mode 100644 index 1d976a2..0000000 --- a/packages/sqlite-js/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch +++ /dev/null @@ -1,169 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Tue, 10 Nov 2026 20:56:10 -0800 -Subject: [PATCH 1/8] Stop JavaScript when the connection is interrupted - -JavaScript runs inside the SQL statement that calls it, but QuickJS had -no interrupt handler, so sqlite3_interrupt() could not stop code that -never returns to SQLite. `SELECT js_eval('while (true) {}')` hung the -sqlite3 shell, where Ctrl-C calls sqlite3_interrupt(), and an app could -not cancel the query. - -Install a QuickJS interrupt handler that reports the connection's -sqlite3_is_interrupted(). QuickJS then stops the code with an -uncatchable "interrupted" error, and the statement fails as interrupted. -sqlite3_is_interrupted() is new in SQLite 3.41.0, so the handler is only -installed when the library is at least that version. - -Add an Interrupt test that interrupts endless loops in js_eval() and in a -scalar function from another thread, and checks that the connection -still works afterwards. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 4 +++ - src/sqlitejs.c | 15 ++++++++++- - test/main.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 85 insertions(+), 1 deletion(-) - -diff --git a/README.md b/README.md -index e389272..45bf583 100644 ---- a/README.md -+++ b/README.md -@@ -410,6 +410,10 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. - SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB - ``` - -+### Interrupting JavaScript -+ -+JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. -+ - ## Examples - - ### Example 1: String Manipulation -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 024a2f8..524581e 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -187,6 +187,15 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - - // MARK: - Initializer - - -+// QuickJS calls this from time to time while it runs code. A non-zero result stops the code -+// with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, -+// a cancelled query in an app) also stops JavaScript that never returns to SQLite. -+static int js_interrupt_handler (JSRuntime *rt, void *opaque) { -+ UNUSED(rt); -+ globaljs_context *js = (globaljs_context *)opaque; -+ return (js->db != NULL) && sqlite3_is_interrupted(js->db); -+} -+ - static globaljs_context *globaljs_init (sqlite3 *db) { - JSRuntime *rt = NULL; - JSContext *ctx = NULL; -@@ -200,7 +209,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - - //JS_SetMemoryLimit(rt, 80 * 1024); - //JS_SetMaxStackSize(rt, 10 * 1024); -- -+ -+ // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry -+ // in its sqlite3_api_routines, so JavaScript cannot be interrupted there -+ if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); -+ - js_std_init_handlers(rt); - JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); - -diff --git a/test/main.c b/test/main.c -index d0ed2e7..0f8da0c 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -11,6 +11,7 @@ - #include - #include - #include -+#include - - #define DB_PATH "js_functions.sqlite" - #define VERBOSE 1 -@@ -488,6 +489,71 @@ abort_test: - return rc; - } - -+// MARK: - Interrupt - -+ -+int test_open (sqlite3 **db) { -+ int rc = sqlite3_open(":memory:", db); -+ if (rc != SQLITE_OK) return rc; -+ -+ #if JS_LOAD_EMBEDDED -+ return sqlite3_js_init(*db, NULL, NULL); -+ #else -+ rc = sqlite3_enable_load_extension(*db, 1); -+ if (rc != SQLITE_OK) return rc; -+ return db_exec(*db, "SELECT load_extension('./dist/js');"); -+ #endif -+} -+ -+void *test_interrupt_worker (void *ptr) { -+ // give the statement time to start running JavaScript -+ usleep(200 * 1000); -+ sqlite3_interrupt((sqlite3 *)ptr); -+ return NULL; -+} -+ -+// Runs sql, which never ends unless it is interrupted, and interrupts it from another thread. -+// The statement must fail as interrupted, and the connection must stay usable. -+int test_interrupt_sql (sqlite3 *db, const char *sql) { -+ pthread_t thread; -+ if (pthread_create(&thread, NULL, test_interrupt_worker, (void *)db) != 0) return SQLITE_ERROR; -+ int rc = sqlite3_exec(db, sql, NULL, NULL, NULL); -+ pthread_join(thread, NULL); -+ -+ if (rc == SQLITE_OK || strstr(sqlite3_errmsg(db), "interrupted") == NULL) { -+ printf("FAIL: %s\n Expected: interrupted, Got: %d %s\n", sql, rc, sqlite3_errmsg(db)); -+ return SQLITE_ERROR; -+ } -+ return check_query(db, "SELECT js_eval('1+1');", "2"); -+} -+ -+int test_interrupt (void) { -+ sqlite3 *db = NULL; -+ -+ // if the code cannot be interrupted, end the test program instead of hanging forever -+ alarm(30); -+ -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ rc = test_interrupt_sql(db, "SELECT js_eval('while (true) {}');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ rc = db_exec(db, "SELECT js_create_scalar('forever', '(function(args){ for (;;) {} })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = test_interrupt_sql(db, "SELECT forever();"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // JavaScript catch blocks cannot keep running code alive -+ rc = test_interrupt_sql(db, "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ alarm(0); -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - - - int test_report(const char *description, int rc){ -@@ -504,6 +570,7 @@ int main (void) { - result += test_report("Serialization 2", test_serialization(DB_PATH, false, 2)); // update functions previously registered in the js_functions table - result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations - result += test_report("Thread", test_thread()); -+ result += test_report("Interrupt", test_interrupt()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch b/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch deleted file mode 100644 index 850f36f..0000000 --- a/packages/sqlite-js/0002-Limit-the-memory-of-the-JavaScript-runtime.patch +++ /dev/null @@ -1,470 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Tue, 10 Nov 2026 20:58:13 -0800 -Subject: [PATCH 2/8] Limit the memory of the JavaScript runtime - -The JavaScript runtime had no memory limit (the JS_SetMemoryLimit call -was commented out), so code that keeps allocating took all the memory of -the process. On a phone that ends with the operating system killing the -process, which in an app takes the app down with it. - -Set a default limit of 64 MB per connection, which SQLITE_JS_DEFAULT_ -MEMORY_LIMIT changes at build time, and add js_set_memory_limit(bytes) -to change it at run time; 0 means no limit, as in JS_SetMemoryLimit(). -Code that needs more fails with an "out of memory" error, and the -connection stays usable. A QuickJS context takes about 54 KB, so the -default leaves room for over a thousand aggregate contexts at once. - -QuickJS cannot always recover from running out of memory while it -creates a context: it can crash. So the limit is set once the -connection's context exists, and the context of each aggregate or -window function, and the trial one that js_create_aggregate() and -js_create_window() make, is created with the limit lifted; the limit -then applies again to the code that runs in it. - -QuickJS collects cyclic garbage only when its memory use passes a -threshold, which it resets after each collection to 1.5 times the -memory still in use. With more than two thirds of the limit in use the -threshold was past the limit, so garbage filled the rest and code that -fits failed. The interrupt handler, js_set_memory_limit() and each -aggregate's setup now lower it, after a collection, to halfway between -the memory in use and the limit. - -When the limit leaves no room even for the "out of memory" error, -QuickJS throws null, which reported "Unknown JavaScript exception". The -runtime now allocates through functions that count its memory as QuickJS -does, and a null exception after the memory in use reached the limit -reports "out of memory". JavaScript that catches it still receives null; -the README says so. - -Add a Memory limit test: allocations under and over the default, code -that never stops allocating, raising, removing and lowering the limit, -and invalid arguments. It also creates and runs an aggregate under -small limits and with little memory left, which crashed while QuickJS -created its context under the limit. With 12 of 16 MB held, code that -makes many times the free memory in cyclic garbage runs, and so does an -aggregate over 300 groups; running out of memory through small -allocations reports "out of memory". Both fail without the collection -and reporting changes. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 9 +++ - src/sqlitejs.c | 163 ++++++++++++++++++++++++++++++++++++++++++++++--- - test/main.c | 115 ++++++++++++++++++++++++++++++++++ - 3 files changed, 277 insertions(+), 10 deletions(-) - -diff --git a/README.md b/README.md -index 45bf583..d88b539 100644 ---- a/README.md -+++ b/README.md -@@ -410,6 +410,15 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. - SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB - ``` - -+### js_set_memory_limit -+ -+Sets the most memory, in bytes, that JavaScript may allocate on this connection; 0 means no limit. The default is 64 MB (64 × 1024 × 1024 bytes); build with `-DSQLITE_JS_DEFAULT_MEMORY_LIMIT=bytes` to change it. Code that needs more fails with an "out of memory" error, and the connection stays usable. JavaScript that catches the error receives `null` instead when the limit leaves no room even for the error. -+ -+```sql -+SELECT js_set_memory_limit(268435456); -- Allow 256 MB -+SELECT js_set_memory_limit(0); -- No limit -+``` -+ - ### Interrupting JavaScript - - JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 524581e..1ba634e 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -11,6 +11,11 @@ - #include - #include - #include -+#if defined(__APPLE__) -+#include -+#elif defined(_WIN32) || defined(__linux__) || defined(__ANDROID__) || defined(__GLIBC__) -+#include -+#endif - #include "sqlitejs.h" - #include "quickjs.h" - #include "quickjs-libc.h" -@@ -31,6 +36,10 @@ typedef struct { - sqlite3 *db; - JSClassID rowSetClassID; - int ref_count; -+ size_t memory_limit; // in bytes, 0 for none: see js_set_memory_limit() -+ size_t gc_threshold; // QuickJS's GC threshold when last checked: see js_keep_gc_below_limit() -+ size_t mem_used; // memory the runtime has allocated: see js_mem_malloc() -+ size_t mem_peak; // the most in use since the last result or error - } globaljs_context; - - typedef struct { -@@ -187,15 +196,107 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - - // MARK: - Initializer - - -+// The most memory, in bytes, the JavaScript runtime of a connection may allocate until -+// js_set_memory_limit() changes it; 0 means no limit. Without a limit, code that keeps -+// allocating takes all the memory of the process, which on a phone ends with the operating -+// system killing it. 64 MB is room for over a thousand aggregate contexts (about 54 KB each). -+#ifndef SQLITE_JS_DEFAULT_MEMORY_LIMIT -+#define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) -+#endif -+ -+// QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets -+// after each collection to 1.5 times the memory still in use. With more than two thirds of the -+// memory limit in use, that is beyond the limit: garbage would fill the rest, and code that fits -+// in the limit would fail. So the threshold is lowered to halfway between the memory in use and -+// the limit. Called often, so it does nothing until a collection has changed the threshold. -+static void js_keep_gc_below_limit (globaljs_context *js) { -+ size_t threshold = JS_GetGCThreshold(js->runtime); -+ if (threshold == js->gc_threshold) return; -+ size_t limit = js->memory_limit; -+ if ((limit > 0) && (threshold > limit - limit / 4)) { -+ size_t used = threshold / 3 * 2; -+ if (used > limit) used = limit; -+ threshold = used + (limit - used) / 2; -+ JS_SetGCThreshold(js->runtime, threshold); -+ } -+ js->gc_threshold = threshold; -+} -+ - // QuickJS calls this from time to time while it runs code. A non-zero result stops the code - // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, - // a cancelled query in an app) also stops JavaScript that never returns to SQLite. - static int js_interrupt_handler (JSRuntime *rt, void *opaque) { - UNUSED(rt); - globaljs_context *js = (globaljs_context *)opaque; -+ js_keep_gc_below_limit(js); - return (js->db != NULL) && sqlite3_is_interrupted(js->db); - } - -+// The runtime's allocator: the system's, as QuickJS's default is, counting the memory in use the -+// way QuickJS counts it against the memory limit, and the most in use since the last result or -+// error (see js_reached_memory_limit). QuickJS refuses an allocation over the limit before it -+// gets here. -+#if defined(__APPLE__) -+#define js_mem_usable_size(ptr) malloc_size(ptr) -+#define JS_MEM_OVERHEAD 0 -+#elif defined(_WIN32) -+#define js_mem_usable_size(ptr) _msize((void *)(ptr)) -+#define JS_MEM_OVERHEAD 8 -+#elif defined(__linux__) || defined(__ANDROID__) || defined(__GLIBC__) -+#define js_mem_usable_size(ptr) malloc_usable_size((void *)(ptr)) -+#define JS_MEM_OVERHEAD 8 -+#else -+#define js_mem_usable_size(ptr) ((size_t)0) -+#define JS_MEM_OVERHEAD 0 -+#endif -+ -+static void js_mem_add (globaljs_context *js, void *ptr) { -+ if (!ptr) return; -+ js->mem_used += js_mem_usable_size(ptr) + JS_MEM_OVERHEAD; -+ if (js->mem_used > js->mem_peak) js->mem_peak = js->mem_used; -+} -+ -+static void js_mem_sub (globaljs_context *js, void *ptr) { -+ if (ptr) js->mem_used -= js_mem_usable_size(ptr) + JS_MEM_OVERHEAD; -+} -+ -+static void *js_mem_calloc (void *opaque, size_t count, size_t size) { -+ void *ptr = calloc(count, size); -+ js_mem_add((globaljs_context *)opaque, ptr); -+ return ptr; -+} -+ -+static void *js_mem_malloc (void *opaque, size_t size) { -+ void *ptr = malloc(size); -+ js_mem_add((globaljs_context *)opaque, ptr); -+ return ptr; -+} -+ -+static void js_mem_free (void *opaque, void *ptr) { -+ js_mem_sub((globaljs_context *)opaque, ptr); -+ free(ptr); -+} -+ -+static void *js_mem_realloc (void *opaque, void *ptr, size_t size) { -+ globaljs_context *js = (globaljs_context *)opaque; -+ size_t old = (ptr) ? js_mem_usable_size(ptr) + JS_MEM_OVERHEAD : 0; -+ void *new_ptr = realloc(ptr, size); -+ if (!new_ptr && size) return NULL; // the old block is unchanged -+ js->mem_used -= old; -+ js_mem_add(js, new_ptr); -+ return new_ptr; -+} -+ -+static size_t js_mem_size (const void *ptr) { -+ return js_mem_usable_size(ptr); -+} -+ -+static const JSMallocFunctions js_mem_funcs = {js_mem_calloc, js_mem_malloc, js_mem_free, js_mem_realloc, js_mem_size}; -+ -+static void js_mem_reset_peak (globaljs_context *js) { -+ if (js) js->mem_peak = js->mem_used; -+} -+ - static globaljs_context *globaljs_init (sqlite3 *db) { - JSRuntime *rt = NULL; - JSContext *ctx = NULL; -@@ -204,7 +305,7 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - if (!js) return NULL; - memset(js, 0, sizeof(globaljs_context)); - -- rt = JS_NewRuntime(); -+ rt = JS_NewRuntime2(&js_mem_funcs, js); - if (!rt) goto abort_init; - - //JS_SetMemoryLimit(rt, 80 * 1024); -@@ -228,7 +329,12 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - JS_SetContextOpaque(ctx, js); - JS_SetRuntimeOpaque(rt, js); - js_global_init(ctx, js); -- -+ -+ // set only now: QuickJS cannot always recover from running out of memory while it creates -+ // a context (see js_setup_aggregate) -+ js->memory_limit = SQLITE_JS_DEFAULT_MEMORY_LIMIT; -+ JS_SetMemoryLimit(rt, js->memory_limit); -+ - return js; - - abort_init: -@@ -543,6 +649,12 @@ static void js_dump_globals (JSContext *ctx) { - } - #endif - -+// True if JavaScript reached its memory limit since the last result or error. QuickJS then may -+// have had no memory left to make its "out of memory" error, and have thrown null instead. -+static bool js_reached_memory_limit (globaljs_context *js) { -+ return js && (js->memory_limit > 0) && (js->mem_peak + 64 * 1024 >= js->memory_limit); -+} -+ - static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSValue value, const char *default_error) { - if (!default_error) default_error = "Unknown JavaScript exception"; - const char *err_msg = NULL; -@@ -558,8 +670,11 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - JS_FreeValue(js_ctx, message); - } else if (JS_IsString(exception)) { - err_msg = JS_ToCString(js_ctx, exception); -+ } else if (JS_IsNull(exception) && js_reached_memory_limit(JS_GetContextOpaque(js_ctx))) { -+ default_error = "out of memory"; - } - } -+ js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); - - // set a default error message and code - sqlite3_result_error(context, (err_msg) ? err_msg : default_error, -1); -@@ -576,6 +691,7 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - js_error_to_sqlite(context, js_ctx, value, NULL); - return; - } -+ js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); - - // check for null or undefined - if (JS_IsNull(value) || JS_IsUndefined(value)) { -@@ -655,16 +771,26 @@ static bool js_setup_aggregate (sqlite3_context *context, globaljs_context *js, - } - - // create a separate context for testing purpose -+ // Each finished aggregate leaves its context behind as cyclic garbage, so the collector must -+ // be able to run before the limit is reached. -+ js_keep_gc_below_limit(js); -+ // QuickJS cannot always recover from running out of memory while it creates a context: it -+ // can crash. So the context is created without the memory limit (it takes about 54 KB), -+ // which then applies again to the code that runs in it. -+ JS_SetMemoryLimit(js->runtime, 0); - JSContext *ctx = JS_NewContext(js->runtime); -+ if (ctx) { -+ // setup global object -+ JS_SetContextOpaque(ctx, js); -+ js_global_init(ctx, js); -+ } -+ JS_SetMemoryLimit(js->runtime, js->memory_limit); -+ js_mem_reset_peak(js); - if (!ctx) { - sqlite3_result_error(context, "Unable to create a JS context.", -1); - return false; - } -- -- // setup global object -- JS_SetContextOpaque(ctx, js); -- js_global_init(ctx, js); -- -+ - // init code is optional - if (init_code) { - JSValue init_result = JS_Eval(ctx, init_code, strlen(init_code), NULL, JS_EVAL_TYPE_GLOBAL); -@@ -1305,6 +1431,23 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** - JS_SetMaxStackSize(js->runtime, stack_size); - } - -+void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { -+ UNUSED(argc); -+ globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); -+ -+ if ((sqlite3_value_type(argv[0]) != SQLITE_INTEGER) || (sqlite3_value_int64(argv[0]) < 0)) { -+ sqlite3_result_error(context, "The memory limit must be an integer number of bytes, or 0 for no limit", -1); -+ return; -+ } -+ -+ // a limit beyond the address space (on a 32-bit system) can never be reached, so it is no limit -+ sqlite3_uint64 limit = (sqlite3_uint64)sqlite3_value_int64(argv[0]); -+ js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; -+ JS_SetMemoryLimit(js->runtime, js->memory_limit); -+ js->gc_threshold = 0; // check the GC threshold against the new limit -+ js_keep_gc_below_limit(js); -+} -+ - // MARK: - - - const char *sqlitejs_version (void) { -@@ -1325,9 +1468,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r - globaljs_context *js = globaljs_init(db); - if (!js) return SQLITE_NOMEM; - -- const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size"}; -- const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size}; -- int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1}; -+ const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; -+ const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; -+ int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; - - size_t f_count = sizeof(f_name) / sizeof(const char *); - for (size_t i=0; i x * 2).join()');", "2,4,6"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a higher limit, then no limit -+ rc = db_exec(db, "SELECT js_set_memory_limit(256 * 1024 * 1024);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');", "134217728"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_set_memory_limit(0);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');", "134217728"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a lower limit -+ rc = db_exec(db, "SELECT js_set_memory_limit(8 * 1024 * 1024);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');", "out of memory"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // garbage is still collected with more than two thirds of the limit in use: with 12 of 16 MB -+ // held, code that makes many times the free memory in cyclic garbage, which only the -+ // collector frees, runs -+ rc = db_exec(db, "SELECT js_set_memory_limit(16 * 1024 * 1024);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('globalThis.keep = new ArrayBuffer(12 * 1024 * 1024); for (let i = 0; i < 300000; i++) { const o = {}; o.o = o; } keep.byteLength');", "12582912"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_create_aggregate('n_rows', 'n = 0;', '(function(args){ n++; })', '(function(){ return n; })');", "0"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "WITH RECURSIVE g(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM g WHERE x < 300) SELECT sum(c) FROM (SELECT n_rows(x) AS c FROM g GROUP BY x);", "300"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_eval('delete globalThis.keep; 0');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // running out of memory through many small allocations, which leaves no room for the error -+ // object, is reported as "out of memory" too -+ rc = check_error(db, "SELECT js_eval('(function () { let h = null; for (;;) h = {n: h}; })()');", "out of memory"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('1 + 1');", "2"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // only a non-negative integer is a limit -+ const char *invalid[] = {"-1", "1.5", "'1000000'", "NULL", "x'00'"}; -+ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { -+ char sql[128]; -+ snprintf(sql, sizeof(sql), "SELECT js_set_memory_limit(%s);", invalid[i]); -+ rc = check_error(db, sql, "The memory limit must be an integer number of bytes"); -+ if (rc != SQLITE_OK) goto abort_test; -+ } -+ -+ // aggregates fail cleanly near the limit: under small limits, and with little memory left -+ for (int kb = 100; kb <= 420; kb += 8) { -+ rc = test_aggregate_near_limit(kb, 0); -+ if (rc != SQLITE_OK) goto abort_test; -+ } -+ for (int kb = 0; kb <= 16; ++kb) { -+ rc = test_aggregate_near_limit(0, kb); -+ if (rc != SQLITE_OK) goto abort_test; -+ } -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - - - int test_report(const char *description, int rc){ -@@ -571,6 +685,7 @@ int main (void) { - result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations - result += test_report("Thread", test_thread()); - result += test_report("Interrupt", test_interrupt()); -+ result += test_report("Memory limit", test_memory_limit()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch b/packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch deleted file mode 100644 index 13558fe..0000000 --- a/packages/sqlite-js/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch +++ /dev/null @@ -1,147 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Tue, 10 Nov 2026 20:59:46 -0800 -Subject: [PATCH 3/8] Keep the functions that run code out of the schema - -js_eval(), js_create_*(), js_load_text(), js_load_blob(), js_init_table() -and the js_set_* functions were registered without SQLITE_DIRECTONLY, so -a view, trigger, CHECK constraint or generated column could call them. -With PRAGMA trusted_schema ON, the default of the SQLite library (the -sqlite3 shell turns it off), a database from an untrusted source could -run JavaScript or read files just by being queried: -`CREATE VIEW v AS SELECT js_eval('...')`. - -Register every function but js_version() with SQLITE_DIRECTONLY, so only -top-level SQL can call them. TEMP views and triggers still can: SQLite -trusts them, since only the connection itself can make them, and the -README says so. The functions created with js_create_* are -unchanged, so they still work in views, triggers and indexes. The flag -is computed from the function's name rather than from a table that -parallels the function list, so a function added later gets it without -a matching edit. - -Add a Direct only test: every function but js_version() has the flag in -function_list; with trusted_schema ON, a view, a trigger and a -generated column cannot call js_eval() or js_load_text(), a top-level -statement can, and a view can still use js_version() and a function made -with js_create_scalar(). - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 6 ++++++ - src/sqlitejs.c | 9 +++++++-- - test/main.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 66 insertions(+), 2 deletions(-) - -diff --git a/README.md b/README.md -index d88b539..bcbb7f0 100644 ---- a/README.md -+++ b/README.md -@@ -419,6 +419,12 @@ SELECT js_set_memory_limit(268435456); -- Allow 256 MB - SELECT js_set_memory_limit(0); -- No limit - ``` - -+### Using the functions from the schema -+ -+Every function above but `js_version` runs JavaScript, reads files or changes the JavaScript runtime, so it is registered with `SQLITE_DIRECTONLY`: only top-level SQL can call it, never a view, trigger, CHECK constraint, generated column or index stored in the database. (TEMP views and triggers can call it: SQLite trusts them, since only the connection itself can make them.) That way a database from an untrusted source cannot run JavaScript just by being queried. The functions you create with `js_create_scalar`, `js_create_aggregate`, `js_create_window` and `js_create_collation` are not restricted. -+ -+A database can still store JavaScript in its `js_functions` table, and `js_init_table(1)` runs it. Call it only on databases you trust. -+ - ### Interrupting JavaScript - - JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 1ba634e..8a48d92 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -1471,11 +1471,16 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r - const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; - const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; - int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; -- -+ - size_t f_count = sizeof(f_name) / sizeof(const char *); - for (size_t i=0; iref_count++; -- int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); -+ // Every function but js_version runs JavaScript, reads files or changes the JavaScript -+ // runtime. SQLITE_DIRECTONLY keeps them out of the schema (views, triggers, CHECK -+ // constraints, generated columns, indexes), so that a database from an untrusted source -+ // cannot run JavaScript just by being queried, whatever PRAGMA trusted_schema says. -+ int flags = (strcmp(f_name[i], "js_version") == 0) ? 0 : SQLITE_DIRECTONLY; -+ int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8 | flags, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); - if (rc != SQLITE_OK) { - if (pzErrMsg) *pzErrMsg = sqlite3_mprintf("Error creating function %s: %s", f_name[i], sqlite3_errmsg(db)); - // sqlite3_create_function_v2 always invokes the xDestroy callback when it fails, -diff --git a/test/main.c b/test/main.c -index 4adeb82..c13e043 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -668,6 +668,58 @@ abort_test: - return rc; - } - -+// MARK: - Direct only - -+ -+int test_direct_only (void) { -+ sqlite3 *db = NULL; -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // every function but js_version is SQLITE_DIRECTONLY (0x80000 in the flags of function_list) -+ rc = check_query_v2(db, "SELECT count(*) > 10, sum(((flags & 0x80000) != 0) != (name <> 'js_version')) FROM pragma_function_list WHERE name LIKE 'js\\_%' ESCAPE '\\';", (const char*[]){"1", "0"}, 2); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // trusted_schema ON lets the schema use any function that is not SQLITE_DIRECTONLY -+ rc = db_exec(db, "PRAGMA trusted_schema = ON; CREATE TABLE t (a); CREATE TABLE log (msg);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a view, a trigger and a generated column cannot run JavaScript or read files -+ // (SQLite reports these either when the schema is created or when it is used) -+ sqlite3_exec(db, "CREATE VIEW v_eval AS SELECT js_eval('6 * 7') AS x;", NULL, NULL, NULL); -+ rc = check_error(db, "SELECT x FROM v_eval;", "unsafe use of js_eval()"); -+ if (rc != SQLITE_OK) goto abort_test; -+ sqlite3_exec(db, "CREATE VIEW v_load AS SELECT js_load_text('/etc/hosts') AS x;", NULL, NULL, NULL); -+ rc = check_error(db, "SELECT x FROM v_load;", "unsafe use of js_load_text()"); -+ if (rc != SQLITE_OK) goto abort_test; -+ sqlite3_exec(db, "CREATE TRIGGER t_insert AFTER INSERT ON t BEGIN INSERT INTO log VALUES (js_eval('\"trigger ran\"')); END;", NULL, NULL, NULL); -+ rc = check_error(db, "INSERT INTO t VALUES (1);", "unsafe use of js_eval()"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT count(*) FROM log;", "0"); -+ if (rc != SQLITE_OK) goto abort_test; -+ sqlite3_exec(db, "DROP TRIGGER IF EXISTS t_insert;", NULL, NULL, NULL); -+ if (sqlite3_exec(db, "CREATE TABLE g (a, b AS (js_eval('1')));", NULL, NULL, NULL) == SQLITE_OK) { -+ rc = check_error(db, "INSERT INTO g (a) VALUES (1);", "unsafe use of js_eval()"); -+ if (rc != SQLITE_OK) goto abort_test; -+ } -+ -+ // a top-level statement can still use them -+ rc = check_query(db, "SELECT js_eval('6 * 7');", "42"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // and the schema can still use js_version() and the functions created with js_create_* -+ rc = db_exec(db, "SELECT js_create_scalar('twice', '(function(args){ return args[0] * 2; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "CREATE VIEW v_ok AS SELECT js_version() IS NOT NULL AS has_version, twice(21) AS answer;"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query_v2(db, "SELECT has_version, answer FROM v_ok;", (const char*[]){"1", "42"}, 2); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - - - int test_report(const char *description, int rc){ -@@ -686,6 +738,7 @@ int main (void) { - result += test_report("Thread", test_thread()); - result += test_report("Interrupt", test_interrupt()); - result += test_report("Memory limit", test_memory_limit()); -+ result += test_report("Direct only", test_direct_only()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch b/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch deleted file mode 100644 index 2aa28ba..0000000 --- a/packages/sqlite-js/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch +++ /dev/null @@ -1,331 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Tue, 10 Nov 2026 21:01:52 -0800 -Subject: [PATCH 4/8] Return ArrayBuffers and typed arrays as BLOBs - -A BLOB argument reaches JavaScript as an ArrayBuffer, but a function -that returned an ArrayBuffer, or a typed array such as Uint8Array, gave -NULL: js_value_to_sqlite() turned every object into NULL. So no function -could return binary data, and `identity(x'00ff')` with -`(function(args){ return args[0]; })` returned NULL. db.exec() bound an -ArrayBuffer but not a typed array, and bound an empty ArrayBuffer as -NULL. - -Add js_get_bytes(), which gets the bytes of an ArrayBuffer or of the part -of a buffer that a typed array views, and use it for function results and -for db.exec() parameters. An empty buffer is an empty BLOB. Returning or -binding a detached buffer, or a typed array out of its buffer's bounds, -is an error: db.exec() throws it rather than binding NULL, which would -make a failed write look like a success. A typed array's offset and -length come from the byteOffset and byteLength getters of -%TypedArray%.prototype, taken when the runtime is made, so a script that -shadows or redefines them cannot change which bytes are read. They are -read before its bytes: one that tracks the length -of a resizable buffer keeps the length QuickJS recorded when it was -made, which goes stale when the buffer is resized, and reading it -after a shrink would read past the buffer. A typed array of fixed -length that its shrunken buffer no longer holds is an error. -Document how values convert in both directions in the README. - -Add a Blobs test: BLOBs round-trip through a function, typed arrays, -subarrays and ArrayBuffers made in JavaScript become BLOBs, a function -can build a BLOB from a BLOB, a detached buffer is an error, and -db.exec() binds typed arrays and empty buffers as BLOBs and throws for a -buffer it cannot read. It also checks typed arrays over resizable -buffers that shrink and grow, and typed arrays whose byteOffset and -byteLength are shadowed or redefined. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 13 ++++++ - src/sqlitejs.c | 113 ++++++++++++++++++++++++++++++++++++++++++++----- - test/main.c | 60 ++++++++++++++++++++++++++ - 3 files changed, 176 insertions(+), 10 deletions(-) - -diff --git a/README.md b/README.md -index bcbb7f0..074735a 100644 ---- a/README.md -+++ b/README.md -@@ -176,6 +176,19 @@ SQLite-JS provides several ways to extend SQLite functionality with JavaScript: - | Collation Sequences | Define custom sort orders for text values | - | JavaScript Evaluation | Directly evaluate JavaScript code within SQLite | - -+### Values -+ -+SQL values reach JavaScript as follows: -+ -+| SQL | JavaScript | -+|-----|------------| -+| NULL | `null` | -+| INTEGER, REAL | number | -+| TEXT | string | -+| BLOB | `ArrayBuffer` | -+ -+A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number in the 32-bit range and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. -+ - ## Scalar Functions - - Scalar functions process one row at a time and return a single value. They are useful for data transformation, calculations, text manipulation, etc. -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 8a48d92..8c614fb 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -40,6 +40,8 @@ typedef struct { - size_t gc_threshold; // QuickJS's GC threshold when last checked: see js_keep_gc_below_limit() - size_t mem_used; // memory the runtime has allocated: see js_mem_malloc() - size_t mem_peak; // the most in use since the last result or error -+ JSValue typed_array_byte_offset; // the getters of every typed array's own -+ JSValue typed_array_byte_length; // offset and length: see js_get_bytes() - } globaljs_context; - - typedef struct { -@@ -304,6 +306,8 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - globaljs_context *js = (globaljs_context *)sqlite3_malloc(sizeof(globaljs_context)); - if (!js) return NULL; - memset(js, 0, sizeof(globaljs_context)); -+ js->typed_array_byte_offset = JS_UNDEFINED; -+ js->typed_array_byte_length = JS_UNDEFINED; - - rt = JS_NewRuntime2(&js_mem_funcs, js); - if (!rt) goto abort_init; -@@ -330,6 +334,14 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - JS_SetRuntimeOpaque(rt, js); - js_global_init(ctx, js); - -+ // taken before any other code runs: a script can shadow or redefine a typed array's -+ // byteOffset and byteLength, but these are its own -+ static const char offset_getter[] = "Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteOffset').get"; -+ static const char length_getter[] = "Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteLength').get"; -+ js->typed_array_byte_offset = JS_Eval(ctx, offset_getter, sizeof(offset_getter) - 1, "", JS_EVAL_TYPE_GLOBAL); -+ js->typed_array_byte_length = JS_Eval(ctx, length_getter, sizeof(length_getter) - 1, "", JS_EVAL_TYPE_GLOBAL); -+ if (!JS_IsFunction(ctx, js->typed_array_byte_offset) || !JS_IsFunction(ctx, js->typed_array_byte_length)) goto abort_init; -+ - // set only now: QuickJS cannot always recover from running out of memory while it creates - // a context (see js_setup_aggregate) - js->memory_limit = SQLITE_JS_DEFAULT_MEMORY_LIMIT; -@@ -338,7 +350,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - return js; - - abort_init: -- if (ctx) JS_FreeContext(ctx); -+ if (ctx) { -+ JS_FreeValue(ctx, js->typed_array_byte_offset); -+ JS_FreeValue(ctx, js->typed_array_byte_length); -+ JS_FreeContext(ctx); -+ } - if (rt) { - js_std_free_handlers(rt); - JS_FreeRuntime(rt); -@@ -352,7 +368,11 @@ static void globaljs_free (globaljs_context *js) { - - // order matters - if (js->runtime) js_std_free_handlers(js->runtime); -- if (js->context) JS_FreeContext(js->context); -+ if (js->context) { -+ JS_FreeValue(js->context, js->typed_array_byte_offset); -+ JS_FreeValue(js->context, js->typed_array_byte_length); -+ JS_FreeContext(js->context); -+ } - if (js->runtime) JS_FreeRuntime(js->runtime); - sqlite3_free(js); - } -@@ -464,6 +484,58 @@ static void functionjs_free (functionjs_context *fctx) { - - // MARK: - Utils - - -+// Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such -+// as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an -+// ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be -+// NULL when *psize is 0), 0 if it is not, and -1 with a pending JavaScript exception if its -+// buffer is detached or the typed array is out of its bounds. -+static int js_get_bytes (JSContext *ctx, JSValueConst value, const uint8_t **pbytes, size_t *psize) { -+ *pbytes = NULL; -+ *psize = 0; -+ -+ if (JS_IsArrayBuffer(value)) { -+ uint8_t *buf = JS_GetArrayBuffer(ctx, psize, value); -+ if (!buf && JS_HasException(ctx)) return -1; -+ *pbytes = buf; -+ return 1; -+ } -+ -+ if (JS_GetTypedArrayType(value) >= 0) { -+ // The offset and length come from the byteOffset and byteLength getters: a typed array -+ // can track the length of a resizable buffer, and the length QuickJS records when the -+ // array is made goes stale when the buffer is resized. They are the getters taken when -+ // the runtime was made (see globaljs_init), not the properties, which a script can -+ // shadow, so they run no JavaScript. -+ globaljs_context *js = (globaljs_context *)JS_GetContextOpaque(ctx); -+ int64_t offset = 0, length = 0; -+ JSValue prop = JS_Call(ctx, js->typed_array_byte_offset, value, 0, NULL); -+ int rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &offset, prop); -+ JS_FreeValue(ctx, prop); -+ if (rc < 0) return -1; -+ prop = JS_Call(ctx, js->typed_array_byte_length, value, 0, NULL); -+ rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &length, prop); -+ JS_FreeValue(ctx, prop); -+ if (rc < 0) return -1; -+ -+ size_t size = 0; -+ JSValue buffer = JS_GetTypedArrayBuffer(ctx, value, NULL, NULL, NULL); -+ if (JS_IsException(buffer)) return -1; -+ uint8_t *buf = JS_GetArrayBuffer(ctx, &size, buffer); -+ // the typed array keeps its buffer alive, so buf stays valid -+ JS_FreeValue(ctx, buffer); -+ if (!buf && JS_HasException(ctx)) return -1; -+ if ((offset < 0) || (length < 0) || ((uint64_t)offset > size) || ((uint64_t)length > size - (size_t)offset)) { -+ JS_ThrowRangeError(ctx, "typed array is out of the bounds of its buffer"); -+ return -1; -+ } -+ *pbytes = (buf) ? buf + offset : NULL; -+ *psize = (size_t)length; -+ return 1; -+ } -+ -+ return 0; -+} -+ - static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueConst val) { - if (JS_IsNull(val) || JS_IsUndefined(val)) { - return sqlite3_bind_null(vm, index); -@@ -498,13 +570,15 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo - JS_FreeCString(ctx, str); - return rc; - } -- if (JS_IsArrayBuffer(val)) { -- size_t size = 0; -- uint8_t *buf = JS_GetArrayBuffer(ctx, &size, val); -- if (buf) { -- return sqlite3_bind_blob(vm, index, buf, (int)size, SQLITE_TRANSIENT); -- } -- return sqlite3_bind_null(vm, index); -+ const uint8_t *bytes = NULL; -+ size_t size = 0; -+ int is_blob = js_get_bytes(ctx, val, &bytes, &size); -+ // a buffer whose bytes cannot be read (detached, or a view out of its bounds) is an error, as -+ // returning it from a function is: the JavaScript exception stays pending for js_sqlite_exec -+ if (is_blob < 0) return SQLITE_ERROR; -+ if (is_blob) { -+ if (size == 0) return sqlite3_bind_zeroblob(vm, index, 0); -+ return sqlite3_bind_blob64(vm, index, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); - } - return sqlite3_bind_null(vm, index); - } -@@ -524,6 +598,11 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int - for (int i = 0; i < nbind; ++i) { - // argv[0] is the first binding argument (SQL string already consumed by caller) - rc = js_bind_value(ctx, vm, i + 1, argv[i + 1]); -+ if ((rc != SQLITE_OK) && JS_HasException(ctx)) { -+ // a JavaScript error, such as a buffer that cannot be read: throw it as it is -+ sqlite3_finalize(vm); -+ return JS_EXCEPTION; -+ } - if (rc != SQLITE_OK) goto abort_with_dberror; - } - } -@@ -744,11 +823,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - return; - } - -+ // handle ArrayBuffer and typed arrays, the forms a BLOB takes in JavaScript -+ const uint8_t *bytes = NULL; -+ size_t size = 0; -+ int is_blob = js_get_bytes(js_ctx, value, &bytes, &size); -+ if (is_blob < 0) { -+ js_error_to_sqlite(context, js_ctx, JS_EXCEPTION, NULL); -+ return; -+ } -+ if (is_blob) { -+ if (size == 0) sqlite3_result_zeroblob(context, 0); -+ else sqlite3_result_blob64(context, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); -+ return; -+ } -+ - if (JS_IsObject(value)) { - sqlite3_result_null(context); - return; - } -- -+ - // fallback for unsupported types - sqlite3_result_error(context, "Unsupported JS value type", -1); - } -diff --git a/test/main.c b/test/main.c -index c13e043..461637a 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -720,6 +720,65 @@ abort_test: - return rc; - } - -+// MARK: - Blobs - -+ -+int test_blobs (void) { -+ sqlite3 *db = NULL; -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a BLOB arrives as an ArrayBuffer and goes back as the same BLOB -+ rc = db_exec(db, "SELECT js_create_scalar('identity', '(function(args){ return args[0]; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query_v2(db, "SELECT quote(identity(x'00ff10')), quote(identity(x'')), typeof(identity(zeroblob(3)));", (const char*[]){"X'00FF10'", "X''", "blob"}, 3); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // ArrayBuffers and typed arrays made in JavaScript, including a view of part of a buffer -+ rc = check_query_v2(db, "SELECT quote(js_eval('new Uint8Array([1, 2, 3])')), quote(js_eval('new Uint8Array([1, 2, 3, 4, 5]).subarray(1, 3)')), quote(js_eval('new Uint8Array([7, 8]).buffer')), quote(js_eval('new ArrayBuffer(0)'));", (const char*[]){"X'010203'", "X'0203'", "X'0708'", "X''"}, 4); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a function that makes a BLOB from a BLOB -+ rc = db_exec(db, "SELECT js_create_scalar('reverse_bytes', '(function(args){ return new Uint8Array(args[0]).reverse(); })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT quote(reverse_bytes(x'010203'));", "X'030201'"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a detached buffer has no bytes, so returning it is an error -+ rc = check_error(db, "SELECT js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); return b; })()');", "detached"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // db.exec() binds them as BLOBs too -+ rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT quote(?), quote(?)\", new Uint8Array([1, 2]), new ArrayBuffer(0)); rs.next(); return rs.get(0) + \" \" + rs.get(1); })()');", "X'0102' X''"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a typed array that tracks the length of a resizable buffer has the buffer's current length, -+ // after the buffer shrinks (by 1 MB, so that reading the old length would read far past it) -+ // or grows -+ rc = check_query_v2(db, "SELECT quote(js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab); u.fill(7); ab.resize(2); return u; })()')), length(js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(1); return u; })()')), length(js_eval('(function () { const ab = new ArrayBuffer(4, { maxByteLength: 16 }); const u = new Uint8Array(ab, 2); ab.resize(16); return u; })()'));", (const char*[]){"X'0707'", "1", "14"}, 3); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(3); const rs = db.exec(\"SELECT length(?)\", u); rs.next(); return rs.get(0); })()');", "3"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a typed array of fixed length that a shrunken buffer no longer holds is an error -+ rc = check_error(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); return u; })()');", "detached or resized"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // db.exec() throws for a buffer it cannot read, as returning it fails, instead of binding NULL -+ rc = check_query_v2(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); try { db.exec(\"SELECT ?\", u); return \"bound\"; } catch (e) { return e.message; } })()'), js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); try { db.exec(\"SELECT ?\", b); return \"bound\"; } catch (e) { return \"thrown\"; } })()');", (const char*[]){"ArrayBuffer is detached or resized", "thrown"}, 2); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a view's own offset and length count, not properties a script defines over them -+ rc = check_query_v2(db, "SELECT quote(js_eval('(function () { const u = new Uint8Array([1, 2, 3]).subarray(1, 2); Object.defineProperty(u, \"byteOffset\", { value: 0 }); Object.defineProperty(u, \"byteLength\", { value: 3 }); return u; })()')), js_eval('(function () { const u = new Uint8Array([1, 2, 3]).subarray(1, 2); Object.defineProperty(u, \"byteOffset\", { value: 0 }); const rs = db.exec(\"SELECT quote(?)\", u); rs.next(); return rs.get(0); })()');", (const char*[]){"X'02'", "X'02'"}, 2); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT quote(js_eval('(function () { Object.defineProperty(Object.getPrototypeOf(Uint8Array.prototype), \"byteOffset\", { get() { return 0; } }); return new Uint8Array([1, 2, 3]).subarray(2); })()'));", "X'03'"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - - - int test_report(const char *description, int rc){ -@@ -739,6 +798,7 @@ int main (void) { - result += test_report("Interrupt", test_interrupt()); - result += test_report("Memory limit", test_memory_limit()); - result += test_report("Direct only", test_direct_only()); -+ result += test_report("Blobs", test_blobs()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch b/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch deleted file mode 100644 index b3e89dc..0000000 --- a/packages/sqlite-js/0005-Return-whole-numbers-as-INTEGERs.patch +++ /dev/null @@ -1,161 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Tue, 10 Nov 2026 21:03:54 -0800 -Subject: [PATCH 5/8] Return whole numbers as INTEGERs - -QuickJS keeps the small whole numbers it can as 32-bit integers, and any -other number as a double, which went back to SQL as a REAL. So an INTEGER -outside the 32-bit range changed type on its way through a function: -`identity(2147483648)` returned 2147483648.0. The result of arithmetic -did too: js_eval('2 + 3') returned the INTEGER 5 but js_eval('2.5 * 2') -the REAL 5.0, and a JavaScript sum of large integers was a REAL. - -Return a number that is a whole number from -(2^53 - 1) to 2^53 - 1 -(Number.isSafeInteger), which a double holds exactly, as an INTEGER, and -any other number as a REAL, for function results and db.exec() -parameters alike. JavaScript cannot tell 3.0 from 3, so a REAL that holds -a whole number now comes back as an INTEGER; the README says so, and how -to pass an INTEGER beyond 2^53 - 1 without losing precision. - -Add a Numbers test: integers in and beyond the 32-bit range round-trip -as INTEGERs, other REALs stay REAL, integers beyond 2^53 - 1 are REALs, -arithmetic results, an aggregate result past the 32-bit range, and -db.exec() parameters. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 4 +++- - src/sqlitejs.c | 19 ++++++++++++++++++- - test/main.c | 43 +++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 64 insertions(+), 2 deletions(-) - -diff --git a/README.md b/README.md -index 074735a..3215216 100644 ---- a/README.md -+++ b/README.md -@@ -187,7 +187,9 @@ SQL values reach JavaScript as follows: - | TEXT | string | - | BLOB | `ArrayBuffer` | - --A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number in the 32-bit range and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. -+A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number from -(2^53 - 1) to 2^53 - 1 (`Number.isSafeInteger`) and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. -+ -+JavaScript has a single number type, a double. So a REAL that holds a whole number, such as 3.0, comes back as the INTEGER 3, and an INTEGER beyond ±(2^53 - 1) loses precision in JavaScript: pass it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. - - ## Scalar Functions - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 8c614fb..2802421 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -11,6 +11,7 @@ - #include - #include - #include -+#include - #if defined(__APPLE__) - #include - #elif defined(_WIN32) || defined(__linux__) || defined(__ANDROID__) || defined(__GLIBC__) -@@ -484,6 +485,18 @@ static void functionjs_free (functionjs_context *fctx) { - - // MARK: - Utils - - -+// A JavaScript number is a double. QuickJS keeps the small whole numbers it can as 32-bit -+// integers, but an INTEGER outside that range, or the result of arithmetic such as 2.5 * 2, -+// is a double too. A whole number that a double holds exactly, from -(2^53 - 1) to 2^53 - 1 -+// (Number.isSafeInteger), goes back to SQL as an INTEGER; any other number is a REAL. -+static bool js_number_to_int64 (double num, sqlite3_int64 *out) { -+ const double max_safe_integer = 9007199254740991.0; -+ // NaN fails both comparisons -+ if (!(num >= -max_safe_integer && num <= max_safe_integer) || (num != floor(num))) return false; -+ *out = (sqlite3_int64)num; -+ return true; -+} -+ - // Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such - // as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an - // ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be -@@ -548,7 +561,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo - return sqlite3_bind_int(vm, index, num); - } else { - double num; -+ sqlite3_int64 inum; - JS_ToFloat64(ctx, &num, val); -+ if (js_number_to_int64(num, &inum)) return sqlite3_bind_int64(vm, index, inum); - return sqlite3_bind_double(vm, index, num); - } - } -@@ -787,8 +802,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - sqlite3_result_int(context, num); - } else { - double num; -+ sqlite3_int64 inum; - JS_ToFloat64(js_ctx, &num, value); -- sqlite3_result_double(context, num); -+ if (js_number_to_int64(num, &inum)) sqlite3_result_int64(context, inum); -+ else sqlite3_result_double(context, num); - } - return; - } -diff --git a/test/main.c b/test/main.c -index 461637a..2c66aa7 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -779,6 +779,48 @@ abort_test: - return rc; - } - -+// MARK: - Numbers - -+ -+int test_numbers (void) { -+ sqlite3 *db = NULL; -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ rc = db_exec(db, "SELECT js_create_scalar('identity', '(function(args){ return args[0]; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // integers keep their type and value through JavaScript, beyond the 32-bit range too -+ rc = check_query(db, "WITH v(x) AS (VALUES (0), (42), (-7), (2147483647), (2147483648), (-2147483649), (9007199254740991), (-9007199254740991)) SELECT group_concat(typeof(identity(x)) || ' ' || (identity(x) = x), ',') FROM v;", "integer 1,integer 1,integer 1,integer 1,integer 1,integer 1,integer 1,integer 1"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // REALs that are not whole numbers stay REAL; a whole number is an INTEGER, as JavaScript cannot tell 3.0 from 3 -+ rc = check_query_v2(db, "SELECT quote(identity(3.5)), quote(identity(-0.25)), quote(identity(1e300)), quote(identity(3.0));", (const char*[]){"3.5", "-0.25", "1.0e+300", "3"}, 4); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // beyond 2^53 - 1 a double cannot hold every integer, so the result is a REAL -+ rc = check_query(db, "SELECT typeof(identity(9007199254740993));", "real"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // results of arithmetic -+ rc = check_query_v2(db, "SELECT quote(js_eval('2.5 * 2')), quote(js_eval('1e10')), typeof(js_eval('0.1 + 0.2')), typeof(js_eval('NaN'));", (const char*[]){"5", "10000000000", "real", "null"}, 4); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // an aggregate whose result is past the 32-bit range -+ rc = db_exec(db, "SELECT js_create_aggregate('js_sum', 'total = 0;', '(function(args){ total += args[0]; })', '(function(){ return total; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "WITH v(x) AS (VALUES (3000000000), (1)) SELECT typeof(js_sum(x)) || ' ' || js_sum(x) FROM v;", "integer 3000000001"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // db.exec() binds numbers the same way -+ rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT typeof(?), typeof(?), typeof(?)\", 2147483648, 2.5 * 2, 2.5); rs.next(); return [rs.get(0), rs.get(1), rs.get(2)].join(); })()');", "integer,integer,real"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - - - int test_report(const char *description, int rc){ -@@ -799,6 +841,7 @@ int main (void) { - result += test_report("Memory limit", test_memory_limit()); - result += test_report("Direct only", test_direct_only()); - result += test_report("Blobs", test_blobs()); -+ result += test_report("Numbers", test_numbers()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch b/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch deleted file mode 100644 index 50f268e..0000000 --- a/packages/sqlite-js/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch +++ /dev/null @@ -1,93 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Tue, 10 Nov 2026 21:16:06 -0800 -Subject: [PATCH 6/8] Report exceptions thrown by aggregate and window steps - -js_execute_common() turned the result of a function into an SQL result -only when the caller wanted the value. The step function of an aggregate -or window function, and the inverse function of a window function, -return nothing, so their result was dropped, and with it any exception -they threw: the aggregate went on as if the row had been added or -removed. A step that threw, or ran out of memory, gave a wrong result -with no error. - -Report an exception thrown by a step or inverse function as an SQL error. -Reported from xStep or xInverse, it makes SQLite abort the statement, -which still calls xFinal, so the aggregate context is released as before. - -Add an Aggregate errors test: an exception in an aggregate step and in a -window inverse function each fail the statement with its message, and the -connection stays usable. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 3 +++ - test/main.c | 33 +++++++++++++++++++++++++++++++++ - 2 files changed, 36 insertions(+) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 2802421..d29ec40 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -1027,6 +1027,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, - JS_FreeValue(js_context, args); - - if (return_value) js_value_to_sqlite(context, js_context, result); -+ // step and inverse functions return nothing, but an exception they throw is still an error: -+ // reported from xStep or xInverse, it makes SQLite abort the statement -+ else if (JS_IsException(result)) js_error_to_sqlite(context, js_context, result, NULL); - JS_FreeValue(js_context, result); - } - -diff --git a/test/main.c b/test/main.c -index 2c66aa7..20e34a0 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -821,6 +821,38 @@ abort_test: - return rc; - } - -+// MARK: - Aggregate errors - -+ -+int test_aggregate_errors (void) { -+ sqlite3 *db = NULL; -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ rc = db_exec(db, "CREATE TABLE t (x); INSERT INTO t VALUES (1), (2), (3);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // an exception thrown by an aggregate's step function fails the statement -+ rc = db_exec(db, "SELECT js_create_aggregate('step_fails', 'n = 0;', '(function(args){ if (args[0] == 2) throw new Error(\"step boom\"); n++; })', '(function(){ return n; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT step_fails(x) FROM t;", "step boom"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // so does one thrown by a window function's inverse function -+ rc = db_exec(db, "SELECT js_create_window('inverse_fails', 'total = 0;', '(function(args){ total += args[0]; })', '(function(){ return total; })', '(function(){ return total; })', '(function(args){ throw new Error(\"inverse boom\"); })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT inverse_fails(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM t;", "inverse boom"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // and the connection stays usable -+ rc = check_query(db, "SELECT js_eval('[1, 2, 3].join()');", "1,2,3"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - - - int test_report(const char *description, int rc){ -@@ -842,6 +874,7 @@ int main (void) { - result += test_report("Direct only", test_direct_only()); - result += test_report("Blobs", test_blobs()); - result += test_report("Numbers", test_numbers()); -+ result += test_report("Aggregate errors", test_aggregate_errors()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch b/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch deleted file mode 100644 index 7838dab..0000000 --- a/packages/sqlite-js/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch +++ /dev/null @@ -1,272 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Wed, 11 Nov 2026 11:47:56 -0800 -Subject: [PATCH 7/8] Keep the JavaScript stack size within the thread's stack - -QuickJS stops code that calls itself too deeply when the stack falls -below a limit it computes from the size it was given. It trusts that -size, so a size larger than the thread's stack never trips the check, -and code that calls itself without end crashes the process instead of -failing with "Maximum call stack size exceeded". - -js_set_max_stack_size() passed its argument to JS_SetMaxStackSize() -unchecked, through sqlite3_value_int(): text such as '1MB' or 'abc' -read as 1 or 0, and a size above the thread's stack, such as 16 MB on -a thread with 8 MB, crashed sqlite3 on endless recursion. The 1 MB -default could itself be too large: on a thread with 512 KB of stack, -endless recursion crashed at the default, and Windows gives a main -thread 1 MB, apps often their threads no more. - -Measure the calling thread's stack (pthread_getattr_np() on Linux and -Android, pthread_get_stackaddr_np() and pthread_get_stacksize_np() on -Apple platforms, VirtualQuery() on Windows) and keep a margin, -SQLITE_JS_STACK_MARGIN (256 KB), for the native code that runs between -two of QuickJS's checks, such as SQLite when JavaScript runs SQL -through db.exec. js_set_max_stack_size() now accepts an integer up to -what the stack allows, and reports the largest size in its error -message; elsewhere it allows up to the default. When the extension is -loaded, the default is lowered to what the loading thread's stack -allows. The stack position is read the way QuickJS reads it, because -under AddressSanitizer a local variable lives on a separate stack. - -0 still turns the check off, as the 1.3.7 changelog documents for a -connection used from several threads, and test_thread relies on. - -Add a Stack size test: endless recursion fails at the default, invalid -sizes are errors, and endless recursion, also through db.exec, fails -cleanly just below the largest size allowed and at a smaller one. It -fails without this change. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 5 ++- - src/sqlitejs.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++++-- - test/main.c | 58 ++++++++++++++++++++++++++++++++++ - 3 files changed, 144 insertions(+), 3 deletions(-) - -diff --git a/README.md b/README.md -index 3215216..a8cdea4 100644 ---- a/README.md -+++ b/README.md -@@ -419,10 +419,13 @@ SELECT js_load_blob('/path/to/file.bin'); -- Returns file contents as a blob - - ### js_set_max_stack_size - --Configures the maximum stack size (in bytes) for the JavaScript engine. -+Sets the most stack, in bytes, that JavaScript may use, which limits how deeply functions can call themselves; code that goes deeper fails with "Maximum call stack size exceeded". The default is 1 MB, or less when the thread that loads the extension has less stack. The size must be an integer no larger than the calling thread's stack allows, less a margin for the native code that runs between QuickJS's checks (`SQLITE_JS_STACK_MARGIN`, 256 KB); the error message gives the largest size allowed. A larger size, or text, which would read as 0, is an error, because QuickJS's check would never trip and code that calls itself without end would crash the process. -+ -+`0` turns the check off, for a connection used from several threads: the check measures from the stack of the thread that loaded the extension. With the check off, code that calls itself without end crashes the process. - - ```sql - SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB -+SELECT js_set_max_stack_size(0); -- No check, for use from several threads - ``` - - ### js_set_memory_limit -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index d29ec40..126d248 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -5,6 +5,11 @@ - // Created by Marco Bambini on 31/03/25. - // - -+// glibc declares pthread_getattr_np() (see js_stack_room) only for _GNU_SOURCE -+#if defined(__linux__) && !defined(_GNU_SOURCE) -+#define _GNU_SOURCE -+#endif -+ - #include - #include - #include -@@ -21,6 +26,15 @@ - #include "quickjs.h" - #include "quickjs-libc.h" - -+#if defined(_WIN32) -+#include -+#if defined(_MSC_VER) -+#include -+#endif -+#elif defined(__APPLE__) || defined(__linux__) -+#include -+#endif -+ - #ifndef SQLITE_CORE - SQLITE_EXTENSION_INIT1 - #endif -@@ -207,6 +221,53 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - #define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) - #endif - -+// Stack, in bytes, kept free below the JavaScript stack limit for the native code that runs -+// between two of QuickJS's stack checks: QuickJS's own C functions, and SQLite when JavaScript -+// runs SQL through db.exec. -+#ifndef SQLITE_JS_STACK_MARGIN -+#define SQLITE_JS_STACK_MARGIN (256 * 1024) -+#endif -+ -+// The stack, in bytes, that the calling thread has left below this function, less the margin. -+// QuickJS trusts its stack size: one larger than the thread has never trips its check, and code -+// that calls itself without end then crashes the process. Returns false where the thread's stack -+// cannot be found. -+static bool js_stack_room (size_t *room) { -+ // where the stack is now, found the way QuickJS finds it: the address of a local variable -+ // can be elsewhere, for example on AddressSanitizer's separate stack -+#if defined(__clang__) || defined(__GNUC__) -+ uintptr_t sp = (uintptr_t)__builtin_frame_address(0); -+#elif defined(_MSC_VER) -+ uintptr_t sp = (uintptr_t)_AddressOfReturnAddress(); -+#else -+ volatile char here = 0; -+ uintptr_t sp = (uintptr_t)&here; -+#endif -+ uintptr_t low = 0; -+#if defined(_WIN32) -+ // the stack is one allocation, reserved from its lowest address -+ MEMORY_BASIC_INFORMATION mbi; -+ if (VirtualQuery((LPCVOID)sp, &mbi, sizeof(mbi)) == 0) return false; -+ low = (uintptr_t)mbi.AllocationBase; -+#elif defined(__APPLE__) -+ pthread_t self = pthread_self(); -+ low = (uintptr_t)pthread_get_stackaddr_np(self) - pthread_get_stacksize_np(self); -+#elif defined(__linux__) -+ pthread_attr_t attr; -+ void *addr = NULL; -+ size_t size = 0; -+ if (pthread_getattr_np(pthread_self(), &attr) != 0) return false; -+ int rc = pthread_attr_getstack(&attr, &addr, &size); -+ pthread_attr_destroy(&attr); -+ if (rc != 0) return false; -+ low = (uintptr_t)addr; -+#else -+ return false; -+#endif -+ *room = (sp > low + SQLITE_JS_STACK_MARGIN) ? (size_t)(sp - low - SQLITE_JS_STACK_MARGIN) : 0; -+ return true; -+} -+ - // QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets - // after each collection to 1.5 times the memory still in use. With more than two thirds of the - // memory limit in use, that is beyond the limit: garbage would fill the rest, and code that fits -@@ -320,6 +381,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - // in its sqlite3_api_routines, so JavaScript cannot be interrupted there - if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); - -+ // the default stack size must fit in the stack of the thread that loads the extension: Windows -+ // gives a main thread 1 MB, and apps often give their threads no more -+ size_t room = 0; -+ if (js_stack_room(&room) && (room < JS_DEFAULT_STACK_SIZE)) JS_SetMaxStackSize(rt, (room > 0) ? room : 1); -+ - js_std_init_handlers(rt); - JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); - -@@ -1540,8 +1606,22 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** - UNUSED(argc); - globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); - -- int stack_size = sqlite3_value_int(argv[0]); -- JS_SetMaxStackSize(js->runtime, stack_size); -+ // 0 turns QuickJS's check off, for a connection used from several threads (the check measures -+ // from the stack of the thread that loaded the extension). Text would read as 0, and a size -+ // larger than the thread's stack is no limit either: code that calls itself without end -+ // would crash the process. Where the stack cannot be measured, allow up to the default. -+ size_t most = JS_DEFAULT_STACK_SIZE; -+ js_stack_room(&most); -+ sqlite3_int64 size = sqlite3_value_int64(argv[0]); -+ if ((sqlite3_value_type(argv[0]) != SQLITE_INTEGER) || (size < 0) || ((sqlite3_uint64)size > most)) { -+ char *msg = sqlite3_mprintf("The stack size must be an integer number of bytes from 1 to %llu, which this thread's stack allows, or 0 for no check", (unsigned long long)most); -+ if (msg) sqlite3_result_error(context, msg, -1); -+ else sqlite3_result_error_nomem(context); -+ sqlite3_free(msg); -+ return; -+ } -+ -+ JS_SetMaxStackSize(js->runtime, (size_t)size); - } - - void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { -diff --git a/test/main.c b/test/main.c -index 20e34a0..6dbcadc 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -10,6 +10,7 @@ - #include "sqlitejs.h" - #include - #include -+#include - #include - #include - -@@ -668,6 +669,62 @@ abort_test: - return rc; - } - -+// MARK: - Stack size - -+ -+int test_stack_size (void) { -+ sqlite3 *db = NULL; -+ char sql[256]; -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // code that calls itself without end fails, and the connection stays usable -+ const char *recurse = "SELECT js_eval('(function f(n) { return f(n + 1); })(0)');"; -+ rc = check_error(db, recurse, "Maximum call stack size exceeded"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('1 + 1');", "2"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a size is an integer no larger than the thread's stack, or 0 for no check: text would read -+ // as 0, and a size larger than the stack never trips the check, so the code above would -+ // crash the process -+ const char *invalid[] = {"'abc'", "-1", "1.5", "'1048576'", "NULL", "x'00'", "1073741824"}; -+ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { -+ snprintf(sql, sizeof(sql), "SELECT js_set_max_stack_size(%s);", invalid[i]); -+ rc = check_error(db, sql, "The stack size must be an integer number of bytes from 1 to "); -+ if (rc != SQLITE_OK) goto abort_test; -+ } -+ -+ // close to the largest size allowed, the code still stops, also when it calls itself -+ // through SQL, which puts SQLite's frames between QuickJS's stack checks -+ const char *most_text = strstr(sqlite3_errmsg(db), "from 1 to "); -+ long long most = most_text ? strtoll(most_text + strlen("from 1 to "), NULL, 10) : 0; -+ if (most <= 64 * 1024) { printf("FAIL: no stack size range in: %s\n", sqlite3_errmsg(db)); rc = SQLITE_ERROR; goto abort_test; } -+ snprintf(sql, sizeof(sql), "SELECT js_set_max_stack_size(%lld);", most - 4096); -+ rc = db_exec(db, sql); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, recurse, "Maximum call stack size exceeded"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_create_scalar('recurse_sql', '(function (args) { try { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (rs.next()) return rs.get(0); } catch (e) {} throw new Error(\"stopped\"); })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT recurse_sql(0);", "stopped"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a smaller size -+ rc = db_exec(db, "SELECT js_set_max_stack_size(256 * 1024);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, recurse, "Maximum call stack size exceeded"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // 0 is still allowed, for connections used from several threads (see test_thread) -+ rc = check_query(db, "SELECT quote(js_set_max_stack_size(0));", "NULL"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ - // MARK: - Direct only - - - int test_direct_only (void) { -@@ -871,6 +928,7 @@ int main (void) { - result += test_report("Thread", test_thread()); - result += test_report("Interrupt", test_interrupt()); - result += test_report("Memory limit", test_memory_limit()); -+ result += test_report("Stack size", test_stack_size()); - result += test_report("Direct only", test_direct_only()); - result += test_report("Blobs", test_blobs()); - result += test_report("Numbers", test_numbers()); diff --git a/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch b/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch deleted file mode 100644 index 613f1a3..0000000 --- a/packages/sqlite-js/0008-Report-SQL-errors-from-db.exec-result-sets.patch +++ /dev/null @@ -1,158 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Wed, 11 Nov 2026 12:24:04 -0800 -Subject: [PATCH 8/8] Report SQL errors from db.exec result sets - -db.exec() prepares a statement and returns a result set; the statement -runs as next() or toArray() steps it. Both treated any sqlite3_step() -result other than SQLITE_ROW as the end of the rows, so an error while -the statement runs was dropped: next() returned false, as at the end of -the rows, and toArray() returned the rows read before the error. A -failed UNIQUE constraint on an INSERT, or an integer overflow, looked -like success, and JavaScript that writes through db.exec() could not -tell. An error found when the statement is prepared, such as an unknown -function, was already thrown by db.exec(). - -Throw an InternalError with the connection's error message when -sqlite3_step() returns neither SQLITE_ROW nor SQLITE_DONE, from next() -and from toArray(). The statement is finalized as before. The end of -the rows is still false. The README now documents db.exec(), including -that a statement runs only when next() or toArray() steps it. - -Add an Exec errors test: a failed constraint and an overflow throw from -next(), an overflow on the second row throws from toArray(), JavaScript -can catch the error, and the end of the rows and a successful INSERT -are unchanged. It fails without this change. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - README.md | 12 ++++++++++++ - src/sqlitejs.c | 19 +++++++++++++++---- - test/main.c | 35 +++++++++++++++++++++++++++++++++++ - 3 files changed, 62 insertions(+), 4 deletions(-) - -diff --git a/README.md b/README.md -index a8cdea4..a1fcea1 100644 ---- a/README.md -+++ b/README.md -@@ -397,6 +397,18 @@ SELECT js_eval('Math.PI * Math.pow(5, 2)'); - SELECT js_eval('new Date(1629381600000).toLocaleDateString()'); - ``` - -+### Running SQL from JavaScript -+ -+JavaScript can run SQL on the same connection through the global `db` object. `db.exec(sql, ...parameters)` prepares one statement, binds the parameters to its `?` placeholders, and returns a result set. The statement runs as you step through it: `next()` moves to the next row and returns `true`, or `false` after the last; `get(i)` and `name(i)` give a column's value and name; `columnCount` is the number of columns; and `toArray()` returns the remaining rows as arrays. A statement that returns no rows, such as an `INSERT`, also runs only when you call `next()` or `toArray()`. -+ -+An error while the statement runs, such as a failed constraint, is thrown from `next()` or `toArray()`, as an error in the SQL itself is thrown from `db.exec()`. -+ -+```sql -+CREATE TABLE t(a UNIQUE); -+SELECT js_eval('db.exec("INSERT INTO t VALUES (?)", 1).next()'); -- 0: the row is inserted, and next() is false, as there are no rows -+SELECT js_eval('(function () { try { db.exec("INSERT INTO t VALUES (?)", 1).next(); } catch (e) { return e.message; } })()'); -- UNIQUE constraint failed: t.a -+``` -+ - ## Utility Functions - - ### js_version -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 126d248..bd7937a 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -125,11 +125,16 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J - if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); - - if (!rs->vm) return JS_FALSE; -- if (sqlite3_step(rs->vm) == SQLITE_ROW) return JS_TRUE; -+ int rc = sqlite3_step(rs->vm); -+ if (rc == SQLITE_ROW) return JS_TRUE; - -+ // an error while the statement runs (a constraint, an overflow, an interrupt) is an -+ // exception, as an error while it is prepared is in js_sqlite_exec; only the end of the -+ // rows is false -+ JSValue result = (rc == SQLITE_DONE) ? JS_FALSE : JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); - sqlite3_finalize(rs->vm); - rs->vm = NULL; -- return JS_FALSE; -+ return result; - } - - static JSValue js_rowset_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { -@@ -178,8 +183,9 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg - - int ncols = rs->ncols; - int nrows = 0; -+ int rc; - while (true) { -- int rc = sqlite3_step(rs->vm); -+ rc = sqlite3_step(rs->vm); - if (rc != SQLITE_ROW) break; - - JSValue row = JS_NewArray(ctx); -@@ -196,7 +202,12 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg - - JS_SetPropertyUint32(ctx, result, nrows++, row); - } -- -+ -+ // as in js_rowset_next: an error is an exception, not a shorter array -+ if (rc != SQLITE_DONE) { -+ JS_FreeValue(ctx, result); -+ result = JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); -+ } - sqlite3_finalize(rs->vm); - rs->vm = NULL; - return result; -diff --git a/test/main.c b/test/main.c -index 6dbcadc..a23b3aa 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -912,6 +912,40 @@ abort_test: - - // MARK: - - -+// MARK: - Exec errors - -+ -+int test_exec_errors (void) { -+ sqlite3 *db = NULL; -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ rc = db_exec(db, "CREATE TABLE u(a UNIQUE); INSERT INTO u VALUES (1);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // an error while the statement runs is an exception, from next() and from toArray() -+ rc = check_error(db, "SELECT js_eval('db.exec(\"INSERT INTO u VALUES (1)\").next()');", "UNIQUE constraint failed"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('db.exec(\"SELECT abs(-9223372036854775808)\").next()');", "integer overflow"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('db.exec(\"SELECT 1 UNION ALL SELECT abs(-9223372036854775808) UNION ALL SELECT 3\").toArray()');", "integer overflow"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // JavaScript can catch it -+ rc = check_query(db, "SELECT js_eval('(function () { try { db.exec(\"INSERT INTO u VALUES (1)\").next(); return \"no error\"; } catch (e) { return e.message; } })()');", "UNIQUE constraint failed: u.a"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // the end of the rows is still false, and a statement that succeeds still runs -+ rc = check_query(db, "SELECT js_eval('[db.exec(\"SELECT 1 WHERE 0\").next(), db.exec(\"INSERT INTO u VALUES (2)\").next(), JSON.stringify(db.exec(\"SELECT a FROM u ORDER BY a\").toArray())].join(\" \")');", "false false [[1],[2]]"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+abort_test: -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ return rc; -+} -+ -+// MARK: - -+ - int test_report(const char *description, int rc){ - printf("%s%-30s %s\n", VERBOSE ? "********** " : "", description, (rc == SQLITE_OK) ? "OK" : "FAILED"); - return (rc == SQLITE_OK) ? 0 : 1; -@@ -933,6 +967,7 @@ int main (void) { - result += test_report("Blobs", test_blobs()); - result += test_report("Numbers", test_numbers()); - result += test_report("Aggregate errors", test_aggregate_errors()); -+ result += test_report("Exec errors", test_exec_errors()); - - sqlite3_int64 current = 0; - sqlite3_int64 highwater = 0; diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index 4e32b84..6665d21 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -2,8 +2,9 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is -[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.3.7 with eight -changes of ours, listed [below](#changes-in-this-build). The JavaScript engine, +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) as of 12 November +2026, which adds nine changes of ours to its 1.3.7 release, listed +[below](#changes-in-this-build). The JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. ## Load it @@ -167,7 +168,10 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. catches the error receives `null` instead when the limit leaves no room even for the error. `js_set_memory_limit` changes the limit; memory that globals still hold - counts against it until they are cleared. + counts against it until they are cleared. A lower limit leaves the session + usable, since garbage is collected as the limit changes, but a limit under + the memory that globals hold leaves no room for any JavaScript until it is + raised again. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with an "interrupted" error, even if the code catches exceptions, and `sqlite3` keeps running. @@ -193,18 +197,20 @@ constraints and generated columns cannot call `js_eval` or the other ## Changes in this build -Eight patches on upstream 1.3.7, each sent upstream; `build.sh` applies them. - -| Patch | Change | -|-------|--------| -| `0001` | Ctrl-C and `sqlite3_interrupt()` stop running JavaScript. Upstream, endless code hangs `sqlite3`. | -| `0002` | A 64 MB memory limit, and `js_set_memory_limit`. Upstream, code that keeps allocating takes all the memory there is. | -| `0003` | `js_eval` and the other functions that run code, read files or change the runtime work only in top-level SQL (and TEMP views and triggers). Upstream, with `trusted_schema` on, a view can call them. | -| `0004` | A result that is an `ArrayBuffer` or typed array is a BLOB, and `db.exec` binds one as a BLOB or throws if it cannot read it. Upstream, a result is NULL, so a BLOB cannot pass through a function. | -| `0005` | A whole-number result is an INTEGER. Upstream, an INTEGER outside the 32-bit range comes back as a REAL. | -| `0006` | An exception in an aggregate's or window function's step is an SQL error. Upstream, it is ignored, and the result is silently wrong. | -| `0007` | The JavaScript stack size stays within the thread's stack: `js_set_max_stack_size` refuses text and larger sizes, and the default shrinks on a small stack. Upstream, those make endless recursion crash `sqlite3`. | -| `0008` | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. Upstream, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | +Upstream merged nine changes of ours after its 1.3.7 release, so this build is +its main branch at commit c8ae85a, with no patches. Compared with 1.3.7: + +| Upstream PR | Change | +|-------------|--------| +| #11 | Ctrl-C and `sqlite3_interrupt()` stop running JavaScript. In 1.3.7, endless code hangs `sqlite3`. | +| #12 | A 64 MB memory limit, and `js_set_memory_limit`. In 1.3.7, code that keeps allocating takes all the memory there is. | +| #13 | `js_eval` and the other functions that run code, read files or change the runtime work only in top-level SQL (and TEMP views and triggers). In 1.3.7, with `trusted_schema` on, a view can call them. | +| #14 | A result that is an `ArrayBuffer` or typed array is a BLOB, and `db.exec` binds one as a BLOB or throws if it cannot read it. In 1.3.7, a result is NULL, so a BLOB cannot pass through a function. | +| #15 | A whole-number result is an INTEGER. In 1.3.7, an INTEGER outside the 32-bit range comes back as a REAL. | +| #16 | An exception in an aggregate's or window function's step is an SQL error. In 1.3.7, it is ignored, and the result is silently wrong. | +| #17 | The JavaScript stack size stays within the thread's stack: `js_set_max_stack_size` refuses text and larger sizes, and the default shrinks on a small stack. In 1.3.7, those make endless recursion crash `sqlite3`. | +| #18 | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. In 1.3.7, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | +| #19 | The stack check follows the thread each call runs on. In 1.3.7, JavaScript run on a thread other than the one that set up the connection fails at once, or crashes on endless recursion. | The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 11e8bf5..be8fd96 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -3,15 +3,17 @@ TERMUX_PKG_DESCRIPTION="SQLite extension for functions written in JavaScript" TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" -TERMUX_PKG_VERSION=1.3.7 -TERMUX_PKG_REVISION=5 -TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz -TERMUX_PKG_SHA256=a3251ba5b10beb4b1f9b001f6595581a85015dd792ee93aa1947db12b2f8f316 +# Upstream merged our changes (ADFA-7081, sqliteai/sqlite-js #11 to #19) after +# 1.3.7, so this is a commit of its main branch, with no patches. Go back to a +# release tag once one includes them. +_COMMIT=c8ae85a29a911977212e6cdd36ed84926b6b8c4e +_COMMIT_DATE=20261112 +TERMUX_PKG_VERSION=1.3.7-p${_COMMIT_DATE} +TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/${_COMMIT}.tar.gz +TERMUX_PKG_SHA256=4f4ebb7e44b20762c11bdbfc6b3abd3aa423daec2b461d20fc47598716ce5561 TERMUX_PKG_BUILD_DEPENDS="libsqlite" TERMUX_PKG_RECOMMENDS="sqlite" TERMUX_PKG_BUILD_IN_SRC=true -# The *.patch files are ours (ADFA-7081) and sent upstream; check each one -# against a new upstream version, and drop those upstream has merged. TERMUX_PKG_AUTO_UPDATE=false termux_step_post_get_source() { diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index c17d601..1585fd8 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -546,6 +546,15 @@ expect "AC9: js_set_memory_limit raises the limit" $'\n134217728' \ expect_error "AC9: js_set_memory_limit lowers the limit" "out of memory" \ "SELECT js_set_memory_limit(8 * 1024 * 1024);" \ "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" +# QuickJS refuses every allocation while the memory in use is over the limit, +# and collects only when it allocates, so garbage over a lowered limit would +# leave the session out of memory until the limit is raised again. +expect "AC9: a limit lowered under garbage leaves the session usable" $'\n200000\n0\n\n2' \ + "SELECT js_set_memory_limit(0);" \ + "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');" \ + "SELECT js_eval('delete globalThis.g; 0');" \ + "SELECT js_set_memory_limit(4 * 1024 * 1024);" \ + "SELECT js_eval('1 + 1');" for bad in -1 1.5 "'64'" NULL; do expect_error "AC9: js_set_memory_limit($bad) is an SQL error" "The memory limit must be an integer number of bytes" \ "SELECT js_set_memory_limit($bad);" From 7916a4e12e3dc29af5012b05b88e2de78af6e5e9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 15:52:14 -0800 Subject: [PATCH 08/17] ADFA-7081: sqlite-js 1.4.1, with two patches for stack and garbage Upstream released 1.4.0 and 1.4.1 on 2026-11-12, after c8ae85a. Both contain it, and 1.4.1 differs from it in src/ and libs/ only in SQLITE_JS_VERSION, so js_version() now reports 1.4.1. build.sh takes the 1.4.1 tag again, as its comment asked (independent review). Two patches, offered upstream as sqliteai/sqlite-js #22 and #23: - 0001 keeps the stack check within the stack where endless recursion crashed: a thread with less than 64 KB of stack left, and a main thread first measured deep in its stack (CodeRabbit, on the AAR's copy in CodeOnTheGo #2244). Neither can happen in sqlite3; the README's stack claim now holds everywhere. - 0002 collects garbage after any "out of memory" error and whenever a limit is set. With 40 MB of cyclic garbage under the 64 MB default, a 30 MB ArrayBuffer failed on every try. After a limit lowered to 32 MB, above the garbage, a 16 MB one failed (independent review, both). The README describes both. Its js_set_max_stack_size row no longer suggests 0 for several threads, which upstream's #19 made unneeded (independent review). run-tests.sh gets an AC9 test for each garbage case, and AC2 expects 1.4.1. On a host build of this package, run-tests.sh passes 99 of 99, with AC12 skipped because sqlite-brotli is not installed. On 1.4.1 without the patches, only the two new tests fail. Upstream's suite with the patches passes 15 of 15, also under ASan and UBSan. The aarch64 and arm builds (NDK 29, build.sh's compile line) have no warnings in sqlitejs.c, and export only the two entry points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...heck-within-the-stack-in-two-more-ca.patch | 110 ++++++++++++++++ ...after-any-out-of-memory-error-and-on.patch | 120 ++++++++++++++++++ packages/sqlite-js/README.md | 27 ++-- packages/sqlite-js/build.sh | 15 +-- packages/sqlite-js/tests/run-tests.sh | 25 +++- 5 files changed, 277 insertions(+), 20 deletions(-) create mode 100644 packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch create mode 100644 packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch diff --git a/packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch b/packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch new file mode 100644 index 0000000..2b06490 --- /dev/null +++ b/packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch @@ -0,0 +1,110 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Thu, 12 Nov 2026 15:17:11 -0800 +Subject: [PATCH 1/2] Keep the stack check within the stack in two more cases + +On the initial thread on Linux, RLIMIT_STACK is now counted from the top +of the stack, as the kernel counts it, rather than from where the first +measurement was taken. Counted from there, a first measurement deep in +the stack put the bound below the real one by that depth: with the +extension loaded 2 MB deep on the main thread, js_set_max_stack_size() +allowed 10 MB of an 8 MB stack, and code that called itself without end +at that size crashed the process. + +A call into JavaScript on a thread with less room than +SQLITE_JS_STACK_MIN now keeps the measured room rather than the size +set for the connection, 1 MB by default: on a thread with a 64 KB stack, +code that called itself without end crashed. JavaScript there now fails +with "Maximum call stack size exceeded". The minimum still applies where +a runtime is created, since QuickJS cannot create a context in less. + +Stack on other threads now also runs forever() on a 64 KB thread. It +crashes without this change and passes with it, also under ASan and +UBSan, and the suite passes 16 of 16. The first case is checked by a +program that loads the extension deep in the main thread's stack: at 2 +and 6 MB deep, the largest size allowed was 10.2 and 14.4 MB of 8 MB +before, and about 7.75 MB after, where forever() stops with an error. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + src/sqlitejs.c | 17 ++++++++++++----- + test/main.c | 12 ++++++++++++ + 2 files changed, 24 insertions(+), 5 deletions(-) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 9137ca8..b0535f8 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -355,9 +355,10 @@ static void js_mem_reset_peak (globaljs_context *js) { + #endif + + // The least stack worth giving JavaScript. QuickJS cannot even create a context below about +-// 16 KB (measured: 4 KB fails, 16 KB works), and it reads 0 as "no check at all", so a smaller +-// measurement is treated as no measurement and leaves the default alone. Failing to catch +-// runaway recursion is the lesser evil next to an extension that cannot load. ++// 16 KB (measured: 4 KB fails, 16 KB works), and it reads 0 as "no check at all", so where a ++// runtime is created a smaller measurement is treated as no measurement and leaves the default ++// alone. Failing to catch runaway recursion is the lesser evil next to an extension that cannot ++// load. A call into JavaScript on an existing runtime keeps any measurement (see js_enter). + #ifndef SQLITE_JS_STACK_MIN + #define SQLITE_JS_STACK_MIN (32 * 1024) + #endif +@@ -395,7 +396,10 @@ static bool js_stack_low (uintptr_t sp, uintptr_t *low) { + if (syscall(SYS_gettid) == (long)getpid()) { + struct rlimit limit; + if ((getrlimit(RLIMIT_STACK, &limit) == 0) && (limit.rlim_cur != RLIM_INFINITY)) { +- uintptr_t grows_to = (sp > (uintptr_t)limit.rlim_cur) ? sp - (uintptr_t)limit.rlim_cur : 0; ++ // counted from the top of the stack, as the kernel counts it: counted from sp, a first ++ // measurement deep in the stack would put the bound below the real one ++ uintptr_t high = (uintptr_t)addr + size; ++ uintptr_t grows_to = (high > (uintptr_t)limit.rlim_cur) ? high - (uintptr_t)limit.rlim_cur : 0; + if (grows_to < thread_low) thread_low = grows_to; + } + } +@@ -443,8 +447,11 @@ static bool js_stack_room (size_t *room) { + static void js_enter (globaljs_context *js) { + if (js->depth++ > 0) return; + JS_UpdateStackTop(js->runtime); ++ // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails ++ // with "Maximum call stack size exceeded" rather than running past the end of the stack. A ++ // size of 1 rather than 0, which would turn the check off. + size_t size = js->stack_size, room = 0; +- if ((size > 0) && js_stack_room(&room) && (room >= SQLITE_JS_STACK_MIN) && (room < size)) size = room; ++ if ((size > 0) && js_stack_room(&room) && (room < size)) size = (room > 0) ? room : 1; + JS_SetMaxStackSize(js->runtime, size); + } + +diff --git a/test/main.c b/test/main.c +index 0c8a47b..0240f3d 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -1022,6 +1022,13 @@ static void *stack_thread_run (void *ptr) { + return NULL; + } + ++// Runs forever() on the calling thread, which must stop with an error instead of crashing. ++static void *stack_thread_forever (void *ptr) { ++ stack_thread_args *args = (stack_thread_args *)ptr; ++ args->rc = check_error(args->db, "SELECT forever();", "Maximum call stack size exceeded"); ++ return NULL; ++} ++ + static void *stack_thread_open (void *ptr) { + stack_thread_args *args = (stack_thread_args *)ptr; + args->rc = test_open(&args->db); +@@ -1095,6 +1102,11 @@ int test_stack_threads (void) { + rc = args.rc; + if (rc != SQLITE_OK) goto abort_test; + ++ // and on a thread with less stack left than SQLITE_JS_STACK_MIN: the size is still lowered to ++ // fit, since the default would let code that calls itself without end run past the stack ++ rc = stack_thread(stack_thread_forever, &args, 64 * 1024); ++ if (rc != SQLITE_OK) goto abort_test; ++ + // a thread whose whole stack is under twice the margin still gets a usable runtime + rc = stack_thread(stack_thread_tiny, &args, 256 * 1024); + +-- +2.53.0 + diff --git a/packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch b/packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch new file mode 100644 index 0000000..79787cb --- /dev/null +++ b/packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch @@ -0,0 +1,120 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Thu, 12 Nov 2026 15:32:30 -0800 +Subject: [PATCH 2/2] Collect garbage after any out-of-memory error and on any + new limit + +Garbage could leave a connection unable to make an allocation that fits +in its memory limit, on every try: + +- After an allocation too large to fit fails. QuickJS refuses it before + making it, so the memory in use never came within 64 KB of the limit + and the collection after the error did not run. With 40 MB of cyclic + garbage under the 64 MB default, new ArrayBuffer(30 MB) failed with + "out of memory" every time. The collection now also runs whenever the + error is "out of memory": the next try succeeds. +- After a lower limit set above the memory in use. Only a limit within + 64 KB of the memory in use collected. With the garbage of 200,000 + cyclic objects and the limit lowered to 32 MB, new ArrayBuffer(16 MB) + failed. Setting a limit now always collects. + +The Memory limit test covers both, each on a connection of its own; each +case fails without its change. The suite passes 16 of 16, also under +ASan and UBSan. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + src/sqlitejs.c | 18 +++++++++++------- + test/main.c | 32 ++++++++++++++++++++++++++++++++ + 2 files changed, 43 insertions(+), 7 deletions(-) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index b0535f8..ce343b6 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -932,7 +932,9 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + default_error = "out of memory"; + } + } +- bool out_of_memory = js_reached_memory_limit(JS_GetContextOpaque(js_ctx)); ++ // An allocation too large to fit is refused before it is counted, so the memory in use need ++ // not have come near the limit: the error itself says so. ++ bool out_of_memory = js_reached_memory_limit(JS_GetContextOpaque(js_ctx)) || (err_msg && (strcmp(err_msg, "out of memory") == 0)); + js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); + + // set a default error message and code +@@ -944,9 +946,9 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + if (!JS_IsNull(exception)) JS_FreeValue(js_ctx, exception); + + // QuickJS refuses every allocation once the memory in use is over the limit, and it collects +- // only when it creates an object, which it cannot do without allocating: the connection +- // would stay out of memory for good. No JavaScript is running here, so collect now, while +- // the garbage that filled the limit is still reachable from nothing. ++ // only when it creates an object past its threshold, which the code that failed may never ++ // do: the connection would stay out of memory for good. No JavaScript is running here, so ++ // collect now, while the garbage that filled the limit is still reachable from nothing. + if (out_of_memory) js_collect_below_limit(JS_GetContextOpaque(js_ctx)); + } + +@@ -1768,9 +1770,11 @@ void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **ar + js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; + JS_SetMemoryLimit(js->runtime, js->memory_limit); + js->gc_threshold = 0; // check the GC threshold against the new limit +- // a limit at or under the memory in use leaves nothing to allocate from, and QuickJS cannot +- // collect without allocating, so collect here instead +- if ((js->memory_limit > 0) && (js->mem_used + 64 * 1024 >= js->memory_limit)) js_collect_below_limit(js); ++ // Garbage left from before counts against the new limit, and QuickJS collects only when it ++ // creates an object past its threshold: a limit at or under the memory in use leaves nothing ++ // to allocate from, and one above it can leave too little for a large allocation. So collect ++ // here, as no JavaScript is running. ++ if (js->memory_limit > 0) js_collect_below_limit(js); + else js_keep_gc_below_limit(js); + js_mem_reset_peak(js); + } +diff --git a/test/main.c b/test/main.c +index 0240f3d..4145904 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -900,6 +900,38 @@ int test_memory_limit (void) { + rc = check_query(db, "SELECT js_eval('[1, 2, 3].map(x => x * 2).join()');", "2,4,6"); + if (rc != SQLITE_OK) goto abort_test; + ++ // and so does a lower limit set above it: the garbage would fill the room left under the new ++ // limit, and an allocation that needs that room would fail ++ if (db) sqlite3_close(db); ++ db = NULL; ++ rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_set_memory_limit(0);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');", "200000"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_eval('delete globalThis.g; 0');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_set_memory_limit(32 * 1024 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');", "16777216"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // garbage that leaves no room for a large allocation is collected after it fails, so the next ++ // try succeeds: QuickJS refuses an allocation that would pass the limit before making it, so ++ // the memory in use never comes near the limit, and nothing else would collect the garbage ++ if (db) sqlite3_close(db); ++ db = NULL; ++ rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 40; i++) { const o = { b: new ArrayBuffer(1024 * 1024) }; o.o = o; g.push(o); } g.length');", "40"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_eval('delete globalThis.g; 0');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');", NULL, NULL, NULL); // may fail ++ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');", "31457280"); ++ if (rc != SQLITE_OK) goto abort_test; ++ + // running out of memory through many small allocations, which leaves no room for the error + // object, is reported as "out of memory" too + rc = check_error(db, "SELECT js_eval('(function () { let h = null; for (;;) h = {n: h}; })()');", "out of memory"); +-- +2.53.0 + diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index 6665d21..e2d4b68 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -2,8 +2,8 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is -[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) as of 12 November -2026, which adds nine changes of ours to its 1.3.7 release, listed +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.1, the first +release with nine changes of ours, plus two patches of ours, all listed [below](#changes-in-this-build). The JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. @@ -106,7 +106,7 @@ or while it runs, is a JavaScript exception. | `js_init_table(1)` | Also creates every function stored in `js_functions`. | | `js_load_text(path)`, `js_load_blob(path)` | Return a file's contents as TEXT or as a BLOB. | | `js_set_memory_limit(bytes)` | Sets the memory JavaScript may use on this connection; 0 means no limit. | -| `js_set_max_stack_size(bytes)` | Sets JavaScript's stack limit, at most what the thread's stack allows (the error gives the largest size). 0 turns the check off, for use from several threads; deep recursion then crashes `sqlite3`. | +| `js_set_max_stack_size(bytes)` | Sets JavaScript's stack limit, at most what the thread's stack allows (the error gives the largest size). 0 turns the check off; deep recursion then crashes `sqlite3`. | | `js_version()`, `js_version(1)` | The sqlite-js version, or with an argument, the quickjs-ng version. | The functions you create last for the session. To keep them, call @@ -166,12 +166,11 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. - **Memory.** JavaScript may use 64 MB per session. Code that needs more fails with an "out of memory" error, and the session stays usable. JavaScript that catches the error receives `null` instead when the limit leaves no room even - for the error. - `js_set_memory_limit` changes the limit; memory that globals still hold - counts against it until they are cleared. A lower limit leaves the session - usable, since garbage is collected as the limit changes, but a limit under - the memory that globals hold leaves no room for any JavaScript until it is - raised again. + for the error. Garbage is collected after the error, so code that failed + because garbage filled the limit works when run again. + `js_set_memory_limit` changes the limit, and collects garbage. Memory that + globals still hold counts against the limit until they are cleared, so a + limit under it leaves no room for any JavaScript until it is raised again. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with an "interrupted" error, even if the code catches exceptions, and `sqlite3` keeps running. @@ -197,8 +196,7 @@ constraints and generated columns cannot call `js_eval` or the other ## Changes in this build -Upstream merged nine changes of ours after its 1.3.7 release, so this build is -its main branch at commit c8ae85a, with no patches. Compared with 1.3.7: +Upstream released nine changes of ours in 1.4.0. Compared with 1.3.7: | Upstream PR | Change | |-------------|--------| @@ -212,6 +210,13 @@ its main branch at commit c8ae85a, with no patches. Compared with 1.3.7: | #18 | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. In 1.3.7, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | | #19 | The stack check follows the thread each call runs on. In 1.3.7, JavaScript run on a thread other than the one that set up the connection fails at once, or crashes on endless recursion. | +This build adds two patches of ours, offered upstream: + +| Patch | Upstream PR | Change | +|-------|-------------|--------| +| 0001 | #22 | The stack check stays within the stack in two more cases. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | +| 0002 | #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | + The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry point argument. diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index be8fd96..10b7106 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -3,14 +3,13 @@ TERMUX_PKG_DESCRIPTION="SQLite extension for functions written in JavaScript" TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" -# Upstream merged our changes (ADFA-7081, sqliteai/sqlite-js #11 to #19) after -# 1.3.7, so this is a commit of its main branch, with no patches. Go back to a -# release tag once one includes them. -_COMMIT=c8ae85a29a911977212e6cdd36ed84926b6b8c4e -_COMMIT_DATE=20261112 -TERMUX_PKG_VERSION=1.3.7-p${_COMMIT_DATE} -TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/${_COMMIT}.tar.gz -TERMUX_PKG_SHA256=4f4ebb7e44b20762c11bdbfc6b3abd3aa423daec2b461d20fc47598716ce5561 +TERMUX_PKG_VERSION=1.4.1 +TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz +TERMUX_PKG_SHA256=d45d394fc7cb37070a64fa248994c7fef7c10cff31541eb57608405753fc3078 +# Upstream released our earlier changes (sqliteai/sqlite-js #11 to #19) in +# 1.4.0. The *.patch files are ours (ADFA-7081) and offered upstream as #22 and +# #23; check each one against a new upstream version, and drop those upstream +# has merged. TERMUX_PKG_BUILD_DEPENDS="libsqlite" TERMUX_PKG_RECOMMENDS="sqlite" TERMUX_PKG_BUILD_IN_SRC=true diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 1585fd8..006da4f 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -234,7 +234,7 @@ expect "loading the extension twice in one session is harmless" "2" \ # --- AC2: the engine is quickjs-ng -------------------------------------------- -expect "AC2: js_version() is the sqlite-js version, 1.3.7" "1.3.7" "SELECT js_version();" +expect "AC2: js_version() is the sqlite-js version, 1.4.1" "1.4.1" "SELECT js_version();" got=$(sql "SELECT js_version(1);" 2>&1) # Bellard's QuickJS has no version function, so sqlite-js does not build with it. if [[ $got =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then @@ -555,6 +555,29 @@ expect "AC9: a limit lowered under garbage leaves the session usable" $'\n200000 "SELECT js_eval('delete globalThis.g; 0');" \ "SELECT js_set_memory_limit(4 * 1024 * 1024);" \ "SELECT js_eval('1 + 1');" +# A limit lowered above the memory in use collects too: the garbage would fill +# the room under the new limit. +expect "AC9: a limit lowered above garbage leaves room for what fits" $'\n200000\n0\n\n16777216' \ + "SELECT js_set_memory_limit(0);" \ + "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');" \ + "SELECT js_eval('delete globalThis.g; 0');" \ + "SELECT js_set_memory_limit(32 * 1024 * 1024);" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" +# QuickJS refuses an allocation too large to fit before it makes it, so the +# memory in use stays far from the limit. The garbage is collected after the +# "out of memory" error, and the next try succeeds. +name="AC9: garbage that leaves no room for a large allocation is collected after it fails" +got=$(sql_nobail \ + "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 40; i++) { const o = { b: new ArrayBuffer(1024 * 1024) }; o.o = o; g.push(o); } g.length');" \ + "SELECT js_eval('delete globalThis.g; 0');" \ + "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');" \ + "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');" 2>&1) +rc=$? +if [[ $rc -lt 128 && ${got##*$'\n'} == 31457280 ]]; then + ok "$name" +else + not_ok "$name" "exit status $rc" "want the last line: 31457280" "got: $got" +fi for bad in -1 1.5 "'64'" NULL; do expect_error "AC9: js_set_memory_limit($bad) is an SQL error" "The memory limit must be an integer number of bytes" \ "SELECT js_set_memory_limit($bad);" From 1d039e3435261ee8dde4248e055f9c8283532555 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 18:44:46 -0800 Subject: [PATCH 09/17] ADFA-7081: End the result sets that Ctrl-C leaves open SQLite keeps an interrupt in effect until no statement of the connection is running, and a db.exec result set that JavaScript keeps open is a running statement. In 1.4.1, Ctrl-C during code that keeps one, in a global say, left every later statement in the sqlite3 session failing with "interrupted" until it was restarted. CodeRabbit found it on the AAR's copy (CodeOnTheGo #2244). Patches 0003 and 0004, offered upstream as sqliteai/sqlite-js #24: when the outermost call into JavaScript returns on an interrupted connection, the result sets still open are finalized, and reading on from a kept one fails with "interrupted". 0004 makes that safe when finalizing runs a JavaScript window or aggregate function's final. The README says so. run-tests.sh's interactive Ctrl-C test is now a function, and a second case keeps a result set open: Ctrl-C, then SELECT 'still' || ' alive'. On a host build of this package, run-tests.sh passes 100 of 100, with AC12 skipped (no sqlite-brotli). With only patches 0001 and 0002, only the new test fails. Upstream's suite with the four patches passes 15 of 15, also under ASan and UBSan. The aarch64 and arm builds (NDK 29, build.sh's compile line) have no warnings in sqlitejs.c and export only the two entry points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...result-sets-an-interrupt-leaves-open.patch | 164 ++++++++++++++++++ ...ult-set-twice-when-finalizing-it-run.patch | 89 ++++++++++ packages/sqlite-js/README.md | 8 +- packages/sqlite-js/tests/run-tests.sh | 28 ++- 4 files changed, 277 insertions(+), 12 deletions(-) create mode 100644 packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch create mode 100644 packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch diff --git a/packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch b/packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch new file mode 100644 index 0000000..d27e2a0 --- /dev/null +++ b/packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch @@ -0,0 +1,164 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Thu, 12 Nov 2026 16:07:37 -0800 +Subject: [PATCH 3/4] End the result sets an interrupt leaves open + +SQLite keeps an interrupt in effect until no statement of the connection +is running, and a db.exec result set that JavaScript leaves open is a +running statement. One kept in a global, or garbage not yet collected, +made every later statement on the connection fail with "interrupted", +the JavaScript that could release it included, until the connection +closed. In the sqlite3 shell, Ctrl-C during + globalThis.held = db.exec("SELECT 1 UNION ALL SELECT 2"); held.next(); + while (true) {} +left the session unable to run anything. + +Each connection now lists its result sets. When the outermost call into +JavaScript returns on an interrupted connection, no result set is being +stepped, so the open ones are finalized there; one that JavaScript kept +then throws "interrupted" from next() and toArray(). The interrupt then +clears as usual once the interrupted statement ends. + +The Interrupt test now interrupts code that keeps a result set in a +global, and code whose result set is garbage, and checks that the +connection runs SQL afterwards and that the kept one throws. It fails +without this change. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + src/sqlitejs.c | 37 +++++++++++++++++++++++++++++++++---- + test/main.c | 14 ++++++++++++++ + 2 files changed, 47 insertions(+), 4 deletions(-) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index ce343b6..4b517a0 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -70,6 +70,7 @@ typedef struct { + size_t mem_peak; // the most in use since the last result or error + size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() + int depth; // calls into JavaScript in progress: see js_enter() ++ struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() + } globaljs_context; + + typedef struct { +@@ -106,9 +107,11 @@ static JSValue sqlite_value_to_js (JSContext *ctx, sqlite3_value *value); + + // MARK: - RowSet - + +-typedef struct { ++typedef struct rowset { + int ncols; + sqlite3_stmt *vm; ++ bool interrupted; // ended by js_end_rowsets(): reading on throws ++ struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() + } rowset; + + static void js_rowset_finalizer(JSRuntime *rt, JSValue val); +@@ -137,7 +140,7 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J + rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); + if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); + +- if (!rs->vm) return JS_FALSE; ++ if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_FALSE; + int rc = sqlite3_step(rs->vm); + if (rc == SQLITE_ROW) return JS_TRUE; + +@@ -189,7 +192,7 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg + globaljs_context *js = JS_GetContextOpaque(ctx); + rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); + if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); +- if (!rs->vm) return JS_NewArray(ctx); ++ if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_NewArray(ctx); + + JSValue result = JS_NewArray(ctx); + if (JS_IsException(result)) return JS_EXCEPTION; +@@ -231,10 +234,27 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + rowset *rs = (rowset *)JS_GetOpaque(val, js->rowSetClassID); + if (!rs) return; + ++ if (rs->prev) rs->prev->next = rs->next; ++ else if (js->rowsets == rs) js->rowsets = rs->next; ++ if (rs->next) rs->next->prev = rs->prev; + if (rs->vm) sqlite3_finalize(rs->vm); + sqlite3_free(rs); + } + ++// Ends every result set of the connection that is still open. SQLite keeps an interrupt in effect ++// until no statement of the connection is running, and an open result set is a running statement: ++// one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every ++// later statement fail with "interrupted" until the connection closed, the statements that could ++// release it included. Only to be called where none of them is being stepped: see js_leave(). ++static void js_end_rowsets (globaljs_context *js) { ++ for (rowset *rs = js->rowsets; rs; rs = rs->next) { ++ if (!rs->vm) continue; ++ sqlite3_finalize(rs->vm); ++ rs->vm = NULL; ++ rs->interrupted = true; ++ } ++} ++ + // MARK: - Initializer - + + // QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets +@@ -455,8 +475,11 @@ static void js_enter (globaljs_context *js) { + JS_SetMaxStackSize(js->runtime, size); + } + ++// Once the outermost call has returned, no result set is being stepped, so those an interrupt left ++// open are ended here: see js_end_rowsets(). + static void js_leave (globaljs_context *js) { +- js->depth--; ++ if (--js->depth > 0) return; ++ if ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)) js_end_rowsets(js); + } + + static globaljs_context *globaljs_init (sqlite3 *db) { +@@ -791,12 +814,18 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int + if (!rs) goto abort_with_dberror; + rs->vm = vm; + rs->ncols = sqlite3_column_count(vm); ++ rs->interrupted = false; ++ rs->prev = rs->next = NULL; + + // create Rowset JS object + globaljs_context *js = JS_GetContextOpaque(ctx); + JSValue obj = JS_NewObjectClass(ctx, js->rowSetClassID); + if (JS_IsException(obj)) goto abort_with_jserror; + JS_SetOpaque(obj, rs); ++ // listed once the object owns it, since its finalizer unlists it ++ rs->next = js->rowsets; ++ if (js->rowsets) js->rowsets->prev = rs; ++ js->rowsets = rs; + JS_SetPropertyStr(ctx, obj, "columnCount", JS_NewInt32(ctx, rs->ncols)); + + return obj; +diff --git a/test/main.c b/test/main.c +index 4145904..877b1a1 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -577,6 +577,20 @@ int test_interrupt (void) { + rc = test_interrupt_sql(db, "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');"); + if (rc != SQLITE_OK) goto abort_test; + ++ // A result set left open, kept in a global or garbage not yet collected, is a statement still ++ // running, and SQLite keeps an interrupt in effect until none is: every later statement on the ++ // connection failed. The interrupted call ends them, and the kept one then throws. ++ rc = test_interrupt_sql(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); while (true) {}');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT 1 + 2;", "3"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = test_interrupt_sql(db, "SELECT js_eval('(function () { const r = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); r.next(); while (true) {} })()');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT 1 + 2;", "3"); ++ if (rc != SQLITE_OK) goto abort_test; ++ + abort_test: + test_watchdog_stop = 1; + if (watching) pthread_join(watchdog, NULL); +-- +2.53.0 + diff --git a/packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch b/packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch new file mode 100644 index 0000000..c51669a --- /dev/null +++ b/packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch @@ -0,0 +1,89 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Thu, 12 Nov 2026 16:29:13 -0800 +Subject: [PATCH 4/4] Do not end a result set twice when finalizing it runs + JavaScript + +Finalizing a statement that is computing a window or aggregate function +runs the function's final, which for a JavaScript function calls +js_enter() and js_leave(). On an interrupted connection that js_leave() +ended the result sets again, before the first finalize had returned: the +same statement was finalized twice, a use after free under ASan, found +by CodeRabbit. Garbage collection while that JavaScript runs can also +free result sets of the list being walked. + +js_end_rowsets() now takes each statement from its result set before it +finalizes it, walks the list again from its head after each one, and +does nothing when called from within itself. The Interrupt test now also +interrupts code that keeps a result set computing a JavaScript window +function; without this change it is a use after free under ASan. The +suite passes 15 of 15, also under ASan and UBSan. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + src/sqlitejs.c | 17 ++++++++++++++--- + test/main.c | 8 ++++++++ + 2 files changed, 22 insertions(+), 3 deletions(-) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 4b517a0..1ba1b98 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -71,6 +71,7 @@ typedef struct { + size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() + int depth; // calls into JavaScript in progress: see js_enter() + struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() ++ bool ending_rowsets; // js_end_rowsets() is running + } globaljs_context; + + typedef struct { +@@ -246,13 +247,23 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + // one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every + // later statement fail with "interrupted" until the connection closed, the statements that could + // release it included. Only to be called where none of them is being stepped: see js_leave(). ++// Finalizing a statement can run JavaScript, the final of a window or aggregate function it was ++// computing, whose js_leave() comes back here and whose garbage collection can free result sets ++// of the list. So each statement is taken from its result set before it is finalized, the list ++// is walked again from its head after each one, and a nested call does nothing. + static void js_end_rowsets (globaljs_context *js) { +- for (rowset *rs = js->rowsets; rs; rs = rs->next) { +- if (!rs->vm) continue; +- sqlite3_finalize(rs->vm); ++ if (js->ending_rowsets) return; ++ js->ending_rowsets = true; ++ for (;;) { ++ rowset *rs = js->rowsets; ++ while (rs && !rs->vm) rs = rs->next; ++ if (!rs) break; ++ sqlite3_stmt *vm = rs->vm; + rs->vm = NULL; + rs->interrupted = true; ++ sqlite3_finalize(vm); + } ++ js->ending_rowsets = false; + } + + // MARK: - Initializer - +diff --git a/test/main.c b/test/main.c +index 877b1a1..302a97e 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -590,6 +590,14 @@ int test_interrupt (void) { + if (rc != SQLITE_OK) goto abort_test; + rc = check_query(db, "SELECT 1 + 2;", "3"); + if (rc != SQLITE_OK) goto abort_test; ++ // ending a result set that is computing a window function runs the function's final, which ++ // is JavaScript too: its end must not end the same result set again ++ rc = db_exec(db, "SELECT js_create_window('running_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = test_interrupt_sql(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT running_sum(column1) OVER (ORDER BY column1) FROM (VALUES (1), (2), (3))\"); held.next(); while (true) {}');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); ++ if (rc != SQLITE_OK) goto abort_test; + + abort_test: + test_watchdog_stop = 1; +-- +2.53.0 + diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index e2d4b68..a6ce991 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -3,7 +3,7 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is [sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.1, the first -release with nine changes of ours, plus two patches of ours, all listed +release with nine changes of ours, plus four patches of ours, all listed [below](#changes-in-this-build). The JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. @@ -173,7 +173,8 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. limit under it leaves no room for any JavaScript until it is raised again. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with an "interrupted" error, even if the code catches exceptions, and `sqlite3` - keeps running. + keeps running. A `db.exec` result set that the stopped code kept, in a + global say, is ended: reading on from it fails with "interrupted". - **Stack.** 1 MB by default, or less on a thread with less stack; `js_set_max_stack_size` changes it. Code that calls itself too deeply fails with "Maximum call stack size exceeded". @@ -210,12 +211,13 @@ Upstream released nine changes of ours in 1.4.0. Compared with 1.3.7: | #18 | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. In 1.3.7, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | | #19 | The stack check follows the thread each call runs on. In 1.3.7, JavaScript run on a thread other than the one that set up the connection fails at once, or crashes on endless recursion. | -This build adds two patches of ours, offered upstream: +This build adds four patches of ours, offered upstream: | Patch | Upstream PR | Change | |-------|-------------|--------| | 0001 | #22 | The stack check stays within the stack in two more cases. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | | 0002 | #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | +| 0003, 0004 | #24 | After an interrupt, the `db.exec` result sets the stopped code left open are ended, and reading on from one fails with "interrupted". In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 006da4f..4770242 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -453,14 +453,21 @@ expect_sigint_stops "AC8: SIGINT stops code that catches every exception" \ # In batch mode the shell exits after an interrupt, whatever stopped; only an # interactive session goes on. script(1) runs one on a pseudo-terminal, where # the byte 0x03 is Ctrl-C. -if command -v script >/dev/null 2>&1; then +# expect_ctrl_c_keeps_session NAME SQL: Ctrl-C a second after SQL starts must +# stop it, and the session must then run SQL. +expect_ctrl_c_keeps_session() { + local name=$1 sql=$2 cmd got started seconds + if ! command -v script >/dev/null 2>&1; then + skip "$name" "needs script(1), from the util-linux package" + return + fi cmd=$(printf '%q ' "$SQLITE3" -noheader -cmd "$LOAD_EXT" "$DB") # The shell also reports "interrupted" once the loop ends by itself, so the # session must end well before the loop's 20 s are up: about 5 s if Ctrl-C works. started=$SECONDS got=$({ sleep 1 - printf '%s\n' "SELECT js_eval('$RUNAWAY');" + printf '%s\n' "$sql" sleep 2 printf '\003' sleep 1 @@ -470,15 +477,18 @@ if command -v script >/dev/null 2>&1; then } | timeout -k 5 30 script -q -c "$cmd" /dev/null 2>&1 | tr -d '\r') seconds=$((SECONDS - started)) if [[ $got == *interrupted* && $got == *"still alive"* && $seconds -lt 15 ]]; then - ok "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" + ok "$name" else - not_ok "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ - "took $seconds s, want under 15" "got: $got" + not_ok "$name" "took $seconds s, want under 15" "got: $got" fi -else - skip "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ - "needs script(1), from the util-linux package" -fi +} +expect_ctrl_c_keeps_session "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ + "SELECT js_eval('$RUNAWAY');" +# A db.exec result set the stopped code keeps open is a statement still running, +# and SQLite keeps an interrupt in effect while one runs: every later statement +# in the session failed with "interrupted" (patches 0003 and 0004). +expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops code that keeps a result set open, sqlite3 still runs SQL" \ + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); $RUNAWAY');" # --- AC9: the memory limit ------------------------------------------------------ From 17d0af98f16a6c16d1d05c923897f6706a42b5ee Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 19:16:10 -0800 Subject: [PATCH 10/17] ADFA-7081: Say which result sets an interrupt ends, and when it cannot An interrupt ends every db.exec result set still open in the session, not only the stopped code's (independent review of the AAR's copy, CodeOnTheGo #2244). And Ctrl-C while no JavaScript runs, during plain SQL, leaves the session failing every statement while JavaScript keeps a result set open, since no JavaScript runs to end it: reproduced on SQLite 3.49, where SELECT 1 + 2 and js_eval() then fail with "interrupted". The README says so, and to finish result sets before the code returns. README only: the stage packages of 1.4.1 (CI run 43355418863) have the earlier wording. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index a6ce991..12bec77 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -173,8 +173,13 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. limit under it leaves no room for any JavaScript until it is raised again. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with an "interrupted" error, even if the code catches exceptions, and `sqlite3` - keeps running. A `db.exec` result set that the stopped code kept, in a - global say, is ended: reading on from it fails with "interrupted". + keeps running. Every `db.exec` result set still open in the session is + ended, including ones that earlier statements kept, and reading on from + one fails with "interrupted". Ctrl-C while no JavaScript runs, during + plain SQL, leaves the session failing every statement for as long as + JavaScript keeps a result set open, until `sqlite3` is restarted; so + finish each result set (`toArray()`, or `next()` until it returns + `false`) before your code returns. - **Stack.** 1 MB by default, or less on a thread with less stack; `js_set_max_stack_size` changes it. Code that calls itself too deeply fails with "Maximum call stack size exceeded". @@ -217,7 +222,7 @@ This build adds four patches of ours, offered upstream: |-------|-------------|--------| | 0001 | #22 | The stack check stays within the stack in two more cases. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | | 0002 | #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | -| 0003, 0004 | #24 | After an interrupt, the `db.exec` result sets the stopped code left open are ended, and reading on from one fails with "interrupted". In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | +| 0003, 0004 | #24 | After an interrupt, the `db.exec` result sets still open in the session are ended, and reading on from one fails with "interrupted". In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry From 86b48e5cca018ba7de51005deeae07cf9539a209 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 13 Nov 2026 10:01:36 -0800 Subject: [PATCH 11/17] ADFA-7081: Move to sqlite-js 1.4.2, which includes our four patches Upstream merged sqliteai/sqlite-js #22, #23 and #24 and released them in 1.4.2; the four patches have the same patch ids as upstream commits ac17d4f, 7776629, 28fa507 and 347ee9d, so they are dropped. The maintainer added two commits to #22: the main thread's stack is measured from the kernel's [stack] mapping, and with no stack limit (ulimit -s unlimited) js_set_max_stack_size allows at most 1 MB. 1.4.2 also has upstream's fix for our report #25 (#26): a db.exec result set ends when the call into JavaScript that created it returns, and reading it later throws "The result set was closed when the call into JavaScript that created it returned". So a result set kept in a global no longer keeps a statement open, and Ctrl-C during plain SQL no longer leaves the session failing every statement. run-tests.sh: AC2 expects 1.4.2; two new tests, one for each behaviour above. On the host (sqlite3 3.46.1) plain 1.4.2 passes 102 of 102; the 1.4.1 build with the old patches fails both new tests for the reasons they name. README: the release, the result-set rule, the stack limit, 1.4.2's changes, and no patches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...heck-within-the-stack-in-two-more-ca.patch | 110 ------------ ...after-any-out-of-memory-error-and-on.patch | 120 ------------- ...result-sets-an-interrupt-leaves-open.patch | 164 ------------------ ...ult-set-twice-when-finalizing-it-run.patch | 89 ---------- packages/sqlite-js/README.md | 45 +++-- packages/sqlite-js/build.sh | 11 +- packages/sqlite-js/tests/run-tests.sh | 19 +- 7 files changed, 46 insertions(+), 512 deletions(-) delete mode 100644 packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch delete mode 100644 packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch delete mode 100644 packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch delete mode 100644 packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch diff --git a/packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch b/packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch deleted file mode 100644 index 2b06490..0000000 --- a/packages/sqlite-js/0001-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch +++ /dev/null @@ -1,110 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 15:17:11 -0800 -Subject: [PATCH 1/2] Keep the stack check within the stack in two more cases - -On the initial thread on Linux, RLIMIT_STACK is now counted from the top -of the stack, as the kernel counts it, rather than from where the first -measurement was taken. Counted from there, a first measurement deep in -the stack put the bound below the real one by that depth: with the -extension loaded 2 MB deep on the main thread, js_set_max_stack_size() -allowed 10 MB of an 8 MB stack, and code that called itself without end -at that size crashed the process. - -A call into JavaScript on a thread with less room than -SQLITE_JS_STACK_MIN now keeps the measured room rather than the size -set for the connection, 1 MB by default: on a thread with a 64 KB stack, -code that called itself without end crashed. JavaScript there now fails -with "Maximum call stack size exceeded". The minimum still applies where -a runtime is created, since QuickJS cannot create a context in less. - -Stack on other threads now also runs forever() on a 64 KB thread. It -crashes without this change and passes with it, also under ASan and -UBSan, and the suite passes 16 of 16. The first case is checked by a -program that loads the extension deep in the main thread's stack: at 2 -and 6 MB deep, the largest size allowed was 10.2 and 14.4 MB of 8 MB -before, and about 7.75 MB after, where forever() stops with an error. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 17 ++++++++++++----- - test/main.c | 12 ++++++++++++ - 2 files changed, 24 insertions(+), 5 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 9137ca8..b0535f8 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -355,9 +355,10 @@ static void js_mem_reset_peak (globaljs_context *js) { - #endif - - // The least stack worth giving JavaScript. QuickJS cannot even create a context below about --// 16 KB (measured: 4 KB fails, 16 KB works), and it reads 0 as "no check at all", so a smaller --// measurement is treated as no measurement and leaves the default alone. Failing to catch --// runaway recursion is the lesser evil next to an extension that cannot load. -+// 16 KB (measured: 4 KB fails, 16 KB works), and it reads 0 as "no check at all", so where a -+// runtime is created a smaller measurement is treated as no measurement and leaves the default -+// alone. Failing to catch runaway recursion is the lesser evil next to an extension that cannot -+// load. A call into JavaScript on an existing runtime keeps any measurement (see js_enter). - #ifndef SQLITE_JS_STACK_MIN - #define SQLITE_JS_STACK_MIN (32 * 1024) - #endif -@@ -395,7 +396,10 @@ static bool js_stack_low (uintptr_t sp, uintptr_t *low) { - if (syscall(SYS_gettid) == (long)getpid()) { - struct rlimit limit; - if ((getrlimit(RLIMIT_STACK, &limit) == 0) && (limit.rlim_cur != RLIM_INFINITY)) { -- uintptr_t grows_to = (sp > (uintptr_t)limit.rlim_cur) ? sp - (uintptr_t)limit.rlim_cur : 0; -+ // counted from the top of the stack, as the kernel counts it: counted from sp, a first -+ // measurement deep in the stack would put the bound below the real one -+ uintptr_t high = (uintptr_t)addr + size; -+ uintptr_t grows_to = (high > (uintptr_t)limit.rlim_cur) ? high - (uintptr_t)limit.rlim_cur : 0; - if (grows_to < thread_low) thread_low = grows_to; - } - } -@@ -443,8 +447,11 @@ static bool js_stack_room (size_t *room) { - static void js_enter (globaljs_context *js) { - if (js->depth++ > 0) return; - JS_UpdateStackTop(js->runtime); -+ // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails -+ // with "Maximum call stack size exceeded" rather than running past the end of the stack. A -+ // size of 1 rather than 0, which would turn the check off. - size_t size = js->stack_size, room = 0; -- if ((size > 0) && js_stack_room(&room) && (room >= SQLITE_JS_STACK_MIN) && (room < size)) size = room; -+ if ((size > 0) && js_stack_room(&room) && (room < size)) size = (room > 0) ? room : 1; - JS_SetMaxStackSize(js->runtime, size); - } - -diff --git a/test/main.c b/test/main.c -index 0c8a47b..0240f3d 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -1022,6 +1022,13 @@ static void *stack_thread_run (void *ptr) { - return NULL; - } - -+// Runs forever() on the calling thread, which must stop with an error instead of crashing. -+static void *stack_thread_forever (void *ptr) { -+ stack_thread_args *args = (stack_thread_args *)ptr; -+ args->rc = check_error(args->db, "SELECT forever();", "Maximum call stack size exceeded"); -+ return NULL; -+} -+ - static void *stack_thread_open (void *ptr) { - stack_thread_args *args = (stack_thread_args *)ptr; - args->rc = test_open(&args->db); -@@ -1095,6 +1102,11 @@ int test_stack_threads (void) { - rc = args.rc; - if (rc != SQLITE_OK) goto abort_test; - -+ // and on a thread with less stack left than SQLITE_JS_STACK_MIN: the size is still lowered to -+ // fit, since the default would let code that calls itself without end run past the stack -+ rc = stack_thread(stack_thread_forever, &args, 64 * 1024); -+ if (rc != SQLITE_OK) goto abort_test; -+ - // a thread whose whole stack is under twice the margin still gets a usable runtime - rc = stack_thread(stack_thread_tiny, &args, 256 * 1024); - --- -2.53.0 - diff --git a/packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch b/packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch deleted file mode 100644 index 79787cb..0000000 --- a/packages/sqlite-js/0002-Collect-garbage-after-any-out-of-memory-error-and-on.patch +++ /dev/null @@ -1,120 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 15:32:30 -0800 -Subject: [PATCH 2/2] Collect garbage after any out-of-memory error and on any - new limit - -Garbage could leave a connection unable to make an allocation that fits -in its memory limit, on every try: - -- After an allocation too large to fit fails. QuickJS refuses it before - making it, so the memory in use never came within 64 KB of the limit - and the collection after the error did not run. With 40 MB of cyclic - garbage under the 64 MB default, new ArrayBuffer(30 MB) failed with - "out of memory" every time. The collection now also runs whenever the - error is "out of memory": the next try succeeds. -- After a lower limit set above the memory in use. Only a limit within - 64 KB of the memory in use collected. With the garbage of 200,000 - cyclic objects and the limit lowered to 32 MB, new ArrayBuffer(16 MB) - failed. Setting a limit now always collects. - -The Memory limit test covers both, each on a connection of its own; each -case fails without its change. The suite passes 16 of 16, also under -ASan and UBSan. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 18 +++++++++++------- - test/main.c | 32 ++++++++++++++++++++++++++++++++ - 2 files changed, 43 insertions(+), 7 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index b0535f8..ce343b6 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -932,7 +932,9 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - default_error = "out of memory"; - } - } -- bool out_of_memory = js_reached_memory_limit(JS_GetContextOpaque(js_ctx)); -+ // An allocation too large to fit is refused before it is counted, so the memory in use need -+ // not have come near the limit: the error itself says so. -+ bool out_of_memory = js_reached_memory_limit(JS_GetContextOpaque(js_ctx)) || (err_msg && (strcmp(err_msg, "out of memory") == 0)); - js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); - - // set a default error message and code -@@ -944,9 +946,9 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - if (!JS_IsNull(exception)) JS_FreeValue(js_ctx, exception); - - // QuickJS refuses every allocation once the memory in use is over the limit, and it collects -- // only when it creates an object, which it cannot do without allocating: the connection -- // would stay out of memory for good. No JavaScript is running here, so collect now, while -- // the garbage that filled the limit is still reachable from nothing. -+ // only when it creates an object past its threshold, which the code that failed may never -+ // do: the connection would stay out of memory for good. No JavaScript is running here, so -+ // collect now, while the garbage that filled the limit is still reachable from nothing. - if (out_of_memory) js_collect_below_limit(JS_GetContextOpaque(js_ctx)); - } - -@@ -1768,9 +1770,11 @@ void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **ar - js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; - JS_SetMemoryLimit(js->runtime, js->memory_limit); - js->gc_threshold = 0; // check the GC threshold against the new limit -- // a limit at or under the memory in use leaves nothing to allocate from, and QuickJS cannot -- // collect without allocating, so collect here instead -- if ((js->memory_limit > 0) && (js->mem_used + 64 * 1024 >= js->memory_limit)) js_collect_below_limit(js); -+ // Garbage left from before counts against the new limit, and QuickJS collects only when it -+ // creates an object past its threshold: a limit at or under the memory in use leaves nothing -+ // to allocate from, and one above it can leave too little for a large allocation. So collect -+ // here, as no JavaScript is running. -+ if (js->memory_limit > 0) js_collect_below_limit(js); - else js_keep_gc_below_limit(js); - js_mem_reset_peak(js); - } -diff --git a/test/main.c b/test/main.c -index 0240f3d..4145904 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -900,6 +900,38 @@ int test_memory_limit (void) { - rc = check_query(db, "SELECT js_eval('[1, 2, 3].map(x => x * 2).join()');", "2,4,6"); - if (rc != SQLITE_OK) goto abort_test; - -+ // and so does a lower limit set above it: the garbage would fill the room left under the new -+ // limit, and an allocation that needs that room would fail -+ if (db) sqlite3_close(db); -+ db = NULL; -+ rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_set_memory_limit(0);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');", "200000"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_eval('delete globalThis.g; 0');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_set_memory_limit(32 * 1024 * 1024);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');", "16777216"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // garbage that leaves no room for a large allocation is collected after it fails, so the next -+ // try succeeds: QuickJS refuses an allocation that would pass the limit before making it, so -+ // the memory in use never comes near the limit, and nothing else would collect the garbage -+ if (db) sqlite3_close(db); -+ db = NULL; -+ rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 40; i++) { const o = { b: new ArrayBuffer(1024 * 1024) }; o.o = o; g.push(o); } g.length');", "40"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_eval('delete globalThis.g; 0');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ sqlite3_exec(db, "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');", NULL, NULL, NULL); // may fail -+ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');", "31457280"); -+ if (rc != SQLITE_OK) goto abort_test; -+ - // running out of memory through many small allocations, which leaves no room for the error - // object, is reported as "out of memory" too - rc = check_error(db, "SELECT js_eval('(function () { let h = null; for (;;) h = {n: h}; })()');", "out of memory"); --- -2.53.0 - diff --git a/packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch b/packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch deleted file mode 100644 index d27e2a0..0000000 --- a/packages/sqlite-js/0003-End-the-result-sets-an-interrupt-leaves-open.patch +++ /dev/null @@ -1,164 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 16:07:37 -0800 -Subject: [PATCH 3/4] End the result sets an interrupt leaves open - -SQLite keeps an interrupt in effect until no statement of the connection -is running, and a db.exec result set that JavaScript leaves open is a -running statement. One kept in a global, or garbage not yet collected, -made every later statement on the connection fail with "interrupted", -the JavaScript that could release it included, until the connection -closed. In the sqlite3 shell, Ctrl-C during - globalThis.held = db.exec("SELECT 1 UNION ALL SELECT 2"); held.next(); - while (true) {} -left the session unable to run anything. - -Each connection now lists its result sets. When the outermost call into -JavaScript returns on an interrupted connection, no result set is being -stepped, so the open ones are finalized there; one that JavaScript kept -then throws "interrupted" from next() and toArray(). The interrupt then -clears as usual once the interrupted statement ends. - -The Interrupt test now interrupts code that keeps a result set in a -global, and code whose result set is garbage, and checks that the -connection runs SQL afterwards and that the kept one throws. It fails -without this change. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 37 +++++++++++++++++++++++++++++++++---- - test/main.c | 14 ++++++++++++++ - 2 files changed, 47 insertions(+), 4 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index ce343b6..4b517a0 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -70,6 +70,7 @@ typedef struct { - size_t mem_peak; // the most in use since the last result or error - size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() - int depth; // calls into JavaScript in progress: see js_enter() -+ struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - } globaljs_context; - - typedef struct { -@@ -106,9 +107,11 @@ static JSValue sqlite_value_to_js (JSContext *ctx, sqlite3_value *value); - - // MARK: - RowSet - - --typedef struct { -+typedef struct rowset { - int ncols; - sqlite3_stmt *vm; -+ bool interrupted; // ended by js_end_rowsets(): reading on throws -+ struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() - } rowset; - - static void js_rowset_finalizer(JSRuntime *rt, JSValue val); -@@ -137,7 +140,7 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J - rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); - if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); - -- if (!rs->vm) return JS_FALSE; -+ if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_FALSE; - int rc = sqlite3_step(rs->vm); - if (rc == SQLITE_ROW) return JS_TRUE; - -@@ -189,7 +192,7 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg - globaljs_context *js = JS_GetContextOpaque(ctx); - rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); - if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); -- if (!rs->vm) return JS_NewArray(ctx); -+ if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_NewArray(ctx); - - JSValue result = JS_NewArray(ctx); - if (JS_IsException(result)) return JS_EXCEPTION; -@@ -231,10 +234,27 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - rowset *rs = (rowset *)JS_GetOpaque(val, js->rowSetClassID); - if (!rs) return; - -+ if (rs->prev) rs->prev->next = rs->next; -+ else if (js->rowsets == rs) js->rowsets = rs->next; -+ if (rs->next) rs->next->prev = rs->prev; - if (rs->vm) sqlite3_finalize(rs->vm); - sqlite3_free(rs); - } - -+// Ends every result set of the connection that is still open. SQLite keeps an interrupt in effect -+// until no statement of the connection is running, and an open result set is a running statement: -+// one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every -+// later statement fail with "interrupted" until the connection closed, the statements that could -+// release it included. Only to be called where none of them is being stepped: see js_leave(). -+static void js_end_rowsets (globaljs_context *js) { -+ for (rowset *rs = js->rowsets; rs; rs = rs->next) { -+ if (!rs->vm) continue; -+ sqlite3_finalize(rs->vm); -+ rs->vm = NULL; -+ rs->interrupted = true; -+ } -+} -+ - // MARK: - Initializer - - - // QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets -@@ -455,8 +475,11 @@ static void js_enter (globaljs_context *js) { - JS_SetMaxStackSize(js->runtime, size); - } - -+// Once the outermost call has returned, no result set is being stepped, so those an interrupt left -+// open are ended here: see js_end_rowsets(). - static void js_leave (globaljs_context *js) { -- js->depth--; -+ if (--js->depth > 0) return; -+ if ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)) js_end_rowsets(js); - } - - static globaljs_context *globaljs_init (sqlite3 *db) { -@@ -791,12 +814,18 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int - if (!rs) goto abort_with_dberror; - rs->vm = vm; - rs->ncols = sqlite3_column_count(vm); -+ rs->interrupted = false; -+ rs->prev = rs->next = NULL; - - // create Rowset JS object - globaljs_context *js = JS_GetContextOpaque(ctx); - JSValue obj = JS_NewObjectClass(ctx, js->rowSetClassID); - if (JS_IsException(obj)) goto abort_with_jserror; - JS_SetOpaque(obj, rs); -+ // listed once the object owns it, since its finalizer unlists it -+ rs->next = js->rowsets; -+ if (js->rowsets) js->rowsets->prev = rs; -+ js->rowsets = rs; - JS_SetPropertyStr(ctx, obj, "columnCount", JS_NewInt32(ctx, rs->ncols)); - - return obj; -diff --git a/test/main.c b/test/main.c -index 4145904..877b1a1 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -577,6 +577,20 @@ int test_interrupt (void) { - rc = test_interrupt_sql(db, "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');"); - if (rc != SQLITE_OK) goto abort_test; - -+ // A result set left open, kept in a global or garbage not yet collected, is a statement still -+ // running, and SQLite keeps an interrupt in effect until none is: every later statement on the -+ // connection failed. The interrupted call ends them, and the kept one then throws. -+ rc = test_interrupt_sql(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); while (true) {}');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT 1 + 2;", "3"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = test_interrupt_sql(db, "SELECT js_eval('(function () { const r = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); r.next(); while (true) {} })()');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT 1 + 2;", "3"); -+ if (rc != SQLITE_OK) goto abort_test; -+ - abort_test: - test_watchdog_stop = 1; - if (watching) pthread_join(watchdog, NULL); --- -2.53.0 - diff --git a/packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch b/packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch deleted file mode 100644 index c51669a..0000000 --- a/packages/sqlite-js/0004-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch +++ /dev/null @@ -1,89 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 16:29:13 -0800 -Subject: [PATCH 4/4] Do not end a result set twice when finalizing it runs - JavaScript - -Finalizing a statement that is computing a window or aggregate function -runs the function's final, which for a JavaScript function calls -js_enter() and js_leave(). On an interrupted connection that js_leave() -ended the result sets again, before the first finalize had returned: the -same statement was finalized twice, a use after free under ASan, found -by CodeRabbit. Garbage collection while that JavaScript runs can also -free result sets of the list being walked. - -js_end_rowsets() now takes each statement from its result set before it -finalizes it, walks the list again from its head after each one, and -does nothing when called from within itself. The Interrupt test now also -interrupts code that keeps a result set computing a JavaScript window -function; without this change it is a use after free under ASan. The -suite passes 15 of 15, also under ASan and UBSan. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 17 ++++++++++++++--- - test/main.c | 8 ++++++++ - 2 files changed, 22 insertions(+), 3 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 4b517a0..1ba1b98 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -71,6 +71,7 @@ typedef struct { - size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() - int depth; // calls into JavaScript in progress: see js_enter() - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() -+ bool ending_rowsets; // js_end_rowsets() is running - } globaljs_context; - - typedef struct { -@@ -246,13 +247,23 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - // one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every - // later statement fail with "interrupted" until the connection closed, the statements that could - // release it included. Only to be called where none of them is being stepped: see js_leave(). -+// Finalizing a statement can run JavaScript, the final of a window or aggregate function it was -+// computing, whose js_leave() comes back here and whose garbage collection can free result sets -+// of the list. So each statement is taken from its result set before it is finalized, the list -+// is walked again from its head after each one, and a nested call does nothing. - static void js_end_rowsets (globaljs_context *js) { -- for (rowset *rs = js->rowsets; rs; rs = rs->next) { -- if (!rs->vm) continue; -- sqlite3_finalize(rs->vm); -+ if (js->ending_rowsets) return; -+ js->ending_rowsets = true; -+ for (;;) { -+ rowset *rs = js->rowsets; -+ while (rs && !rs->vm) rs = rs->next; -+ if (!rs) break; -+ sqlite3_stmt *vm = rs->vm; - rs->vm = NULL; - rs->interrupted = true; -+ sqlite3_finalize(vm); - } -+ js->ending_rowsets = false; - } - - // MARK: - Initializer - -diff --git a/test/main.c b/test/main.c -index 877b1a1..302a97e 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -590,6 +590,14 @@ int test_interrupt (void) { - if (rc != SQLITE_OK) goto abort_test; - rc = check_query(db, "SELECT 1 + 2;", "3"); - if (rc != SQLITE_OK) goto abort_test; -+ // ending a result set that is computing a window function runs the function's final, which -+ // is JavaScript too: its end must not end the same result set again -+ rc = db_exec(db, "SELECT js_create_window('running_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = test_interrupt_sql(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT running_sum(column1) OVER (ORDER BY column1) FROM (VALUES (1), (2), (3))\"); held.next(); while (true) {}');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); -+ if (rc != SQLITE_OK) goto abort_test; - - abort_test: - test_watchdog_stop = 1; --- -2.53.0 - diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index 12bec77..a44a9bf 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -2,9 +2,8 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is -[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.1, the first -release with nine changes of ours, plus four patches of ours, all listed -[below](#changes-in-this-build). The JavaScript engine, +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.2, which +includes twelve changes of ours, listed [below](#changes-in-this-build). The JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. ## Load it @@ -91,7 +90,10 @@ SELECT js_eval('(function () { `db.exec` returns a result set, and the statement runs as `next()` or `toArray()` steps it, so call `next()` once to run an `INSERT` or another statement that returns no rows. An SQL error, while the statement is prepared -or while it runs, is a JavaScript exception. +or while it runs, is a JavaScript exception. A result set lasts until the call +into JavaScript that created it returns: one kept in a global and read by a +later call throws "The result set was closed when the call into JavaScript that +created it returned". ## Functions @@ -173,16 +175,12 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. limit under it leaves no room for any JavaScript until it is raised again. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with an "interrupted" error, even if the code catches exceptions, and `sqlite3` - keeps running. Every `db.exec` result set still open in the session is - ended, including ones that earlier statements kept, and reading on from - one fails with "interrupted". Ctrl-C while no JavaScript runs, during - plain SQL, leaves the session failing every statement for as long as - JavaScript keeps a result set open, until `sqlite3` is restarted; so - finish each result set (`toArray()`, or `next()` until it returns - `false`) before your code returns. + keeps running. - **Stack.** 1 MB by default, or less on a thread with less stack; - `js_set_max_stack_size` changes it. Code that calls itself too deeply fails - with "Maximum call stack size exceeded". + `js_set_max_stack_size` changes it, up to what the stack allows. With no + stack limit (`ulimit -s unlimited`) that is 1 MB, since there is no size to + measure. Code that calls itself too deeply fails with "Maximum call stack + size exceeded". - **Collations that fail.** A collation that throws an exception, or runs out of memory, compares the two strings as equal. `ORDER BY` then returns a wrong order rather than an error, so keep collation code simple. @@ -216,13 +214,22 @@ Upstream released nine changes of ours in 1.4.0. Compared with 1.3.7: | #18 | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. In 1.3.7, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | | #19 | The stack check follows the thread each call runs on. In 1.3.7, JavaScript run on a thread other than the one that set up the connection fails at once, or crashes on endless recursion. | -This build adds four patches of ours, offered upstream: +Upstream released three more in 1.4.2, compared with 1.4.1: -| Patch | Upstream PR | Change | -|-------|-------------|--------| -| 0001 | #22 | The stack check stays within the stack in two more cases. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | -| 0002 | #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | -| 0003, 0004 | #24 | After an interrupt, the `db.exec` result sets still open in the session are ended, and reading on from one fails with "interrupted". In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | +| Upstream PR | Change | +|-------------|--------| +| #22 | The stack check stays within the stack in two more cases, and upstream added a third: the main thread's stack is measured from the top the kernel counts from. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | +| #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | +| #24 | After an interrupt, the `db.exec` result sets still open in the session are ended. In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | + +Upstream's own fix for a crash we reported (#25), also in 1.4.2, ends every +`db.exec` result set when the call into JavaScript that created it returns. In +1.4.1, freeing a result set that was part-way through a JavaScript window +function could crash `sqlite3`, and a result set kept in a global kept a +statement open: Ctrl-C during plain SQL then left every later statement +failing with "interrupted". + +This build carries no patches. The build also exports only the extension's entry points, and adds the one SQLite derives from the file name, so that `.load sqlite-js` needs no entry diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 10b7106..74d22a9 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -3,13 +3,12 @@ TERMUX_PKG_DESCRIPTION="SQLite extension for functions written in JavaScript" TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" -TERMUX_PKG_VERSION=1.4.1 +TERMUX_PKG_VERSION=1.4.2 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz -TERMUX_PKG_SHA256=d45d394fc7cb37070a64fa248994c7fef7c10cff31541eb57608405753fc3078 -# Upstream released our earlier changes (sqliteai/sqlite-js #11 to #19) in -# 1.4.0. The *.patch files are ours (ADFA-7081) and offered upstream as #22 and -# #23; check each one against a new upstream version, and drop those upstream -# has merged. +TERMUX_PKG_SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 +# Upstream released our changes (sqliteai/sqlite-js #11 to #19) in 1.4.0, and +# #22 to #24 in 1.4.2, so this build carries no patches. Patches of ours would +# go here as *.patch files, each offered upstream first. TERMUX_PKG_BUILD_DEPENDS="libsqlite" TERMUX_PKG_RECOMMENDS="sqlite" TERMUX_PKG_BUILD_IN_SRC=true diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 4770242..6a05687 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -234,7 +234,7 @@ expect "loading the extension twice in one session is harmless" "2" \ # --- AC2: the engine is quickjs-ng -------------------------------------------- -expect "AC2: js_version() is the sqlite-js version, 1.4.1" "1.4.1" "SELECT js_version();" +expect "AC2: js_version() is the sqlite-js version, 1.4.2" "1.4.2" "SELECT js_version();" got=$(sql "SELECT js_version(1);" 2>&1) # Bellard's QuickJS has no version function, so sqlite-js does not build with it. if [[ $got =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then @@ -484,11 +484,16 @@ expect_ctrl_c_keeps_session() { } expect_ctrl_c_keeps_session "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ "SELECT js_eval('$RUNAWAY');" -# A db.exec result set the stopped code keeps open is a statement still running, -# and SQLite keeps an interrupt in effect while one runs: every later statement -# in the session failed with "interrupted" (patches 0003 and 0004). +# A db.exec result set left open is a statement still running, and SQLite keeps +# an interrupt in effect while one runs. In 1.4.1 a result set kept in a global +# stayed open, so after Ctrl-C, during the code or during plain SQL later, every +# statement in the session failed with "interrupted". From 1.4.2 the result set +# ends when the call that created it returns. expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops code that keeps a result set open, sqlite3 still runs SQL" \ "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); $RUNAWAY');" +expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops plain SQL, run after code kept a result set, sqlite3 still runs SQL" \ + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); 0'); +WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 2000000000) SELECT count(*) FROM c;" # --- AC9: the memory limit ------------------------------------------------------ @@ -718,6 +723,12 @@ expect "AC14: a statement runs only when stepped, and the end of the rows is fal "$EXEC_SETUP" "SELECT js_eval('db.exec(\"INSERT INTO ac14 VALUES (3)\"); 0');" \ "SELECT js_eval('[db.exec(\"SELECT 1 WHERE 0\").next(), db.exec(\"INSERT INTO ac14 VALUES (2)\").next()].join(\" \")');" \ "SELECT group_concat(a) FROM (SELECT a FROM ac14 ORDER BY a);" +# A result set ends when the call into JavaScript that created it returns, so +# one kept in a global throws when a later call reads it. +expect_error "AC14: a result set kept in a global throws when a later call reads it" \ + "closed when the call into JavaScript that created it returned" \ + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); 0');" \ + "SELECT js_eval('held.next()');" echo "1..$n" if [[ $failed -ne 0 ]]; then From 70f264305d7d1d2f346c377be85fb2c6353b36ac Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 20:13:03 -0800 Subject: [PATCH 12/17] ADFA-7081: Test the 1 MB stack cap, and say what a kept result set does From the independent review of 86b48e5 (nothing blocking; three low findings, three nits), and the review of the ADFA-7083 pages: - README: a result set made in a call that SQL in another call's db.exec ran lasts until the outer call returns. Read later, it throws "interrupted" if Ctrl-C stopped its call, and one whose next() returned false or whose toArray() ran just reports no more rows (F01). #24's row again says reading on fails with "interrupted". - README: four tests need other packages, not two (F02); #22's row names both of upstream's additions (F04); a long line rewrapped (F05). - run-tests.sh: AC13 checks that with no stack limit sizes above 1 MB are refused, as the README says, and skips where `ulimit -s unlimited` is not allowed (F03). Corrections to 86b48e5's message (F06): the maintainer's two commits on #22 are bd3d6c4, which skips upstream's 64 KB-thread test where the platform has no stack that small, and 31ed714, which has both changes named there; and of its "102 of 102", one test (AC12) was skipped. On the host (sqlite3 3.46.1, no sqlite-brotli): 1.4.2 passes 103 of 103 with AC12 skipped; the 1.4.1 build fails the new AC13 test, AC2 and the two tests 86b48e5 added, each for the reason it names. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/README.md | 28 +++++++++++++++------------ packages/sqlite-js/tests/run-tests.sh | 12 ++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index a44a9bf..fe8e423 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -3,8 +3,9 @@ A SQLite loadable extension for writing SQL functions in JavaScript: scalar functions, aggregates, window functions and collations (ADFA-7081). It is [sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.2, which -includes twelve changes of ours, listed [below](#changes-in-this-build). The JavaScript engine, -[quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, is built in. +includes twelve changes of ours, listed [below](#changes-in-this-build). The +JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, +is built in. ## Load it @@ -91,9 +92,12 @@ SELECT js_eval('(function () { `toArray()` steps it, so call `next()` once to run an `INSERT` or another statement that returns no rows. An SQL error, while the statement is prepared or while it runs, is a JavaScript exception. A result set lasts until the call -into JavaScript that created it returns: one kept in a global and read by a -later call throws "The result set was closed when the call into JavaScript that -created it returned". +into JavaScript that created it returns, or until the outer call returns when +SQL that the outer call ran with `db.exec` made that call. One kept in a global +and read by a later call throws "The result set was closed when the call into +JavaScript that created it returned", or "interrupted" if Ctrl-C stopped the +call; one whose `next()` returned `false`, or whose `toArray()` ran, just +reports no more rows. ## Functions @@ -218,9 +222,9 @@ Upstream released three more in 1.4.2, compared with 1.4.1: | Upstream PR | Change | |-------------|--------| -| #22 | The stack check stays within the stack in two more cases, and upstream added a third: the main thread's stack is measured from the top the kernel counts from. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | +| #22 | The stack check stays within the stack in two more cases, and upstream added two more: the main thread's stack is measured from the top the kernel counts from, and with no stack limit (`ulimit -s unlimited`) at most 1 MB is allowed. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | | #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | -| #24 | After an interrupt, the `db.exec` result sets still open in the session are ended. In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | +| #24 | After an interrupt, the `db.exec` result sets still open in the session are ended, and reading on from one fails with "interrupted". In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | Upstream's own fix for a crash we reported (#25), also in 1.4.2, ends every `db.exec` result set when the call into JavaScript that created it returns. In @@ -241,11 +245,11 @@ point argument. $ bash $PREFIX/share/sqlite-js/run-tests.sh ``` -They print TAP and exit 0 only if every test passes. Two tests need other -packages and are skipped without them: `sqlite-brotli`, to check that both -extensions load together, and `util-linux`, whose `script` drives an -interactive `sqlite3` to check that Ctrl-C leaves it running. The last line -says how many were skipped. +They print TAP and exit 0 only if every test passes. Four tests need other +packages and are skipped without them: one needs `sqlite-brotli`, to check that +both extensions load together, and three need `util-linux`, whose `script` +drives an interactive `sqlite3` to check that Ctrl-C leaves it running. The +last line says how many were skipped. ## License diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 6a05687..2631c3d 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -699,6 +699,18 @@ else not_ok "AC13: the error names the largest size" "got: $most" fi +# With no stack limit there is no size to measure, so at most 1 MB is allowed +# (1.4.2). Skipped where the limit cannot be raised. +if got=$(ulimit -s unlimited 2>/dev/null && sql "SELECT js_set_max_stack_size(2097152);" 2>&1); then + not_ok "AC13: with no stack limit, sizes above 1 MB are refused" "got: $got" +elif [[ $got =~ "from 1 to 1048576," ]]; then + ok "AC13: with no stack limit, sizes above 1 MB are refused" +elif ! (ulimit -s unlimited 2>/dev/null); then + skip "AC13: with no stack limit, sizes above 1 MB are refused" "ulimit -s unlimited is not allowed here" +else + not_ok "AC13: with no stack limit, sizes above 1 MB are refused" "want: from 1 to 1048576" "got: $got" +fi + # On a thread with less stack than the 1 MB default, the default shrinks. got=$(ulimit -s 512 && sql "$RECURSE" 2>&1) rc=$? From f882b355f86bd8c8b73319c7cf77050b813b62dd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 20:22:26 -0800 Subject: [PATCH 13/17] ADFA-7081: Release sqlite-js 1.4.2-1 with the new tests and README 70f2643 changed run-tests.sh and the README, which the package installs, but not the version, so apt on a phone with 1.4.2 would keep the old files. Revision 1 makes it 1.4.2-1, which dpkg sorts above 1.4.2. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/build.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 74d22a9..81e347d 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,6 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.4.2 +TERMUX_PKG_REVISION=1 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 # Upstream released our changes (sqliteai/sqlite-js #11 to #19) in 1.4.0, and From c21aeb969fffd4c9f84a1f75d72ad1c66f1239b1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 02:54:38 -0800 Subject: [PATCH 14/17] ADFA-7081: Answer the review of 1.4.2-1 From review 5918442139 of f882b35 (MINOR and NITPICK only): - Ctrl-C tests: expect_sigint_stops slept 1 s and expect_ctrl_c_keeps_session 2 s before the signal, so on a slow start it could arrive before the runaway statement ran and be lost. Each runaway statement now creates the file "started" as it begins (WHERE writefile('started', '') IS NOT NULL), and the helpers wait for it, up to 10 s. The file is made inside the statement because SQLite drops an interrupt that arrives between statements. - The plain-SQL runaway counted to 2,000,000,000, minutes past the 20 s cap the other runaways keep; it counts to 200,000,000 (about 18 s on the host). - AC4 "stores the new code" checked only the session that redefined the function. A new test loads js_functions in a fresh session (js_init_table(1)) and expects the new code's result. - README: sqlite3 keeps running after Ctrl-C only in an interactive session; from a file or arguments it exits. The repository README no longer says the package has patches. - AC10: the view block's comment says what it checks. Host (sqlite3 3.46.1): 104 tests, all pass but AC12, skipped (no sqlite-brotli); 103 before. The SIGINT tests now take 0.2 s, not 1.2. With a sqlite3 wrapper that starts 4 s late, all six AC8 tests failed before and pass now. Against a js_functions row that kept the old code, the new AC4 test fails (42, not 63). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- README.md | 2 +- packages/sqlite-js/README.md | 5 +-- packages/sqlite-js/tests/run-tests.sh | 52 ++++++++++++++++++--------- 3 files changed, 39 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 1f9dee5..06e133e 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Packages that are not in `termux-packages` live in `packages//`, laid out | Package | What it is | |---------|------------| | `sqlite-brotli` | SQLite extension adding `encodeBrotli()` and `decodeBrotli()`. See [its README](packages/sqlite-brotli/README.md). | -| `sqlite-js` | SQLite extension for SQL functions written in JavaScript: [sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) with our patches. See [its README](packages/sqlite-js/README.md). | +| `sqlite-js` | SQLite extension for SQL functions written in JavaScript: [sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.2, which includes our changes. See [its README](packages/sqlite-js/README.md). | The key specified with the `-s` option is the **public key** (**NOT** the private key!), which can be generated using : diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md index fe8e423..933ed1d 100644 --- a/packages/sqlite-js/README.md +++ b/packages/sqlite-js/README.md @@ -178,8 +178,9 @@ it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. globals still hold counts against the limit until they are cleared, so a limit under it leaves no room for any JavaScript until it is raised again. - **Endless code.** Ctrl-C stops running JavaScript: the statement fails with - an "interrupted" error, even if the code catches exceptions, and `sqlite3` - keeps running. + an "interrupted" error, even if the code catches exceptions. In an + interactive session `sqlite3` keeps running; with SQL from a file or from + arguments it exits. - **Stack.** 1 MB by default, or less on a thread with less stack; `js_set_max_stack_size` changes it, up to what the stack allows. With no stack limit (`ulimit -s unlimited`) that is 1 MB, since there is no size to diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 2631c3d..0216186 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -190,15 +190,24 @@ expect_nobail() { fi } -# Starts the SQL in the background, sends SIGINT, as Ctrl-C does, after a -# second, and expects the statement to fail as interrupted within 5 seconds. -# sqlite3 is started directly, not through sql(), so that $! is its process. +# Starts the SQL in the background, sends SIGINT, as Ctrl-C does, once the +# runaway statement has started, and expects the statement to fail as +# interrupted within 5 seconds. The statement must be one that creates the file +# "started" as it begins, with WHERE $STARTED: SQLite drops an interrupt that +# arrives while no statement runs, so the signal must not come before it, or +# between two statements. sqlite3 is started directly, not through sql(), so +# that $! is its process. +STARTED="writefile('started', '') IS NOT NULL" expect_sigint_stops() { local name=$1 pid i rc got shift + rm -f started "$SQLITE3" -bail -batch -noheader -cmd "$LOAD_EXT" "$DB" "$@" >sigint.out 2>&1 & pid=$! - sleep 1 + for ((i = 0; i < 100; i++)); do + [[ -e started ]] && break + sleep 0.1 + done kill -INT "$pid" 2>/dev/null for ((i = 0; i < 50; i++)); do kill -0 "$pid" 2>/dev/null || break @@ -331,9 +340,12 @@ expect_error "AC4: a function cannot be redefined in the session that created it "Function updates must be performed using a separate database connection" \ "SELECT js_init_table(1);" \ "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 3; })');" -expect "AC4: a new session can redefine it, and stores the new code" $'0\n63' \ +expect "AC4: a new session can redefine it" $'0\n63' \ "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 3; })');" \ "SELECT twice(21);" +expect "AC4: and stores the new code, which the next new session loads" $'0\n63' \ + "SELECT js_init_table(1);" \ + "SELECT twice(21);" DB=$WORK/test.db # --- AC5: JavaScript errors are SQL errors ----------------------------------- @@ -444,19 +456,20 @@ DB=$WORK/test.db # behind: timeout(1) below can stop script(1), but not the sqlite3 it runs. RUNAWAY='for (const end = Date.now() + 20000; Date.now() < end;) {}' expect_sigint_stops "AC8: SIGINT (Ctrl-C) stops a runaway loop in js_eval" \ - "SELECT js_eval('$RUNAWAY');" + "SELECT js_eval('$RUNAWAY') WHERE $STARTED;" expect_sigint_stops "AC8: SIGINT stops a runaway scalar function" \ - "SELECT js_create_scalar('forever', '(function (args) { $RUNAWAY })');" "SELECT forever(1);" + "SELECT js_create_scalar('forever', '(function (args) { $RUNAWAY })');" "SELECT forever(1) WHERE $STARTED;" expect_sigint_stops "AC8: SIGINT stops code that catches every exception" \ - "SELECT js_eval('for (const end = Date.now() + 20000; Date.now() < end;) { try { while (Date.now() < end) {} } catch (e) {} }');" + "SELECT js_eval('for (const end = Date.now() + 20000; Date.now() < end;) { try { while (Date.now() < end) {} } catch (e) {} }') WHERE $STARTED;" # In batch mode the shell exits after an interrupt, whatever stopped; only an # interactive session goes on. script(1) runs one on a pseudo-terminal, where # the byte 0x03 is Ctrl-C. -# expect_ctrl_c_keeps_session NAME SQL: Ctrl-C a second after SQL starts must -# stop it, and the session must then run SQL. +# expect_ctrl_c_keeps_session NAME SQL: Ctrl-C once SQL has started, which it +# signals by creating the file "started" (see expect_sigint_stops), must stop +# it, and the session must then run SQL. expect_ctrl_c_keeps_session() { - local name=$1 sql=$2 cmd got started seconds + local name=$1 sql=$2 cmd got started seconds i if ! command -v script >/dev/null 2>&1; then skip "$name" "needs script(1), from the util-linux package" return @@ -464,11 +477,15 @@ expect_ctrl_c_keeps_session() { cmd=$(printf '%q ' "$SQLITE3" -noheader -cmd "$LOAD_EXT" "$DB") # The shell also reports "interrupted" once the loop ends by itself, so the # session must end well before the loop's 20 s are up: about 5 s if Ctrl-C works. + rm -f started started=$SECONDS got=$({ sleep 1 printf '%s\n' "$sql" - sleep 2 + for ((i = 0; i < 100; i++)); do + [[ -e started ]] && break + sleep 0.1 + done printf '\003' sleep 1 printf '%s\n' "SELECT 'still' || ' alive';" @@ -483,17 +500,17 @@ expect_ctrl_c_keeps_session() { fi } expect_ctrl_c_keeps_session "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ - "SELECT js_eval('$RUNAWAY');" + "SELECT js_eval('$RUNAWAY') WHERE $STARTED;" # A db.exec result set left open is a statement still running, and SQLite keeps # an interrupt in effect while one runs. In 1.4.1 a result set kept in a global # stayed open, so after Ctrl-C, during the code or during plain SQL later, every # statement in the session failed with "interrupted". From 1.4.2 the result set # ends when the call that created it returns. expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops code that keeps a result set open, sqlite3 still runs SQL" \ - "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); $RUNAWAY');" + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); $RUNAWAY') WHERE $STARTED;" expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops plain SQL, run after code kept a result set, sqlite3 still runs SQL" \ "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); 0'); -WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 2000000000) SELECT count(*) FROM c;" +WITH RECURSIVE c(x) AS (SELECT 1 + writefile('started', '') UNION ALL SELECT x + 1 FROM c WHERE x < 200000000) SELECT count(*) FROM c;" # --- AC9: the memory limit ------------------------------------------------------ @@ -628,8 +645,9 @@ expect "AC10: every js_* function but js_version is SQLITE_DIRECTONLY" "13|0" \ # TEMP view can call js_eval, as the README says. expect "AC10: a TEMP view can call js_eval" "42" \ "CREATE TEMP VIEW v_temp AS SELECT js_eval('6 * 7') AS x;" "SELECT x FROM v_temp;" -# The view is in the database file: SQLite trusts the TEMP schema, which only -# the session itself can fill. +# This view is in the database file, which anyone can fill. It uses twice(), a +# function js_create_scalar defines for the session, and SQLite only lets a view +# use such a function when trusted_schema is ON; sqlite3 turns it off. DB=$WORK/views.db "$SQLITE3" -bail -batch "$DB" "CREATE VIEW v_twice AS SELECT twice(21) AS x;" || not_ok "AC10: create a view that uses a function made with js_create_scalar" From 39a35c73bd9d4f01597cf0329b94edc54c502975 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 02:54:38 -0800 Subject: [PATCH 15/17] ADFA-7081: Release sqlite-js 1.4.2-2 with the review's test fixes The package installs run-tests.sh and the README, which the previous commit changed, so the revision goes up for apt to install them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 81e347d..4358936 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,7 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.4.2 -TERMUX_PKG_REVISION=1 +TERMUX_PKG_REVISION=2 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 # Upstream released our changes (sqliteai/sqlite-js #11 to #19) in 1.4.0, and From 0f27b51eb280114cf55e90c437eeed87f50e19d3 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 11:24:06 -0800 Subject: [PATCH 16/17] ADFA-7081: Answer the independent review of 1.4.2-2 - A runaway statement that has not started within 10 s now fails its AC8 test as such ("the statement did not start within 10 s"), in both helpers, instead of sending Ctrl-C anyway and blaming the build. The batch helper also stops waiting once sqlite3 has exited. With a sqlite3 that starts 12 s late, all six AC8 tests report that; the old tests reported "still running 5 s after SIGINT" or "took 13 s". - The plain-SQL runaway counts to 50,000,000, not 200,000,000: about 5 s on an x86_64 host (measured), so a lost Ctrl-C leaves sqlite3 busy for about as long as the other runaways' 20 s cap on a phone. Host: passed all 104, AC12 skipped (no sqlite-brotli). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/tests/run-tests.sh | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh index 0216186..a087dd7 100644 --- a/packages/sqlite-js/tests/run-tests.sh +++ b/packages/sqlite-js/tests/run-tests.sh @@ -195,8 +195,9 @@ expect_nobail() { # interrupted within 5 seconds. The statement must be one that creates the file # "started" as it begins, with WHERE $STARTED: SQLite drops an interrupt that # arrives while no statement runs, so the signal must not come before it, or -# between two statements. sqlite3 is started directly, not through sql(), so -# that $! is its process. +# between two statements. A statement that has not started within 10 s fails +# the test as such, so the failure does not blame Ctrl-C. sqlite3 is started +# directly, not through sql(), so that $! is its process. STARTED="writefile('started', '') IS NOT NULL" expect_sigint_stops() { local name=$1 pid i rc got @@ -206,8 +207,15 @@ expect_sigint_stops() { pid=$! for ((i = 0; i < 100; i++)); do [[ -e started ]] && break + kill -0 "$pid" 2>/dev/null || break sleep 0.1 done + if [[ ! -e started ]]; then + kill -KILL "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + not_ok "$name" "the statement did not start within 10 s, so no SIGINT was sent" "got: $(/dev/null for ((i = 0; i < 50; i++)); do kill -0 "$pid" 2>/dev/null || break @@ -453,7 +461,8 @@ DB=$WORK/test.db # Each runaway loop gives up after 20 s, long after the tests expect Ctrl-C to # have stopped it, so that a build where Ctrl-C does nothing leaves no sqlite3 -# behind: timeout(1) below can stop script(1), but not the sqlite3 it runs. +# behind: timeout(1) below can stop script(1), but not the sqlite3 it runs. The +# plain-SQL runaway counts to 50,000,000 instead, about 5 s on an x86_64 host. RUNAWAY='for (const end = Date.now() + 20000; Date.now() < end;) {}' expect_sigint_stops "AC8: SIGINT (Ctrl-C) stops a runaway loop in js_eval" \ "SELECT js_eval('$RUNAWAY') WHERE $STARTED;" @@ -477,7 +486,7 @@ expect_ctrl_c_keeps_session() { cmd=$(printf '%q ' "$SQLITE3" -noheader -cmd "$LOAD_EXT" "$DB") # The shell also reports "interrupted" once the loop ends by itself, so the # session must end well before the loop's 20 s are up: about 5 s if Ctrl-C works. - rm -f started + rm -f started not-started started=$SECONDS got=$({ sleep 1 @@ -486,6 +495,7 @@ expect_ctrl_c_keeps_session() { [[ -e started ]] && break sleep 0.1 done + [[ -e started ]] || : >not-started printf '\003' sleep 1 printf '%s\n' "SELECT 'still' || ' alive';" @@ -493,7 +503,9 @@ expect_ctrl_c_keeps_session() { printf '.quit\n' } | timeout -k 5 30 script -q -c "$cmd" /dev/null 2>&1 | tr -d '\r') seconds=$((SECONDS - started)) - if [[ $got == *interrupted* && $got == *"still alive"* && $seconds -lt 15 ]]; then + if [[ -e not-started ]]; then + not_ok "$name" "the statement did not start within 10 s of being typed, so Ctrl-C came before it" "got: $got" + elif [[ $got == *interrupted* && $got == *"still alive"* && $seconds -lt 15 ]]; then ok "$name" else not_ok "$name" "took $seconds s, want under 15" "got: $got" @@ -510,7 +522,7 @@ expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops code that keeps a result se "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); $RUNAWAY') WHERE $STARTED;" expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops plain SQL, run after code kept a result set, sqlite3 still runs SQL" \ "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); 0'); -WITH RECURSIVE c(x) AS (SELECT 1 + writefile('started', '') UNION ALL SELECT x + 1 FROM c WHERE x < 200000000) SELECT count(*) FROM c;" +WITH RECURSIVE c(x) AS (SELECT 1 + writefile('started', '') UNION ALL SELECT x + 1 FROM c WHERE x < 50000000) SELECT count(*) FROM c;" # --- AC9: the memory limit ------------------------------------------------------ From fbc3be38344a19ed606e15ab05f9086b81b1c8fc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 11:24:06 -0800 Subject: [PATCH 17/17] ADFA-7081: Release sqlite-js 1.4.2-3 with the review's test fixes The package installs run-tests.sh, so the test changes need a new revision for the publish to pick them up. The library is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- packages/sqlite-js/build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh index 4358936..ff3a297 100644 --- a/packages/sqlite-js/build.sh +++ b/packages/sqlite-js/build.sh @@ -4,7 +4,7 @@ TERMUX_PKG_LICENSE="Apache-2.0, MIT" TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" TERMUX_PKG_MAINTAINER="@appdevforall" TERMUX_PKG_VERSION=1.4.2 -TERMUX_PKG_REVISION=2 +TERMUX_PKG_REVISION=3 TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 # Upstream released our changes (sqliteai/sqlite-js #11 to #19) in 1.4.0, and