diff --git a/README.md b/README.md index 50cdb8b..06e133e 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Packages that are not in `termux-packages` live in `packages//`, laid out | Package | What it is | |---------|------------| | `sqlite-brotli` | SQLite extension adding `encodeBrotli()` and `decodeBrotli()`. See [its README](packages/sqlite-brotli/README.md). | +| `sqlite-js` | SQLite extension for SQL functions written in JavaScript: [sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.2, which includes our changes. See [its README](packages/sqlite-js/README.md). | The key specified with the `-s` option is the **public key** (**NOT** the private key!), which can be generated using : diff --git a/packages.sh b/packages.sh index bcc8bf7..eef4183 100644 --- a/packages.sh +++ b/packages.sh @@ -99,4 +99,8 @@ COTG_PACKAGES+=( # Brotli functions for the sqlite3 shell, used to maintain # documentation.db (ADFA-6635). Built from packages/sqlite-brotli. "sqlite-brotli" + + # SQL functions written in JavaScript for the sqlite3 shell + # (ADFA-7081). Built from packages/sqlite-js. + "sqlite-js" ) diff --git a/packages/sqlite-js/README.md b/packages/sqlite-js/README.md new file mode 100644 index 0000000..933ed1d --- /dev/null +++ b/packages/sqlite-js/README.md @@ -0,0 +1,258 @@ +# sqlite-js + +A SQLite loadable extension for writing SQL functions in JavaScript: scalar +functions, aggregates, window functions and collations (ADFA-7081). It is +[sqliteai/sqlite-js](https://github.com/sqliteai/sqlite-js) 1.4.2, which +includes twelve changes of ours, listed [below](#changes-in-this-build). The +JavaScript engine, [quickjs-ng](https://github.com/quickjs-ng/quickjs) 0.12.1, +is built in. + +## Load it + +```text +$ sqlite3 my.db +sqlite> .load sqlite-js +``` + +If `.load sqlite-js` reports that it cannot find the file, give the full path, +which `echo $PREFIX/lib/sqlite-js` prints. (`.load` does not expand `$PREFIX` +itself.) + +Load it in the sessions that need it, rather than in `~/.sqliterc`, so that +running a database's stored JavaScript stays a deliberate step: see +[Databases from other people](#databases-from-other-people). + +## Examples + +A scalar function returns one value per row. Its code is a function that gets +the SQL arguments as an array: + +```sql +SELECT js_create_scalar('slugify', '(function (args) { + return args[0].toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); +})'); +SELECT slugify('Hello, World!'); -- hello-world +``` + +An aggregate takes code to run before the first row, a function to call for +each row, and a function that returns the result: + +```sql +SELECT js_create_aggregate('median', + 'values = [];', + '(function (args) { values.push(args[0]); })', + '(function () { + values.sort((a, b) => a - b); + const m = values.length >> 1; + return values.length % 2 ? values[m] : (values[m - 1] + values[m]) / 2; + })'); +WITH v(x) AS (VALUES (3), (1), (4), (1), (5)) +SELECT median(x) FROM v; -- 3 +``` + +A window function also takes a function that returns the current result and +one that removes a row that leaves the window: + +```sql +SELECT js_create_window('moving_sum', + 'total = 0;', + '(function (args) { total += args[0]; })', + '(function () { return total; })', + '(function () { return total; })', + '(function (args) { total -= args[0]; })'); +WITH v(x) AS (VALUES (1), (2), (3), (4)) +SELECT group_concat(s, ' ') FROM ( + SELECT moving_sum(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS s + FROM v); -- 1 3 5 7 +``` + +A collation compares two strings, like a JavaScript sort comparator: + +```sql +SELECT js_create_collation('by_length', '(function (a, b) { + return a.length - b.length || a.localeCompare(b); +})'); +WITH v(s) AS (VALUES ('ccc'), ('a'), ('bb')) +SELECT group_concat(s, ' ') FROM (SELECT s FROM v ORDER BY s COLLATE by_length); -- a bb ccc +``` + +`js_eval` runs code and returns its value. In JavaScript, `db.exec` runs SQL +on the same database, with `?` parameters: + +```sql +SELECT js_eval('[1, 2, 3].map(x => x * x).join(" ")'); -- 1 4 9 +SELECT js_eval('(function () { + const rows = db.exec("SELECT ? * 2 AS doubled", 21); + rows.next(); + return rows.get(0); +})()'); -- 42 +``` + +`db.exec` returns a result set, and the statement runs as `next()` or +`toArray()` steps it, so call `next()` once to run an `INSERT` or another +statement that returns no rows. An SQL error, while the statement is prepared +or while it runs, is a JavaScript exception. A result set lasts until the call +into JavaScript that created it returns, or until the outer call returns when +SQL that the outer call ran with `db.exec` made that call. One kept in a global +and read by a later call throws "The result set was closed when the call into +JavaScript that created it returned", or "interrupted" if Ctrl-C stopped the +call; one whose `next()` returned `false`, or whose `toArray()` ran, just +reports no more rows. + +## Functions + +| Function | What it does | +|----------|--------------| +| `js_create_scalar(name, code)` | Creates a scalar function. | +| `js_create_aggregate(name, init, step, final)` | Creates an aggregate. `init` is code; `step` and `final` are functions. | +| `js_create_window(name, init, step, final, value, inverse)` | Creates a window function. | +| `js_create_collation(name, code)` | Creates a collation. | +| `js_eval(code)` | Runs code; returns the value of its last expression. | +| `js_init_table()` | Creates the `js_functions` table. From then on, `js_create_*` also stores each function there. | +| `js_init_table(1)` | Also creates every function stored in `js_functions`. | +| `js_load_text(path)`, `js_load_blob(path)` | Return a file's contents as TEXT or as a BLOB. | +| `js_set_memory_limit(bytes)` | Sets the memory JavaScript may use on this connection; 0 means no limit. | +| `js_set_max_stack_size(bytes)` | Sets JavaScript's stack limit, at most what the thread's stack allows (the error gives the largest size). 0 turns the check off; deep recursion then crashes `sqlite3`. | +| `js_version()`, `js_version(1)` | The sqlite-js version, or with an argument, the quickjs-ng version. | + +The functions you create last for the session. To keep them, call +`js_init_table()` before creating them, then `js_init_table(1)` in a later +session. A function cannot be redefined in the session that created it; use a +new session. + +All but `js_version` work only in top-level SQL, not in views, triggers, CHECK +constraints, generated columns or indexes stored in a database. (TEMP views and +triggers can call them: SQLite trusts them, since only the session can make +them.) The functions you create have no +such restriction of their own, but `sqlite3` turns `trusted_schema` off, which +keeps them out of a database's views and triggers as well (TEMP ones excepted); run +`PRAGMA trusted_schema = ON;` in a session to use them there. The collations +you create work in table and index definitions either way. + +## Values + +SQL values reach JavaScript as follows: + +| SQL | JavaScript | +|-----|------------| +| NULL | `null` | +| INTEGER, REAL | number | +| TEXT | string | +| BLOB | `ArrayBuffer` | + +A result goes back to SQL as follows: `null` and `undefined` become NULL, a +boolean an INTEGER (1 or 0), a whole number from -(2^53 - 1) to 2^53 - 1 an +INTEGER and any other number a REAL, a BigInt an INTEGER, a string TEXT, and an +`ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects +become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters +of `db.exec` convert the same way. + +JavaScript has a single number type, a double. So a REAL that holds a whole +number, such as 3.0, comes back as the INTEGER 3, and an INTEGER beyond +±(2^53 - 1) loses precision in JavaScript. To keep such an INTEGER exact, pass +it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. + +## JavaScript here + +- quickjs-ng runs modern JavaScript (ES2023 and later), with no browser or + Node.js APIs: no `fetch`, `require`, `setTimeout`, DOM or `process`. +- Promises never settle and `async` functions never finish, because nothing + runs JavaScript's job queue. Write synchronous code. +- JavaScript has no file, network or process functions of its own. Through + `db.exec` it can run any SQL, including `js_load_text` and the shell's + `readfile()` and `writefile()`. +- `console.log` and `print` write to `sqlite3`'s standard output, among the + query results. +- Each session has its own JavaScript globals, shared by `js_eval` and the + scalar functions and collations you create. Each running aggregate or window + function gets globals of its own, set up by its `init` code. + +## Limits + +- **Memory.** JavaScript may use 64 MB per session. Code that needs more fails + with an "out of memory" error, and the session stays usable. JavaScript that + catches the error receives `null` instead when the limit leaves no room even + for the error. Garbage is collected after the error, so code that failed + because garbage filled the limit works when run again. + `js_set_memory_limit` changes the limit, and collects garbage. Memory that + globals still hold counts against the limit until they are cleared, so a + limit under it leaves no room for any JavaScript until it is raised again. +- **Endless code.** Ctrl-C stops running JavaScript: the statement fails with + an "interrupted" error, even if the code catches exceptions. In an + interactive session `sqlite3` keeps running; with SQL from a file or from + arguments it exits. +- **Stack.** 1 MB by default, or less on a thread with less stack; + `js_set_max_stack_size` changes it, up to what the stack allows. With no + stack limit (`ulimit -s unlimited`) that is 1 MB, since there is no size to + measure. Code that calls itself too deeply fails with "Maximum call stack + size exceeded". +- **Collations that fail.** A collation that throws an exception, or runs out + of memory, compares the two strings as equal. `ORDER BY` then returns a + wrong order rather than an error, so keep collation code simple. + +## Databases from other people + +A database can store JavaScript in its `js_functions` table, and +`js_init_table(1)` runs it with your access. Through `db.exec` it can run any +SQL: read and change every attached database and, in `sqlite3`, read and write +your files with `readfile()` and `writefile()` and load other extensions. Call +`js_init_table(1)` only on databases you trust. + +Nothing else in a database runs JavaScript on its own: views, triggers, CHECK +constraints and generated columns cannot call `js_eval` or the other +`js_*` functions (see [changes](#changes-in-this-build)), and `sqlite3` turns +`trusted_schema` off as well. + +## Changes in this build + +Upstream released nine changes of ours in 1.4.0. Compared with 1.3.7: + +| Upstream PR | Change | +|-------------|--------| +| #11 | Ctrl-C and `sqlite3_interrupt()` stop running JavaScript. In 1.3.7, endless code hangs `sqlite3`. | +| #12 | A 64 MB memory limit, and `js_set_memory_limit`. In 1.3.7, code that keeps allocating takes all the memory there is. | +| #13 | `js_eval` and the other functions that run code, read files or change the runtime work only in top-level SQL (and TEMP views and triggers). In 1.3.7, with `trusted_schema` on, a view can call them. | +| #14 | A result that is an `ArrayBuffer` or typed array is a BLOB, and `db.exec` binds one as a BLOB or throws if it cannot read it. In 1.3.7, a result is NULL, so a BLOB cannot pass through a function. | +| #15 | A whole-number result is an INTEGER. In 1.3.7, an INTEGER outside the 32-bit range comes back as a REAL. | +| #16 | An exception in an aggregate's or window function's step is an SQL error. In 1.3.7, it is ignored, and the result is silently wrong. | +| #17 | The JavaScript stack size stays within the thread's stack: `js_set_max_stack_size` refuses text and larger sizes, and the default shrinks on a small stack. In 1.3.7, those make endless recursion crash `sqlite3`. | +| #18 | An SQL error while a `db.exec` statement runs is an exception from `next()` or `toArray()`. In 1.3.7, `next()` returns `false` as at the end of the rows, and `toArray()` returns the rows before the error, so a failed write looks like success. | +| #19 | The stack check follows the thread each call runs on. In 1.3.7, JavaScript run on a thread other than the one that set up the connection fails at once, or crashes on endless recursion. | + +Upstream released three more in 1.4.2, compared with 1.4.1: + +| Upstream PR | Change | +|-------------|--------| +| #22 | The stack check stays within the stack in two more cases, and upstream added two more: the main thread's stack is measured from the top the kernel counts from, and with no stack limit (`ulimit -s unlimited`) at most 1 MB is allowed. In 1.4.1, endless recursion crashes on a thread with less than 64 KB of stack left, or on a main thread whose stack was first measured deep down. Neither happens in `sqlite3`, which runs JavaScript on its main thread and loads the extension near the top of its stack. | +| #23 | Garbage is collected after any "out of memory" error and whenever the limit is set. In 1.4.1, garbage can make code that fits in the limit fail with "out of memory" every time: an allocation too large to fit, or one made after the limit was lowered to above the memory in use. | +| #24 | After an interrupt, the `db.exec` result sets still open in the session are ended, and reading on from one fails with "interrupted". In 1.4.1, Ctrl-C during code that keeps one open, in a global say, leaves every later statement in the session failing with "interrupted". | + +Upstream's own fix for a crash we reported (#25), also in 1.4.2, ends every +`db.exec` result set when the call into JavaScript that created it returns. In +1.4.1, freeing a result set that was part-way through a JavaScript window +function could crash `sqlite3`, and a result set kept in a global kept a +statement open: Ctrl-C during plain SQL then left every later statement +failing with "interrupted". + +This build carries no patches. + +The build also exports only the extension's entry points, and adds the one +SQLite derives from the file name, so that `.load sqlite-js` needs no entry +point argument. + +## Tests + +```text +$ bash $PREFIX/share/sqlite-js/run-tests.sh +``` + +They print TAP and exit 0 only if every test passes. Four tests need other +packages and are skipped without them: one needs `sqlite-brotli`, to check that +both extensions load together, and three need `util-linux`, whose `script` +drives an interactive `sqlite3` to check that Ctrl-C leaves it running. The +last line says how many were skipped. + +## License + +sqlite-js is under the Apache License 2.0 and quickjs-ng under the MIT +License; both licenses are in `$PREFIX/share/doc/sqlite-js/`. diff --git a/packages/sqlite-js/build.sh b/packages/sqlite-js/build.sh new file mode 100644 index 0000000..ff3a297 --- /dev/null +++ b/packages/sqlite-js/build.sh @@ -0,0 +1,65 @@ +TERMUX_PKG_HOMEPAGE=https://github.com/sqliteai/sqlite-js +TERMUX_PKG_DESCRIPTION="SQLite extension for functions written in JavaScript" +TERMUX_PKG_LICENSE="Apache-2.0, MIT" +TERMUX_PKG_LICENSE_FILE="LICENSE, LICENSE.quickjs" +TERMUX_PKG_MAINTAINER="@appdevforall" +TERMUX_PKG_VERSION=1.4.2 +TERMUX_PKG_REVISION=3 +TERMUX_PKG_SRCURL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/${TERMUX_PKG_VERSION}.tar.gz +TERMUX_PKG_SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 +# Upstream released our changes (sqliteai/sqlite-js #11 to #19) in 1.4.0, and +# #22 to #24 in 1.4.2, so this build carries no patches. Patches of ours would +# go here as *.patch files, each offered upstream first. +TERMUX_PKG_BUILD_DEPENDS="libsqlite" +TERMUX_PKG_RECOMMENDS="sqlite" +TERMUX_PKG_BUILD_IN_SRC=true +TERMUX_PKG_AUTO_UPDATE=false + +termux_step_post_get_source() { + # QuickJS (quickjs-ng, amalgamated into libs/quickjs.c) is MIT-licensed, + # with the license only in the comment that heads each amalgamated file. + # Collect every copyright line, then the license text once. + { + grep -o 'Copyright (c) [^*]*' libs/quickjs.c | sed 's/[[:space:]]*$//' | sort -u + echo + awk '/Permission is hereby granted/ { on = 1 } + on { sub(/^ \* ?/, ""); print } + on && /THE SOFTWARE\.$/ { exit }' libs/quickjs.c + } >LICENSE.quickjs +} + +termux_step_make() { + # QuickJS is compiled in. The SQLite API comes from the loading process + # through sqlite3ext.h, so the extension works with any sqlite3 that can + # load it. -idirafter puts the SQLite headers bundled in libs/ after + # Termux's, which $CPPFLAGS adds with -isystem; quickjs.h is only in libs/. + # + # SQLite derives the entry point from the file name, sqlite3_sqlitejs_init + # for sqlite-js.so, but upstream names it sqlite3_js_init, so --defsym adds + # the first as an alias. sqlite-js.map exports only those two: SQLite opens + # extensions with RTLD_GLOBAL, so an exported QuickJS function or + # sqlite3_api could bind to another extension's copy. + $CC $CPPFLAGS $CFLAGS -fPIC -shared -DQJS_BUILD_LIBC -idirafter libs \ + src/sqlitejs.c libs/quickjs.c \ + -o sqlite-js.so \ + $LDFLAGS -lm \ + -Wl,--version-script="$TERMUX_PKG_BUILDER_DIR/sqlite-js.map" \ + -Wl,--defsym=sqlite3_sqlitejs_init=sqlite3_js_init + + local exports + exports=$($NM -D --defined-only sqlite-js.so | awk '{ print $3 }' | sort | tr '\n' ' ') + if [[ $exports != "sqlite3_js_init sqlite3_sqlitejs_init " ]]; then + termux_error_exit "sqlite-js.so must export only its entry points, but exports: $exports" + fi +} + +termux_step_make_install() { + # In $PREFIX/lib, where the sqlite3 shell's RUNPATH finds it, so + # `.load sqlite-js` works without a path. + install -Dm600 sqlite-js.so "$TERMUX_PREFIX/lib/sqlite-js.so" + install -Dm600 "$TERMUX_PKG_BUILDER_DIR/README.md" \ + "$TERMUX_PREFIX/share/doc/sqlite-js/README.md" + # Executable, so it runs directly as well as with bash. + install -Dm700 "$TERMUX_PKG_BUILDER_DIR/tests/run-tests.sh" \ + "$TERMUX_PREFIX/share/sqlite-js/run-tests.sh" +} diff --git a/packages/sqlite-js/sqlite-js.map b/packages/sqlite-js/sqlite-js.map new file mode 100644 index 0000000..9c41c91 --- /dev/null +++ b/packages/sqlite-js/sqlite-js.map @@ -0,0 +1,12 @@ +/* + * Linker version script for sqlite-js.so: export only the entry points. + * sqlite3_js_init is upstream's; sqlite3_sqlitejs_init is the name SQLite + * derives from the file name, added with --defsym (see build.sh). + */ +{ + global: + sqlite3_js_init; + sqlite3_sqlitejs_init; + local: + *; +}; diff --git a/packages/sqlite-js/tests/run-tests.sh b/packages/sqlite-js/tests/run-tests.sh new file mode 100644 index 0000000..a087dd7 --- /dev/null +++ b/packages/sqlite-js/tests/run-tests.sh @@ -0,0 +1,784 @@ +#!/usr/bin/env bash +# +# Acceptance tests for the sqlite-js extension (ADFA-7081). +# +# Runs in Code on the Go's terminal with the sqlite, sqlite-js and +# sqlite-brotli packages installed, and on a Linux host against a local build. +# +# Usage: bash run-tests.sh +# +# Environment: +# SQLITE3 the sqlite3 shell to test (default: sqlite3) +# EXT the extension, as given to .load (default: sqlite-js) +# BROTLI_EXT sqlite-brotli, as given to .load, for AC12 (default: sqlite-brotli) +# README the README whose sql examples to run (default: found next +# to this script, installed or in the source tree) +# +# Prints TAP. Exits 0 only if every test passes. AC numbers are those of the +# acceptance criteria in ADFA-7081. + +set -u + +SQLITE3=${SQLITE3:-sqlite3} +EXT=${EXT:-sqlite-js} +BROTLI_EXT=${BROTLI_EXT:-sqlite-brotli} +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) + +usage() { + sed -n '3,19s/^# \{0,1\}//p' "$0" +} + +while getopts h opt; do + case $opt in + h) + usage + exit 0 + ;; + *) + usage >&2 + exit 2 + ;; + esac +done + +# Installed, the README is in $PREFIX/share/doc/sqlite-js and this script in +# $PREFIX/share/sqlite-js; in the source tree, the README is one level up. +if [[ -z ${README:-} ]]; then + for c in "$SCRIPT_DIR/../doc/sqlite-js/README.md" "$SCRIPT_DIR/../README.md"; do + if [[ -f $c ]]; then + README=$c + break + fi + done +fi + +# Relative paths must survive the cd into the work directory. +abs_path() { + if [[ $1 == */* && $1 != /* ]]; then + printf '%s/%s' "$(cd "$(dirname "$1")" && pwd)" "$(basename "$1")" + else + printf '%s' "$1" + fi +} +EXT=$(abs_path "$EXT") +BROTLI_EXT=$(abs_path "$BROTLI_EXT") +[[ -n ${README:-} ]] && README=$(abs_path "$README") + +# As an SQL string literal. +sql_str() { + printf "'%s'" "${1//\'/\'\'}" +} + +# As a sqlite3 shell dot-command argument: in double quotes, the shell reads +# backslash escapes. +dot_arg() { + local s=${1//\\/\\\\} + printf '"%s"' "${s//\"/\\\"}" +} + +LOAD_EXT=".load $(dot_arg "$EXT")" +LOAD_BROTLI=".load $(dot_arg "$BROTLI_EXT")" + +WORK=$(mktemp -d "${TMPDIR:-/tmp}/sqlite-js-tests.XXXXXX") || exit 1 +trap 'rm -rf "$WORK"' EXIT +cd "$WORK" || exit 1 +DB=$WORK/test.db + +n=0 +failed=0 +# Microseconds; the locale may make the decimal separator a comma. +last=${EPOCHREALTIME//[!0-9]/} + +# Sets took to the seconds since the previous test finished, to spot slow +# tests on a phone. Not run in $(...): a subshell could not update last. +took= +elapsed() { + local now=${EPOCHREALTIME//[!0-9]/} tenths + tenths=$(((now - last) / 100000)) + took="$((tenths / 10)).$((tenths % 10)) s" + last=$now +} + +ok() { + n=$((n + 1)) + elapsed + echo "ok $n - $1 ($took)" +} + +not_ok() { + n=$((n + 1)) + failed=$((failed + 1)) + elapsed + echo "not ok $n - $1 ($took)" + shift + local line + for line in "$@"; do + printf '# %s\n' "${line:0:400}" + done +} + +# For a test that needs a tool that is not installed. TAP counts it as +# passed, so the summary at the end lists the skips. +skipped=0 +skip() { + n=$((n + 1)) + skipped=$((skipped + 1)) + elapsed + echo "ok $n - $1 # SKIP $2 ($took)" +} + +note() { + printf '# %s\n' "$*" +} + +# Runs SQL against $DB in a new session, with the extension loaded. Every +# session starts without the functions created in earlier ones. +sql() { + "$SQLITE3" -bail -batch -noheader -cmd "$LOAD_EXT" "$DB" "$@" +} + +# The same, but going on after an error, as an interactive session does. The +# SQL goes in on standard input: sqlite3 exits at the first error in an SQL +# argument, -bail or not. +sql_nobail() { + printf '%s\n' "$@" | "$SQLITE3" -batch -noheader -cmd "$LOAD_EXT" "$DB" +} + +# expect NAME WANT SQL...: the SQL must succeed and print exactly WANT. +expect() { + local name=$1 want=$2 got rc + shift 2 + got=$(sql "$@" 2>&1) + rc=$? + if [[ $rc -eq 0 && $got == "$want" ]]; then + ok "$name" + else + not_ok "$name" "exit status $rc" "want: $want" "got: $got" + fi +} + +# expect_error NAME PATTERN SQL...: the SQL must fail with an SQL error whose +# message matches the extended regex PATTERN. The shell exits with the SQLite +# result code; 128 and up means a signal, a crash. +expect_error() { + local name=$1 pattern=$2 got rc + shift 2 + got=$(sql "$@" 2>&1) + rc=$? + if [[ $rc -ge 1 && $rc -lt 128 && $got =~ $pattern ]]; then + ok "$name" + else + not_ok "$name" "exit status $rc, want 1 to 127" "want an error matching: $pattern" "got: $got" + fi +} + +# expect_nobail NAME WANT ERROR SQL...: run as sql_nobail, the statements +# must print exactly WANT, and exactly one of them must fail, with an error +# message containing ERROR. The shell must not crash. +expect_nobail() { + local name=$1 want=$2 error=$3 got err rc + local one_error=$'^[^\n]*'"$error"$'[^\n]*$' + shift 3 + got=$(sql_nobail "$@" 2>nobail.err) + rc=$? + err=$(sigint.out 2>&1 & + pid=$! + for ((i = 0; i < 100; i++)); do + [[ -e started ]] && break + kill -0 "$pid" 2>/dev/null || break + sleep 0.1 + done + if [[ ! -e started ]]; then + kill -KILL "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + not_ok "$name" "the statement did not start within 10 s, so no SIGINT was sent" "got: $(/dev/null + for ((i = 0; i < 50; i++)); do + kill -0 "$pid" 2>/dev/null || break + sleep 0.1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -KILL "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + not_ok "$name" "still running 5 s after SIGINT; killed" + return + fi + wait "$pid" + rc=$? + got=$(&1) +# Bellard's QuickJS has no version function, so sqlite-js does not build with it. +if [[ $got =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + ok "AC2: js_version(1) reports the quickjs-ng version" + note "quickjs-ng $got" +else + not_ok "AC2: js_version(1) reports the quickjs-ng version" "got: $got" +fi + +# --- AC3: scalar, aggregate, window and collation functions ------------------ +# +# First the README's examples, as written: each ```sql block runs in a session +# of its own, and its "-- result" comments are the last lines it must print. + +if [[ -n ${README:-} && -f $README ]]; then + note "README: $README" + rm -f example*.sql + awk '/^```sql$/ { n++; on = 1; next } /^```$/ { on = 0 } on { print > ("example" n ".sql") }' "$README" + examples=0 + for f in example*.sql; do + [[ -f $f ]] || continue + examples=$((examples + 1)) + want=$(grep -o -- '-- .*$' "$f" | sed 's/^-- //') + lines=$(printf '%s\n' "$want" | wc -l) + got=$(sql "$(<"$f")" 2>&1) + rc=$? + first=$(grep -m1 -o 'js_create_[a-z]*(.[a-z_]*\|js_eval' "$f") + if [[ $rc -eq 0 && -n $want && $(printf '%s\n' "$got" | tail -n "$lines") == "$want" ]]; then + ok "AC3: README example ${f//[!0-9]/} ($first...) prints what it says" + else + not_ok "AC3: README example ${f//[!0-9]/} ($first...) prints what it says" \ + "exit status $rc" "want (last lines): $want" "got: $got" + fi + done + [[ $examples -ge 5 ]] || not_ok "AC3: the README has at least 5 sql examples" "found $examples in $README" +else + not_ok "AC3: README examples" "README not found; set README" +fi + +MEDIAN="SELECT js_create_aggregate('median', 'values = [];', '(function (args) { values.push(args[0]); })', '(function () { values.sort((a, b) => a - b); const m = values.length >> 1; return values.length % 2 ? values[m] : (values[m - 1] + values[m]) / 2; })');" +expect "AC3: an aggregate keeps the state of each group apart (GROUP BY)" $'0\na|2\nb|25\nc|7' \ + "$MEDIAN" \ + "WITH v(g, x) AS (VALUES ('a', 1), ('b', 10), ('a', 3), ('c', 7), ('b', 40), ('a', 2)) + SELECT g, median(x) FROM v GROUP BY g ORDER BY g;" + +expect "AC3: two aggregates of one function in one query keep separate state" $'0\n2|20' \ + "$MEDIAN" \ + "WITH v(x, y) AS (VALUES (1, 10), (2, 20), (3, 30)) SELECT median(x), median(y) FROM v;" + +expect "AC3: a window function over partitions" $'0\na:1 a:3 a:5 b:10 b:30' \ + "SELECT js_create_window('moving_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');" \ + "WITH v(g, x) AS (VALUES ('a', 1), ('a', 2), ('a', 3), ('b', 10), ('b', 20)) + SELECT group_concat(g || ':' || s, ' ') FROM ( + SELECT g, moving_sum(x) OVER (PARTITION BY g ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS s + FROM v ORDER BY g, x);" + +expect "AC3: a collation orders a column, its index and a UNIQUE constraint" $'0\na bb ccc\n1' \ + "SELECT js_create_collation('nocase_js', '(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); })');" \ + "CREATE TEMP TABLE words (w TEXT COLLATE nocase_js UNIQUE); INSERT INTO words VALUES ('bb'), ('ccc'), ('a');" \ + "SELECT group_concat(w, ' ') FROM (SELECT w FROM words ORDER BY w);" \ + "SELECT count(*) FROM words WHERE w = 'BB';" + +expect_error "AC3: the collation's UNIQUE index rejects a duplicate that differs in case" "UNIQUE constraint failed" \ + "SELECT js_create_collation('nocase_js', '(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); })');" \ + "CREATE TEMP TABLE words (w TEXT COLLATE nocase_js UNIQUE); INSERT INTO words VALUES ('bb');" \ + "INSERT INTO words VALUES ('BB');" + +expect "AC3: scalar functions and js_eval share the session's globals" $'3\n0\n5' \ + "SELECT js_eval('globalThis.base = 3');" \ + "SELECT js_create_scalar('add_base', '(function (args) { return base + args[0]; })');" \ + "SELECT add_base(2);" + +# --- AC4: stored functions load in a new session ---------------------------- + +DB=$WORK/ac4.db +sql "SELECT js_init_table();" \ + "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 2; })');" \ + "$MEDIAN" \ + "SELECT js_create_window('moving_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');" \ + "SELECT js_create_collation('by_length', '(function (a, b) { return a.length - b.length || a.localeCompare(b); })');" \ + >/dev/null 2>&1 || not_ok "AC4: store four functions with js_init_table()" +expect "AC4: js_functions holds the four functions" "by_length|collation;median|aggregate;moving_sum|window;twice|scalar" \ + "SELECT group_concat(name || '|' || kind, ';') FROM (SELECT name, kind FROM js_functions ORDER BY name);" +expect_error "AC4: a new session does not have them before js_init_table(1)" "no such function: twice" \ + "SELECT twice(21);" +expect "AC4: js_init_table(1) in a new session creates all four" $'0\n42|2|1 3 5|a bb ccc' \ + "SELECT js_init_table(1);" \ + "WITH v(x) AS (VALUES (1), (2), (3)), w(s) AS (VALUES ('ccc'), ('a'), ('bb')) + SELECT twice(21), + (SELECT median(x) FROM v), + (SELECT group_concat(s, ' ') FROM (SELECT moving_sum(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS s FROM v)), + (SELECT group_concat(s, ' ') FROM (SELECT s FROM w ORDER BY s COLLATE by_length));" +expect_error "AC4: a function cannot be redefined in the session that created it" \ + "Function updates must be performed using a separate database connection" \ + "SELECT js_init_table(1);" \ + "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 3; })');" +expect "AC4: a new session can redefine it" $'0\n63' \ + "SELECT js_create_scalar('twice', '(function (args) { return args[0] * 3; })');" \ + "SELECT twice(21);" +expect "AC4: and stores the new code, which the next new session loads" $'0\n63' \ + "SELECT js_init_table(1);" \ + "SELECT twice(21);" +DB=$WORK/test.db + +# --- AC5: JavaScript errors are SQL errors ----------------------------------- + +expect_error "AC5: an exception thrown by js_eval is an SQL error with its message" "boom" \ + "SELECT js_eval('throw new Error(\"boom\")');" +expect_error "AC5: a reference to an undefined name is an SQL error" "undefined_name is not defined" \ + "SELECT js_eval('undefined_name + 1');" +expect_error "AC5: a syntax error in js_eval is an SQL error" "SyntaxError|expected|unexpected" \ + "SELECT js_eval('function (');" +expect_error "AC5: an exception in a scalar function is an SQL error" "scalar boom" \ + "SELECT js_create_scalar('fails', '(function (args) { throw new Error(\"scalar boom\"); })');" \ + "SELECT fails(1);" +expect_error "AC5: an exception in an aggregate step is an SQL error" "step boom" \ + "SELECT js_create_aggregate('agg_fails', 'n = 0;', '(function (args) { throw new Error(\"step boom\"); })', '(function () { return n; })');" \ + "WITH v(x) AS (VALUES (1), (2)) SELECT agg_fails(x) FROM v;" +expect_error "AC5: an exception in a window function's inverse is an SQL error" "inverse boom" \ + "SELECT js_create_window('inverse_fails', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { throw new Error(\"inverse boom\"); })');" \ + "WITH v(x) AS (VALUES (1), (2), (3)) SELECT inverse_fails(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM v;" +expect_error "AC5: code with a syntax error does not create a function" "SyntaxError|expected|unexpected" \ + "SELECT js_create_scalar('broken', '(function (args) { return args[0] +; })');" +expect_error "AC5: code that is not a function does not create one" "must evaluate to a function" \ + "SELECT js_create_scalar('not_a_function', '42');" +expect_error "AC5: js_create_scalar with non-TEXT arguments is an SQL error" "Two parameters of type TEXT are required" \ + "SELECT js_create_scalar(1, 2);" +expect_error "AC5: js_eval with a non-TEXT argument is an SQL error" "A parameter of type TEXT is required" \ + "SELECT js_eval(NULL);" + +# --- AC6: values pass correctly in both directions ------------------------- + +IDENTITY="SELECT js_create_scalar('identity', '(function (args) { return args[0]; })');" +JSTYPE="SELECT js_create_scalar('jstype', '(function (args) { const v = args[0]; return v === null ? \"null\" : v instanceof ArrayBuffer ? \"ArrayBuffer\" : typeof v; })');" +expect "AC6: SQL values reach JavaScript with the right type and come back unchanged" \ + $'0\n0\nnull:null:1 number:integer:1 number:integer:1 number:integer:1 number:integer:1 number:integer:1 number:integer:1 number:real:1 number:real:1 number:real:1 string:text:1 string:text:1 string:text:1 ArrayBuffer:blob:1 ArrayBuffer:blob:1 ArrayBuffer:blob:1' \ + "$IDENTITY" "$JSTYPE" \ + "WITH v(x) AS (VALUES (NULL), (0), (42), (-7), (2147483648), (-2147483649), (9007199254740991), (3.5), (-0.25), (1e300), + ('plain'), ('Grüße aus Zürich — 世界 ✓ 😀'), (''), (x'00ff10'), (x''), (randomblob(100000))) + SELECT group_concat(jstype(x) || ':' || typeof(identity(x)) || ':' || (identity(x) IS x), ' ') FROM v;" +expect "AC6: JavaScript results reach SQL with the right type" \ + "1|0|4611686018427387904|X'010203'|X'0203'|X'0708'|NULL|{\"a\":1}|NULL|5|real" \ + "SELECT quote(js_eval('true')), quote(js_eval('false')), quote(js_eval('2n ** 62n')), + quote(js_eval('new Uint8Array([1, 2, 3])')), quote(js_eval('new Uint8Array([1, 2, 3]).subarray(1)')), + quote(js_eval('new Uint8Array([7, 8]).buffer')), quote(js_eval('({a: 1})')), + js_eval('JSON.stringify({a: 1})'), quote(js_eval('undefined')), quote(js_eval('2.5 * 2')), + typeof(js_eval('0.1 + 0.2'));" +expect "AC6: a function can make a BLOB from a BLOB" $'0\nX\'030201\'' \ + "SELECT js_create_scalar('reverse_bytes', '(function (args) { return new Uint8Array(args[0]).reverse(); })');" \ + "SELECT quote(reverse_bytes(x'010203'));" +expect "AC6: a typed array over a resizable buffer passes its current bytes, after a shrink or a grow" \ + "X'0707'|1|14|3" \ + "SELECT quote(js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab); u.fill(7); ab.resize(2); return u; })()')), + length(js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(1); return u; })()')), + length(js_eval('(function () { const ab = new ArrayBuffer(4, { maxByteLength: 16 }); const u = new Uint8Array(ab, 2); ab.resize(16); return u; })()')), + js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(3); const r = db.exec(\"SELECT length(?)\", u); r.next(); return r.get(0); })()');" +expect_error "AC6: a typed array that its shrunken buffer no longer holds is an SQL error" "detached or resized" \ + "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); return u; })()');" +expect "AC6: text passes byte for byte, non-ASCII included" $'0\n0\n1|1|1' \ + "$IDENTITY" \ + "SELECT js_create_scalar('js_length', '(function (args) { return args[0].length; })');" \ + "SELECT identity('Grüße 世界 😀') = 'Grüße 世界 😀', js_length('Grüße 世界') = 8, length(identity('😀')) = 1;" +expect "AC6: as documented, a whole REAL comes back as an INTEGER, and an INTEGER beyond 2^53 - 1 as a REAL" $'0\n3|real' \ + "$IDENTITY" "SELECT quote(identity(3.0)), typeof(identity(9007199254740993));" +expect "AC6: as documented, an INTEGER passed as TEXT keeps every digit with BigInt" $'0\n9223372036854775807' \ + "SELECT js_create_scalar('big_next', '(function (args) { return BigInt(args[0]) + 1n; })');" \ + "SELECT big_next(CAST(9223372036854775806 AS TEXT));" +expect "AC6: db.exec passes parameters and returns rows with the same conversions" \ + "integer,real,text,blob,null|X'0102'" \ + "SELECT js_eval('(function () { + const r = db.exec(\"SELECT typeof(?), typeof(?), typeof(?), typeof(?), typeof(?)\", 2147483648, 2.5, \"x\", new Uint8Array([1]), null); + r.next(); + return [0, 1, 2, 3, 4].map(i => r.get(i)).join(); + })()'), quote(js_eval('(function () { const r = db.exec(\"SELECT x''0102''\"); r.next(); return r.get(0); })()'));" +printf 'line one\nline two ✓\n' >loadme.txt +expect "js_load_text and js_load_blob read a file" "line one|X'6C696E65206F6E650A6C696E652074776F20E29C930A'" \ + "SELECT substr(js_load_text($(sql_str "$WORK/loadme.txt")), 1, 8), quote(js_load_blob($(sql_str "$WORK/loadme.txt")));" + +expect "AC6: db.exec throws for a buffer it cannot read, instead of binding NULL" \ + "ArrayBuffer is detached or resized|thrown" \ + "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); try { db.exec(\"SELECT ?\", u); return \"bound\"; } catch (e) { return e.message; } })()'), js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); try { db.exec(\"SELECT ?\", b); return \"bound\"; } catch (e) { return \"thrown\"; } })()');" +expect "AC6: a typed array's own offset and length count, not properties defined over them" "X'02'" \ + "SELECT quote(js_eval('(function () { const u = new Uint8Array([1, 2, 3]).subarray(1, 2); Object.defineProperty(u, \"byteOffset\", { value: 0 }); Object.defineProperty(u, \"byteLength\", { value: 3 }); return u; })()'));" + +# --- AC7: the crash cases fixed in 1.3.6 are SQL errors ---------------------- + +DB=$WORK/ac7.db +JS_FUNCTIONS="CREATE TABLE js_functions (name TEXT PRIMARY KEY COLLATE NOCASE, kind TEXT NOT NULL, init_code TEXT, step_code TEXT, final_code TEXT, value_code TEXT, inverse_code TEXT);" +rm -f "$DB" +expect_error "AC7: a stored scalar with NULL step_code is an SQL error, not a crash" "step code is required" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind) VALUES ('no_code', 'scalar');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: a stored aggregate with NULL final_code is an SQL error, not a crash" "final code is required" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind, step_code) VALUES ('no_final', 'aggregate', '(function (args) {})');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: a stored function of an unknown kind is an SQL error" "Unsupported function kind" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind, step_code) VALUES ('odd', 'procedure', '(function (args) {})');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: a js_functions table with other columns is an SQL error, not a crash" "no such column" \ + "CREATE TABLE js_functions (name TEXT, kind TEXT);" "INSERT INTO js_functions VALUES ('f', 'scalar');" "SELECT js_init_table(1);" +rm -f "$DB" +expect_error "AC7: stored code that is not a function is an SQL error" "must evaluate to a function" \ + "$JS_FUNCTIONS" "INSERT INTO js_functions (name, kind, step_code) VALUES ('not_fn', 'scalar', '42');" "SELECT js_init_table(1);" +DB=$WORK/test.db + +# --- AC8: Ctrl-C stops runaway JavaScript ----------------------------------- + +# Each runaway loop gives up after 20 s, long after the tests expect Ctrl-C to +# have stopped it, so that a build where Ctrl-C does nothing leaves no sqlite3 +# behind: timeout(1) below can stop script(1), but not the sqlite3 it runs. The +# plain-SQL runaway counts to 50,000,000 instead, about 5 s on an x86_64 host. +RUNAWAY='for (const end = Date.now() + 20000; Date.now() < end;) {}' +expect_sigint_stops "AC8: SIGINT (Ctrl-C) stops a runaway loop in js_eval" \ + "SELECT js_eval('$RUNAWAY') WHERE $STARTED;" +expect_sigint_stops "AC8: SIGINT stops a runaway scalar function" \ + "SELECT js_create_scalar('forever', '(function (args) { $RUNAWAY })');" "SELECT forever(1) WHERE $STARTED;" +expect_sigint_stops "AC8: SIGINT stops code that catches every exception" \ + "SELECT js_eval('for (const end = Date.now() + 20000; Date.now() < end;) { try { while (Date.now() < end) {} } catch (e) {} }') WHERE $STARTED;" + +# In batch mode the shell exits after an interrupt, whatever stopped; only an +# interactive session goes on. script(1) runs one on a pseudo-terminal, where +# the byte 0x03 is Ctrl-C. +# expect_ctrl_c_keeps_session NAME SQL: Ctrl-C once SQL has started, which it +# signals by creating the file "started" (see expect_sigint_stops), must stop +# it, and the session must then run SQL. +expect_ctrl_c_keeps_session() { + local name=$1 sql=$2 cmd got started seconds i + if ! command -v script >/dev/null 2>&1; then + skip "$name" "needs script(1), from the util-linux package" + return + fi + cmd=$(printf '%q ' "$SQLITE3" -noheader -cmd "$LOAD_EXT" "$DB") + # The shell also reports "interrupted" once the loop ends by itself, so the + # session must end well before the loop's 20 s are up: about 5 s if Ctrl-C works. + rm -f started not-started + started=$SECONDS + got=$({ + sleep 1 + printf '%s\n' "$sql" + for ((i = 0; i < 100; i++)); do + [[ -e started ]] && break + sleep 0.1 + done + [[ -e started ]] || : >not-started + printf '\003' + sleep 1 + printf '%s\n' "SELECT 'still' || ' alive';" + sleep 1 + printf '.quit\n' + } | timeout -k 5 30 script -q -c "$cmd" /dev/null 2>&1 | tr -d '\r') + seconds=$((SECONDS - started)) + if [[ -e not-started ]]; then + not_ok "$name" "the statement did not start within 10 s of being typed, so Ctrl-C came before it" "got: $got" + elif [[ $got == *interrupted* && $got == *"still alive"* && $seconds -lt 15 ]]; then + ok "$name" + else + not_ok "$name" "took $seconds s, want under 15" "got: $got" + fi +} +expect_ctrl_c_keeps_session "AC8: in an interactive session, Ctrl-C stops a runaway loop and sqlite3 keeps running" \ + "SELECT js_eval('$RUNAWAY') WHERE $STARTED;" +# A db.exec result set left open is a statement still running, and SQLite keeps +# an interrupt in effect while one runs. In 1.4.1 a result set kept in a global +# stayed open, so after Ctrl-C, during the code or during plain SQL later, every +# statement in the session failed with "interrupted". From 1.4.2 the result set +# ends when the call that created it returns. +expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops code that keeps a result set open, sqlite3 still runs SQL" \ + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); $RUNAWAY') WHERE $STARTED;" +expect_ctrl_c_keeps_session "AC8: after Ctrl-C stops plain SQL, run after code kept a result set, sqlite3 still runs SQL" \ + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); 0'); +WITH RECURSIVE c(x) AS (SELECT 1 + writefile('started', '') UNION ALL SELECT x + 1 FROM c WHERE x < 50000000) SELECT count(*) FROM c;" + +# --- AC9: the memory limit ------------------------------------------------------ + +# The default limit is 64 MB: 48 MB fits beside the runtime's own use, and +# 70 MB does not. +expect "AC9: the default limit allows 48 MB" "50331648" \ + "SELECT js_eval('new ArrayBuffer(48 * 1024 * 1024).byteLength');" +expect_error "AC9: the default limit refuses 70 MB" "out of memory" \ + "SELECT js_eval('new ArrayBuffer(70 * 1024 * 1024).byteLength');" +# The allocation loops stop at about 4 times the 64 MB default, so that a build +# without the limit fails the test rather than exhausting the device's memory. +expect_nobail "AC9: code that keeps allocating fails at the limit, and the session stays usable" \ + "1,2,3" "out of memory" \ + "SELECT js_eval('(function () { const a = []; for (let i = 0; i < 160; i++) a.push(new Array(100000).fill(1)); })()');" \ + "SELECT js_eval('[1, 2, 3].join()');" +expect_nobail "AC9: memory held by a global counts until the global is cleared" \ + $'0\n16777216' "out of memory" \ + "SELECT js_eval('globalThis.keep = new ArrayBuffer(60 * 1024 * 1024); 0');" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" \ + "SELECT js_eval('keep = null; new ArrayBuffer(16 * 1024 * 1024).byteLength');" + +# QuickJS collects cyclic garbage only past a threshold it sets to 1.5 times the +# memory in use, which with more than two thirds of the limit held is past the +# limit: garbage would fill the rest. +expect "AC9: garbage is still collected with 48 of 64 MB held" "50331648" \ + "SELECT js_eval('globalThis.keep = new ArrayBuffer(48 * 1024 * 1024); for (let i = 0; i < 300000; i++) { const o = {}; o.o = o; } keep.byteLength');" +expect "AC9: an aggregate over 300 groups runs with 48 of 64 MB held" $'0\n0\n300' \ + "SELECT js_eval('globalThis.keep = new ArrayBuffer(48 * 1024 * 1024); 0');" \ + "SELECT js_create_aggregate('n_rows', 'n = 0;', '(function (args) { n++; })', '(function () { return n; })');" \ + "WITH RECURSIVE g(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM g WHERE x < 300) SELECT sum(c) FROM (SELECT n_rows(x) AS c FROM g GROUP BY x);" +# Small allocations fill the limit so far that not even the error object fits. +# The loop stops at about 4 times the limit, like the ones above. +expect_nobail "AC9: running out of memory through small allocations is an \"out of memory\" error" \ + "2" "out of memory" \ + "SELECT js_eval('(function () { let h = null; for (let i = 0; i < 4000000; i++) h = { n: h }; })()');" \ + "SELECT js_eval('1 + 1');" + +# QuickJS can crash if it runs out of memory while it creates a context, which +# every aggregate needs. Aggregates under small limits, and with little memory +# left under the default one, may fail, but must not crash. +AGGREGATE="SELECT js_create_aggregate('n_rows', 'n = 0;', '(function (args) { n++; })', '(function () { return n; })'); +WITH v(x) AS (VALUES (1), (2)) SELECT n_rows(x) FROM v;" +runs=0 +crashes=() +for kb in 100 140 180 220 260 300 340 380 420; do + sql_nobail "SELECT js_set_memory_limit($kb * 1024);" "$AGGREGATE" >/dev/null 2>&1 + (($? >= 128)) && crashes+=("limit $kb KB") + runs=$((runs + 1)) +done +for kb in 0 1 2 3 4 6 8 12 16; do + sql_nobail "SELECT js_eval('globalThis.keep = []; try { for (let i = 0; i < 262144; i++) keep.push(new ArrayBuffer(1024)); } catch (e) {} keep.length -= $kb; 0');" \ + "$AGGREGATE" >/dev/null 2>&1 + (($? >= 128)) && crashes+=("$kb KB left") + runs=$((runs + 1)) +done +if [[ ${#crashes[@]} -eq 0 ]]; then + ok "AC9: aggregates near the memory limit fail cleanly, never crash ($runs runs)" +else + not_ok "AC9: aggregates near the memory limit fail cleanly, never crash ($runs runs)" "crashed: ${crashes[*]}" +fi +# js_set_memory_limit returns NULL, which prints as an empty line. +expect "AC9: js_set_memory_limit raises the limit" $'\n134217728' \ + "SELECT js_set_memory_limit(256 * 1024 * 1024);" \ + "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');" +expect_error "AC9: js_set_memory_limit lowers the limit" "out of memory" \ + "SELECT js_set_memory_limit(8 * 1024 * 1024);" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" +# QuickJS refuses every allocation while the memory in use is over the limit, +# and collects only when it allocates, so garbage over a lowered limit would +# leave the session out of memory until the limit is raised again. +expect "AC9: a limit lowered under garbage leaves the session usable" $'\n200000\n0\n\n2' \ + "SELECT js_set_memory_limit(0);" \ + "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');" \ + "SELECT js_eval('delete globalThis.g; 0');" \ + "SELECT js_set_memory_limit(4 * 1024 * 1024);" \ + "SELECT js_eval('1 + 1');" +# A limit lowered above the memory in use collects too: the garbage would fill +# the room under the new limit. +expect "AC9: a limit lowered above garbage leaves room for what fits" $'\n200000\n0\n\n16777216' \ + "SELECT js_set_memory_limit(0);" \ + "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');" \ + "SELECT js_eval('delete globalThis.g; 0');" \ + "SELECT js_set_memory_limit(32 * 1024 * 1024);" \ + "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');" +# QuickJS refuses an allocation too large to fit before it makes it, so the +# memory in use stays far from the limit. The garbage is collected after the +# "out of memory" error, and the next try succeeds. +name="AC9: garbage that leaves no room for a large allocation is collected after it fails" +got=$(sql_nobail \ + "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 40; i++) { const o = { b: new ArrayBuffer(1024 * 1024) }; o.o = o; g.push(o); } g.length');" \ + "SELECT js_eval('delete globalThis.g; 0');" \ + "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');" \ + "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');" 2>&1) +rc=$? +if [[ $rc -lt 128 && ${got##*$'\n'} == 31457280 ]]; then + ok "$name" +else + not_ok "$name" "exit status $rc" "want the last line: 31457280" "got: $got" +fi +for bad in -1 1.5 "'64'" NULL; do + expect_error "AC9: js_set_memory_limit($bad) is an SQL error" "The memory limit must be an integer number of bytes" \ + "SELECT js_set_memory_limit($bad);" +done + +# --- AC10: a database cannot run JavaScript from its schema ---------------------- + +# The database is made without the extension, as someone else's would be. +rm -f untrusted.db +"$SQLITE3" -bail -batch untrusted.db " +CREATE TABLE t (a); +CREATE TABLE log (msg); +CREATE VIEW v_eval AS SELECT js_eval('6 * 7') AS x; +CREATE VIEW v_load AS SELECT js_load_text('/proc/self/status') AS x; +CREATE VIEW v_init AS SELECT js_init_table(1) AS x; +CREATE TRIGGER t_insert AFTER INSERT ON t BEGIN INSERT INTO log VALUES (js_eval('\"trigger ran\"')); END; +" || not_ok "AC10: create a database with JavaScript in its schema" +DB=$WORK/untrusted.db +for trusted in "sqlite3's default" ON; do + if [[ $trusted == ON ]]; then pragma="PRAGMA trusted_schema = ON;"; else pragma="SELECT 1 WHERE 0;"; fi + for view_function in v_eval:js_eval v_load:js_load_text v_init:js_init_table; do + expect_error "AC10: a view cannot call ${view_function#*:} (trusted_schema $trusted)" "unsafe use of ${view_function#*:}" \ + "$pragma" "SELECT x FROM ${view_function%%:*};" + done + expect_error "AC10: a trigger cannot call js_eval (trusted_schema $trusted)" "unsafe use of js_eval" \ + "$pragma" "INSERT INTO t VALUES (1);" +done +expect "AC10: so the trigger never ran" "0" "SELECT count(*) FROM log;" +# SQLITE_DIRECTONLY is 0x80000 in function_list's flags. +expect "AC10: every js_* function but js_version is SQLITE_DIRECTONLY" "13|0" \ + "SELECT count(*), sum(((flags & 0x80000) != 0) != (name <> 'js_version')) FROM pragma_function_list WHERE name LIKE 'js\_%' ESCAPE '\\';" +# SQLite trusts the TEMP schema, which only the session itself can fill, so a +# TEMP view can call js_eval, as the README says. +expect "AC10: a TEMP view can call js_eval" "42" \ + "CREATE TEMP VIEW v_temp AS SELECT js_eval('6 * 7') AS x;" "SELECT x FROM v_temp;" +# This view is in the database file, which anyone can fill. It uses twice(), a +# function js_create_scalar defines for the session, and SQLite only lets a view +# use such a function when trusted_schema is ON; sqlite3 turns it off. +DB=$WORK/views.db +"$SQLITE3" -bail -batch "$DB" "CREATE VIEW v_twice AS SELECT twice(21) AS x;" || + not_ok "AC10: create a view that uses a function made with js_create_scalar" +TWICE="SELECT js_create_scalar('twice', '(function (args) { return args[0] * 2; })');" +expect "AC10: with trusted_schema ON, a view can use a function made with js_create_scalar" $'0\n42' \ + "PRAGMA trusted_schema = ON;" "$TWICE" "SELECT x FROM v_twice;" +expect_error "AC10: with sqlite3's default (trusted_schema off), it cannot" "unsafe use of twice" \ + "$TWICE" "SELECT x FROM v_twice;" +DB=$WORK/test.db + +# --- AC11: no file or process access through the std or os modules ------------ + +expect "AC11: std, os and bjson are not globals; neither are require or process" "undefined undefined undefined undefined undefined" \ + "SELECT js_eval('[typeof std, typeof os, typeof bjson, typeof require, typeof process].join(\" \")');" +expect "AC11: import(\"os\") never completes" $'1\npending' \ + "SELECT js_eval('globalThis.r = \"pending\"; import(\"os\").then(m => { r = \"loaded: \" + typeof m.exec; }, e => { r = \"rejected\"; }); 1');" \ + "SELECT js_eval('r');" +printf 'globalThis.moduleRan = true;\nexport const x = 1;\n' >module.mjs +expect "AC11: import() of a module file never runs it" $'1\nfalse' \ + "SELECT js_eval('import(\"./module.mjs\"); 1');" "SELECT js_eval('String(globalThis.moduleRan === true)');" + +# --- AC12: sqlite-js and sqlite-brotli load together --------------------------- + +if "$SQLITE3" -bail -batch :memory: "$LOAD_BROTLI" "SELECT 1;" >/dev/null 2>&1; then + BOTH="SELECT CAST(decodeBrotli(encodeBrotli(js_eval('\"ab\".repeat(5000)'))) AS TEXT) = js_eval('\"ab\".repeat(5000)'), + js_eval('(function () { const r = db.exec(\"SELECT length(decodeBrotli(encodeBrotli(?)))\", \"hello\"); r.next(); return r.get(0); })()');" + expect "AC12: sqlite-js, then sqlite-brotli: both work in one session" "1|5" "$LOAD_BROTLI" "$BOTH" + got=$("$SQLITE3" -bail -batch -noheader -cmd "$LOAD_BROTLI" -cmd "$LOAD_EXT" "$DB" "$BOTH" 2>&1) + if [[ $got == "1|5" ]]; then + ok "AC12: sqlite-brotli, then sqlite-js: both work in one session" + else + not_ok "AC12: sqlite-brotli, then sqlite-js: both work in one session" "got: $got" + fi +else + skip "AC12: sqlite-js and sqlite-brotli load together" \ + "cannot load $BROTLI_EXT; install the sqlite-brotli package, or set BROTLI_EXT" +fi + +# --- AC13: the stack size stays within the thread's stack --------------------- + +# QuickJS trusts its stack size: a size larger than the thread's stack, or 0, +# never trips its check, and code that calls itself without end crashes. +RECURSE="SELECT js_eval('(function f(n) { return f(n + 1); })(0)');" +expect_error "AC13: endless recursion fails at the default size" \ + "Maximum call stack size exceeded" "$RECURSE" +for size in "'abc'" -1 1.5 "'1048576'" 1073741824; do + expect_error "AC13: js_set_max_stack_size($size) is an error" \ + "The stack size must be an integer number of bytes from 1 to [0-9]+" \ + "SELECT js_set_max_stack_size($size);" +done +expect "AC13: js_set_max_stack_size(0) turns the check off, for use from several threads" "NULL" \ + "SELECT quote(js_set_max_stack_size(0));" + +# Close to the largest size allowed (each process has its own, since the stack +# starts at a slightly different place), recursion still fails cleanly, also +# through db.exec, which puts SQLite's frames between QuickJS's checks. +most=$(sql "SELECT js_set_max_stack_size(1073741824);" 2>&1 | sed -n 's/.*from 1 to \([0-9]*\).*/\1/p') +if [[ $most =~ ^[0-9]+$ ]] && ((most > 128 * 1024)); then + near=$((most - 64 * 1024)) + expect_error "AC13: endless recursion fails just below the largest size" \ + "Maximum call stack size exceeded" "SELECT js_set_max_stack_size($near);" "$RECURSE" + expect_error "AC13: endless recursion through db.exec fails just below the largest size" "stopped" \ + "SELECT js_set_max_stack_size($near);" \ + "SELECT js_create_scalar('recurse_sql', '(function (args) { try { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (rs.next()) return rs.get(0); } catch (e) {} throw new Error(\"stopped\"); })');" \ + "SELECT recurse_sql(0);" +else + not_ok "AC13: the error names the largest size" "got: $most" +fi + +# With no stack limit there is no size to measure, so at most 1 MB is allowed +# (1.4.2). Skipped where the limit cannot be raised. +if got=$(ulimit -s unlimited 2>/dev/null && sql "SELECT js_set_max_stack_size(2097152);" 2>&1); then + not_ok "AC13: with no stack limit, sizes above 1 MB are refused" "got: $got" +elif [[ $got =~ "from 1 to 1048576," ]]; then + ok "AC13: with no stack limit, sizes above 1 MB are refused" +elif ! (ulimit -s unlimited 2>/dev/null); then + skip "AC13: with no stack limit, sizes above 1 MB are refused" "ulimit -s unlimited is not allowed here" +else + not_ok "AC13: with no stack limit, sizes above 1 MB are refused" "want: from 1 to 1048576" "got: $got" +fi + +# On a thread with less stack than the 1 MB default, the default shrinks. +got=$(ulimit -s 512 && sql "$RECURSE" 2>&1) +rc=$? +if [[ $rc -ge 1 && $rc -lt 128 && $got =~ "Maximum call stack size exceeded" ]]; then + ok "AC13: with 512 KB of stack, endless recursion fails at the default size" +else + not_ok "AC13: with 512 KB of stack, endless recursion fails at the default size" "exit status $rc" "got: $got" +fi + +# --- AC14: SQL errors in db.exec are exceptions --------------------------------- + +# The statement runs as next() or toArray() steps it; an error while it runs +# must not look like the end of the rows. +EXEC_SETUP="CREATE TABLE IF NOT EXISTS ac14(a UNIQUE); INSERT OR IGNORE INTO ac14 VALUES (1);" +expect_error "AC14: a failed constraint throws from next()" "UNIQUE constraint failed" \ + "$EXEC_SETUP" "SELECT js_eval('db.exec(\"INSERT INTO ac14 VALUES (1)\").next()');" +expect_error "AC14: an overflow on the second row throws from toArray()" "integer overflow" \ + "SELECT js_eval('db.exec(\"SELECT 1 UNION ALL SELECT abs(-9223372036854775808)\").toArray()');" +expect "AC14: JavaScript can catch the error" "UNIQUE constraint failed: ac14.a" \ + "$EXEC_SETUP" "SELECT js_eval('(function () { try { db.exec(\"INSERT INTO ac14 VALUES (1)\").next(); return \"no error\"; } catch (e) { return e.message; } })()');" +expect "AC14: a statement runs only when stepped, and the end of the rows is false" $'0\nfalse false\n1,2' \ + "$EXEC_SETUP" "SELECT js_eval('db.exec(\"INSERT INTO ac14 VALUES (3)\"); 0');" \ + "SELECT js_eval('[db.exec(\"SELECT 1 WHERE 0\").next(), db.exec(\"INSERT INTO ac14 VALUES (2)\").next()].join(\" \")');" \ + "SELECT group_concat(a) FROM (SELECT a FROM ac14 ORDER BY a);" +# A result set ends when the call into JavaScript that created it returns, so +# one kept in a global throws when a later call reads it. +expect_error "AC14: a result set kept in a global throws when a later call reads it" \ + "closed when the call into JavaScript that created it returned" \ + "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); 0');" \ + "SELECT js_eval('held.next()');" + +echo "1..$n" +if [[ $failed -ne 0 ]]; then + echo "# FAILED $failed of $n" + exit 1 +fi +if [[ $skipped -ne 0 ]]; then + echo "# passed all $n, but skipped $skipped: install what they name to run them" +else + echo "# passed all $n" +fi