diff --git a/docs/docdb/ADFA-7083/CLAIMS.md b/docs/docdb/ADFA-7083/CLAIMS.md index d6b6d8b94b..5e04c0a7fb 100644 --- a/docs/docdb/ADFA-7083/CLAIMS.md +++ b/docs/docdb/ADFA-7083/CLAIMS.md @@ -1,6 +1,8 @@ -# Claims in the ADFA-7083 pages and how each was checked +# Claims in these pages and how each was checked -`run` = executed by `test_examples.py` against a host build of the package (66 of 66 on plain 1.4.2, the package from the move to 1.4.2, 2026-11-13: 28 SQL examples, 19 of them run a second time, and 19 links; on 1.4.1 the `js_version` example and the kept result set example fail, as they should. Before that, 64 of 64 on 1.4.1 with the package's two patches, stack and garbage collection, which change none of the pages' claims, and on 1.4.1 without them, 2026-11-12: 27 SQL examples, 18 of them run a second time in the same session, and 19 links; earlier, 1.3.7-p20261112, upstream main at c8ae85a, and 1.3.7-1 to 1.3.7-5, 1.3.7 with patches 0001 to 0008). `code` = read in the source: the patched 1.3.7 up to 1.3.7-5, then upstream main at c8ae85a, then 1.4.1, whose `src/` and `libs/` differ from c8ae85a only in `SQLITE_JS_VERSION`, with the package's patches 0001 and 0002 (sqliteai/sqlite-js #22 and #23), then 1.4.2 (tag 74557b2), which the package builds with no patches. `probe` = run by hand against the host build, in the accuracy review (2026-11-11), the review of PR 2241 (2026-11-12) or the move to 1.4.1 (2026-11-12), or the move to 1.4.2 and its review (2026-11-13 to 2026-11-15). `TODO` = still open. +The terminal pages are ADFA-7083's, changed for sqlite-js 1.4.4 by ADFA-7243. The app pages (`sqlite-js-app-*`) are ADFA-7247's: their sections, and what the words in them mean, come after the terminal pages'. + +`run` = executed by `test_examples.py` against a host build of the package (on 2026-11-22, after CodeRabbit's review of #2293: 88 of 88 on a build of the 1.4.4 tag with `/usr/bin/sqlite3` 3.46.1, with no `~/.sqliterc` read and each error matched to the line where its statement starts. On 2026-11-21, for ADFA-7243 and ADFA-7247: 88 of 88 on a build of the 1.4.4 tag with `/usr/bin/sqlite3` 3.46.1, 29 SQL examples, 19 of them run a second time, and 40 links; on 1.4.3 the `half` and `js_version` examples fail, as they should. Before that: 66 of 66 on plain 1.4.2, the package from the move to 1.4.2, 2026-11-13: 28 SQL examples, 19 of them run a second time, and 19 links; on 1.4.1 the `js_version` example and the kept result set example fail, as they should. Before that, 64 of 64 on 1.4.1 with the package's two patches, stack and garbage collection, which change none of the pages' claims, and on 1.4.1 without them, 2026-11-12: 27 SQL examples, 18 of them run a second time in the same session, and 19 links; earlier, 1.3.7-p20261112, upstream main at c8ae85a, and 1.3.7-1 to 1.3.7-5, 1.3.7 with patches 0001 to 0008). `code` = read in the source: the patched 1.3.7 up to 1.3.7-5, then upstream main at c8ae85a, then 1.4.1, whose `src/` and `libs/` differ from c8ae85a only in `SQLITE_JS_VERSION`, with the package's patches 0001 and 0002 (sqliteai/sqlite-js #22 and #23), then 1.4.2 (tag 74557b2), which the package builds with no patches. `probe` = run by hand against the host build, in the accuracy review (2026-11-11), the review of PR 2241 (2026-11-12) or the move to 1.4.1 (2026-11-12), or the move to 1.4.2 and its review (2026-11-13 to 2026-11-15), and on the 1.4.4 build after CodeRabbit's review of #2293 (2026-11-22). `TODO` = still open. ## sqlite-js-top @@ -34,9 +36,18 @@ | `js_set_memory_limit`: default 64 MB, 0 no limit, a whole number 0 or more, error text, returns NULL; a limit below the memory variables still hold leaves no room for any JavaScript until raised | run (package AC9), code; probe: `'64'`, `-1` and `1.5` each give the error; probe on 1.3.7-5, 1.3.7-p20261112 and 1.4.1: with 40 MB held in a global and the limit at 4 MB, `js_eval('1 + 1')` and `js_eval('2 + 2')` fail with `out of memory`, and after raising it to 64 MB `js_eval('3 + 3')` gives 6 | | `js_set_max_stack_size` (1.4.0; 1.3.7-2 to 1.3.7-5 as patch 0007): default 1 MB; only a whole number the stack allows, else an error naming the largest size; 0 turns the check off and deep recursion crashes; with no stack limit, at most 1 MB | code (1.4.1; patch 0007 before; 1.4.2's 31ed714 counts an unlimited `RLIMIT_STACK` as unmeasurable); probe on the 1.4.2 host build (glibc, 2026-11-13): under `ulimit -s unlimited` the error names 1048576 as the largest size, and with 8 MB it names 8109952. TODO: the unlimited case on the phone (Bionic); probe on the 1.4.1 host build (2026-11-12): the same inputs give the error, naming 8131952 as the largest size, `262144`, `1048576` and `0` are accepted, and endless recursion at 4 KB below the largest fails with `Maximum call stack size exceeded`; probe on the 1.3.7-2 host build: `'abc'`, `-1`, `1.5`, `NULL`, `1073741824` and `16777216` give the error, `262144` and `1048576` are accepted, endless recursion fails cleanly just below the largest size; package run-tests.sh AC13 (87 of 87). 1.3.7-1 instead crashed on text, 0, or sizes above the stack. Phone: 1.3.7-2 passed 87 of 87; 1.3.7-3 and 1.3.7-4 passed 91 of 91 on aarch64 and arm | | `js_version(1)` is quickjs-ng | run (package AC2) | -| `js_version()` gives `1.4.2` | run (the example's `-- 1.4.2`); `SQLITE_JS_VERSION` is "1.4.2" in the 1.4.2 tag's `src/sqlitejs.h` | +| `js_version()` gives the installed version, such as `1.4.4` | run on the 1.4.4 host build (the example's `-- 1.4.4`; on the 1.4.2 and 1.4.3 host builds the example fails, printing `1.4.2` and `1.4.3`) | | sqlite-js 1.4.0 includes fixes from App Dev For All; the eight differences from 1.3.7 listed | code: 1.4.0 contains c8ae85a (2026-11-12), which merges PRs #11 to #18, the changes of patches 0001 to 0008, and #19, and its CHANGELOG lists the same changes; 1.4.1's C code is c8ae85a's; package run-tests.sh: 98 of 98 on the 1.3.7-p20261112 host build, the same C code | | sqlite-js 1.4.2 has more fixes, several sent or reported by App Dev For All; the five differences from 1.4.1 listed | code: upstream's 1.4.2 tag (74557b2) contains App Dev For All's sqliteai/sqlite-js PRs #22 (stack, with the maintainer's bd3d6c4 and 31ed714), #23 (garbage collection) and #24 (result sets an interrupt leaves open), whose patch ids match the package's former patches 0001 to 0004, and the maintainer's #26 for App Dev For All's issue #25 (window function crash) with the result set lifetime change; 1.4.2's CHANGELOG lists the same. run: the kept result set example (fails on 1.4.1, where `next()` returned `true` and `sqlite3` reported `unable to close due to unfinalized statements`). probe (review of 139870bad, 2026-11-15): a window function whose `final` allocates, read through `db.exec(...).next()` and dropped in a loop, crashes `sqlite3` on the 1.4.1 host build (segmentation fault within 60 turns) and passes on 1.4.2; with `toArray()` in place of `next()`, 1.4.1 passes too | +| ADFA-7243, 1.4.4: a `js_create_` function fails when `js_functions` exists but the function cannot be written to it; the error starts with `The function was registered on this connection, but it could not be stored in js_functions:` and ends with SQLite's reason; `attempt to write a readonly database` for `sqlite3 -readonly`, `.open --readonly` and `PRAGMA query_only`, `database is locked` while another program writes | run (the `half` example: the `-- Error:` line, on the 1.4.4 host build, 2026-11-21); code: `js_create_function` in 1.4.4's `src/sqlitejs.c`, lines 1686 to 1700 (the source `vendor.sh --check` shows `subprojects/sqlite-js/upstream` to be, at `stage` 5a49afda9); probe on the 1.4.4 host build with `/usr/bin/sqlite3` 3.46.1 (2026-11-21): a file opened with `-readonly` and with `.open --readonly`, and `PRAGMA query_only = ON` on a file and on `:memory:`, each give `... could not be stored in js_functions: attempt to write a readonly database (8)`, for `js_create_scalar`, `js_create_aggregate`, `js_create_window` and `js_create_collation`; with another `sqlite3` holding `BEGIN IMMEDIATE` on the file, `... database is locked (5)`; terminal-packages `run-tests.sh` at `main` e90033b, test "ADFA-7200: a function that cannot be stored in js_functions is an error" | +| After that error the function works until `sqlite3` closes, is not stored, and is not there in the next session; if `js_functions` already held a function of that name, it keeps that one, and the next session's `js_init_table(1)` creates the older version | run (the `half` example: `half(10)` gives 5 and `js_functions` lists only `twice`); probe (same builds): after the error on the read-only file the scalar, aggregate, window function and collation all work; the next session's `js_init_table(1)` succeeds and `SELECT half(10)` fails with `no such function: half`. Probe on the 1.4.4 host build, 2026-11-22 (CodeRabbit on #2293): with `half` stored as `args[0] / 2`, a new session under `query_only` creating `half` as `return 999` fails with the store error; `js_functions` still holds the `/ 2` code, and the next session's `js_init_table(1)` gives `half(10)` = 5. code: `js_add_to_table` writes with one `REPLACE` (`src/sqlitejs.c` line 1582), so a failed write leaves the stored row as it was | +| To store it: remove the cause, and create it again in a new session; creating it again in the same session fails | probe: with `query_only` off again, the same `js_create_scalar` in the same session fails with `Function updates must be performed using a separate database connection.` | +| A function already stored with the same code needs no write, so creating it succeeds on a read-only database; a database without `js_functions` cannot give this error | code: `js_add_to_table` returns before the `REPLACE` when the stored row has the same kind and code, and returns true when the table does not exist (`src/sqlitejs.c` lines 1533 to 1580); probe: under `query_only`, re-creating the stored `twice` with the same code reaches the redefinition error, not the store error, and in a new session on the file `total_changes()` stays 0 after creating a stored function again and becomes 1 after a new one; on a read-only file without the table, `js_create_scalar` prints 0 and the function works | +| A `js_functions` table that `js_init_table()` did not make, and that lacks one of its columns, gives no error: the `js_create_` function returns `0` and stores nothing | code: `js_add_to_table` returns true, as for a missing table, whenever its lookup `SELECT kind,init_code,step_code,final_code,value_code,inverse_code FROM js_functions` cannot be prepared (`src/sqlitejs.c` lines 1533 to 1539); probe on the 1.4.4 host build, 2026-11-22 (CodeRabbit on #2293): after `CREATE TABLE js_functions (name TEXT)`, `js_create_scalar('twice', ...)` prints 0, `twice(4)` gives 8, and `js_functions` has 0 rows. CodeRabbit asked for sqlite-js to report this as a store error: that is a change to upstream's code, not made here | +| 1.4.2 and 1.4.3 return `0` instead, and the function is missing in the next session | probe on the 1.4.3 host build: every case above prints 0, the function works, and the next session lacks it; on 1.4.2, `-readonly` prints 0; run: the `half` example fails on the 1.4.3 host build for lack of the error | +| 1.4.4: an error while building the arguments, or a `toArray()` row, fails the call; before, the function ran with fewer arguments or `toArray()` returned fewer or shorter rows; the causes are JavaScript out of memory or a setter on `Array.prototype` | probe on the 1.4.2, 1.4.3 and 1.4.4 host builds: after `Object.defineProperty(Array.prototype, "0", { set(v) { throw new Error("index setter"); } })`, `first_arg(5)` gives `missing` on 1.4.2 and 1.4.3 and fails with `index setter` on 1.4.4; `toArray().length` over one row gives 0 on 1.4.3, with the error surfacing in the next call, and fails with `index setter` on 1.4.4; code: lines 222 to 236 and 1383 to 1398; upstream's CHANGELOG for 1.4.4; `run-tests.sh` tests "an error building a call's arguments fails the call" and "an error building a toArray() row fails the call". The out-of-memory cause is read in the code only | +| 1.4.4: text SQLite has no memory left to convert fails with `out of memory`; before, `sqlite3` crashed | code: `sqlite_value_to_js` throws out of memory when `sqlite3_value_text` returns NULL (lines 1347 to 1351); upstream's suite, run by `subprojects/sqlite-js/test.sh` at 87fa768be (2026-11-21): `PASS: text_length() failed with no memory for its argument's UTF-8 copy: 7 out of memory`. Not probed in `sqlite3`: it needs an allocation to fail. The crash before 1.4.4 is upstream's CHANGELOG's statement, not reproduced here | +| 1.4.3 changed nothing that you can see in `sqlite3` | upstream's CHANGELOG for 1.4.3: "Nothing changes for an application that never calls it"; the terminal package does not export `sqlitejs_cancel_all` (its `build.sh` checks the exports) | | quickjs-ng is MIT-licensed; `LICENSE` and `LICENSE.quickjs` are in `$PREFIX/share/doc/sqlite-js/` | code: package build (`LICENSE.quickjs` collected from the sources); file list of the 1.3.7-1 aarch64 `.deb` checked | | Apache-2.0 attribution wording | TODO: legal wording check; upstream names no copyright holder | @@ -68,10 +79,64 @@ | Months count from 0; `true` shows as 1 | run (the Dates and Text examples) | | `const` is never reassigned, `let` can be; arrow function syntax; one kind of number for whole numbers and fractions (BigInt aside, which the intro does not cover) | JavaScript language facts | +## sqlite-js-app-top, sqlite-js-app-database, sqlite-js-app-cancel (ADFA-7247) + +`aar` = the AAR module `subprojects/sqlite-js` at CodeOnTheGo `stage` 5a49afda9 (#2285; the module is identical at #2285's 87fa768be), sqlite-js 1.4.4. `template` = dev-assets `templates/JavaScriptInSQLite` at `main` 322d533. `compiled` = `test_app_examples.py` (2026-11-22, after CodeRabbit's review of #2293: 13 of 13 without the device on the examples and tests as they now stand. Earlier that day, 14 of 15 with the device; the 15th was the Java device run, which Gradle skipped and which was run by hand, as `device` says. Both runs used the released `sqlite-js-latest` AAR, SHA-256 `b894b132...4940c`, built by CodeOnTheGo run 45020709361 from `main` 672b7b869, and the template at dev-assets 7dad8f4, which is the template at `main` 8b04de662 and differs from 322d533 only in `NOTICES.txt` naming 1.4.4. 2026-11-21: 13 of 13 without a device since the Java examples were added; before them 7 of 7, and 8 of 8 with the device): the template rendered by dev-assets' `scripts/render-template.py` (AGP 9.3.1, Kotlin 2.3.21, Gradle 9.6.1, compileSdk 36), with the 1.4.4 AAR built locally from 87fa768be (`createSqliteJsAar`, SHA-256 `13360a12...5071a`; its `libsqlitejs.so` holds the strings `1.4.4` and the store error) and the six Kotlin examples in one file, builds with `:app:assembleDebug`. `compiled (java)` = the same script's second project: the template without its Kotlin sources and activity and without the Kotlin-only lines of its build files (the KSP plugin in both, `ksp(room-compiler)`, `room-ktx`, `lifecycle-runtime-ktx`, `kotlinx-coroutines-android` and the `kotlin { }` block; the Kotlin compiler's `buildscript` block, the forced `kotlin-stdlib` versions, the packaging rules for Kotlin Multiplatform metadata files and `kotlin.code.style`; the script stops unless it removes exactly one of each, and stops if `build.gradle.kts`, `app/build.gradle.kts`, `gradle.properties` or `settings.gradle.kts` contains `kotlin`, `ksp`, `ktx` or `coroutines`, read as the build reads them, after the page's Java block and the test's own settings are added; the version catalog is not checked, because its entries declare nothing until a build file names them), with the page's Java Room settings added to `app/build.gradle.kts` and each of the six Java examples in a file named after its first class, builds with `:app:assembleDebug`; Room's annotation processor writes `ProductDatabase_Impl.java` and `ProductDao_Impl.java` there. `host` = run on this host in `/usr/bin/sqlite3` 3.46.1 with a build of the 1.4.4 tag, by `test_app_examples.py` or by hand. `glue` = `subprojects/sqlite-js/test.sh` at 87fa768be on this host (2026-11-21): upstream's suite passes, and `glue_test.c` passes 50 of 50 twice. + +`device` = the two instrumented tests, which call every Kotlin and every Java example, on a Galaxy J7 (SM-J737A, Android 9, armeabi-v7a, so the 32-bit library) on the examples and tests as they now stand, 2026-11-22, after CodeRabbit's review of #2293, with the released AAR named under `compiled`: `app-test/DocExamplesTest.kt` passes 5 of 5 and `app-test/JavaDocExamplesTest.java` 2 of 2, each twice in a row under `am instrument`. Five earlier builds that day, as the review fixes went in, passed the same way. The first also passed the Kotlin test once under Gradle's `connectedDebugAndroidTest`, which found the phone not "compatible" for the Java one. With both `start()` guards taken out of the page, both tests' `roomCallsTheStoredFunctionsAndCancelStopsARunaway` fail, as the `RunawayQuery` rows describe. The Java test fails with `a second spin() is running`; the Kotlin test's process crashes. Before that, on 2026-11-21, with the AAR built locally, 5 of 5 and 2 of 2, each run twice in a row (the last of five such sessions). How the tests time their cancels. A cancel aimed at `spin()`, including the plain coroutine cancel that a test shows does not stop it, is sent once `spin()` is seen running in SQLite (a thread whose stack has sqlite-android's native statement call and Room's generated `spin()`); that test's cleanup, in a `finally`, then calls `cancelAll()` every 10 ms until its job ends, for at most 60 s. The `RunawayQuery` cancels and the Java test's `CancellableQuery` cancel of `spin()` are sent from a `finally` too, so a wait for `spin()` that fails still stops it; the coroutine running `cancellable { products.spin() }` is a child of the test's own, which such a failure cancels. A cancel meant to stop a write (`cancelledWrite` inside `withTransaction` and inside `runInTransaction`, and the two collation writes) starts once the insert before that write has returned, and is repeated every 10 ms until the write ends, so it does not need the write to have started: `cancelAll()` stops only JavaScript that began before it, and interrupts a connection only from inside such JavaScript running on it (1.4.4's `src/sqlitejs.c`, `js_interrupt_handler`, lines 395 to 398), so a call that comes before the write's JavaScript starts does nothing. The Java `runInTransaction` case starts its `cancel()`, which repeats `cancelAll()` in the same way until the write ends, at once, without waiting for the insert; that is safe for the same reason, since the insert runs no JavaScript, and the test asserts that the cause of the `CancellationException` is the `interrupted` error, so a write that failed for another reason cannot pass. `cancellableDropsAResultThatArrivesAfterTheCancel` cancels once its query has opened a latch of the test's. The Java test's other three cancels test `cancel()` itself, and none of them depends on timing: one comes before `start()`, one after its query has ended, and one on a query held on a latch, where `cancel()` must return while that query still runs. Other fixed times remain. One of them could let a test pass when its claim is false, on a very slow phone: the Java test's 2 s watch for a second `spin()`, under the Java `RunawayQuery` row. None of the others can: in the Java test, a 300 ms pause after a `RunawayQuery` or `CancellableQuery` cancel, before the next query, so that a late `cancelAll()` from its loop cannot reach that query (the test cannot see that loop end; the Kotlin test instead waits for its `RunawayQuery`'s job to end, which it does only after its loop has); in `cancellableDropsAResultThatArrivesAfterTheCancel`, a 200 ms pause before the cancel and a check 200 ms after it, while the query is held on a latch, so a slower phone cannot fail either (nothing in `cancellable()` can suspend between `async` and `await()`, so a cancel that lands before `await()` is seen at `await()`, inside its `try`, and the query cannot end until the test releases it); the check 2 s after a plain cancel that `spin()` is still running in SQLite (the stack check above) and has not ended, which a slower phone cannot fail, since `spin()` never returns by itself; 20 `cancelAll()` calls, 10 ms apart (about 200 ms), after the plain-cancel test's job has ended and before its `count()`, which cannot stop `count()` because they all come before it starts; and limits of 10 s to 120 s on waits, which a very slow phone could reach and so fail a correct run, but which cannot make a false claim pass. The APKs `test_app_examples.py` built were installed with `adb install`, run with `am instrument` and removed, because Gradle's `connectedDebugAndroidTest` skipped the phone three times that day ("Unknown API Level", after ddmlib timed out reading the phone's properties) and ran it once, 8 of 8 with the three Kotlin tests of the time. What no device has shown for this ticket is marked `not run on a device` below: the template's own screen, the pages in the help viewer, and a 64-bit device. + +| Claim | Check | +|-------|-------| +| The template is named JavaScript in SQLite, and its project is Kotlin | template: `template/template.json` (`"name": "JavaScript in SQLite"`); every source file is `.kt`; dev-assets' `build-artifact-candidate.yml` lists it as Kotlin only | +| The sample app: four products in a Room database `products.db`; the three buttons and what they do; it runs the functions when it starts; Cancel shows the milliseconds | template: `ProductDatabase.kt.peb` (`NAME`, lines 66 and 74 to 78), `MainActivity.kt.peb` (lines 55 to 59, 63 to 111, 119 to 124), `res/values/strings.xml.peb`, `res/layout/activity_main.xml`. Not run on a device for this ticket; the AAR's README records the template's runs on a Galaxy Note20 Ultra with builds from 1.4.2 and 1.4.3 | +| The output shown: the four slugs and `Median price: 2.23` | host: the template's own three `js_create_` statements and its two queries, over the four sample products, give the four slugs and 2.225; `String.format("%2$.2f")` of 2.225 prints 2.23 (run with Java 17). `test_app_examples.py` checks the same for the page's examples and that the page shows it | +| Where the files are | template file list | +| ARM only: arm64-v8a and armeabi-v7a; `minSdk` 26 | aar: `build.gradle.kts` lines 13 to 21; the AAR holds `jni/arm64-v8a/libsqlitejs.so` and `jni/armeabi-v7a/libsqlitejs.so` only; template: `app/build.gradle.kts.peb` lines 49 to 55; the debug APK built from the template holds `lib/` for those two ABIs only | +| sqlite-js is an SQLite extension; Android's own SQLite gives an app no way to load one; the template adds requery's `sqlite-android`, which brings its own SQLite, and Room uses it | aar: README, "Using it in an app"; template: `app/build.gradle.kts.peb` lines 122 to 126 and `ProductDatabase.kt.peb` lines 92 to 105; the APK holds requery's `libsqlite3x.so`. That Android's SQLite cannot load extensions is the README's and the template's statement, not tested here | +| These pages describe 1.4.4; `SELECT js_version()` shows the version | aar: `vendor.sh` line 5 (`VERSION=1.4.4`), and `vendor.sh --check` passes (2026-11-21); the AAR's library holds the string `1.4.4`. device: `SELECT js_version()` gives `1.4.4` | +| The three works and their licenses; the template's `NOTICES.txt` has the notices and both license texts; the button shows the file | template: `app/src/main/assets/NOTICES.txt` (sqlite-js and sqlite-android under Apache-2.0, QuickJS under MIT, then both texts), `MainActivity.kt.peb` lines 104 to 111. At 322d533 the file names sqlite-js 1.4.3; dev-assets #84 (open on 2026-11-21) changes it to 1.4.4. The page names no version there | +| Each license asks you to pass its notice on | Apache-2.0 section 4 (a copy of the license, and the notices); the MIT text ("The above copyright notice and this permission notice shall be included in all copies"). TODO: legal wording check, as for the terminal pages | +| Ctrl-C and `.load` belong to Terminal only | Ctrl-C is the `sqlite3` shell's interrupt handler and `.load` one of its dot-commands (terminal pages); an app loads the extension through `SQLiteCustomExtension` (the examples) and stops JavaScript with `SqliteJs.cancelAll()` | +| The terminal pages' SQL and JavaScript work the same way in an app; each connection has its own engine, functions and limits | aar: `SqliteJs.java` line 25 ("each connection has its own JavaScript runtime") and `upstream/` is the 1.4.4 source the host build uses; glue: both entry points load sqlite-js and run `js_eval`; device: `js_eval('6 * 7')` gives 42, and the functions the examples store give the host's results through Room | +| The gradle example; `sqlite-js.aar` needs no other library; `sqlite-android` needs `androidx.core`, and `androidx.sqlite`, which Room brings; the template writes the `androidx.core` line as `libs.androidx.core` | compiled: `test_app_examples.py` checks that every line of the example is in the template's `app/build.gradle.kts`, in order, reading `implementation(libs.androidx.core)` there as the `androidx.core:core:1.15.0` its `gradle/libs.versions.toml` gives; template: the comment at lines 122 to 124; the AAR holds one class, `SqliteJs`, which uses only `android.content.Context`; `sqlite-android` 3.49.0's POM on JitPack lists `androidx.core:core:1.15.0` and `androidx.sqlite:sqlite:2.4.0` and nothing else (read 2026-11-21) | +| `useLegacyPackaging = true` makes Android copy the native libraries to files; without it they stay in the APK | probe (2026-11-21): the template's merged manifest has `android:extractNativeLibs="true"`, and `"false"` with the setting changed to `false`; aar: README ("SQLite loads the extension from a file") and `SqliteJs.java` line 12. That loading then fails: not run on a device | +| `sqlite-android.aar` is requery's `sqlite-android` 3.49.0 with its ARM libraries only: the file published on JitPack as `com.github.requery:sqlite-android:3.49.0`, with its x86 libraries taken out; a project made with the template has both `.aar` files in `app/libs`, with no download; copy them to use sqlite-js elsewhere; the template uses Room 2.8.4 with KSP 2.3.13 | dev-assets `README.md` at 322d533 ("requery's `sqlite-android` 3.49.0 without its x86 and x86_64 libraries", "JitPack, its only publisher"; `sqlite-js.aar` is "not in the template's own `.gitignore`, since a user's project needs it"), `scripts/fetch-sqlite-js-template-libs.sh` (JitPack's file has SHA-256 `2a746d7d...`, the template's `adc520fe...`, made by `zip -d` of `jni/x86/*` and `jni/x86_64/*`), `build-core-cgt.sh` (refuses to pack the template without both); the template's AAR holds `jni/arm64-v8a` and `jni/armeabi-v7a` only (the APK's `lib/`); template: `gradle/libs.versions.toml.peb` (`room = "2.8.4"`, `ksp = "2.3.13"`). Checked on 2026-11-21: JitPack's `sqlite-android-3.49.0.aar` has SHA-256 `2a746d7d...`, and after `zip -d` of its x86 libraries it is byte-identical to the template's file (`adc520fe...`). A project made on a device was not inspected | +| The Room build settings: Kotlin with `room-runtime`, `room-ktx`, `ksp(room-compiler)` 2.8.4 and coroutines 1.10.2, and the KSP plugin; Java with `room-runtime` and `annotationProcessor(room-compiler)`, no KSP and no coroutines | compiled: the Kotlin block is checked line by line against the template's `app/build.gradle.kts`, its catalog names read as coordinates; compiled (java): that project declares no Kotlin, KSP, `-ktx` or coroutines library, plugin or setting (the script checks its build files for the words); besides the page's Java block and the three lines of its first block it declares only the template's `appcompat`, `material` and `junit`; the build and the device test pass. Room 2.8.4 itself is written in Kotlin and brings `kotlin-stdlib` and coroutines in as its own dependencies: "no coroutines" on the page means that the app declares and calls none | +| The Java examples `SharedFiles`, `ProductFunctions`, `ProductDatabases`, and `Product` with `ProductDao` and `ProductDatabase`: the same steps as the Kotlin ones; each in a file named after its first class | compiled (java); host: `test_app_examples.py` joins the Java string pieces and runs the three `js_create_` statements, which store three functions, and the DAO queries, which give the four slugs and 2.225 (`SELECT spin()` is still running after 3 s); device: through Room, `slugs()` and `medianPrice()` give the four slugs and 2.225, `ProductFunctions.store` runs again on the existing database and a second database object has the functions; `SharedFiles.open` on a file that stores a function gives a read-only connection where `js_version()` is `1.4.4`, `js_eval` works and the stored function is `no such function` | +| The Java DAO methods wait for their result; Room refuses a query on the main thread | Room's documented default (`allowMainThreadQueries()` is off); the examples do not call it. The refusal itself was not tested: the instrumented test calls the methods off the main thread only | +| The two entry points: what each loads and runs, and when to use each; a downloaded or shared file or a restored backup is opened with `ENTRY_POINT` | aar: `SqliteJs.java` lines 19 to 27, `sqlitejs_android.c` lines 14 to 19 and 66 to 116, README; glue: "ENTRY_POINT does not load stored functions", "ENTRY_POINT runs no stored code", "the trusted entry point loads a", "loading d ran its stored code once" | +| Stored code can run SQL and read the app's files | aar: `SqliteJs.java` line 25; the terminal pages' probe of `db.exec` with `readfile()`; `js_load_text` is an SQL function | +| The `openSharedFile` example; the package names | compiled; device: on a file that stores a function, the connection it returns runs `js_eval`, fails `SELECT stored()` with `no such function`, and a connection opened with the trusted entry point on the same file answers `SELECT stored()` | +| A stored function that fails to load is skipped and logged, the rest load, and calling it fails with `no such function` | glue: "it skips b" (`no such function: b`), "it logs that b did not load", "it loads c, stored after the broken b"; aar: `sqlitejs_android.c` lines 47 to 60 | +| A connection that opened before a function was stored does not have it; a connection cannot redefine a function it has; so store on a connection opened with `ENTRY_POINT` before Room opens the database | aar: `SqliteJs.java` lines 20 and 25, README lines 36 and 37, `sqlitejs_android.c` lines 69 to 71; probe on the 1.4.4 host build: a connection that ran `js_init_table(1)` before another stored `two` fails `SELECT two()` with `no such function`, and one opened afterwards has it; the terminal pages' redefinition claim; template: `ProductDatabase.kt.peb` lines 108 to 124 | +| `js_init_table()` creates `js_functions`, and each `js_create_` then stores its function | host: `test_app_examples.py` runs the examples' statements and counts three rows in `js_functions` | +| The `FUNCTIONS` and `storeFunctions` examples | compiled; host: the three statements run as written, raw strings included; device: `storeFunctions` runs on a new database and again on the existing one | +| `rawQuery` runs nothing until its result is read | template: every statement in `storeFunctions` ends with `moveToFirst()` (lines 121 and 122); device: after a `js_create_scalar` whose cursor is closed unread, calling the function fails with `no such function` | +| A function stored with the same code is not written again; changed code replaces the stored function, and connections opened afterwards get it | code and probe: see "already stored with the same code" in the functions page's claims; probe on the 1.4.4 host build: after creating `keep` again with other code in a new session, the next session's `js_init_table(1)` gives the new one | +| If a function cannot be stored, `moveToFirst()` throws, and the message contains `could not be stored in js_functions` | host: the error text, on a locked and on a read-only database (functions page's claims); device: on a read-only connection to a file with a `js_functions` table, `js_create_scalar` throws from `moveToFirst()` with that text in the message, and the function then works on that connection. The locked case was not run on the device | +| The `openProductDatabase` example; every Room connection loads sqlite-js and the stored functions | compiled; aar: README's example, which it shortens; template: `ProductDatabase.kt.peb` lines 90 to 106. device: `slugs()` and `medianPrice()` through Room give the four slugs and 2.225, on the first database object and on a second one opened after it closed | +| Open the database once, keep it for the whole app, and open it off the main thread | template: `ProductDatabase.kt.peb` lines 80 to 88 (`get`, and its comment: "The first call does disk work, so call it off the main thread") | +| `@SkipQueryVerification`: Room checks queries at build time with an SQLite that has no JavaScript functions; without it the build fails with `no such function` | probe (2026-11-21): with the annotations deleted from the examples, `:app:kspDebugKotlin` fails with `There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such function...` for `slugs()` and `spin()`; with them, compiled | +| The entity, DAO and database example | compiled; host: the two queries that end give the slugs and the median, and `SELECT spin()` is still running after 3 s | +| To remove a function: take it out of `FUNCTIONS`, and delete its row from `js_functions`; an open connection keeps it until it closes | the `storeFunctions` example stores every entry of `FUNCTIONS` on each start; probe on the 1.4.4 host build: after the `DELETE`, the next session's `js_init_table(1)` creates the other function, and the deleted one is `no such function`, while the connection that created it still answers `SELECT gone()` after the `DELETE`; aar: the trusted entry point loads the rows of `main.js_functions` (`sqlitejs_android.c` line 87) | +| Neither Room nor Android's own way to cancel a query can stop a function that never returns, and cancelling the coroutine that waits for the query does not stop it either | aar: README line 40 ("Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs"); upstream's CHANGELOG for 1.4.3. device: `DocExamplesTest` waits until a thread is inside sqlite-android's native statement call for Room's generated `spin()`, cancels the coroutine that called `products.spin()` without `cancellable()`, and asserts that it has not completed, and has no result, 2 s later, and that it then ends, as a failure, once `cancelAll()` is called (it also logs `2 s after a plain cancel of spin(): job completed = false`); once `spin()` is seen running, a coroutine running `cancellable { products.spin() }` is still active, and it ends when cancelled. Room's and Android's own cancelling were not exercised by a test here | +| `cancelAll()` stops the JavaScript running at that moment, in every query on every connection; each stopped call fails with `interrupted`, which JavaScript cannot catch; the connection is interrupted too, so other statements in progress on it stop | aar: `SqliteJs.java` lines 33 to 37; upstream's CHANGELOG for 1.4.3; upstream's suite ("Cancel all OK", which stops a function, an aggregate and a collation) and glue tests 31 to 44. Probe on the 1.4.4 host build (`sqlitejs_cancel_all()` called through Python's ctypes on the library Python's sqlite3 loaded, SQLite 3.46.1): `SELECT spin()` and writes that call `spin()` fail with `interrupted` | +| A function stopped inside an `INSERT`, `UPDATE` or `DELETE` fails that statement and undoes only its changes; the transaction stays open with its earlier changes; Room's `withTransaction` and `runInTransaction` roll back when the block throws; a transaction begun with `BEGIN` needs `ROLLBACK`; SQLite rolls the whole transaction back itself only when the interrupt of the connection ends an `INSERT`, `UPDATE` or `DELETE`, as with a JavaScript collation, and `ROLLBACK` then fails; a `SELECT` that `cancelAll()` stops never ends the transaction | probe on the 1.4.4 host build (`sqlitejs_cancel_all()` called through Python's ctypes on the library Python's sqlite3 loaded, SQLite 3.46.1), after `BEGIN` and one `INSERT`: `UPDATE t SET x = spin()`, `INSERT INTO t VALUES (spin())`, `DELETE FROM t WHERE spin()` and a many-row `UPDATE t SET x = busy(x)` fail with SQLITE_ERROR `interrupted`, and the transaction stays open with its earlier insert; `INSERT INTO t2 SELECT x FROM t ORDER BY x COLLATE spin_collation` fails with SQLITE_INTERRUPT and the transaction is gone, with its earlier insert; `sqlite3_interrupt()` gives the same results; `ROLLBACK` outside a transaction fails with `cannot rollback - no transaction is active`. Probe on the same build, 2026-11-22 (CodeRabbit on #2293), the same way, after `BEGIN` and one `INSERT`: `SELECT x FROM t ORDER BY x COLLATE spin_collation` fails with SQLITE_INTERRUPT and `SELECT spin()` with SQLITE_ERROR, each `interrupted`, and after either the transaction is still open: the count is 4, and `ROLLBACK` succeeds and leaves 3. code: SQLite's `sqlite3VdbeHalt` rolls the transaction back after SQLITE_INTERRUPT only for a statement that is not read-only (`if( !p->readOnly \|\| mrc!=SQLITE_INTERRUPT )`, line 88460 of the 3.49.1 amalgamation in sqlite-js 1.4.4's `libs/sqlite3.c`). device: inside `withTransaction` and inside `runInTransaction`, after an insert, `UPDATE Product SET price = spin()` stopped by `cancelAll()` throws with `interrupted` in its message, a count inside the block still sees the inserted row (5), and after the error leaves the block the count is 4. When SQLite has already rolled back, Room's own rollback fails the same way and its error replaces the `interrupted` one: device, for a write stopped in its collation inside `withTransaction` and again inside `runInTransaction` (the test calls `cancelAll()` only after the insert before it has returned), `DocExamplesTest` asserts that the statement's error contains `interrupted`, that the error leaving Room contains `cannot rollback`, and that the table then has its 4 rows; logcat, tag `DocExamples`, has the errors in full: `statement threw [androidx.core.os.OperationCanceledException: interrupted (code 9)]`, and `withTransaction` (then `runInTransaction`) `threw [android.database.sqlite.SQLiteException: cannot rollback - no transaction is active (code 1)]`. The ticket says that an interrupted write rolls the whole transaction back, as the AAR's README and `SqliteJs.java` did until they were corrected to these results on this branch | +| It does not stop JavaScript that has not started, so call it again until the query ends; nor the JavaScript run while a connection is set up or a stored function loads; SQL run through `db.exec` finishes first; safe from any thread | aar: `SqliteJs.java` lines 34 and 35; glue: "the cancel does not stop v's code while it loads", "the trusted entry point loads w again after the cancel stops it"; upstream's CHANGELOG for 1.4.3 ("JavaScript that begins afterwards runs normally", "safe to call from any thread") | +| The `cancellable` example is the template's, calling `cancelAll()` every 10 ms until the query ends | compiled; template: `ProductDatabase.kt.peb` lines 135 to 155, which it copies with shorter comments and `delay(10)` for `delay(CANCEL_RETRY_MS)`. device: once `spin()` is seen running, a coroutine running `cancellable { products.spin() }` is still active, and it ends when cancelled; the database answers queries afterwards | +| The Java `CancellableQuery`: runs the query on its own thread; `cancel()` returns at once and calls `cancelAll()` every 10 ms until the query has ended; a query that had ended keeps its result, and a second `cancel()` starts no second loop; `get()` waits for the end and throws `CancellationException`, with the query's own error as its cause, when `cancel()` stopped the query; it does the same work as `cancellable()` with one difference: Java's `get()` returns a result that arrives after `cancel()`, and Kotlin drops it; if the coroutine is cancelled while `cancellable()` waits for the query, `cancellable()` ends as cancelled and the query's result or error is dropped; a query that fails with its own error after `cancel()` was called is reported as cancelled, in Java with that error as the cause | compiled (java). Kotlin, device: `DocExamplesTest.cancellableDropsAResultThatArrivesAfterTheCancel` cancels a coroutine whose `cancellable()` query is known to be running (it waits on a latch), asserts that `cancellable()` has not ended 200 ms later, releases the query, which returns 7, and asserts that `cancellable()` ended with `CancellationException`. Kotlin, read: `cancellable()` catches the `CancellationException` from `running.await()` and rethrows it without reading the kept `Result`; in kotlinx-coroutines 1.10.2, the version the template uses, `JobSupport.awaitInternal` (`kotlinx-coroutines-core/common/src/JobSupport.kt` lines 1320 to 1335 at tag 1.10.2) returns a completed state's value, or throws its error, without looking at cancellation, and otherwise suspends in `awaitSuspend`, which is cancellable (lines 1337 to 1348): so the page says "while it waits", and a query that had already ended still gives its result or error. That fast path is read, not tested. Java, read: `get()` wraps any failure once `cancelled` is set. device, `JavaDocExamplesTest`: a query that ends gives its result through `get()`, and gives it again after a `cancel()` that came after its end; `cancel()` is called twice on a running `spin()`, and `get()` then throws `CancellationException` whose cause's message contains `interrupted`, within the test's 10 s limit; `cancel()` returns while its query, which waits on a latch and so cannot end, is still running ("returns at once" on the page is this: it does not wait for the query; no time is measured), and that query's later result comes back from `get()`; a query that throws by itself gives `ExecutionException`; a write stopped inside `runInTransaction` ends as cancelled, its cause's message contains `interrupted`, and the table keeps its 4 rows. `isDone()` is true only once the query has ended and the loop of any `cancel()` can call `cancelAll()` no more. Read in the code: `isDone()` reads `running` first and `stopping` after it, and `cancel()` writes `stopping` before handing the loop to a thread. So when `isDone()` finds the query ended and no loop recorded, a loop still to come starts after the query ended, finds it ended at its first check, and calls no `cancelAll()`. `RunawayQuery.start()` uses it, tested below. The moment it guards against, a loop paused between its check and its `cancelAll()` while the query ends, is too short to test. Read in the code only, not tested: the 10 ms between calls, that the loop cannot be abandoned (it goes on after an `InterruptedException`, as Kotlin's runs under `NonCancellable`), that it always ends, and that the second `cancel()` starts no second loop (the `compareAndSet`) | +| The Java `RunawayQuery`; it never reads the query's result, so it does not notice a failure; `start()` does nothing until the query it started earlier has ended and the loop of its `cancel()` can call `cancelAll()` no more, so that `cancel()` always cancels that query and no late `cancelAll()` of it reaches the next one | compiled (java); device: `cancel()` before `start()` does not throw (that it does nothing else is read in the code: `query` is null), and after `start()` and `cancel()` the database answers queries. After `spin()` is seen running, a second `start()` starts no second one: for 2 s no second thread is seen running `spin()` in SQLite, where a second query arrives within milliseconds. That 2 s is the one fixed time that a very slow phone could let pass with the check missing. With the check taken out of the page, the test fails there. Only that window can show it: after `cancel()`, one query and two look the same, because the second query's `cancel()` loop stops the first `spin()` too (`cancelAll()` stops all JavaScript). That it does not notice a failure is read in the code: nothing calls `get()` | +| The `RunawayQuery` example; `start()` does nothing while the query it started earlier still runs | compiled; device: after `spin()` is seen running, a second `start()` leaves its scope with one job; after `cancel()` that job ends, and the database answers queries. With the check taken out of the page, the test fails: the scope has two jobs when it is counted, and the process then crashes once `cancel()` runs, because the second job's `cancelAll()` calls stop the first job's `spin()`, which fails in a scope with no handler. The check is `job?.isCompleted == false`, not `isActive`: read in kotlinx-coroutines, a cancelled job stops being active at once but completes only when its body has ended, and `cancellable()`'s body ends only after its query has ended and its `cancelAll()` loop has stopped. With `isActive`, a `start()` in that moment would launch a second query that the old loop could stop. template: `MainActivity.kt.peb`'s `startRunaway()` checks `if (runaway?.isActive == true) return`, so it has that narrow window | +| In an activity, pass `lifecycleScope` as the scope | template: `MainActivity.kt.peb` lines 86 to 88 launch `cancellable { ... spin() }` in `lifecycleScope` and line 101 cancels that job. `RunawayQuery` itself was not built into an activity | +| Do not wrap every query: each cancel also interrupts the JavaScript of other queries | follows from what `cancelAll()` stops; aar: `SqliteJs.java` line 34 ("not whenever a coroutine is cancelled") | +| The pages reach readers from the Terminal pages and from Create a new project | `apply.py` on scratch copies (see Format); `test_examples.py` checks every link, parent, prev and next | + ## Format | Claim | Check | |-------|-------| | Pages render through `helpmanual-topic.peb` | rendered with Pebble 4.1.1, the app's engine before it was vendored, from a test database built by `apply.py`: the four pages, `terminal-top` and `cogo-top` render, with titles, unescaped bodies and working links. TODO: render in the app; on 2026-11-13, in the app on a Galaxy Note20 Ultra (debug build C-d-1113-0401) with the test database built from its installed one: the Terminal page shows the new section, its link and the links between the four pages work in the help viewer, and each page was read through at font scale 1.0 and 2.0 | | `apply.py`: a second run changes nothing; it refuses a database below version 2; the Terminal page's link has a heading of its own | run on copies of documentation.db 3.0.0: the second run printed `unchanged` for each page and left the file byte-identical; one declaring 1.9.0 was refused with no row changed; `LastChange`'s `content-i` and `wholedb` rows were stamped, not added; on 2026-11-13 also run on the phone's installed database (`wholedb` 2026-11-02, every page finished HTML, 365 stored `jstopics` files): it adds the section to `terminal-top.html` and to `jstopics/terminal-top.js`, which evaluates in Node with the section at the end of `hmBody`, and a second run changes nothing. Before this, it failed on that database: it read the page as JSON | +| ADFA-7243 and ADFA-7247: `apply.py` adds the three app pages, updates the changed terminal pages and appends a section to `i/project-create-new.html` as it does to `i/terminal-top.html` | run on 2026-11-21 on scratch copies of the two databases in the row above (`wholedb` 2026-10-16, JSON pages; the phone's, `wholedb` 2026-11-02, HTML pages) and of one that already had ADFA-7083's pages: on each, the app pages are added and the changed pages updated, both link sections go in (into `jstopics/terminal-top.js` and `jstopics/project-create-new.js` too on the HTML database), `integrity_check` prints `ok`, and a second run prints `nothing changed` and leaves the file byte-identical. `build.py`'s output for the two pages nobody changed is byte-identical to the merged folder's. Not rendered in the app | +| The app pages at a phone's width and at double font size | body-only render in headless Chrome with the help's own `hmprojectstyles.css`, 500 px wide, at 100% and 200% root font size: text and code wrap, nothing overflows; two tables with long code in a narrow column read badly at 200% and became lists. TODO: in the app at font scale 1.0 and 2.0 | | Phone layout of tables and code blocks | body-only render in headless Chrome (code blocks wrap, tables fit); TODO: on a device at font scale 1.0 and 2.0 | diff --git a/docs/docdb/ADFA-7083/README.md b/docs/docdb/ADFA-7083/README.md index 30ea6692be..445cb398dd 100644 --- a/docs/docdb/ADFA-7083/README.md +++ b/docs/docdb/ADFA-7083/README.md @@ -1,6 +1,8 @@ -# ADFA-7083: sqlite-js documentation pages +# sqlite-js documentation pages (ADFA-7083, ADFA-7243, ADFA-7247) -Four Help+Manual style pages for `documentation.db`, in the `i/` set, reached from the Terminal page (`i/terminal-top.html`): +Seven Help+Manual style pages for `documentation.db`, in the `i/` set. + +Four cover the terminal package ([ADFA-7081](https://appdevforall.atlassian.net/browse/ADFA-7081)) and are reached from the Terminal page (`i/terminal-top.html`): | Page | Path | |------|------| @@ -9,16 +11,29 @@ Four Help+Manual style pages for `documentation.db`, in the `i/` set, reached fr | JavaScript in sqlite-js | `i/sqlite-js-javascript.html` | | JavaScript basics | `i/javascript-intro.html` | -They document the terminal package ([ADFA-7081](https://appdevforall.atlassian.net/browse/ADFA-7081)), sqlite-js 1.4.2 and later: upstream's 1.4.0 and 1.4.2 releases merged our fixes. Apps built with Code on the Go ([ADFA-7082](https://appdevforall.atlassian.net/browse/ADFA-7082)) are not covered yet. +They describe sqlite-js 1.4.2 and later, and say what 1.4.4 changed ([ADFA-7243](https://appdevforall.atlassian.net/browse/ADFA-7243)): a `js_create_` function fails when it cannot store the function. + +Three cover apps built with Code on the Go ([ADFA-7247](https://appdevforall.atlassian.net/browse/ADFA-7247)): the sqlite-js AAR (`subprojects/sqlite-js`, 1.4.4) and the JavaScript in SQLite project template (dev-assets `templates/JavaScriptInSQLite`). They are reached from Create a new project (`i/project-create-new.html`) and from the terminal pages: + +| Page | Path | +|------|------| +| JavaScript in SQLite for apps | `i/sqlite-js-app-top.html` | +| Set up a database with JavaScript functions | `i/sqlite-js-app-database.html` | +| Stop JavaScript that never ends | `i/sqlite-js-app-cancel.html` | + +All seven are in this one folder, though three tickets wrote them, because `apply.py` writes a page by its path: a second folder with its own copy of a page would undo the first one's. One run of `apply.py` brings a database up to date, whether or not it has the earlier pages. - `pages/*.md`: the source, a small Markdown subset (see `build.py`). - `build.py OUT_DIR`: turns each page into the JSON facts that `helpmanual-topic.peb` renders. -- `apply.py DB`: adds the pages to a `documentation.db` in one transaction, compressed against its `CompressionDictionary`, and appends a section with a link to `i/terminal-top.html`. It handles both forms of that page: a template context (JSON), as in databases up to `wholedb` 2026-10-16, and a finished Help+Manual page (HTML), as from 2026-11-02. A database of the second form also stores `i/jstopics/terminal-top.js`, which the help viewer loads to move between pages, and the section goes into it too. A second run changes nothing. It refuses a database that declares a version below 2. Run it on a copy first; the master is edited by a `docdb-studio` maintainer. Needs the `brotli` command. -- `test_examples.py`: runs every ` ```sql ` example against a real `sqlite3` with sqlite-js loaded, runs again each one that creates nothing, as a reader would, and checks that links, including each page's parent, prev and next, resolve: `SQLITE3=sqlite3 EXT=/path/to/sqlite-js.so python3 test_examples.py`. +- `apply.py DB`: adds the pages to a `documentation.db` in one transaction, compressed against its `CompressionDictionary`. A page whose stored row already matches is left alone. It also appends a section with a link to `i/terminal-top.html` and one to `i/project-create-new.html`. It handles both forms of those pages: a template context (JSON), as in databases up to `wholedb` 2026-10-16, and a finished Help+Manual page (HTML), as from 2026-11-02. A database of the second form also stores each page's `i/jstopics/` file, which the help viewer loads to move between pages, and the section goes into it too. A second run changes nothing. It refuses a database that declares a version below 2. Run it on a copy first; the master is edited by a `docdb-studio` maintainer. Needs the `brotli` command. +- `test_examples.py`: runs every ` ```sql ` example against a real `sqlite3` with sqlite-js loaded, runs again each one that creates nothing, as a reader would, and checks that links, including each page's parent, prev and next, resolve. An example's `-- Error:` line names an error that its statement must report. Run it against sqlite-js 1.4.4: `SQLITE3=sqlite3 EXT=/path/to/sqlite-js.so python3 test_examples.py`. +- `test_app_examples.py`: checks the app pages' ` ```gradle `, ` ```kotlin ` and ` ```java ` examples. It builds the Kotlin ones in a project made from the template, with the AAR, and the Java ones in a second project, the template with its Kotlin sources and Kotlin-only build lines removed and the page's ` ```gradle-java ` settings added. It runs their SQL on the host. With `DEVICE=1` it also runs them on a device, under `app-test/DocExamplesTest.kt` and `app-test/JavaDocExamplesTest.java`, each of which installs and removes its own app. If Gradle skips a slow device ("Unknown API Level"), install the two APKs it built for each project with `adb install`, run `adb shell am instrument -w org.appdevforall.sqlitejs.docexamples.test/androidx.test.runner.AndroidJUnitRunner` (Kotlin) and `adb shell am instrument -w org.appdevforall.sqlitejs.docexamples.java.test/androidx.test.runner.AndroidJUnitRunner` (Java), and uninstall the four packages: those two, and the same names without `.test`. Its docstring has the usage. It needs a dev-assets checkout, the AAR, the Android SDK and Gradle. - `CLAIMS.md`: every factual claim in the pages, and how each was checked. ## Not done here -- The table of contents (`i/hmcontent.html`), the keyword index and the search index (`i/zoom_*.js`) are generated by Help+Manual and do not list these pages. The pages are reachable from `terminal-top.html` and from each other. Regenerate those files with the next Help+Manual export. +- The app pages' examples are compiled, their SQL has run on a host, and the two tests in `app-test/` have run the Kotlin and the Java ones on one phone (32-bit ARM, Android 9). No 64-bit device has run them. The template's own screen and the pages in the help viewer have not been checked on a device for these tickets: see `CLAIMS.md`. +- The table of contents (`i/hmcontent.html`), the keyword index and the search index (`i/zoom_*.js`) are generated by Help+Manual and do not list these pages. The pages are reachable from `terminal-top.html`, from `project-create-new.html` and from each other. Regenerate those files with the next Help+Manual export. +- The template's tooltip (`template.javascript.sqlite`) is not in the databases these scripts were tried on, and these scripts do not add it. - Attribution: `sqlite-js-functions.html` adapts the upstream README (Apache-2.0) and carries the notice. The other pages are original text. `javascript-intro.html` reuses no MDN text. - External addresses appear as text, not links: documentation stays on the device. diff --git a/docs/docdb/ADFA-7083/app-test/DocExamplesTest.kt b/docs/docdb/ADFA-7083/app-test/DocExamplesTest.kt new file mode 100644 index 0000000000..3adb0d5538 --- /dev/null +++ b/docs/docdb/ADFA-7083/app-test/DocExamplesTest.kt @@ -0,0 +1,359 @@ +// Runs the Kotlin examples of the app pages on a device. test_app_examples.py copies this file +// into the template project, next to the examples, when DEVICE=1. +package docexamples + +import android.content.Context +import android.util.Log +import androidx.room.withTransaction +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import io.requery.android.database.sqlite.SQLiteCustomExtension +import io.requery.android.database.sqlite.SQLiteDatabase +import io.requery.android.database.sqlite.SQLiteDatabaseConfiguration +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.job +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import org.appdevforall.sqlitejs.SqliteJs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class DocExamplesTest { + private val context: Context + get() = InstrumentationRegistry.getInstrumentation().targetContext + + private val sample = listOf( + Product(name = "Red Apple", price = 0.5), + Product(name = "Whole Wheat Bread", price = 3.25), + Product(name = "Milk, 1 litre", price = 1.2), + Product(name = "Coffee & Tea Sampler", price = 12.0), + ) + + private fun SQLiteDatabase.text(sql: String): String? = + rawQuery(sql, emptyArray()).use { if (it.moveToFirst()) it.getString(0) else null } + + private fun failure(run: () -> Unit): String { + try { + run() + } catch (e: Exception) { + return e.message ?: e.toString() + } + fail("no exception was thrown") + return "" + } + + @Test + fun roomCallsTheStoredFunctionsAndCancelStopsARunaway() = runBlocking { + context.deleteDatabase("products.db") + val db = openProductDatabase(context) + try { + val products = db.products() + products.insert(sample) + assertEquals( + listOf("red-apple", "whole-wheat-bread", "milk-1-litre", "coffee-tea-sampler"), + products.slugs(), + ) + assertEquals(2.225, products.medianPrice()!!, 1e-9) + + // cancellable(): cancelling the coroutine stops JavaScript that never ends + withTimeout(120_000) { + val runaway = launch { cancellable { products.spin() } } + awaitSpin(true) + assertTrue("spin is still running", runaway.isActive) + runaway.cancelAndJoin() + } + + // RunawayQuery, as a Cancel button would use it; the database works afterwards + val scope = CoroutineScope(Dispatchers.Default + Job()) + val runaway = RunawayQuery(scope, products) + runaway.start() + try { + awaitSpin(true) + // a second start() while the query runs starts no second query + runaway.start() + assertEquals(1, scope.coroutineContext.job.children.count()) + } finally { + runaway.cancel() + // its job ends only once cancellable()'s cancelAll() calls have ended, so that none + // reaches slugs() + withTimeout(60_000) { scope.coroutineContext.job.children.forEach { it.join() } } + } + withTimeout(60_000) { assertEquals(4, cancellable { products.slugs() }.size) } + } finally { + db.close() + } + + // storing again, as on the app's next start, changes nothing and does not fail + storeFunctions(context) + // a second database object sees the stored functions on its new connections + val again = openProductDatabase(context) + try { + assertEquals(4, again.products().slugs().size) + } finally { + again.close() + } + } + + private fun ProductDatabase.count(): Int = + openHelper.writableDatabase.query("SELECT count(*) FROM Product").use { it.moveToFirst(); it.getInt(0) } + + // Runs, inside a transaction that transaction() opens, an insert and then an UPDATE whose + // JavaScript never ends, which cancelAll() stops. Returns the row count the transaction saw + // after the UPDATE failed, the UPDATE's error, and the row count after the transaction. + private fun cancelledWrite(db: ProductDatabase, transaction: (block: () -> Unit) -> Unit): Triple { + val stopped = AtomicBoolean(false) + // cancels only once the plain INSERT has returned, so that no cancel can reach it; a cancel + // before the UPDATE's JavaScript starts does nothing, so it is called until the UPDATE ends + val inserted = CountDownLatch(1) + val canceller = Thread { + inserted.await() + while (!stopped.get()) { + SqliteJs.cancelAll() + Thread.sleep(10) + } + } + canceller.start() + var inside = -1 + var message = "" + try { + transaction { + val raw = db.openHelper.writableDatabase + try { + raw.execSQL("INSERT INTO Product (name, price) VALUES ('Extra', 1.0)") + } finally { + inserted.countDown() + } + try { + raw.execSQL("UPDATE Product SET price = spin()") + stopped.set(true) + fail("the UPDATE ended without an error") + } catch (e: Exception) { + stopped.set(true) + message = e.message ?: e.toString() + inside = db.count() + throw e + } + } + } catch (e: Exception) { + // the block's error leaves the transaction, as the page says to let it + } finally { + stopped.set(true) + inserted.countDown() + canceller.join() + } + return Triple(inside, message, db.count()) + } + + @Test + fun aStoppedWriteLeavesItsTransactionOpenAndRoomRollsItBack() = runBlocking { + context.deleteDatabase("products.db") + val db = openProductDatabase(context) + try { + db.products().insert(sample) + for (how in listOf("withTransaction", "runInTransaction")) { + val (inside, message, after) = cancelledWrite(db) { block -> + if (how == "withTransaction") runBlocking(Dispatchers.IO) { db.withTransaction { block() } } + else db.runInTransaction { block() } + } + assertTrue("$how: $message", message.contains("interrupted")) + assertEquals("$how: the transaction stayed open, with its earlier insert", 5, inside) + assertEquals("$how: Room rolled the transaction back", 4, after) + } + } finally { + db.close() + } + } + + // whether a thread is in sqlite-android's native code for the DAO's spin() query, and for no + // other statement: the stack must have Room's generated spin() too + private fun spinIsRunning(): Boolean = + Thread.getAllStackTraces().values.any { stack -> + stack.any { it.className.endsWith(".SQLiteConnection") && it.methodName.startsWith("nativeExecute") } && + stack.any { it.className.endsWith("ProductDao_Impl") && it.methodName.contains("spin") } + } + + // waits until spin() is, or is no longer, running in SQLite + private suspend fun awaitSpin(running: Boolean) { + withTimeout(60_000) { + while (spinIsRunning() != running) delay(20) + } + } + + // cancellable() drops a result that arrives after the cancel: the Java CancellableQuery keeps it + @Test + fun cancellableDropsAResultThatArrivesAfterTheCancel() = runBlocking { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val ended = AtomicReference?>(null) + val job = CoroutineScope(Dispatchers.Default).launch { + try { + ended.set(Result.success(cancellable { entered.countDown(); release.await(); 7 })) + } catch (e: CancellationException) { + ended.set(Result.failure(e)) + throw e + } + } + try { + // the query is running, so cancellable() is waiting for it, or about to + val running = withContext(Dispatchers.IO) { entered.await(60, TimeUnit.SECONDS) } + assertTrue("the query started", running) + delay(200) + job.cancel() + // cancellable() goes on calling cancelAll() until the query ends: it ends when released + delay(200) + assertTrue("cancellable() waits for the query to end", !job.isCompleted) + } finally { + // whatever failed above, the query ends, and with it cancellable()'s cancelAll() calls + release.countDown() + } + withTimeout(60_000) { job.join() } + assertTrue("ended as cancelled, without the 7: ${ended.get()}", ended.get()?.exceptionOrNull() is CancellationException) + } + + // What Room reports when SQLite has already rolled the transaction back (a write whose + // collation is stopped ends with SQLITE_INTERRUPT), and that cancelling a coroutine without + // cancellable() does not end a query that never returns. + @Test + fun whatRoomDoesWhenSqliteRolledBackAndWhenAPlainCoroutineIsCancelled() = runBlocking { + context.deleteDatabase("products.db") + storeFunctions(context) + val config = SQLiteDatabaseConfiguration(context.getDatabasePath("products.db").path, SQLiteDatabase.OPEN_READWRITE) + config.customExtensions.add(SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT)) + SQLiteDatabase.openDatabase(config, null, null).use { raw -> + raw.text("SELECT js_create_collation('spin_collation', '(function (a, b) { for (;;) {} })')") + } + val db = openProductDatabase(context) + try { + db.products().insert(sample) + for (how in listOf("withTransaction", "runInTransaction")) { + val stopped = AtomicBoolean(false) + // cancels only once the plain INSERT has returned, so that no cancel can reach it; + // a cancel before the collation starts does nothing, so it is called until the end + val inserted = CountDownLatch(1) + val canceller = Thread { + inserted.await() + while (!stopped.get()) { + SqliteJs.cancelAll() + Thread.sleep(10) + } + } + canceller.start() + var inner = "none" + val block = { + val raw = db.openHelper.writableDatabase + try { + raw.execSQL("INSERT INTO Product (name, price) VALUES ('Extra', 1.0)") + } finally { + inserted.countDown() + } + try { + raw.execSQL("INSERT INTO Product (name, price) SELECT name, price FROM Product ORDER BY name COLLATE spin_collation") + } catch (e: Exception) { + inner = "${e.javaClass.name}: ${e.message}" + throw e + } finally { + stopped.set(true) + } + } + val outer = try { + if (how == "withTransaction") withContext(Dispatchers.IO) { db.withTransaction { block() } } + else withContext(Dispatchers.IO) { db.runInTransaction { block() } } + "none" + } catch (e: Exception) { + "${e.javaClass.name}: ${e.message}" + } finally { + stopped.set(true) + inserted.countDown() + canceller.join() + } + Log.i("DocExamples", "collation write in $how: statement threw [$inner], $how threw [$outer]") + assertTrue("$how: the statement was interrupted: $inner", inner.contains("interrupted")) + assertTrue("$how: Room's rollback failed: $outer", outer.contains("cannot rollback")) + assertEquals("$how: nothing of the transaction is kept", 4, db.count()) + } + + // A plain cancel, without cancellable(). In a scope of its own: its failure, once + // cancelAll() stops it, is not this test's. + val ended = AtomicReference?>(null) + val plain = CoroutineScope(Dispatchers.Default).launch { + ended.set(runCatching { db.products().spin() }) + } + try { + // cancel only once spin() is running in SQLite: a cancel before the query started + // would end the job at once, and prove nothing + awaitSpin(true) + plain.cancel() + // spin() never returns, so no wait is too short for this check: it fails only if + // the cancel ended the query + delay(2000) + Log.i("DocExamples", "2 s after a plain cancel of spin(): job completed = ${plain.isCompleted}") + assertTrue("a plain cancel left spin() running in SQLite", spinIsRunning() && !plain.isCompleted && ended.get() == null) + } finally { + // only cancelAll() ends it; also after a failure above, or spin() would run on + withTimeout(60_000) { + while (!plain.isCompleted) { + SqliteJs.cancelAll() + delay(10) + } + } + } + // it ended as a failure, not with a value + assertTrue("spin() ended by failing: ${ended.get()}", ended.get()?.isFailure == true) + // spin() keeps its connection busy until cancelAll() stops it: the database answers again + repeat(20) { SqliteJs.cancelAll(); delay(10) } + assertEquals(4, db.count()) + } finally { + db.close() + } + } + + @Test + fun entryPointRunsNothingStoredInASharedFile() { + val file = File(context.cacheDir, "shared.db") + file.delete() + File(file.path + "-journal").delete() + // another party's file: it stores a function + val config = SQLiteDatabaseConfiguration(file.path, SQLiteDatabase.CREATE_IF_NECESSARY or SQLiteDatabase.OPEN_READWRITE) + config.customExtensions.add(SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT)) + SQLiteDatabase.openDatabase(config, null, null).use { db -> + db.text("SELECT js_init_table()") + db.text("SELECT js_create_scalar('stored', '(function (args) { return 1; })')") + // rawQuery runs nothing until its cursor is read + db.rawQuery("SELECT js_create_scalar('unread', '(function (args) { return 2; })')", emptyArray()).close() + assertTrue(failure { db.text("SELECT unread()") }.contains("no such function")) + } + + openSharedFile(context, file).use { db -> + assertEquals("1.4.4", db.text("SELECT js_version()")) + assertEquals("42", db.text("SELECT js_eval('6 * 7')")) + assertTrue(failure { db.text("SELECT stored()") }.contains("no such function")) + // read-only, with a js_functions table: a new function cannot be stored, but works here + val message = failure { db.text("SELECT js_create_scalar('mine', '(function (args) { return 3; })')") } + assertTrue(message, message.contains("could not be stored in js_functions")) + assertEquals("3", db.text("SELECT mine()")) + } + + // the trusted entry point loads what the file stores + val trusted = SQLiteDatabaseConfiguration(file.path, SQLiteDatabase.OPEN_READONLY) + trusted.customExtensions.add(SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT_FOR_TRUSTED_DATABASE)) + SQLiteDatabase.openDatabase(trusted, null, null).use { db -> + assertEquals("1", db.text("SELECT stored()")) + } + } +} diff --git a/docs/docdb/ADFA-7083/app-test/JavaDocExamplesTest.java b/docs/docdb/ADFA-7083/app-test/JavaDocExamplesTest.java new file mode 100644 index 0000000000..73143cb96a --- /dev/null +++ b/docs/docdb/ADFA-7083/app-test/JavaDocExamplesTest.java @@ -0,0 +1,246 @@ +// Runs the Java examples of the app pages on a device. test_app_examples.py copies this file +// into its Java project, next to the examples, and runs it when DEVICE=1. +package docexamples; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import android.content.Context; +import android.database.Cursor; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import io.requery.android.database.sqlite.SQLiteCustomExtension; +import io.requery.android.database.sqlite.SQLiteDatabase; +import io.requery.android.database.sqlite.SQLiteDatabaseConfiguration; +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.appdevforall.sqlitejs.SqliteJs; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class JavaDocExamplesTest { + + private static Context context() { + return InstrumentationRegistry.getInstrumentation().getTargetContext(); + } + + private static List sample() { + return Arrays.asList( + new Product("Red Apple", 0.5), + new Product("Whole Wheat Bread", 3.25), + new Product("Milk, 1 litre", 1.2), + new Product("Coffee & Tea Sampler", 12.0)); + } + + private static String text(SQLiteDatabase db, String sql) { + try (Cursor cursor = db.rawQuery(sql, new Object[0])) { + return cursor.moveToFirst() ? cursor.getString(0) : null; + } + } + + private static String failure(SQLiteDatabase db, String sql) { + try { + text(db, sql); + } catch (Exception e) { + return String.valueOf(e.getMessage()); + } + fail("no exception was thrown by " + sql); + return ""; + } + + // how many threads are in sqlite-android's native code for the DAO's spin() query, and for no + // other statement: the stack must have Room's generated spin() too + private static int spinsRunning() { + int running = 0; + for (StackTraceElement[] stack : Thread.getAllStackTraces().values()) { + boolean inSqlite = false; + boolean inSpin = false; + for (StackTraceElement frame : stack) { + inSqlite |= frame.getClassName().endsWith(".SQLiteConnection") && frame.getMethodName().startsWith("nativeExecute"); + inSpin |= frame.getClassName().endsWith("ProductDao_Impl") && frame.getMethodName().contains("spin"); + } + if (inSqlite && inSpin) { + running++; + } + } + return running; + } + + private static boolean spinIsRunning() { + return spinsRunning() > 0; + } + + // waits until spin() is, or is no longer, running in SQLite + private static void awaitSpin(boolean running) throws InterruptedException { + long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + while (spinIsRunning() != running) { + assertTrue("spin() running = " + running + " within 60 s", System.nanoTime() < end); + Thread.sleep(20); + } + } + + // what get() throws, on another thread so that a get() that never returns fails the test + private static Throwable thrownByGet(CancellableQuery query) throws Exception { + ExecutorService waiter = Executors.newSingleThreadExecutor(); + try { + Future thrown = waiter.submit(() -> { + try { + query.get(); + return null; + } catch (Throwable t) { + return t; + } + }); + return thrown.get(10, TimeUnit.SECONDS); + } finally { + waiter.shutdownNow(); + } + } + + @Test + public void roomCallsTheStoredFunctionsAndCancelStopsARunaway() throws Exception { + context().deleteDatabase(ProductFunctions.NAME); + ProductDatabase db = ProductDatabases.open(context()); + try { + ProductDao products = db.products(); + products.insert(sample()); + assertEquals( + Arrays.asList("red-apple", "whole-wheat-bread", "milk-1-litre", "coffee-tea-sampler"), + products.slugs()); + assertEquals(2.225, products.medianPrice(), 1e-9); + + // a query that ends gives its result through get(), also after a cancel() that came too late + CancellableQuery> ended = new CancellableQuery<>(products::slugs); + assertEquals(4, ended.get().size()); + ended.cancel(); + assertEquals(4, ended.get().size()); + + // cancel() stops JavaScript that never ends, and get() then reports a cancel + CancellableQuery spin = new CancellableQuery<>(products::spin); + try { + awaitSpin(true); + } finally { + spin.cancel(); + } + spin.cancel(); + Throwable thrown = thrownByGet(spin); + assertTrue(String.valueOf(thrown), thrown instanceof CancellationException); + // the query's own error is its cause + assertTrue(String.valueOf(thrown.getCause()), + thrown.getCause() != null && String.valueOf(thrown.getCause().getMessage()).contains("interrupted")); + + // cancel() does not wait for the query: this one cannot end until the latch opens, so + // a cancel() that waited would never return. A query that ends with a result after + // the cancel gives that result. + CountDownLatch latch = new CountDownLatch(1); + CancellableQuery waiting = new CancellableQuery<>(() -> { + latch.await(); + return 7; + }); + ExecutorService canceller = Executors.newSingleThreadExecutor(); + try { + canceller.submit(waiting::cancel).get(60, TimeUnit.SECONDS); + } finally { + canceller.shutdownNow(); + // also after a failure above, so that the query and the loop of its cancel() end + latch.countDown(); + } + assertEquals(Integer.valueOf(7), waiting.get()); + + // a query that fails by itself is not reported as cancelled + CancellableQuery broken = new CancellableQuery<>(() -> { + throw new IllegalStateException("broken"); + }); + thrown = thrownByGet(broken); + assertTrue(String.valueOf(thrown), thrown instanceof ExecutionException); + + // RunawayQuery, as a Cancel button would use it; the database works afterwards + RunawayQuery runaway = new RunawayQuery(products); + runaway.cancel(); + runaway.start(); + try { + awaitSpin(true); + // a second start() while the query runs starts no second query. A second spin() + // reaches SQLite within milliseconds, so none in 2 s means there is none. (After + // cancel(), a second query could not be told apart: its cancel() loop would stop + // the first spin() too, since cancelAll() stops all JavaScript.) + runaway.start(); + long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (System.nanoTime() < end) { + assertTrue("a second spin() is running", spinsRunning() < 2); + Thread.sleep(20); + } + } finally { + runaway.cancel(); + } + // its cancelAll() calls end with its query; a moment more, so that none reaches slugs() + awaitSpin(false); + Thread.sleep(300); + assertEquals(4, products.slugs().size()); + + // a write stopped inside runInTransaction: Room rolls the transaction back. cancel() calls + // cancelAll() until the write ends, so it need not wait for the UPDATE to start: the + // insert before it runs no JavaScript, and cancelAll() stops nothing else + CancellableQuery write = new CancellableQuery<>(() -> { + db.runInTransaction(() -> { + db.getOpenHelper().getWritableDatabase() + .execSQL("INSERT INTO Product (name, price) VALUES ('Extra', 1.0)"); + db.getOpenHelper().getWritableDatabase().execSQL("UPDATE Product SET price = spin()"); + }); + return null; + }); + write.cancel(); + thrown = thrownByGet(write); + assertTrue(String.valueOf(thrown), thrown instanceof CancellationException); + // the cancel stopped the UPDATE's JavaScript: the write did not fail for another reason + assertTrue(String.valueOf(thrown.getCause()), + thrown.getCause() != null && String.valueOf(thrown.getCause().getMessage()).contains("interrupted")); + // a moment, so that the last cancelAll() of that cancel cannot reach slugs() + Thread.sleep(300); + assertEquals(4, products.slugs().size()); + } finally { + db.close(); + } + + // storing again, as on the app's next start, changes nothing and does not fail + ProductFunctions.store(context()); + ProductDatabase again = ProductDatabases.open(context()); + try { + assertEquals(4, again.products().slugs().size()); + } finally { + again.close(); + } + } + + @Test + public void entryPointRunsNothingStoredInASharedFile() { + File file = new File(context().getCacheDir(), "shared.db"); + file.delete(); + new File(file.getPath() + "-journal").delete(); + // another party's file: it stores a function + SQLiteDatabaseConfiguration config = new SQLiteDatabaseConfiguration( + file.getPath(), SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.OPEN_READWRITE); + config.customExtensions.add(new SQLiteCustomExtension(SqliteJs.libraryPath(context()), SqliteJs.ENTRY_POINT)); + try (SQLiteDatabase db = SQLiteDatabase.openDatabase(config, null, null)) { + text(db, "SELECT js_init_table()"); + text(db, "SELECT js_create_scalar('stored', '(function (args) { return 1; })')"); + } + + try (SQLiteDatabase db = SharedFiles.open(context(), file)) { + assertEquals("1.4.4", text(db, "SELECT js_version()")); + assertEquals("42", text(db, "SELECT js_eval('6 * 7')")); + assertTrue(failure(db, "SELECT stored()").contains("no such function")); + assertTrue(db.isReadOnly()); + } + } +} diff --git a/docs/docdb/ADFA-7083/apply.py b/docs/docdb/ADFA-7083/apply.py index 1357acb1e0..ed450e340b 100644 --- a/docs/docdb/ADFA-7083/apply.py +++ b/docs/docdb/ADFA-7083/apply.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Adds the ADFA-7083 pages to a documentation.db. +"""Adds the pages of this folder (ADFA-7083, ADFA-7243, ADFA-7247) to a documentation.db. Usage: python3 apply.py DOCUMENTATION_DB @@ -8,14 +8,15 @@ pipeline does), and in ONE transaction: - upserts a Content row per page whose row is missing or differs, path i/, templateId of helpmanual-topic.peb, text/html, EN-us; - - appends a section that links to the new pages to i/terminal-top.html, - unless it has one. The page's other sections start collapsed, so the link + - appends a section that links to the new pages to i/terminal-top.html, and + one to i/project-create-new.html, which lists the project templates, unless + the page has it. A page's other sections start collapsed, so the link gets a heading of its own, where readers see it. The page is either a template context (JSON, rendered by helpmanual-topic.peb), as in databases up to wholedb 2026-10-16, or a finished Help+Manual page (HTML), as from wholedb 2026-11-02; the section goes at the end of the topic's body in both. - A database of the second kind also stores the page's i/jstopics/ - terminal-top.js, which the help viewer loads to move between pages, so the + A database of the second kind also stores the page's i/jstopics/ file + (terminal-top.js), which the help viewer loads to move between pages, so the section goes into that file's hmBody too; - if a page or the link changed, stamps the content-i and wholedb rows of LastChange, inserting any that is missing, as docdb-studio does. @@ -37,47 +38,55 @@ import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) -LINK_FILE = "terminal-top.html" -LINK_TARGET = "sqlite-js-top.html" -LINK_HTML = ('

' - 'SQL functions in JavaScript

\r\n' - '

To write SQL functions in JavaScript, see ' - 'JavaScript in SQLite (sqlite-js).

\r\n') -WHO = "ADFA-7083" +HEADING = ('

' + '%s

\r\n') +# (page that gets the section, page the section links to, the section's anchor id, the section) +LINKS = [ + ("terminal-top.html", "sqlite-js-top.html", "sqlite-js", + HEADING % ("sqlite-js", "SQL functions in JavaScript") + + '

To write SQL functions in JavaScript, see ' + 'JavaScript in SQLite (sqlite-js).

\r\n'), + ("project-create-new.html", "sqlite-js-app-top.html", "sqlite-js-app", + HEADING % ("sqlite-js-app", "JavaScript in SQLite template") + + '

The JavaScript in SQLite template creates an app whose Room database calls ' + 'functions written in JavaScript. See ' + 'JavaScript in SQLite for apps.

\r\n'), +] +WHO = "ADFA-7247" # A finished page's topic body ends where the skin closes its scroller div. HTML_BODY_END = re.compile(r"\n\s*\s*") # A stored jstopics file is hmLoadTopic({...}) whose last property is the hmBody string. JSTOPIC_BODY_END = re.compile(r'"\s*\}\)\s*$') -def add_link(text): - """The page with the link section added, or None if it already has it.""" +def add_link(text, file, anchor, section): + """The page with the section added, or None if it already has it.""" if text.lstrip("\ufeff \t\r\n").startswith("{"): page = json.loads(text) - if 'id="sqlite-js"' in page["hmBody"]: + if 'id="%s"' % anchor in page["hmBody"]: return None - page["hmBody"] += LINK_HTML + page["hmBody"] += section return json.dumps(page, ensure_ascii=False) - if 'id="sqlite-js"' in text: + if 'id="%s"' % anchor in text: return None ends = list(HTML_BODY_END.finditer(text)) if len(ends) != 1: raise RuntimeError("i/%s is HTML, but its topic body's end was found %d times, not once" - % (LINK_FILE, len(ends))) + % (file, len(ends))) at = ends[0].start() - return text[:at] + "\n" + LINK_HTML.replace("\r\n", "\n").rstrip("\n") + text[at:] + return text[:at] + "\n" + section.replace("\r\n", "\n").rstrip("\n") + text[at:] -def add_link_to_jstopic(text): - """The jstopics file with the link section added to its hmBody, or None if it has it.""" - if 'id=\\"sqlite-js\\"' in text: +def add_link_to_jstopic(text, file, anchor, section): + """The jstopics file with the section added to its hmBody, or None if it has it.""" + if 'id=\\"%s\\"' % anchor in text: return None ends = list(JSTOPIC_BODY_END.finditer(text)) body = text.rfind("hmBody:") if len(ends) != 1 or body < 0 or re.search(r"\n\s*hm\w+:", text[body:]): - raise RuntimeError("i/jstopics/%s does not end with its hmBody string" % LINK_FILE.replace(".html", ".js")) + raise RuntimeError("i/jstopics/%s does not end with its hmBody string" % file.replace(".html", ".js")) # escaped as Help+Manual writes these strings: \" for quotes, <\/ for ` notes, pipe tables, fenced code blocks, `code`, **bold** and [links](page.html). A link to an http(s) address is shown as text, because the documentation stays on the device. +The word after a code block's opening fence (`sql`, `kotlin`, `gradle`, `text`) is +for the tests, which run or compile the block: the page shows every block the same. """ import html import json @@ -30,8 +32,12 @@ HERE = os.path.dirname(os.path.abspath(__file__)) -# Pages of the existing help that these pages hang under, outermost first. -ROOT_TRAIL = [("cogo-top.html", "Code on the Go"), ("terminal-top.html", "Terminal")] +# Pages of the existing help that these pages hang under: file -> (title, parent). +EXISTING = { + "cogo-top.html": ("Code on the Go", None), + "terminal-top.html": ("Terminal", "cogo-top.html"), + "project-create-new.html": ("Create a new project", "cogo-top.html"), +} P_STYLE = { "p_Normal": "", @@ -160,16 +166,16 @@ def main(): if name.endswith(".md"): meta, md = read_page(os.path.join(HERE, "pages", name)) pages[meta["file"]] = (meta, md) - titles = dict(ROOT_TRAIL) + titles = {f: title for f, (title, _) in EXISTING.items()} titles.update({f: m["title"] for f, (m, _) in pages.items()}) - parents = {f: m["parent"] for f, (m, _) in pages.items()} + parents = {f: parent for f, (_, parent) in EXISTING.items()} + parents.update({f: m["parent"] for f, (m, _) in pages.items()}) for file, (meta, md) in pages.items(): trail, p = [], meta["parent"] - while p in titles and p != "cogo-top.html": + while p is not None: # a parent that is neither a page here nor in EXISTING is a KeyError trail.insert(0, p) - p = parents.get(p, "terminal-top.html" if p != "terminal-top.html" else "cogo-top.html") - trail.insert(0, "cogo-top.html") + p = parents[p] crumbs = " > ".join('%s' % (f, esc(titles[f])) for f in trail) facts = { "file": file, diff --git a/docs/docdb/ADFA-7083/pages/sqlite-js-app-cancel.md b/docs/docdb/ADFA-7083/pages/sqlite-js-app-cancel.md new file mode 100644 index 0000000000..0237633a9c --- /dev/null +++ b/docs/docdb/ADFA-7083/pages/sqlite-js-app-cancel.md @@ -0,0 +1,204 @@ +--- +file: sqlite-js-app-cancel.html +title: Stop JavaScript that never ends +description: How SqliteJs.cancelAll() stops a runaway JavaScript function in an app, and what else it interrupts. +parent: sqlite-js-app-top.html +prev: sqlite-js-app-database.html +--- + +`SqliteJs.cancelAll()` stops a JavaScript function that never returns. Neither Room nor Android's own way to cancel a query can stop one, and cancelling the coroutine that waits for the query does not stop it either. Until the function stops, its query keeps one database connection busy. + +Call `cancelAll()` only when you know that a runaway function is running, for example from a **Cancel** button. It interrupts more than one query, as this page explains. + +## What cancelAll() stops + +`cancelAll()` stops the JavaScript that is running at that moment, in every query, on every connection of your app. + +- Each call into JavaScript that it stops fails with the error `interrupted`. JavaScript cannot catch this error. +- The connection of each such call is interrupted too. Any other statement in progress on that connection also stops. + +So a query that you did not mean to stop can fail too, if it was running JavaScript at that moment. Run it again. + +## A stopped statement inside a transaction + +When `cancelAll()` stops a function that an `INSERT`, `UPDATE` or `DELETE` called, that statement fails, and SQLite undoes the changes of that statement only. The transaction stays open, with the changes made before the statement. + +So roll the transaction back, and run all of it again: + +- Room's `withTransaction` and `runInTransaction` roll back when their block throws. Let the error leave the block. +- If your code began the transaction itself with `BEGIN`, run `ROLLBACK`. + +In one case SQLite rolls the whole transaction back by itself: when the interrupt of the connection, not the function's error, ends an `INSERT`, `UPDATE` or `DELETE`. That happens to one that sorts with a JavaScript collation, such as `INSERT ... SELECT ... ORDER BY name COLLATE ...`. The transaction is then already gone: + +- `ROLLBACK` fails with `cannot rollback - no transaction is active`. +- Room's own rollback fails the same way. `withTransaction` and `runInTransaction` then throw that error, not the `interrupted` error. + +Treat either error the same way: the transaction is gone, so run all of it again. + +A `SELECT` that `cancelAll()` stops never ends the transaction, even one that sorts with a JavaScript collation. The changes made before it stay in the transaction until you commit it or roll it back. + +## What cancelAll() does not stop + +- **JavaScript that has not started.** A query that has not reached its JavaScript yet runs it normally afterward. So call `cancelAll()` again until the query you want to stop has ended. +- **The JavaScript that sqlite-js runs while it sets up a connection**: while it loads, and while it creates each stored function. +- **SQL that JavaScript is running through `db.exec`.** A long `next()` or `toArray()` finishes first. The cancel takes effect when JavaScript runs again. + +You can call `cancelAll()` from any thread. + +## Cancel in Kotlin, with a coroutine + +The template's `cancellable()` runs a query so that cancelling the coroutine also stops the query's JavaScript. It calls `cancelAll()` again and again, 10 milliseconds apart, until the query ends. + +```kotlin +suspend fun cancellable(query: suspend () -> T): T = coroutineScope { + // The result or failure is kept, not thrown, so that a query the cancel stops + // ends this as cancelled, not as failed. + val running = async(Dispatchers.IO) { runCatching { query() } } + try { + running.await().getOrThrow() + } catch (e: CancellationException) { + withContext(NonCancellable) { + while (!running.isCompleted) { + SqliteJs.cancelAll() + delay(10) + } + } + throw e + } +} +``` + +If the coroutine is cancelled while `cancellable()` waits for the query, `cancellable()` ends as cancelled, and the query's result or error is dropped. So a query that fails with an error of its own at about that moment is reported as cancelled too. + +Wrap only a query that may need stopping, and cancel its coroutine from your **Cancel** button: + +```kotlin +class RunawayQuery(private val scope: CoroutineScope, private val products: ProductDao) { + private var job: Job? = null + + /** Starts JavaScript that never ends, unless its earlier start still runs. */ + fun start() { + if (job?.isCompleted == false) return + job = scope.launch { + cancellable { products.spin() } + } + } + + /** Call this from the Cancel button. */ + fun cancel() { + job?.cancel() + } +} +``` + +`start()` does nothing while the query it started earlier still runs, including the moment after `cancel()` while `cancellable()` stops it. A second query would replace the first in `job`, and `cancel()` would no longer cancel the first. + +`ProductDao` and its `spin()` are on the page [Set up a database with JavaScript functions](sqlite-js-app-database.html). In an activity, pass `lifecycleScope` as the scope. + +Do not wrap every query in `cancellable()`. A coroutine can be cancelled for many reasons, such as the user leaving a screen, and each cancel would also interrupt the JavaScript of your other queries. + +## Cancel in Java, with a thread + +Java has no coroutines. This class does the same work as `cancellable()`, with one difference: a result that arrives after `cancel()` is not dropped, and `get()` returns it. It runs the query on a thread of its own. Its `cancel()` calls `cancelAll()` again and again, 10 milliseconds apart, until the query has ended, and returns at once, so you can call it from a button. + +```java +final class CancellableQuery { + private static final ExecutorService THREADS = Executors.newCachedThreadPool(); + + private final Future running; + private final AtomicBoolean cancelled = new AtomicBoolean(); + private volatile Future stopping; + + /** Starts the query on another thread. */ + CancellableQuery(Callable query) { + running = THREADS.submit(query); + } + + /** + * Waits until the query has ended, and returns its result. If the query + * failed after cancel() was called, throws CancellationException, with the + * query's own error as its cause. + */ + T get() throws ExecutionException, InterruptedException { + try { + return running.get(); + } catch (ExecutionException e) { + if (cancelled.get()) { + CancellationException stopped = new CancellationException("cancelled"); + stopped.initCause(e.getCause()); + throw stopped; + } + throw e; + } + } + + /** + * Whether the query has ended and the loop of cancel() can call + * cancelAll() no more. A late call could stop a query started after this. + */ + boolean isDone() { + // The query first: a loop recorded after this finds it ended, and stops. + if (!running.isDone()) { + return false; + } + Future loop = stopping; + return loop == null || loop.isDone(); + } + + /** Stops the query's JavaScript. Returns at once. */ + void cancel() { + // A query that has ended keeps its result. A second call starts no second loop. + if (running.isDone() || !cancelled.compareAndSet(false, true)) { + return; + } + FutureTask loop = new FutureTask<>(() -> { + // Future.cancel() could not stop the JavaScript. Only cancelAll() can. + while (!running.isDone()) { + SqliteJs.cancelAll(); + try { + running.get(10, TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + // the query has not ended: cancel again + } catch (ExecutionException | InterruptedException e) { + // the loop ends when the query has ended + } + } + }, null); + // Recorded before it runs, so a loop that isDone() does not see has yet to look at the query. + stopping = loop; + THREADS.execute(loop); + } +} +``` + +A query that fails after `cancel()` was called is reported as cancelled, whatever made it fail. So a query that fails with an error of its own at about that moment is reported as cancelled too. The `CancellationException` keeps that error as its cause. + +Cancel it from your **Cancel** button: + +```java +final class RunawayQuery { + private final ProductDao products; + private CancellableQuery query; + + RunawayQuery(ProductDao products) { + this.products = products; + } + + /** Starts JavaScript that never ends, unless its earlier start still runs. */ + void start() { + if (query != null && !query.isDone()) { + return; + } + query = new CancellableQuery<>(products::spin); + } + + /** Call this from the Cancel button. */ + void cancel() { + if (query != null) { + query.cancel(); + } + } +} +``` + +Its `start()`, like the Kotlin one, does nothing until the query it started earlier has ended and the loop of its `cancel()` can call `cancelAll()` no more. So `cancel()` always cancels that query, and no late `cancelAll()` of it reaches the next one. This `RunawayQuery` never reads the query's result, so it does not notice a query that fails. To read a result, or learn of a failure, call `get()` on a thread other than the main thread: it waits until the query has ended. As in Kotlin, use `CancellableQuery` only for a query that may need stopping. diff --git a/docs/docdb/ADFA-7083/pages/sqlite-js-app-database.md b/docs/docdb/ADFA-7083/pages/sqlite-js-app-database.md new file mode 100644 index 0000000000..5b675106af --- /dev/null +++ b/docs/docdb/ADFA-7083/pages/sqlite-js-app-database.md @@ -0,0 +1,371 @@ +--- +file: sqlite-js-app-database.html +title: Set up a database with JavaScript functions +description: The build settings, the two ways to load sqlite-js, and where to create JavaScript functions in an app. +parent: sqlite-js-app-top.html +prev: sqlite-js-app-top.html +next: sqlite-js-app-cancel.html +--- + +This page explains each step that the **JavaScript in SQLite** template takes to give a Room database JavaScript functions. Start with [JavaScript in SQLite for apps](sqlite-js-app-top.html) if you have not created the sample app yet. + +The steps are: + +1. Add the two libraries and three build settings. +2. Store your JavaScript functions in the database, before Room opens it. +3. Open the database with Room, and load sqlite-js on every connection. +4. Call the functions from your queries. + +The examples on this page are a shorter form of the template's `ProductDatabase.kt`. Each one is shown in Kotlin and in Java. The template itself is in Kotlin. + +The examples leave out their `import` lines. In Java, put each example in a file of its own, named after its first class, such as `ProductFunctions.java`. + +## Build settings + +These lines of `app/build.gradle.kts` are the ones sqlite-js needs: + +```gradle +android { + defaultConfig { + minSdk = 26 + ndk { + abiFilters += listOf("arm64-v8a", "armeabi-v7a") + } + } + packaging { + jniLibs { + useLegacyPackaging = true + } + } +} +dependencies { + implementation(files("libs/sqlite-js.aar")) + implementation(files("libs/sqlite-android.aar")) + implementation("androidx.core:core:1.15.0") +} +``` + +- `minSdk = 26`: sqlite-js needs Android 8.0 or later. +- `abiFilters`: the two libraries are built for ARM devices only, so the app is too. +- `useLegacyPackaging = true`: **do not remove this.** SQLite loads sqlite-js from a file. This setting makes Android copy the app's native libraries to files when it installs the app. Without it, they stay inside the APK, and SQLite finds no file to load. +- `libs/sqlite-js.aar` is sqlite-js. It needs no other library. +- `libs/sqlite-android.aar` is an SQLite that can load sqlite-js: version 3.49.0 of `sqlite-android`, from the requery project, with its ARM libraries only. It needs `androidx.core`, which the last line adds, and `androidx.sqlite`, which Room brings. + +A project made with the template has both `.aar` files in its `app/libs` folder. That is where you get them: the template brings them, so they need no download. `sqlite-android.aar` is the file that the requery project publishes on JitPack as `com.github.requery:sqlite-android:3.49.0`, with its x86 libraries taken out. + +To use sqlite-js in another app, create a project from the template if you have none, copy both files from its `app/libs` folder into that app's `app/libs` folder, and add these settings. The template writes the `androidx.core` line with a name from its version catalog, `libs.androidx.core`. The line above works in any project. + +The examples below also need Room. The template uses Room 2.8.4. + +**Kotlin** + +```gradle +dependencies { + implementation("androidx.room:room-runtime:2.8.4") + implementation("androidx.room:room-ktx:2.8.4") + ksp("androidx.room:room-compiler:2.8.4") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +} +``` + +The `ksp` line needs the KSP plugin, `com.google.devtools.ksp`. The template uses version 2.3.13 of it, and names these libraries through its version catalog, `gradle/libs.versions.toml`. + +**Java** + +```gradle-java +dependencies { + implementation("androidx.room:room-runtime:2.8.4") + annotationProcessor("androidx.room:room-compiler:2.8.4") +} +``` + +A Java project needs no KSP plugin and no coroutines. + +## Two ways to load sqlite-js + +A database can keep JavaScript functions in a table named `js_functions`. sqlite-js can create those functions each time a connection opens, and creating a function runs its stored code. That code can run SQL and read your app's files. So `SqliteJs` gives you two entry points. An entry point is the name SQLite calls in the library when it loads it. + +- `SqliteJs.ENTRY_POINT` loads sqlite-js and runs nothing that the database stores. It is safe for any database file. +- `SqliteJs.ENTRY_POINT_FOR_TRUSTED_DATABASE` loads sqlite-js, then creates the functions stored in `js_functions`, on every connection. Use it only for a database that your app made and keeps. + +**Open a file your app did not make with `SqliteJs.ENTRY_POINT`.** That means a downloaded file, a file another app shared, or a restored backup. With the trusted entry point, code stored in such a file would run as soon as your app opened it. + +**Kotlin** + +```kotlin +/** Opens a database file that the app did not make. No code stored in the file runs. */ +fun openSharedFile(context: Context, file: File): SQLiteDatabase { + val config = SQLiteDatabaseConfiguration(file.path, SQLiteDatabase.OPEN_READONLY) + config.customExtensions.add( + SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT) + ) + return SQLiteDatabase.openDatabase(config, null, null) +} +``` + +**Java** + +```java +final class SharedFiles { + /** Opens a database file that the app did not make. No code stored in the file runs. */ + static SQLiteDatabase open(Context context, File file) { + SQLiteDatabaseConfiguration config = + new SQLiteDatabaseConfiguration(file.getPath(), SQLiteDatabase.OPEN_READONLY); + config.customExtensions.add( + new SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT)); + return SQLiteDatabase.openDatabase(config, null, null); + } +} +``` + +`SQLiteDatabase`, `SQLiteDatabaseConfiguration` and `SQLiteCustomExtension` come from `sqlite-android`, in the package `io.requery.android.database.sqlite`. `SqliteJs` is in the package `org.appdevforall.sqlitejs`. + +With the trusted entry point, a stored function that fails to load is skipped. sqlite-js writes the reason to SQLite's log, and the other functions still load. A query that calls the skipped function fails with `no such function`. + +## Store your functions before Room opens the database + +Create your functions on a connection of your own, opened with `SqliteJs.ENTRY_POINT`, before Room opens the database. There are two reasons: + +- **A connection that opened before a function was stored does not have it.** Room opens several connections, and each one gets the stored functions only when it opens. +- **A connection cannot redefine a function that it already has.** A connection opened with `SqliteJs.ENTRY_POINT` has none of the stored functions, so it can replace them all. + +`js_init_table()` creates the table `js_functions`. After that, each `js_create_` function also stores the function it creates. The [sqlite-js function reference](sqlite-js-functions.html) describes them. + +**Kotlin** + +```kotlin +private const val NAME = "products.db" + +// Each string is one SQL statement that creates and stores one JavaScript function. +private val FUNCTIONS = listOf( + """ + SELECT js_create_scalar('slugify', '(function (args) { + return String(args[0]).toLowerCase().trim() + .replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); + })') + """, + """ + SELECT js_create_aggregate('median', + 'const values = [];', + '(function (args) { values.push(args[0]); })', + '(function () { + values.sort((a, b) => a - b); + const mid = Math.floor(values.length / 2); + return (values.length % 2) ? values[mid] : (values[mid - 1] + values[mid]) / 2; + })') + """, + "SELECT js_create_scalar('spin', '(function (args) { while (true) {} })')", +) + +fun storeFunctions(context: Context) { + val file = context.getDatabasePath(NAME) + file.parentFile?.mkdirs() + val config = SQLiteDatabaseConfiguration( + file.path, SQLiteDatabase.CREATE_IF_NECESSARY or SQLiteDatabase.OPEN_READWRITE + ) + config.customExtensions.add( + SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT) + ) + SQLiteDatabase.openDatabase(config, null, null).use { db -> + db.rawQuery("SELECT js_init_table()", emptyArray()).use { it.moveToFirst() } + FUNCTIONS.forEach { sql -> + db.rawQuery(sql, emptyArray()).use { it.moveToFirst() } + } + } +} +``` + +**Java** + +```java +final class ProductFunctions { + static final String NAME = "products.db"; + + // Each entry is one SQL statement that creates and stores one JavaScript function. + static final String[] FUNCTIONS = { + "SELECT js_create_scalar('slugify', '(function (args) {" + + " return String(args[0]).toLowerCase().trim()" + + " .replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\");" + + " })')", + "SELECT js_create_aggregate('median'," + + " 'const values = [];'," + + " '(function (args) { values.push(args[0]); })'," + + " '(function () {" + + " values.sort((a, b) => a - b);" + + " const mid = Math.floor(values.length / 2);" + + " return (values.length % 2) ? values[mid] : (values[mid - 1] + values[mid]) / 2;" + + " })')", + "SELECT js_create_scalar('spin', '(function (args) { while (true) {} })')", + }; + + static void store(Context context) { + File file = context.getDatabasePath(NAME); + File folder = file.getParentFile(); + if (folder != null) { + folder.mkdirs(); + } + SQLiteDatabaseConfiguration config = new SQLiteDatabaseConfiguration( + file.getPath(), SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.OPEN_READWRITE); + config.customExtensions.add( + new SQLiteCustomExtension(SqliteJs.libraryPath(context), SqliteJs.ENTRY_POINT)); + try (SQLiteDatabase db = SQLiteDatabase.openDatabase(config, null, null)) { + run(db, "SELECT js_init_table()"); + for (String sql : FUNCTIONS) { + run(db, sql); + } + } + } + + private static void run(SQLiteDatabase db, String sql) { + try (Cursor cursor = db.rawQuery(sql, new Object[0])) { + cursor.moveToFirst(); + } + } +} +``` + +- `rawQuery` does not run a statement until you read its result, which is why each call ends with `moveToFirst()`. +- Storing the functions on every start costs little: a function that is already stored with the same code is not written again. It also means that a new version of your app replaces the functions whose code you changed. +- If a function cannot be stored, for example because the database is locked, `moveToFirst()` throws an exception. Its message contains `could not be stored in js_functions`. +- `spin` never returns. It is here only to show how to stop such a function, in [Stop JavaScript that never ends](sqlite-js-app-cancel.html). + +## Open the database with Room + +Give Room the `sqlite-android` helper factory, and add sqlite-js to its configuration with the trusted entry point. Every connection that Room opens then loads sqlite-js and the functions you stored. + +**Kotlin** + +```kotlin +fun openProductDatabase(context: Context): ProductDatabase { + storeFunctions(context) + val factory = RequerySQLiteOpenHelperFactory( + listOf( + RequerySQLiteOpenHelperFactory.ConfigurationOptions { config -> + config.customExtensions.add( + SQLiteCustomExtension( + SqliteJs.libraryPath(context), + SqliteJs.ENTRY_POINT_FOR_TRUSTED_DATABASE, + ) + ) + config + }, + ), + ) + return Room.databaseBuilder(context, ProductDatabase::class.java, NAME) + .openHelperFactory(factory) + .build() +} +``` + +**Java** + +```java +final class ProductDatabases { + static ProductDatabase open(Context context) { + ProductFunctions.store(context); + RequerySQLiteOpenHelperFactory.ConfigurationOptions options = config -> { + config.customExtensions.add( + new SQLiteCustomExtension( + SqliteJs.libraryPath(context), + SqliteJs.ENTRY_POINT_FOR_TRUSTED_DATABASE)); + return config; + }; + RequerySQLiteOpenHelperFactory factory = + new RequerySQLiteOpenHelperFactory(Collections.singletonList(options)); + return Room.databaseBuilder(context, ProductDatabase.class, ProductFunctions.NAME) + .openHelperFactory(factory) + .build(); + } +} +``` + +Call this once and keep the result for the whole app, as the template's `ProductDatabase.get()` does. Call it off the main thread: it reads and writes the database file. + +## Call the functions from your queries + +Mark each DAO method whose query calls a JavaScript function with `@SkipQueryVerification`. Room checks every query when it builds your app, with an SQLite of its own that has no JavaScript functions. Without the annotation, the build fails with `no such function`. + +**Kotlin** + +```kotlin +@Entity +data class Product( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val name: String, + val price: Double, +) + +@Dao +interface ProductDao { + @Insert + suspend fun insert(products: List) + + @SkipQueryVerification + @Query("SELECT slugify(name) FROM Product ORDER BY id") + suspend fun slugs(): List + + @SkipQueryVerification + @Query("SELECT median(price) FROM Product") + suspend fun medianPrice(): Double? + + @SkipQueryVerification + @Query("SELECT spin()") + suspend fun spin(): Int? +} + +@Database(entities = [Product::class], version = 1, exportSchema = false) +abstract class ProductDatabase : RoomDatabase() { + abstract fun products(): ProductDao +} +``` + +**Java** + +```java +@Entity +class Product { + @PrimaryKey(autoGenerate = true) + long id; + @NonNull + String name; + double price; + + Product(@NonNull String name, double price) { + this.name = name; + this.price = price; + } +} + +@Dao +interface ProductDao { + @Insert + void insert(List products); + + @SkipQueryVerification + @Query("SELECT slugify(name) FROM Product ORDER BY id") + List slugs(); + + @SkipQueryVerification + @Query("SELECT median(price) FROM Product") + Double medianPrice(); + + @SkipQueryVerification + @Query("SELECT spin()") + Integer spin(); +} + +@Database(entities = {Product.class}, version = 1, exportSchema = false) +abstract class ProductDatabase extends RoomDatabase { + abstract ProductDao products(); +} +``` + +The Java methods wait for their result, so call them off the main thread. Room refuses a query on the main thread. + +Room does not check a query that has the annotation, so a mistake in its SQL shows only when the query runs. Test each one. + +## Change a function + +Change its code in your app. The next time the app starts, `storeFunctions`, or `ProductFunctions.store` in Java, replaces the stored function, and every connection that Room then opens gets the new one. + +To remove a function, take it out of `FUNCTIONS`, or the app stores it again on its next start. Also delete its row from `js_functions`, for example with `DELETE FROM js_functions WHERE name = 'spin'`, on the connection that stores your functions. A connection that is already open keeps the function until it closes. diff --git a/docs/docdb/ADFA-7083/pages/sqlite-js-app-top.md b/docs/docdb/ADFA-7083/pages/sqlite-js-app-top.md new file mode 100644 index 0000000000..5bd9fb60bd --- /dev/null +++ b/docs/docdb/ADFA-7083/pages/sqlite-js-app-top.md @@ -0,0 +1,81 @@ +--- +file: sqlite-js-app-top.html +title: JavaScript in SQLite for apps +description: Call functions written in JavaScript from the SQL queries of an app that you build with Code on the Go. +parent: project-create-new.html +prev: project-create-new.html +next: sqlite-js-app-database.html +--- + +An app that you build with Code on the Go can call functions written in JavaScript from its SQL queries. The sqlite-js library adds them to the app's SQLite database. You write a JavaScript function, give it a name, and use it in a query like any built-in SQL function. + +The quickest way to start is the **JavaScript in SQLite** project template. It creates a sample app that already works. + +To write JavaScript functions for the `sqlite3` command in Terminal instead, see [JavaScript in SQLite (sqlite-js)](sqlite-js-top.html). + +## Create the sample app + +1. [Create a new project](project-create-new.html) and select the **JavaScript in SQLite** template. +2. Enter a name for the app and tap **Create project**. +3. Build the app and run it. + +The project is written in Kotlin. + +## What the sample app shows + +The app keeps four products, each with a name and a price, in a Room database named `products.db`. Its queries call three JavaScript functions. + +- **Run the JavaScript functions** runs two queries. The scalar function `slugify` turns each product name into a web address slug, so `Red Apple` becomes `red-apple`. The aggregate function `median` finds the median price. The app also runs them when it starts. +- **Start endless JavaScript** calls `spin`, a function that never returns. The app stays responsive, and **Cancel** stops the function. The app then shows how many milliseconds the stop took. +- **Open source notices** shows the license notices of the libraries in the app. + +With the sample products, the app shows: + +```text +Slugs: +red-apple +whole-wheat-bread +milk-1-litre +coffee-tea-sampler + +Median price: 2.23 +``` + +## Where to look in the project + +- `ProductDatabase.kt`, in `app/src/main/java/` under your package name: the database, the three JavaScript functions, and `cancellable()`, which stops JavaScript that never ends. +- `MainActivity.kt`, in the same folder: the buttons, and the code that runs when you tap them. +- `app/build.gradle.kts`: the libraries and the build settings that sqlite-js needs. +- `app/libs/sqlite-js.aar`: sqlite-js, with its JavaScript engine. +- `app/libs/sqlite-android.aar`: an SQLite that can load sqlite-js. +- `app/src/main/assets/NOTICES.txt`: the license notices that the app shows. + +## What sqlite-js needs + +- **An ARM device.** The libraries are built for arm64-v8a and armeabi-v7a only. +- **Android 8.0 or later.** The app's `minSdk` must be 26 or more. +- **An SQLite that can load extensions.** sqlite-js is an SQLite extension, and Android's own SQLite gives an app no way to load one. The template adds `sqlite-android`, a library from the requery project that brings its own SQLite, and Room uses it. + +These pages describe sqlite-js 1.4.4. To see which version an app has, run the query `SELECT js_version()`. + +## License notices your app must carry + +The app includes three open source works. Each license asks you to pass its notice on to the people who get your app: + +| Work | License | +|------|---------| +| sqlite-js | Apache License 2.0 | +| `sqlite-android`, from the requery project | Apache License 2.0 | +| QuickJS (quickjs-ng), the JavaScript engine inside sqlite-js | MIT License | + +The template's `app/src/main/assets/NOTICES.txt` has the notices and both license texts, and **Open source notices** shows that file. When you turn the sample into your own app, keep the file and keep a way for your users to read it. When you copy the libraries into another app, copy the file too. + +## Learn more + +- [Set up a database with JavaScript functions](sqlite-js-app-database.html): the build settings, the two ways to load sqlite-js, and where to create your functions. +- [Stop JavaScript that never ends](sqlite-js-app-cancel.html): `SqliteJs.cancelAll()` and what it interrupts. +- [sqlite-js function reference](sqlite-js-functions.html): `js_create_scalar`, `js_create_aggregate` and the other SQL functions that create and keep JavaScript functions. +- [JavaScript in sqlite-js](sqlite-js-javascript.html): how SQL values and JavaScript values convert, what the engine supports, and the limits. +- [JavaScript basics](javascript-intro.html): a short introduction for new JavaScript users. + +The last three pages are written for `sqlite3` in Terminal. The SQL and the JavaScript on them work the same way in an app. Where they say session, read database connection: each connection has its own JavaScript engine, its own functions and its own limits. Ctrl-C and `.load` belong to Terminal only. diff --git a/docs/docdb/ADFA-7083/pages/sqlite-js-functions.md b/docs/docdb/ADFA-7083/pages/sqlite-js-functions.md index 39e3073bc9..ae022ab48f 100644 --- a/docs/docdb/ADFA-7083/pages/sqlite-js-functions.md +++ b/docs/docdb/ADFA-7083/pages/sqlite-js-functions.md @@ -15,6 +15,8 @@ An error in your JavaScript, such as a thrown exception or a syntax error, becom In the code you pass, a **function expression** is a JavaScript function written inside parentheses, like `(function (args) { ... })`. Every `js_create_` function returns `0` when it succeeds. +If the database keeps your functions and the new one cannot be stored, a `js_create_` function fails, as described in When a function cannot be stored. + A function cannot be redefined in a session that already has it: you get `Function updates must be performed using a separate database connection.` To change one, close `sqlite3`, open it again and create the new version first, without calling `js_init_table(1)`, which would create the old one. If the database keeps your functions, the new version replaces the stored one, and `js_init_table(1)` creates it in your next session. ### js_create_scalar @@ -140,6 +142,34 @@ SELECT name, kind FROM js_functions; > Call `js_init_table(1)` only on databases you trust. It runs the JavaScript that the database stores. +### When a function cannot be stored + +If the table `js_functions` exists but sqlite-js cannot write the new function to it, the `js_create_` function fails. The error starts with `The function was registered on this connection, but it could not be stored in js_functions:` and ends with the reason from SQLite. This happens when: + +- The database is read-only: you opened it with `sqlite3 -readonly` or `.open --readonly`, or `PRAGMA query_only` is on. The reason is `attempt to write a readonly database`. +- Another program is writing to the database. The reason is `database is locked`. + +After this error, the function still works until you close `sqlite3`. It is not stored, so `js_init_table(1)` in your next session does not create it. If `js_functions` already held a function of that name, it still holds that one, and `js_init_table(1)` creates that older version. + +A `js_functions` table that `js_init_table()` did not make, and that lacks one of its columns, gives no error: the `js_create_` function returns `0` and stores nothing. + +```sql +PRAGMA query_only = ON; +SELECT js_create_scalar('half', '(function (args) { return args[0] / 2; })'); +-- Error: could not be stored in js_functions: attempt to write a readonly database +SELECT half(10); +-- 5 +PRAGMA query_only = OFF; +SELECT name FROM js_functions; +-- twice +``` + +To store the function, remove the cause, close `sqlite3`, open it again and create the function again. Creating it again in the same session fails, because the session already has it. + +A function that is already stored with the same code needs no write, so creating it succeeds even on a read-only database. A database without the table `js_functions` stores nothing, so this error cannot happen there. + +sqlite-js 1.4.4 and later report this error. Versions 1.4.2 and 1.4.3 return `0` instead, and the function is missing in your next session. + ## Read files ### js_load_text and js_load_blob @@ -178,11 +208,11 @@ js_version() js_version(1) ``` -`js_version()` returns the version of sqlite-js. `js_version(1)` returns the version of the JavaScript engine, quickjs-ng. +`js_version()` returns the version of sqlite-js that you have, such as `1.4.4`. `js_version(1)` returns the version of the JavaScript engine, quickjs-ng. ```sql SELECT js_version(); --- 1.4.2 +-- 1.4.4 ``` ## What changed in sqlite-js 1.4 @@ -206,6 +236,14 @@ sqlite-js 1.4.2 has more fixes, several of them sent or reported by App Dev For - JavaScript that runs out of memory while much of its memory is garbage no longer fails again on every try. - A query that computes a JavaScript window function no longer crashes `sqlite3` when JavaScript drops its result set partway. +sqlite-js 1.4.4 reports three errors that 1.4.3 and earlier versions hide: + +- A `js_create_` function fails when the database keeps your functions but the new one cannot be stored, as on a read-only database. Before, it returned `0`, and the function was missing in the next session. See When a function cannot be stored. +- An error while sqlite-js builds the array of arguments for your function, or a row for `toArray()`, fails the call with that error. Before, the function ran with fewer arguments, or `toArray()` returned fewer or shorter rows. Such an error is rare: JavaScript ran out of memory, or code put a setter on `Array.prototype`. +- Text that SQLite has no memory left to convert fails the call with `out of memory`. Before, `sqlite3` crashed. + +sqlite-js 1.4.3 changed nothing that you can see in `sqlite3`. + ## Credits This page adapts the README of sqlite-js (the project sqliteai/sqlite-js on GitHub), which is licensed under the Apache License, Version 2.0. It has been rewritten and changed for Code on the Go. The software is provided "as is", without warranties or conditions of any kind. diff --git a/docs/docdb/ADFA-7083/pages/sqlite-js-top.md b/docs/docdb/ADFA-7083/pages/sqlite-js-top.md index 389c67bad7..4a46bd394f 100644 --- a/docs/docdb/ADFA-7083/pages/sqlite-js-top.md +++ b/docs/docdb/ADFA-7083/pages/sqlite-js-top.md @@ -29,7 +29,7 @@ apt install sqlite sqlite-js The `sqlite` package provides the `sqlite3` command that sqlite-js works with. -These pages describe sqlite-js 1.4.2 and later versions. To see which version you have, enter `dpkg -s sqlite-js` and read its `Version` line. `apt update` and then `apt install sqlite-js` bring an older one up to date. +These pages describe sqlite-js 1.4.2 and later versions. Where a later version behaves differently, the page says so. To see which version you have, enter `dpkg -s sqlite-js` and read its `Version` line. `apt update` and then `apt install sqlite-js` bring an older one up to date. ## Load sqlite-js @@ -65,6 +65,8 @@ SELECT t, slugify(t) FROM titles; A function you create lasts until you close `sqlite3`. To keep your functions in the database, see [sqlite-js function reference](sqlite-js-functions.html). +These pages are about `sqlite3` in Terminal. To use JavaScript functions in the database of an app that you build, see [JavaScript in SQLite for apps](sqlite-js-app-top.html). + ## Stay safe - **Load sqlite-js only for databases you trust.** A database can store JavaScript, and `js_init_table(1)` runs it with your access. Through `db.exec`, that code can run any SQL, including `readfile()` and `writefile()`, which read and write your files. @@ -77,5 +79,6 @@ A function you create lasts until you close `sqlite3`. To keep your functions in - [sqlite-js function reference](sqlite-js-functions.html): every function, with arguments, results and errors. - [JavaScript in sqlite-js](sqlite-js-javascript.html): how SQL values and JavaScript values convert, what the engine supports, and the limits. - [JavaScript basics](javascript-intro.html): a short introduction for new JavaScript users. +- [JavaScript in SQLite for apps](sqlite-js-app-top.html): call JavaScript functions from the database of an app that you build with Code on the Go. sqlite-js is developed on GitHub, in the project sqliteai/sqlite-js, under the Apache License 2.0. Version 1.4.0 and later include fixes from App Dev For All, described in the reference. diff --git a/docs/docdb/ADFA-7083/test_app_examples.py b/docs/docdb/ADFA-7083/test_app_examples.py new file mode 100644 index 0000000000..27f0ccf342 --- /dev/null +++ b/docs/docdb/ADFA-7083/test_app_examples.py @@ -0,0 +1,393 @@ +#!/usr/bin/env python3 +"""Checks the examples of the app pages (pages/sqlite-js-app-*.md). + +- Every ```gradle example must be lines of the template's app/build.gradle.kts, in order. A + dependency the example writes as "group:name:version" matches the template's line that + names the same one through its version catalog (libs.some.name). +- Every ```kotlin example is compiled, as written: the examples go, in page order, into one + file of a project made from the JavaScript in SQLite template, which is then built with + the sqlite-js AAR under test. app-test/DocExamplesTest.kt, an instrumented test that + calls the examples, is compiled with them. With DEVICE=1 it also runs, on the device adb + reaches (ANDROID_SERIAL picks one): it installs and removes its own app there. +- Every ```java example is compiled, as written, each in a file named after its first class, + in a second project: the template without its Kotlin sources and activity and without + the Kotlin-only lines of its build files (KOTLIN_ONLY), with the ```gradle-java examples + added to its app/build.gradle.kts, so that Room's annotation processor builds the Java + database with the page's Java settings and nothing Kotlin beside them: the script stops + if the project's build files still name Kotlin, KSP, a -ktx library or coroutines. + app-test/JavaDocExamplesTest.java is compiled with them, and runs with DEVICE=1. +- The SQL in the Kotlin and Java examples, the statements that create the JavaScript + functions and the DAO queries, runs on this host in sqlite3 with sqlite-js loaded. + +Usage: + DEV_ASSETS=/path/to/dev-assets AAR=/path/to/sqlite-js.aar ANDROID_HOME=/path/to/sdk \\ + SQLITE3=sqlite3 EXT=/path/to/sqlite-js.so [GRADLE=gradle] [GRADLE_ARGS="..."] [DEVICE=1] \\ + python3 test_app_examples.py WORK_DIR + +DEV_ASSETS is a checkout of appdevforall/dev-assets: its templates/JavaScriptInSQLite and +scripts/render-template.py are used. WORK_DIR is made; one that exists is emptied only if an +earlier run of this script made it, and is otherwise refused unless it is empty; a symbolic +link is refused. GRADLE_ARGS replaces the options Gradle runs with, by default --no-daemon +and a 2 GB heap. The build downloads what Gradle has not cached. Prints TAP. Exits 0 only +if every check passes. +""" +import glob +import os +import re +import shlex +import shutil +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +SQLITE3 = os.environ.get("SQLITE3", "sqlite3") +EXT = os.environ.get("EXT", "sqlite-js") +GRADLE = os.environ.get("GRADLE", "gradle") +GRADLE_ARGS = shlex.split(os.environ.get("GRADLE_ARGS", "--no-daemon -Dorg.gradle.jvmargs=-Xmx2g")) +DEVICE = os.environ.get("DEVICE") == "1" +PACKAGE = "docexamples" +# Marks a WORK_DIR as this script's, so that a later run may empty it. +MARKER = ".test_app_examples" +# What the examples use. An example shows no imports: the pages name the packages. +IMPORTS = """ +import android.content.Context +import androidx.room.Dao +import androidx.room.Database +import androidx.room.Entity +import androidx.room.Insert +import androidx.room.PrimaryKey +import androidx.room.Query +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.SkipQueryVerification +import io.requery.android.database.sqlite.RequerySQLiteOpenHelperFactory +import io.requery.android.database.sqlite.SQLiteCustomExtension +import io.requery.android.database.sqlite.SQLiteDatabase +import io.requery.android.database.sqlite.SQLiteDatabaseConfiguration +import java.io.File +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.appdevforall.sqlitejs.SqliteJs +""" +# What the Java project drops from the template's build files: each must match exactly once, +# so that a changed template stops the test. +KOTLIN_ONLY = { + "build.gradle.kts": [ + # the Kotlin compiler for AGP, with its comment + r"\A// AGP 9 compiles Kotlin itself.*?^buildscript \{\n.*?^\}\n\n", + r"^\s*alias\(libs\.plugins\.ksp\) apply false\n", + ], + os.path.join("app", "build.gradle.kts"): [ + r"^\s*alias\(libs\.plugins\.ksp\)\n", + r"^\s*ksp\(libs\.androidx\.room\.compiler\)\n", + r"^\s*implementation\(libs\.androidx\.room\.ktx\)\n", + r"^\s*implementation\(libs\.androidx\.lifecycle\.runtime\.ktx\)\n", + r"^\s*implementation\(libs\.kotlinx\.coroutines\.android\)\n", + r"^kotlin \{\n\s*compilerOptions \{\n.*\n\s*\}\n\}\n", + # the kotlin-stdlib versions it forces + r"^ configurations\.all \{\n\s*resolutionStrategy \{\n(?:\s*force\(.*\n){3}\s*\}\n \}\n", + # packaging rules for the metadata files of Kotlin Multiplatform libraries + r"^\s*excludes\.add\(\"META-INF/kotlinx_coroutines_core\.version\"\)\n", + r"^\s*// Kotlin Multiplatform libraries.*\n(?:\s*//.*\n)*(?:\s*(?:pickFirsts|merges)\.add\(.*\n)+", + ], + "gradle.properties": [r"^# Kotlin code style.*\nkotlin\.code\.style=official\n"], +} +# What may not be left in those files or in settings.gradle.kts. The version catalog, gradle/libs.versions.toml, is not +# checked: its entries declare nothing until a build file names them. +KOTLIN_WORDS = re.compile(r"kotlin|ksp|ktx|coroutines", re.I) +JAVA_IMPORTS = """ +import android.content.Context; +import android.database.Cursor; +import androidx.annotation.NonNull; +import androidx.room.Dao; +import androidx.room.Database; +import androidx.room.Entity; +import androidx.room.Insert; +import androidx.room.PrimaryKey; +import androidx.room.Query; +import androidx.room.Room; +import androidx.room.RoomDatabase; +import androidx.room.SkipQueryVerification; +import io.requery.android.database.sqlite.RequerySQLiteOpenHelperFactory; +import io.requery.android.database.sqlite.SQLiteCustomExtension; +import io.requery.android.database.sqlite.SQLiteDatabase; +import io.requery.android.database.sqlite.SQLiteDatabaseConfiguration; +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.appdevforall.sqlitejs.SqliteJs; +""" +# Added to the project's app/build.gradle.kts for the instrumented test. Its own +# application id, so that the test never replaces an app made from the template on the device. +DEVICE_BUILD = """ +android { + defaultConfig { + applicationId = "org.appdevforall.sqlitejs.docexamples%s" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } +} +dependencies { + androidTestImplementation("androidx.test.ext:junit:1.2.1") + androidTestImplementation("androidx.test:runner:1.6.2") +} +""" +# The template's sample products, and what the app pages say the app shows for them. +PRODUCTS = [("Red Apple", 0.5), ("Whole Wheat Bread", 3.25), ("Milk, 1 litre", 1.2), ("Coffee & Tea Sampler", 12.0)] +SLUGS = ["red-apple", "whole-wheat-bread", "milk-1-litre", "coffee-tea-sampler"] +MEDIAN = "2.225" + +n = failed = 0 + + +def check(ok, what, detail=""): + global n, failed + n += 1 + print("%s %d - %s" % ("ok" if ok else "not ok", n, what)) + if not ok: + failed += 1 + for line in str(detail).strip().split("\n")[-40:]: + print("# " + line) + return ok + + +def blocks(kind): + """(page name, example number, text) of each example of that kind, in page order.""" + found = [] + for path in sorted(glob.glob(os.path.join(HERE, "pages", "sqlite-js-app-*.md"))): + text = open(path, encoding="utf-8").read() + for k, block in enumerate(re.findall(r"^```%s\n(.*?)^```" % kind, text, re.M | re.S), 1): + found.append((os.path.basename(path), k, block)) + return found + + +def in_order(lines, text): + """The first of lines that is not a line of text after the ones before it, or None.""" + have, at = [l.strip() for l in text.split("\n")], 0 + for line in (l.strip() for l in lines if l.strip()): + try: + at = have.index(line, at) + 1 + except ValueError: + return line + return None + + +def catalog(project): + """The version catalog's libraries: accessor (libs.androidx.core) -> "group:name:version".""" + text = open(os.path.join(project, "gradle", "libs.versions.toml"), encoding="utf-8").read() + versions = dict(re.findall(r'^([\w-]+) = "([^"]*)"', text[:text.index("[libraries]")], re.M)) + found = {} + for alias, group, name, ref in re.findall( + r'^([\w-]+) = \{ group = "([^"]*)", name = "([^"]*)", version\.ref = "([^"]*)" \}', text, re.M): + found["libs." + alias.replace("-", ".")] = "%s:%s:%s" % (group, name, versions[ref]) + return found + + +def kotlin_strings(kotlin): + """The SQL statements in the examples' string literals: ("create" or "query", sql).""" + found = [] + for m in re.finditer(r'"""(.*?)"""|"((?:[^"\\\n]|\\.)*)"', kotlin, re.S): + raw, plain = m.group(1), m.group(2) + sql = raw if raw is not None else re.sub(r"\\(.)", r"\1", plain) + before = kotlin[:m.start()].rstrip() + if before.endswith("@Query("): + found.append(("query", sql.strip())) + elif re.match(r"\s*SELECT js_create_", sql): + found.append(("create", sql.strip())) + return found + + +def java_strings(java): + """As kotlin_strings, for Java, where "a" + "b" is one string.""" + literal = r'"((?:[^"\\\n]|\\.)*)"' + found = [] + for m in re.finditer(r'%s(?:\s*\+\s*%s)*' % (literal, literal), java): + sql = "".join(re.sub(r"\\(.)", r"\1", part) for part in re.findall(literal, m.group(0))) + if java[:m.start()].rstrip().endswith("@Query("): + found.append(("query", sql.strip())) + elif re.match(r"\s*SELECT js_create_", sql): + found.append(("create", sql.strip())) + return found + + +def check_sql(language, strings): + """Runs the examples' statements and queries on the host.""" + creates = [s for kind, s in strings if kind == "create"] + queries = [s for kind, s in strings if kind == "query"] + setup = ["SELECT js_init_table();"] + [s + ";" for s in creates] + [ + "CREATE TABLE Product (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL, price REAL NOT NULL);" + ] + ["INSERT INTO Product (name, price) VALUES ('%s', %r);" % p for p in PRODUCTS] + out, err = sqlite("\n".join(setup + ["SELECT count(*) FROM js_functions;"])) + check(creates and not err and out == ["0"] * (1 + len(creates)) + [str(len(creates))], + "%s: the %d statements that create functions run, and store them" % (language, len(creates)), + "%r %r" % (out, err)) + endless = [q for q in queries if "spin" in q] + ending = [q for q in queries if "spin" not in q] + out, err = sqlite("\n".join(setup + ["SELECT 'queries';"] + [q + ";" for q in ending])) + got = out[out.index("queries") + 1:] if "queries" in out else out + check(not err and got == SLUGS + [MEDIAN], "%s: the %d DAO queries that end give the slugs and the median" + % (language, len(ending)), "%r %r" % (got, err)) + for q in endless: + try: + out, err = sqlite("\n".join(setup + ["SELECT 'started';", q + ";"]), timeout=3) + check(False, "%s: the DAO query %r never ends" % (language, q), "%r %r" % (out, err)) + except subprocess.TimeoutExpired as e: + # sqlite3 prints the marker before it reads the query, so the 3 s were the query's + out = e.stdout or "" + started = "started" in (out.decode() if isinstance(out, bytes) else out).split("\n") + check(started, "%s: the DAO query %r never ends (stopped after 3 s)" % (language, q), + "the setup before it did not end: %r" % e.stdout) + + +def java_project(work, assets): + """A Java project from the template: no Kotlin sources, Kotlin-only build lines or activity; the + ```gradle-java examples added; one file for each ```java example. Returns its path.""" + project = os.path.join(work, "project-java") + subprocess.run([sys.executable, os.path.join(assets, "scripts", "render-template.py"), + os.path.join(assets, "templates"), "JavaScriptInSQLite", project, "kotlin"], + check=True, stdout=subprocess.DEVNULL) + shutil.copy(os.environ["AAR"], os.path.join(project, "app", "libs", "sqlite-js.aar")) + shutil.rmtree(os.path.join(project, "app", "src", "main", "java")) + shutil.rmtree(os.path.join(project, "app", "src", "test")) + manifest = os.path.join(project, "app", "src", "main", "AndroidManifest.xml") + text = open(manifest, encoding="utf-8").read() + with open(manifest, "w", encoding="utf-8") as f: + f.write(re.sub(r"", "", text, flags=re.S)) + for name, patterns in KOTLIN_ONLY.items(): + path = os.path.join(project, name) + text = open(path, encoding="utf-8").read() + for pattern in patterns: + text, count = re.subn(pattern, "", text, flags=re.M | re.S if pattern.startswith(r"\A") else re.M) + if count != 1: + sys.exit("%s: expected exactly one match of %s, found %d" % (name, pattern, count)) + if name.startswith("app"): + text += "\n".join(b for _, _, b in blocks("gradle-java")) + DEVICE_BUILD % ".java" + with open(path, "w", encoding="utf-8") as f: + f.write(text) + # checked as the build will read them, with everything added + for name in list(KOTLIN_ONLY) + ["settings.gradle.kts"]: + text = open(os.path.join(project, name), encoding="utf-8").read() + left = [l for l in text.split("\n") if KOTLIN_WORDS.search(l)] + if left: + sys.exit("%s of the Java project still names Kotlin: %r" % (name, left)) + source = os.path.join(project, "app", "src", "main", "java", PACKAGE) + os.makedirs(source) + for page, k, block in blocks("java"): + name = re.search(r"^(?:(?:public|final|abstract)\s+)*(?:class|interface)\s+(\w+)", block, re.M).group(1) + if os.path.exists(os.path.join(source, name + ".java")): + sys.exit("%s, java example %d: an earlier example already starts with class %s" % (page, k, name)) + with open(os.path.join(source, name + ".java"), "x", encoding="utf-8") as f: + f.write("package %s;\n%s\n%s" % (PACKAGE, JAVA_IMPORTS, block)) + test_dir = os.path.join(project, "app", "src", "androidTest", "java", PACKAGE) + os.makedirs(test_dir) + shutil.copy(os.path.join(HERE, "app-test", "JavaDocExamplesTest.java"), test_dir) + return project + + +def sqlite(sql, timeout=60): + # -init: none of the settings of the user's ~/.sqliterc, such as .bail on + r = subprocess.run([SQLITE3, "-batch", "-noheader", "-init", os.devnull, "-cmd", '.load "%s"' % EXT, ":memory:"], + input=sql + "\n", capture_output=True, text=True, timeout=timeout) + return r.stdout.strip().split("\n"), r.stderr.strip() + + +def gradle(project, *tasks): + return subprocess.run([GRADLE] + GRADLE_ARGS + ["--console=plain", "-q"] + list(tasks), + cwd=project, capture_output=True, text=True) + + +def main(): + if len(sys.argv) != 2 or not os.environ.get("DEV_ASSETS") or not os.environ.get("AAR"): + sys.exit(__doc__) + work, assets = os.path.abspath(sys.argv[1]), os.environ["DEV_ASSETS"] + # checked once normalized: "link/" names the directory the link points to, "link" the link + if os.path.islink(work): + sys.exit("%s is a symbolic link: give a directory" % sys.argv[1]) + project = os.path.join(work, "project") + if os.path.isdir(work) and os.listdir(work): + if not os.path.isfile(os.path.join(work, MARKER)): + sys.exit("%s is not empty, and this script did not make it: give another WORK_DIR" % work) + shutil.rmtree(work) + elif os.path.exists(work) and not os.path.isdir(work): + sys.exit("%s is not a directory" % work) + os.makedirs(work, exist_ok=True) + open(os.path.join(work, MARKER), "w").close() + subprocess.run([sys.executable, os.path.join(assets, "scripts", "render-template.py"), + os.path.join(assets, "templates"), "JavaScriptInSQLite", project, "kotlin"], + check=True, stdout=subprocess.DEVNULL) + shutil.copy(os.environ["AAR"], os.path.join(project, "app", "libs", "sqlite-js.aar")) + + build_file = os.path.join(project, "app", "build.gradle.kts") + build_text = open(build_file, encoding="utf-8").read() + # as the example may write them: with the coordinates in place of the catalog's accessor + for accessor, coordinates in catalog(project).items(): + build_text = build_text.replace("(%s)" % accessor, '("%s")' % coordinates) + for page, k, block in blocks("gradle"): + missing = in_order(block.split("\n"), build_text) + check(missing is None, "%s gradle example %d is in the template's app/build.gradle.kts" % (page, k), + "not found, or out of order: %s" % missing) + + kotlin = "\n".join(block for _, _, block in blocks("kotlin")) + source = os.path.join(project, "app", "src", "main", "java", PACKAGE) + os.makedirs(source) + with open(os.path.join(source, "DocExamples.kt"), "w", encoding="utf-8") as f: + f.write("package %s\n%s\n%s" % (PACKAGE, IMPORTS, kotlin)) + test_dir = os.path.join(project, "app", "src", "androidTest", "java", PACKAGE) + os.makedirs(test_dir) + shutil.copy(os.path.join(HERE, "app-test", "DocExamplesTest.kt"), test_dir) + with open(build_file, "a", encoding="utf-8") as f: + f.write(DEVICE_BUILD % "") + count = len(blocks("kotlin")) + r = gradle(project, ":app:assembleDebug") + check(r.returncode == 0, "the %d kotlin examples compile in the template (:app:assembleDebug)" % count, + r.stdout + r.stderr) + r = gradle(project, ":app:assembleDebugAndroidTest") + check(r.returncode == 0, "the test that runs them on a device compiles (:app:assembleDebugAndroidTest)", + r.stdout + r.stderr) + + check_sql("kotlin", kotlin_strings(kotlin)) + top = open(os.path.join(HERE, "pages", "sqlite-js-app-top.md"), encoding="utf-8").read() + check("\n".join(["Slugs:"] + SLUGS + ["", "Median price: %.2f" % float(MEDIAN)]) in top, + "sqlite-js-app-top.md shows that output") + + java = java_project(work, assets) + count = len(blocks("java")) + r = gradle(java, ":app:assembleDebug") + check(r.returncode == 0, "the %d java examples compile, with the %d gradle-java examples' settings " + "(:app:assembleDebug)" % (count, len(blocks("gradle-java"))), r.stdout + r.stderr) + r = gradle(java, ":app:assembleDebugAndroidTest") + check(r.returncode == 0, "the test that runs the java examples on a device compiles " + "(:app:assembleDebugAndroidTest)", r.stdout + r.stderr) + check_sql("java", java_strings("\n".join(block for _, _, block in blocks("java")))) + + if DEVICE: + r = gradle(project, ":app:connectedDebugAndroidTest") + check(r.returncode == 0, "the kotlin examples run on the device (app-test/DocExamplesTest.kt)", + r.stdout + r.stderr) + r = gradle(java, ":app:connectedDebugAndroidTest") + check(r.returncode == 0, "the java examples run on the device (app-test/JavaDocExamplesTest.java)", + r.stdout + r.stderr) + + print("1..%d" % n) + print("# FAILED %d of %d" % (failed, n) if failed else "# passed all %d" % n) + sys.exit(1 if failed else 0) + + +main() diff --git a/docs/docdb/ADFA-7083/test_examples.py b/docs/docdb/ADFA-7083/test_examples.py index 8ade976f60..02a78c4019 100644 --- a/docs/docdb/ADFA-7083/test_examples.py +++ b/docs/docdb/ADFA-7083/test_examples.py @@ -10,12 +10,22 @@ second time in the same session, as a reader trying it again would, and must give the same output. +A `-- Error: text` line says that the statement above it fails, with a message +that contains the text. A session must report exactly the errors its examples +name, in order, each at the line where that statement starts, and no others. +sqlite3 reads the examples from its standard input, where, as when a reader +types them, it goes on after an error. + +The ```kotlin and ```gradle examples of the app pages are checked by +test_app_examples.py. + Usage: SQLITE3=sqlite3 EXT=/path/to/sqlite-js.so python3 test_examples.py Prints TAP. Exits 0 only if every example passes. """ import glob import os import re +import sqlite3 import subprocess import sys @@ -23,17 +33,66 @@ SQLITE3 = os.environ.get("SQLITE3", "sqlite3") EXT = os.environ.get("EXT", "sqlite-js") # Pages of the existing help that the new pages link to. -EXISTING = {"terminal-top.html", "cogo-top.html"} +EXISTING = {"terminal-top.html", "cogo-top.html", "project-create-new.html"} # An example that makes something cannot simply run again: a second CREATE TABLE fails. -MAKES_SOMETHING = re.compile(r"\b(CREATE|INSERT|js_create_\w+|js_init_table)\b", re.I) +MAKES_SOMETHING = re.compile(r"\b(CREATE|INSERT|PRAGMA|js_create_\w+|js_init_table)\b", re.I) # Printed just before the run under test, so that only its own output is compared. BOUNDARY = "test_examples: run under test" +# What sqlite3 prints on standard error for a failed statement, across its versions: +# "Runtime error near line 3: ...", "Parse error near line 3: ..." or "Error: near line 3: ...". +ERROR_LINE = re.compile(r"^(Runtime error|Parse error|Error)\b") +# The line of its standard input where the failed input starts, in each of those forms. +NEAR_LINE = re.compile(r"near line (\d+):") + + def run(sql): - r = subprocess.run([SQLITE3, "-batch", "-noheader", "-cmd", '.load "%s"' % EXT, ":memory:", sql], - capture_output=True, text=True, timeout=60) - return r, (r.stdout.rstrip("\n").split("\n") if r.stdout.strip() else []) + """Runs sql in one session; returns the lines it printed, the errors it reported, its + standard error and its exit code.""" + # -init: none of the settings of the user's ~/.sqliterc, such as .bail on + r = subprocess.run([SQLITE3, "-batch", "-noheader", "-init", os.devnull, "-cmd", '.load "%s"' % EXT, ":memory:"], + input=sql + "\n", capture_output=True, text=True, timeout=60) + out = r.stdout.rstrip("\n").split("\n") if r.stdout.strip() else [] + return out, [l for l in r.stderr.split("\n") if ERROR_LINE.match(l)], r.stderr, r.returncode + + +def split(block): + """An example's SQL; the output lines it must end with; and the errors it must report, each + as its text and the line of the SQL, from 0, where the statement above its note starts. + + sqlite3 reports an error at the line where the input it was running starts: the first line + that is not blank after the last complete statement, or a line starting with a dot command.""" + lines, want, errors = [], [], [] + pending, start, last = "", None, None + for line in block.split("\n"): + if line.startswith("--"): + note = re.match(r"^-- ?(.*)$", line).group(1) + if note.startswith("Error: "): + errors.append((note[len("Error: "):], last)) + else: + want.append(note) + continue + if not pending and line.strip(): + start = len(lines) + lines.append(line) + if start is not None and not pending and line.startswith("."): + last, start = start, None + elif start is not None: + pending += line + "\n" + if sqlite3.complete_statement(pending): + last, pending, start = start, "", None + return "\n".join(lines), want, errors + + +def at(errors, first): + """The errors, each with the line of standard input, from 1, where its statement starts, for + SQL whose first line is line first.""" + return [(text, first + line) for text, line in errors] + + +def lines(sql): + return sql.count("\n") + 1 def main(): @@ -43,25 +102,34 @@ def main(): for path in files: text = open(path, encoding="utf-8").read() name = os.path.basename(path) - earlier = [] + earlier, earlier_errors = [], [] for k, block in enumerate(re.findall(r"^```sql\n(.*?)^```", text, re.M | re.S), 1): - want = [m.group(1) for m in re.finditer(r"^-- ?(.*)$", block, re.M)] - sql = "\n".join(l for l in block.split("\n") if not l.startswith("--")) + sql, want, errors = split(block) mark = "SELECT '%s';" % BOUNDARY - runs = [("", "\n".join(earlier + [mark, sql]))] + # the line of standard input, from 1, where this example starts in each run + before = sum(lines(e) for e in earlier) + runs = [("", "\n".join(earlier + [mark, sql]), earlier_errors + at(errors, before + 2))] if not MAKES_SOMETHING.search(sql): - runs.append((" run again", "\n".join(earlier + [sql, mark, sql]))) + runs.append((" run again", "\n".join(earlier + [sql, mark, sql]), + earlier_errors + at(errors, before + 1) + at(errors, before + lines(sql) + 2))) earlier.append(sql) - for label, all_sql in runs: + earlier_errors += at(errors, before + 1) + for label, all_sql, want_errors in runs: n += 1 - r, out = run(all_sql) + out, got_errors, stderr, code = run(all_sql) got = out[len(out) - out[::-1].index(BOUNDARY):] if BOUNDARY in out else [] - ok = r.returncode == 0 and BOUNDARY in out and (not want or got[-len(want):] == want) + # sqlite3 exits with 1 after a session that reported an error and with 0 after one + # that reported none: anything else is a crash + ok = (code == (1 if want_errors else 0) + and BOUNDARY in out and (not want or got[-len(want):] == want) + and len(got_errors) == len(want_errors) + and all(w in g and NEAR_LINE.search(g) and int(NEAR_LINE.search(g).group(1)) == n + for (w, n), g in zip(want_errors, got_errors))) print("%s %d - %s example %d%s" % ("ok" if ok else "not ok", n, name, k, label)) if not ok: failed += 1 - print("# exit %d, want %r, got %r, stderr %r" - % (r.returncode, want, got[-(len(want) or 1):], r.stderr[:200])) + print("# exit %d, want %r, got %r, want errors %r, stderr %r" + % (code, want, got[-(len(want) or 1):], want_errors, stderr[:300])) front = re.match(r"---\n(.*?)\n---\n", text, re.S).group(1) for key, url in re.findall(r"^(parent|prev|next): (.*)$", front, re.M): n += 1 diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index 50417ba803..a0fb5e7ff5 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -37,7 +37,7 @@ Room.databaseBuilder(context, AppDb::class.java, name).openHelperFactory(factory - A connection that opened before a function was stored does not have it. So store the functions before Room opens the database, on a connection opened with `ENTRY_POINT`, since a connection cannot redefine a function it has. - Room checks queries at build time with its own SQLite, which has no JavaScript functions: mark DAO methods that call them `@SkipQueryVerification`. - SQLite loads the extension from a file, so set `packaging.jniLibs.useLegacyPackaging = true`. -- Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its connection is interrupted too, as `sqlite3_interrupt()` does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted `INSERT`, `UPDATE` or `DELETE` inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. The `db.exec` result sets of a call it stops are ended, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. +- Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its connection is interrupted too, as `sqlite3_interrupt()` does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An `INSERT`, `UPDATE` or `DELETE` whose function it stops fails with "interrupted", and only that statement's changes are undone: a transaction it is part of stays open with its earlier changes, so roll the transaction back and run all of it again. Room's `withTransaction` and `runInTransaction` roll back when their block throws; a transaction the app began with `BEGIN` needs a `ROLLBACK`. SQLite rolls the whole transaction back by itself only when the statement ends with SQLITE_INTERRUPT, as one whose collation was stopped does. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. The `db.exec` result sets of a call it stops are ended, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. Built from 1.4.1 with our patches of the time, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 25 ms. The build from 1.4.2 with our two cancel patches, which 1.4.3 has, passed the trial app's checks in both processes and on both databases, and the template stopped its runaway query 11 to 13 ms after Cancel. The build from 1.4.3 passed the same checks, and the template stopped its runaway query 11 to 12 ms after Cancel, in its 64-bit and 32-bit debug builds and its release build. diff --git a/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java b/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java index f829bb88c9..43fe1f4b7e 100644 --- a/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java +++ b/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java @@ -31,8 +31,8 @@ public final class SqliteJs { } /** - * Stops the JavaScript that is running now, in every query on every connection: each running call fails with an "interrupted" error, and its connection is interrupted too, as sqlite3_interrupt() does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted INSERT, UPDATE or DELETE inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started: a query that has not reached its JavaScript yet runs it normally, so call it again until the query being stopped ends. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, - * and while it loads each stored function. It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through db.exec (a long next() or toArray()), finishes before the cancel reaches it. Safe from any thread. Android's own cancelling (a CancellationSignal) cannot stop a JavaScript function. + * Stops the JavaScript that is running now, in every query on every connection: each running call fails with an "interrupted" error, and its connection is interrupted too, as sqlite3_interrupt() does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An INSERT, UPDATE or DELETE whose function it stops fails with "interrupted", and only that statement's changes are undone: a transaction it is part of stays open with its earlier changes, so roll the transaction back and run all of it again. Room's withTransaction and runInTransaction roll back when their block throws; a transaction the app began with BEGIN needs a ROLLBACK. SQLite rolls the whole transaction back by itself only when the statement ends with SQLITE_INTERRUPT, as one whose collation was stopped does. So call it only when a + * runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started: a query that has not reached its JavaScript yet runs it normally, so call it again until the query being stopped ends. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through db.exec (a long next() or toArray()), finishes before the cancel reaches it. Safe from any thread. Android's own cancelling (a CancellationSignal) cannot stop a JavaScript function. */ public static native void cancelAll();