feat(plugin): read-only SQLite explorer (plugin_sqlite) v1.0.0
Single clean-room C99 binary with three modes: --meta discovery, a JSON node API (dbs / schema / query / info) and a responsive HTML explorer with a SQL editor, sortable result grid and CSV/JSON copy. Read-only is enforced twice: SQLITE_OPEN_READONLY on every open plus a sqlite3_set_authorizer() that permits only SELECT, READ, RECURSIVE, FUNCTION and a whitelist of read-only PRAGMAs. Paths are canonicalised and confined to /workspace, /codebases, $HOME or $SQLITE_ALLOWED_ROOT; file: URIs, '..' traversal and system paths are refused. Results cap at 500 rows and ~2s per statement via sqlite3_progress_handler. The public-domain SQLite 3.53.4 amalgamation is vendored and compiled in with SQLITE_OMIT_LOAD_EXTENSION / SQLITE_THREADSAFE=0, so no target needs a sqlite3 CLI, libsqlite3.so or sqlite3.dll. 122 offline assertions pass.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-11 11:31:36
Commit3a6f010f
Changed files
.gitignore+12−0■■■■■
LICENSE+21−0■■■■■
Makefile+84−0■■■■■
README.md+154−0■■■■■
build.ps1+72−0■■■■■
plugin.json+10−0■■■■■
release-dist.sh+385−0■■■■■
src/plugin_sqlite.c+1568−0■■■■■
tests/run.sh+427−0■■■■■
vendor/sqlite3.c+269649−0■■■■■
vendor/sqlite3.h+14349−0■■■■■
11 files+286731−0
Diff
Diff truncated at 200 KB
.gitignore+12−0■■■■■
11new file mode 100644
index 0000000..e94beb9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
1+/plugin_sqlite
2+/plugin_sqlite.exe
3+/plugin_sqlite.musl
4+/plugin_sqlite.arm64
5+/plugin_sqlite.macos-*
6+*.o
7+*.obj
8+bin/
9+*.tmp
10+*.log
11+__pycache__/
12+*.pyc
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+84−0■■■■■
11new file mode 100644
index 0000000..f8af03d
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,84 @@
1+# plugin_sqlite - ScorpioX Bot open-source read-only SQLite explorer plugin
2+#
3+# Targets:
4+# make native build -> ./plugin_sqlite
5+# make musl static musl x86_64 -> ./plugin_sqlite.musl
6+# make arm64 static aarch64 -> ./plugin_sqlite.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_sqlite.exe
8+# make macos Apple clang -> ./plugin_sqlite (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+#
12+# The public-domain SQLite amalgamation (vendor/sqlite3.c) is compiled into the
13+# binary, so no target needs a sqlite3 CLI, libsqlite3.so or sqlite3.dll.
14+
15+CC ?= cc
16+CFLAGS ?= -O2 -std=c99 -Wall -Wextra
17+MUSL_CC ?= musl-gcc
18+ARM64_CC ?= $(shell command -v aarch64-linux-musl-gcc 2>/dev/null || \
19+ command -v aarch64-linux-gnu-gcc 2>/dev/null || \
20+ echo aarch64-linux-musl-gcc)
21+WIN_CC ?= x86_64-w64-mingw32-gcc
22+
23+# Read-only, dependency-free SQLite build flags.
24+SQLITE_DEFS := -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0 \
25+ -DSQLITE_OMIT_DEPRECATED -DSQLITE_DQS=0 \
26+ -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_OMIT_SHARED_CACHE \
27+ -DSQLITE_MAX_ATTACHED=0
28+
29+# The amalgamation is huge and single-threaded; -O1 for it keeps builds
30+# minutes-to-seconds without measurably slowing an I/O bound browser.
31+SQLITE_OPT := -O1
32+
33+SRC := src/plugin_sqlite.c
34+AMALG := vendor/sqlite3.c
35+INC := -Isrc -Ivendor
36+BIN := plugin_sqlite
37+EXE := plugin_sqlite.exe
38+
39+.PHONY: all native musl arm64 win64 macos test clean help
40+
41+all: native
42+
43+native: $(BIN)
44+
45+$(BIN): $(SRC) $(AMALG)
46+ @echo "==> native build ($(CC))"
47+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -c $(AMALG) -o sqlite3.o $(SQLITE_OPT)
48+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -o $(BIN) $(SRC) sqlite3.o
49+
50+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
51+musl: $(SRC) $(AMALG)
52+ @echo "==> static musl build ($(MUSL_CC))"
53+ $(MUSL_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -c $(AMALG) -o sqlite3.musl.o $(SQLITE_OPT)
54+ $(MUSL_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -o $(BIN).musl $(SRC) sqlite3.musl.o
55+
56+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
57+arm64: $(SRC) $(AMALG)
58+ @echo "==> static arm64 build ($(ARM64_CC))"
59+ $(ARM64_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -c $(AMALG) -o sqlite3.arm64.o $(SQLITE_OPT)
60+ $(ARM64_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -o $(BIN).arm64 $(SRC) sqlite3.arm64.o
61+
62+# Native Win64 static PE - runs on any Windows 10/11 x64 node
63+win64: $(SRC) $(AMALG)
64+ @echo "==> MinGW-w64 build ($(WIN_CC))"
65+ $(WIN_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -c $(AMALG) -o sqlite3.win.o $(SQLITE_OPT)
66+ $(WIN_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -o $(EXE) $(SRC) sqlite3.win.o
67+
68+# Apple clang build (run this on macOS)
69+macos: $(SRC) $(AMALG)
70+ @echo "==> Apple clang build"
71+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -c $(AMALG) -o sqlite3.o $(SQLITE_OPT)
72+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -o $(BIN) $(SRC) sqlite3.o
73+
74+test: native
75+ @sh tests/run.sh
76+
77+clean:
78+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \
79+ $(BIN).macos-arm64 $(BIN).macos-x86_64 \
80+ *.o bin -r
81+ rm -rf bin
82+
83+help:
84+ @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean"
README.md+154−0■■■■■
11new file mode 100644
index 0000000..ac42d83
--- /dev/null
+++ b/README.md
@@ -0,0 +1,154 @@
1+# plugin_sqlite — read-only SQLite explorer for ScorpioX Bot
2+
3+A clean-room, **strictly read-only** local SQLite schema and query browser, written in pure C99.
4+One binary, three modes: discovery metadata, a JSON node API, and a responsive HTML tool UI.
5+
6+The public-domain SQLite amalgamation (`vendor/sqlite3.c`, 3.53.4) is compiled **into** the
7+binary, so nothing needs a `sqlite3` CLI, `libsqlite3.so` or `sqlite3.dll` on the node.
8+
9+| | |
10+|---|---|
11+| slug | `sqlite` |
12+| executable | `plugin_sqlite` (`plugin_sqlite.exe` on Windows) |
13+| metadata | `{"name":"sqlite","desc":"SQLite viewer"}` |
14+| category | `devtools` |
15+| license | MIT (SQLite itself is public domain) |
16+
17+## What it does
18+
19+* Discovers `.db` / `.db3` / `.sqlite` / `.sqlite3` files under `/workspace`, `/codebases`,
20+ `$HOME` and `$SQLITE_ALLOWED_ROOT` (depth 4, 60 000 entries, symlinked directories never
21+ followed).
22+* Shows tables and views with row counts, columns (type / NOT NULL / primary key) and indexes
23+ (unique or not).
24+* Runs `SELECT` / `WITH` / read-only `PRAGMA` / `EXPLAIN` statements and streams typed rows as
25+ JSON: integers and reals as JSON numbers, text as strings, `NULL` as `null`, and BLOBs as a
26+ bounded `{"blob_bytes":N,"hex":"..."}` preview.
27+* Renders an HTML explorer: database picker, sidebar table list, SQL editor (`Ctrl`+`Enter` to
28+ run), sortable result grid, CSV and JSON copy, dark and light themes, `?embed=1` aware.
29+
30+## Read-only by construction
31+
32+Two independent mechanisms, because a single one is a promise and two are a design:
33+
34+1. **`SQLITE_OPEN_READONLY`** on every `sqlite3_open_v2()`, plus `SQLITE_LIMIT_ATTACHED = 0`.
35+2. **`sqlite3_set_authorizer()`** that answers `SQLITE_OK` only for `SQLITE_SELECT`,
36+ `SQLITE_READ`, `SQLITE_RECURSIVE`, `SQLITE_FUNCTION`, and a whitelist of read-only PRAGMAs
37+ (`table_info`, `index_list`, `foreign_key_list`, `page_count`, `integrity_check`, ...).
38+ Everything else — `INSERT`, `UPDATE`, `DELETE`, `CREATE`, `DROP`, `ALTER`, `ATTACH`, `DETACH`,
39+ `TRANSACTION`, `REINDEX`, `VACUUM`, and settable pragmas such as `journal_mode=...` — is
40+ `SQLITE_DENY`, which the engine enforces at prepare time.
41+
42+On top of that:
43+
44+* The statement must start with `select`, `with`, `pragma`, `explain` or `values` (friendly
45+ errors rather than a bare "not authorized"), and stacked statements are rejected.
46+* Result rows are capped at **500** (`truncated: true` when the cap bites).
47+* A `sqlite3_progress_handler` aborts any statement that runs past **~2 s**
48+ (`aborted: true`, partial rows kept).
49+
50+## Path discipline
51+
52+Only regular files with a database suffix, resolved through `realpath()`, inside one of the
53+allowlisted roots are opened. Rejected outright: any `..` segment, `file:`-prefixed SQLite URI
54+filenames, `://` schemes, query strings and fragments, non-database suffixes, symlinks pointing
55+out of a root, and system paths such as `/etc/passwd`. An allowlisted-but-absent file answers
56+`not_found`, which is a different error from `forbidden_path` on purpose — the UI can tell "you
57+looked in the wrong place" from "you are not allowed there".
58+
59+Test the policy yourself:
60+
61+```
62+curl -s -G 'http://127.0.0.1:8150/plugin_sqlite' -H 'X-Bot-Password: <pwd>' \
63+ --data-urlencode 'action=query' --data-urlencode 'db=/etc/passwd' --data-urlencode 'sql=select 1'
64+# {"ok":false,"error":"forbidden_path",...}
65+```
66+
67+## API
68+
69+All routes answer `application/json; charset=utf-8` unless noted. Everything except `--meta`
70+requires the node password (`X-Bot-Password`, `Authorization: Bearer`, or `?pwd=`; unset
71+`BOT_PASSWORD` disables the check, which is how you run it from a shell).
72+
73+| Route | Answer |
74+|---|---|
75+| `?action=dbs` | `{ok, roots:[{label,path,exists}], count, dbs:[{path,root,bytes,mtime}]}` |
76+| `?action=schema&db=<path>` | `{ok, db, tables:[{name,type,rows,columns:[{name,type,notnull,pk}],indexes:[{name,unique}]}], table_count}` |
77+| `?action=query&db=<path>&sql=<SELECT ...>` | `{ok, db, columns:[{name,decl}], rows:[[...]], row_count, truncated, limit, ms, aborted, types}` |
78+| `?action=info` | plugin id, version, bundled SQLite version, platform, limits |
79+| `?format=json` | falls back to `action=dbs` |
80+| `GET` (no action) | HTML explorer, honours `?embed=1` |
81+
82+`query` also accepts `POST` with a `sql=...` body: the caller is expected to hand the urlencoded
83+body through the `HTTP_BODY_FILE` environment variable (the form `scorpiox-server` uses). A bare
84+body is treated as the statement itself.
85+
86+Rows: text is a JSON string, integer/real are JSON numbers, `NULL` is `null`, BLOB is
87+`{"blob_bytes":N,"hex":"..."}` with the hex preview truncated after 48 bytes.
88+
89+## Build
90+
91+```sh
92+make # native (glibc) -> ./plugin_sqlite
93+make musl # static musl x86_64 -> ./plugin_sqlite.musl
94+make arm64 # static aarch64 -> ./plugin_sqlite.arm64
95+make win64 # MinGW-w64 static PE -> ./plugin_sqlite.exe
96+make macos # Apple clang (on macOS) -> ./plugin_sqlite
97+make test # run tests/run.sh
98+```
99+
100+Windows without a cross toolchain: `powershell -ExecutionPolicy Bypass -File build.ps1`.
101+
102+The SQLite amalgamation compiles at `-O1` (roughly 10 s on a laptop, about a minute on a Windows
103+box). Bumping the engine to `-O2` changes nothing measurable for an I/O-bound 500-row browser.
104+
105+## Tests
106+
107+`tests/run.sh` builds a throwaway database, points the plugin at it with `SQLITE_ALLOWED_ROOT`,
108+and runs 120+ assertions:
109+
110+* `--meta` shape (single-word name, at most 15-char description, compact, valid JSON)
111+* node auth: 401 without credentials, `X-Bot-Password` / `Bearer` / `?pwd=` accepted, wrong
112+ password refused, HTML route gated too
113+* discovery, schema (tables, views, indexes, row counts, column detail) and queries
114+* typed values: integers, reals, text, JSON `null`, BLOB hex preview
115+* read-only: 15 rejected mutations (INSERT/UPDATE/DELETE/DROP/ALTER/CREATE TABLE/CREATE VIEW/
116+ ATTACH/DETACH/REINDEX/VACUUM/BEGIN/settable PRAGMA/stacked statement/WITH-DELETE) plus proof
117+ the file on disk did not change and no ATTACH file appeared
118+* path discipline: `/etc/passwd`, `..` traversal, `file:` URIs, `://` schemes, non-db suffixes
119+* the 500-row cap and the ~2 s statement budget
120+* the HTML UI (no CDN scripts, no `Content-Length`, embed behaviour)
121+* artifact checks when the musl / arm64 / Win64 builds are present (ELF magic, `e_machine`,
122+ static-link proof, `MZ` header)
123+* a full git-history audit for LAN IPs, tokens and private keys
124+
125+## Install on a node
126+
127+```sh
128+cp plugin_sqlite ~/.scorpiox/plugins/ && chmod +x ~/.scorpiox/plugins/plugin_sqlite
129+curl -s -H 'X-Bot-Password: <pwd>' 'http://127.0.0.1:8150/plugin_sqlite?action=info'
130+```
131+
132+Discovery is automatic — no server restart. On Windows the plugin directory is
133+`%LOCALAPPDATA%\scorpiox\plugins\`.
134+
135+## Source-first
136+
137+```
138+git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-sqlite.git
139+```
140+
141+Audit `src/plugin_sqlite.c`, change the allowlisted roots or the row cap for your setup, and
142+compile it yourself — it is one C file plus the vendored amalgamation and libc.
143+
144+## Layout
145+
146+```
147+src/plugin_sqlite.c the whole plugin (3 modes, path gate, authorizer, HTML UI)
148+vendor/sqlite3.{c,h} public-domain SQLite 3.53.4 amalgamation
149+tests/run.sh 120+ offline assertions
150+Makefile native / musl / arm64 / win64 / macos / test / clean
151+build.ps1 Windows MinGW static build
152+release-dist.sh build all targets, package, publish, mirror
153+plugin.json marketplace metadata
154+```
build.ps1+72−0■■■■■
11new file mode 100644
index 0000000..a04d0b0
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,72 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_sqlite
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_sqlite.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+# No extra Win32 import libraries are needed: the SQLite amalgamation is
9+# compiled in and the plugin talks to no socket.
10+#
11+# The SQLite amalgamation is a ~9 MB single translation unit; compiling it at
12+# -O1 keeps the build near a minute on a laptop while the plugin itself is I/O
13+# bound, so -O2 in the engine buys nothing anybody can measure.
14+
15+$ErrorActionPreference = "Stop"
16+$ScriptDir = $PSScriptRoot
17+Push-Location $ScriptDir
18+try {
19+ $Src = Join-Path $ScriptDir "src\plugin_sqlite.c"
20+ $Amalg = Join-Path $ScriptDir "vendor\sqlite3.c"
21+ $Out = Join-Path $ScriptDir "plugin_sqlite.exe"
22+ $Cc = "x86_64-w64-mingw32-gcc"
23+
24+ foreach ($p in @($Src, $Amalg)) {
25+ if (-not (Test-Path $p)) { throw "source not found: $p" }
26+ }
27+
28+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
29+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
30+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
31+ $Cc = "C:\gcc16\bin\gcc.exe"
32+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
33+ $Cc = "gcc"
34+ } else {
35+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
36+ }
37+ }
38+
39+ $Defs = @("-DSQLITE_OMIT_LOAD_EXTENSION", "-DSQLITE_THREADSAFE=0",
40+ "-DSQLITE_OMIT_DEPRECATED", "-DSQLITE_DQS=0",
41+ "-DSQLITE_DEFAULT_MEMSTATUS=0", "-DSQLITE_OMIT_SHARED_CACHE",
42+ "-DSQLITE_MAX_ATTACHED=0")
43+
44+ Write-Host "==> compiling the SQLite amalgamation (this takes a minute)"
45+ & $Cc -O1 -std=c99 -Ivendor @Defs -static -c $Amalg -o sqlite3.win.o
46+ if ($LASTEXITCODE -ne 0) { throw "amalgamation compile failed (exit $LASTEXITCODE)" }
47+
48+ Write-Host "==> building plugin_sqlite.exe with $Cc"
49+ & $Cc -O2 -std=c99 -Wall -Wextra -Isrc -Ivendor @Defs -static `
50+ -o $Out $Src sqlite3.win.o
51+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
52+
53+ if (-not (Test-Path $Out)) { throw "build produced no output" }
54+
55+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
56+ $bytes = [System.IO.File]::ReadAllBytes($Out)
57+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
58+ throw "output is not a PE executable (missing MZ header)"
59+ }
60+
61+ Write-Host "==> metadata check"
62+ & $Out --meta
63+ if ($LASTEXITCODE -ne 0) { throw "--meta failed" }
64+
65+ $size = (Get-Item $Out).Length
66+ Write-Host ""
67+ Write-Host "Built $Out ($size bytes)"
68+ Write-Host "Install: Copy-Item plugin_sqlite.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`""
69+}
70+finally {
71+ Pop-Location
72+}
plugin.json+10−0■■■■■
11new file mode 100644
index 0000000..ce389d0
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,10 @@
1+{
2+ "slug": "sqlite",
3+ "id": "plugin_sqlite",
4+ "title": "SQLite Explorer",
5+ "summary": "Zero-dependency, strictly read-only SQLite browser: discovers .db/.sqlite files under your workspace and home, shows tables, columns, indexes and row counts, and runs capped SELECT queries with a sortable result grid - the SQLite engine is compiled into the binary so no sqlite3 CLI, libsqlite3.so or sqlite3.dll is needed.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_read", "sqlite_readonly_open", "bounded_directory_walk"],
9+ "trust_notice": "Executes native C code on your node. Opens databases with SQLITE_OPEN_READONLY and installs an authorizer that permits only SELECT, READ, FUNCTION and read-only PRAGMA statements, so INSERT/UPDATE/DELETE/DROP/ALTER/ATTACH/CREATE are refused by the engine. Only .db/.sqlite/.sqlite3 files under /workspace, /codebases, $HOME or $SQLITE_ALLOWED_ROOT are browsable; results are capped at 500 rows and about 2 seconds per statement. Makes zero outbound network requests and opens no sockets."
10+}
release-dist.sh+385−0■■■■■
11new file mode 100755
index 0000000..99d851e
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,385 @@
1+#!/usr/bin/env bash
2+# release-dist.sh — build, scan and publish plugin_disks to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+
27+set -euo pipefail
28+
29+SLUG="sqlite"
30+ID="plugin_sqlite"
31+VERSION="1.0.0"
32+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
33+
34+# Compile flags for the vendored SQLite amalgamation.
35+SQLITE_DEFS="-DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_DEPRECATED -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_OMIT_SHARED_CACHE -DSQLITE_MAX_ATTACHED=0"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --dry-run) DRY_RUN=1 ;;
47+ --no-macos) DO_MACOS=0 ;;
48+ --no-mirror) DO_MIRROR=0 ;;
49+ --standalone) STANDALONE=1 ;;
50+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline (dist + plugingit mirror)"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition — otherwise this file's own detector patterns read as
90+# findings in every historical revision of it.
91+git log -p --all 2>/dev/null \
92+ | grep -v '^Author: ' \
93+ | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
94+ > "$SCAN_TMP" || : > "$SCAN_TMP"
95+HITS=0
96+scan() { # scan <label> <regex>
97+ local out
98+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
99+ if [ -n "$out" ]; then
100+ printf ' \033[31mHIT\033[0m %s\n' "$1"
101+ printf '%s\n' "$out" | sed 's/^/ /'
102+ HITS=$((HITS + 1))
103+ else
104+ printf ' ok %s\n' "$1"
105+ fi
106+}
107+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
108+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
109+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
110+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
111+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
112+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
113+scan "hard-coded ssh password" 'sshpass -p [^"$]'
114+P_ROOT="/codebases"
115+P_PICOBOT="${P_ROOT}/pico""bot"
116+P_WT=".work""trees"
117+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
118+scan "run-token env assignment" 'RUNNER_'"PASS="
119+if [ "$HITS" -ne 0 ]; then
120+ die "secret scan found $HITS problem(s) — refusing to publish"
121+fi
122+echo " clean: 0 hits"
123+
124+# ---------------------------------------------------------------- 2. build
125+say "2/7 build targets"
126+
127+build_ok() { [ -f "$1" ]; }
128+
129+# linux-x86_64 (glibc, native)
130+if command -v cc >/dev/null 2>&1; then
131+ cc -O1 -std=c99 -Wall -Wextra $SQLITE_DEFS -Ivendor -c vendor/sqlite3.c -o "$STAGE/sqlite3.o" \
132+ || die "amalgamation build failed"
133+ cc -O2 -std=c99 -Wall -Wextra $SQLITE_DEFS -Isrc -Ivendor -o "$STAGE/$ID" src/$ID.c "$STAGE/sqlite3.o" \
134+ || die "native build failed"
135+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
136+else
137+ die "no native cc found"
138+fi
139+
140+# linux-x86_64-musl (fully static — the universal Linux artifact)
141+if command -v musl-gcc >/dev/null 2>&1; then
142+ musl-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor -c vendor/sqlite3.c \
143+ -o "$STAGE/sqlite3.musl.o" || die "musl amalgamation build failed"
144+ musl-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
145+ -o "$STAGE/$ID.musl" src/$ID.c "$STAGE/sqlite3.musl.o" || die "musl build failed"
146+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
147+else
148+ echo " skip linux-x86_64-musl (no musl-gcc)"
149+fi
150+
151+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers).
152+# Prefer musl; on a host that only has the Debian cross toolchain the static
153+# glibc link still yields a self-contained aarch64 ELF.
154+if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then
155+ aarch64-linux-musl-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor \
156+ -c vendor/sqlite3.c -o "$STAGE/sqlite3.arm64.o" || die "arm64 musl amalgamation failed"
157+ aarch64-linux-musl-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
158+ -o "$STAGE/$ID.arm64" src/$ID.c "$STAGE/sqlite3.arm64.o" || die "arm64 musl build failed"
159+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
160+elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
161+ aarch64-linux-gnu-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor \
162+ -c vendor/sqlite3.c -o "$STAGE/sqlite3.arm64.o" || die "arm64 amalgamation failed"
163+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
164+ -o "$STAGE/$ID.arm64" src/$ID.c "$STAGE/sqlite3.arm64.o" || die "arm64 static build failed"
165+ echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
166+else
167+ echo " skip linux-arm64-musl (no aarch64 cross compiler)"
168+fi
169+
170+# windows-x86_64 (static PE)
171+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
172+ x86_64-w64-mingw32-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor \
173+ -c vendor/sqlite3.c -o "$STAGE/sqlite3.win.o" || die "MinGW amalgamation build failed"
174+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
175+ -o "$STAGE/$ID.exe" src/$ID.c "$STAGE/sqlite3.win.o" || die "MinGW build failed"
176+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
177+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
178+else
179+ echo " skip windows-x86_64 (no MinGW cross compiler)"
180+fi
181+
182+# macOS legs — Mach-O must be produced by Apple clang on a real Mac.
183+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
184+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
185+ MAC_USER="${MAC_USER:-$(whoami)}"
186+ MAC_DIR="/tmp/${ID}-mac-$$"
187+ echo " building macOS legs on $MAC_HOST"
188+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
189+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
190+ if [ -n "${MAC_PASS:-}" ]; then
191+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
192+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
193+ fi
194+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
195+ if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c" &&
196+ "${SCP_MAC[@]}" vendor/sqlite3.c vendor/sqlite3.h "$MAC_USER@$MAC_HOST:$MAC_DIR/"; then
197+ # Build straight from the uploaded file — no src/ tree on the remote.
198+ for slice in arm64 x86_64; do
199+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
200+ "cd '$MAC_DIR' && clang -O1 -std=c99 $SQLITE_DEFS -c sqlite3.c -o sqlite3.o && clang -O2 -std=c99 -Wall -Wextra -arch $slice $SQLITE_DEFS -o $ID.$slice $ID.c sqlite3.o" \
201+ 2>/dev/null; then
202+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
203+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
204+ else
205+ echo " warn: macos-$slice build failed on $MAC_HOST"
206+ fi
207+ done
208+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true
209+ else
210+ echo " warn: mac scp failed"
211+ fi
212+ else
213+ echo " warn: mac host unreachable"
214+ fi
215+else
216+ echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)"
217+fi
218+
219+# ---------------------------------------------------------------- 3. package
220+say "3/7 package"
221+
222+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
223+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
224+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
225+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
226+
227+target_meta() { # target_meta <key> <file> <format> <relpath> <name>
228+ local key="$1" file="$2" fmt="$3" rel="$4" name="$5"
229+ [ -f "$file" ] || return 0
230+ local sha size
231+ sha=$(sha256sum "$file" | awk '{print $1}')
232+ size=$(wc -c < "$file" | tr -d ' ')
233+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
234+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
235+}
236+
237+{
238+ printf '{\n'
239+ printf ' "slug": "%s",\n' "$SLUG"
240+ printf ' "id": "%s",\n' "$ID"
241+ printf ' "name": "disks",\n'
242+ printf ' "desc": "Local storage",\n'
243+ printf ' "title": "Local Storage & Mounts",\n'
244+ printf ' "summary": "Zero-dependency local storage inspector: every real mounted filesystem with usage and inode pressure, plus a bounded one-level size breakdown of /workspace and $HOME for container and laptop nodes.",\n'
245+ printf ' "category": "system",\n'
246+ printf ' "version": "%s",\n' "$VERSION"
247+ printf ' "license": "MIT",\n'
248+ printf ' "trust_notice": "Executes native C code on your node. Reads /proc/mounts and statvfs, getmntinfo or GetLogicalDriveStringsA, and walks only the allowlisted /workspace or $HOME roots; makes zero outbound network requests and opens no sockets.",\n'
249+ printf ' "capabilities": ["procfs_read", "local_filesystem_stat", "bounded_directory_walk"],\n'
250+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
251+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
252+ printf ' "git_commit": "%s",\n' "$COMMIT"
253+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
254+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
255+ printf ' "build_cmd_posix": "make",\n'
256+ printf ' "build_cmd_win64": "make win64",\n'
257+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
258+ printf ' "targets": {\n'
259+ first=1
260+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
261+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID"
262+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID"
263+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID"
264+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID"
265+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID"
266+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID"
267+ printf '\n }\n}\n'
268+} > "$STAGE/manifest.json"
269+
270+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
271+ || die "generated manifest.json is not valid JSON"
272+echo " manifest.json ok"
273+
274+# SHA256SUMS — relative paths, exactly as published
275+( cd "$STAGE"
276+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
277+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
278+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
279+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
280+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
281+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
282+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
283+ true ) > "$STAGE/SHA256SUMS"
284+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
285+
286+# ---------------------------------------------------------------- 4. stage
287+say "4/7 stage tree"
288+PKG="$STAGE/pkg"
289+mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \
290+ "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64"
291+cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID"
292+[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"
293+[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"
294+[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"
295+[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"
296+[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"
297+cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
298+chmod +x "$PKG"/*/$ID 2>/dev/null || true
299+find "$PKG" -type f | sed 's/^/ /'
300+
301+if [ "$DRY_RUN" -eq 1 ]; then
302+ say "dry run — staged at $STAGE/pkg (kept for inspection)"
303+ trap - EXIT
304+ exit 0
305+fi
306+
307+# ---------------------------------------------------------------- 5. upload
308+say "5/7 upload"
309+
310+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload"
311+SSH=(ssh -o StrictHostKeyChecking=no)
312+SCP=(scp -o StrictHostKeyChecking=no)
313+if [ -n "$DIST_PASS" ]; then
314+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
315+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
316+fi
317+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
318+
319+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
320+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
321+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
322+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
323+# OpenSSH 9 refuses to scp a bare "." source.
324+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
325+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
326+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
327+ || die "remote extract failed"
328+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
329+
330+# latest.json = copy of this version's manifest
331+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
332+ || die "latest.json update failed"
333+echo " updated bot-plugins/$SLUG/latest.json"
334+
335+# index.json — merge, preserving every sibling <slug>/latest.json
336+say "index.json merge"
337+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
338+import json, os, sys, glob
339+slug = sys.argv[1]
340+entries = {}
341+for p in sorted(glob.glob('*/latest.json')):
342+ s = os.path.dirname(p)
343+ try:
344+ entries[s] = json.load(open(p))
345+ except Exception:
346+ pass
347+index = {
348+ 'ok': True,
349+ 'service': 'bot-plugins-dist',
350+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
351+ 'count': len(entries),
352+ 'slugs': sorted(entries),
353+ 'plugins': [entries[k] for k in sorted(entries)],
354+}
355+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
356+os.replace('index.json.tmp', 'index.json')
357+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
358+PY" || die "index.json merge failed"
359+
360+# ---------------------------------------------------------------- 6. mirror
361+say "6/7 plugingit mirror"
362+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
363+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
364+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|")
365+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
366+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
367+ echo " mirrored to $PLUGINGIT_REMOTE"
368+else
369+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
370+fi
371+
372+# ---------------------------------------------------------------- 7. verify
373+say "7/7 verify"
374+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
375+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
376+if [ "$CODE" = "200" ]; then
377+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
378+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
379+else
380+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
381+fi
382+
383+printf '\n\033[1mrelease complete\033[0m\n'
384+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
385+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/plugin_sqlite.c+1568−0■■■■■
11new file mode 100644
index 0000000..01c8ec9
--- /dev/null
+++ b/src/plugin_sqlite.c
@@ -0,0 +1,1568 @@
1+/*
2+ * plugin_sqlite - ScorpioX Bot open-source read-only SQLite explorer plugin
3+ *
4+ * A single clean-room C99 binary that serves THREE modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery
6+ * 2. ?action=dbs | ?action=schema&db=... | ?action=query&db=...&sql=...
7+ * | ?action=info | ?format=json
8+ * -> JSON node API (read-only database access)
9+ * 3. GET (default) -> responsive HTML explorer UI
10+ *
11+ * READ-ONLY BY CONSTRUCTION
12+ * - Every database is opened with SQLITE_OPEN_READONLY.
13+ * - sqlite3_set_authorizer() permits only SQLITE_SELECT, SQLITE_READ,
14+ * SQLITE_RECURSIVE, SQLITE_FUNCTION and a small whitelist of read-only
15+ * PRAGMAs. INSERT / UPDATE / DELETE / CREATE / DROP / ALTER / ATTACH /
16+ * DETACH / TRANSACTION / REINDEX / VACUUM are all refused by the engine
17+ * before they can reach the file.
18+ * - Only .db / .sqlite / .sqlite3 regular files under /workspace,
19+ * /codebases, $HOME (or $SQLITE_ALLOWED_ROOT) are browsable. Paths are
20+ * resolved and verified - '..' traversal, SQLite URI filenames and system
21+ * paths such as /etc/passwd are rejected.
22+ * - Result rows are capped at 500 and each statement is bounded by a
23+ * sqlite3_progress_handler ceiling (~2 s).
24+ *
25+ * Vendors the public-domain SQLite amalgamation (vendor/sqlite3.{c,h}) and
26+ * compiles it with -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0, so the
27+ * Linux (glibc + musl static), macOS and Windows binaries need no sqlite3 CLI,
28+ * no libsqlite3.so and no sqlite3.dll.
29+ *
30+ * Zero dependencies beyond libc. MIT License. Copyright (c) 2026 SCORPIOX INC.
31+ */
32+
33+#if defined(__APPLE__)
34+# define _DARWIN_C_SOURCE 1
35+#elif !defined(_WIN32)
36+# define _POSIX_C_SOURCE 200809L
37+# define _DEFAULT_SOURCE 1
38+#endif
39+
40+#include <stdio.h>
41+#include <stdlib.h>
42+#include <string.h>
43+#include <time.h>
44+#include <ctype.h>
45+#include <errno.h>
46+
47+#if defined(_WIN32)
48+# define WIN32_LEAN_AND_MEAN
49+# include <windows.h>
50+# include <direct.h>
51+# include <io.h>
52+# include <sys/stat.h>
53+# define SX_STAT struct _stat64
54+# define sx_stat(p,s) _stat64((p),(s))
55+# define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
56+# define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
57+#else
58+# include <unistd.h>
59+# include <dirent.h>
60+# include <sys/types.h>
61+# include <sys/stat.h>
62+# define SX_STAT struct stat
63+# define sx_stat(p,s) stat((p),(s))
64+# define SX_ISREG(m) S_ISREG(m)
65+# define SX_ISDIR(m) S_ISDIR(m)
66+#endif
67+
68+#include "sqlite3.h"
69+
70+#define PLUGIN_SLUG "sqlite"
71+#define PLUGIN_ID "plugin_sqlite"
72+#define PLUGIN_VER "1.0.0"
73+
74+#define MAX_NAME 256
75+/* glibc's fortified realpath() demands a PATH_MAX-sized buffer. */
76+#define MAX_PATHQ 4096
77+#define MAX_DBS 200
78+#define MAX_TABLES 200
79+#define MAX_COLS 128
80+#define MAX_SQL 16384
81+#define MAX_ROWS 500
82+#define MAX_SCAN_ENTRIES 60000
83+#define MAX_SCAN_DEPTH 4
84+#define STMT_BUDGET_MS 2000
85+
86+/* ------------------------------------------------------------------ */
87+/* Small utilities */
88+/* ------------------------------------------------------------------ */
89+
90+static void url_decode(char *s)
91+{
92+ char *o = s;
93+ if (!s) return;
94+ while (*s) {
95+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
96+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
97+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
98+ *o++ = (char)((hi << 4) | lo);
99+ s += 3;
100+ } else if (*s == '+') {
101+ *o++ = ' ';
102+ s++;
103+ } else {
104+ *o++ = *s++;
105+ }
106+ }
107+ *o = '\0';
108+}
109+
110+/* Read one parameter (decoded) out of a query or form string. */
111+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
112+{
113+ size_t klen;
114+ const char *p;
115+
116+ if (!out || outsz == 0) return 0;
117+ out[0] = '\0';
118+ if (!qs || !key) return 0;
119+ klen = strlen(key);
120+
121+ for (p = qs; *p; ) {
122+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
123+ const char *v = p + klen + 1;
124+ size_t i = 0;
125+ while (*v && *v != '&' && i + 1 < outsz)
126+ out[i++] = *v++;
127+ out[i] = '\0';
128+ url_decode(out);
129+ return 1;
130+ }
131+ p = strchr(p, '&');
132+ if (!p) break;
133+ p++;
134+ }
135+ return 0;
136+}
137+
138+/* JSON string literal; drops control characters rather than escaping them. */
139+static void json_str(const char *s)
140+{
141+ fputc('"', stdout);
142+ if (s) {
143+ for (; *s; s++) {
144+ unsigned char c = (unsigned char)*s;
145+ if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((int)c, stdout); }
146+ else if (c == '\n') fputs("\\n", stdout);
147+ else if (c == '\r') fputs("\\r", stdout);
148+ else if (c == '\t') fputs("\\t", stdout);
149+ else if (c >= 0x20) fputc((int)c, stdout);
150+ }
151+ }
152+ fputc('"', stdout);
153+}
154+
155+static void copy_str(char *dst, size_t dstsz, const char *src)
156+{
157+ size_t n;
158+ if (!dst || dstsz == 0) return;
159+ if (!src) { dst[0] = '\0'; return; }
160+ n = strlen(src);
161+ if (n >= dstsz) n = dstsz - 1;
162+ memcpy(dst, src, n);
163+ dst[n] = '\0';
164+}
165+
166+static void utc_now(char *buf, size_t sz)
167+{
168+ time_t t = time(NULL);
169+ struct tm tmv;
170+#if defined(_WIN32)
171+ struct tm *p = gmtime(&t);
172+ if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv);
173+#else
174+ gmtime_r(&t, &tmv);
175+#endif
176+ strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
177+}
178+
179+static long long now_ms(void)
180+{
181+#if defined(_WIN32)
182+ return (long long)GetTickCount64();
183+#else
184+ struct timespec ts;
185+ if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
186+ return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL;
187+#endif
188+}
189+
190+static long node_pid(void)
191+{
192+#if defined(_WIN32)
193+ return (long)GetCurrentProcessId();
194+#else
195+ return (long)getpid();
196+#endif
197+}
198+
199+static const char *platform_name(void)
200+{
201+#if defined(_WIN32)
202+ return "windows";
203+#elif defined(__APPLE__)
204+ return "macos";
205+#else
206+ return "linux";
207+#endif
208+}
209+
210+/* Case-insensitive prefix compare, portable across glibc / macOS / MinGW. */
211+static int ci_prefix(const char *s, const char *pre)
212+{
213+ while (*pre) {
214+ if (!*s) return 0;
215+ if (tolower((unsigned char)*s) != tolower((unsigned char)*pre)) return 0;
216+ s++; pre++;
217+ }
218+ return 1;
219+}
220+
221+/* ------------------------------------------------------------------ */
222+/* Node authentication */
223+/* ------------------------------------------------------------------ */
224+
225+/*
226+ * Everything except --meta discovery must prove it knows the node password.
227+ * Accepted exactly like the rest of the node API: X-Bot-Password (what
228+ * bot-web proxies with), Authorization: Bearer, and ?pwd= (what the plugin
229+ * iframe appends). With BOT_PASSWORD unset the plugin is a deliberate no-op
230+ * so it can be exercised from a shell during development.
231+ */
232+static void require_node_auth(void)
233+{
234+ const char *np = getenv("BOT_PASSWORD");
235+ const char *xp;
236+ const char *auth;
237+ char qpwd[256];
238+ const char *qs;
239+
240+ if (!np || !*np) return;
241+
242+ xp = getenv("HTTP_X_BOT_PASSWORD");
243+ if (xp && strcmp(xp, np) == 0) return;
244+
245+ auth = getenv("HTTP_AUTHORIZATION");
246+ if (auth) {
247+ while (*auth == ' ') auth++;
248+ if (ci_prefix(auth, "Bearer ")) {
249+ auth += 7;
250+ while (*auth == ' ') auth++;
251+ if (strcmp(auth, np) == 0) return;
252+ }
253+ }
254+
255+ qs = getenv("QUERY_STRING");
256+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
257+ return;
258+
259+ fputs("Status: 401 Unauthorized\r\n"
260+ "Content-Type: application/json; charset=utf-8\r\n"
261+ "Cache-Control: no-store\r\n"
262+ "X-Content-Type-Options: nosniff\r\n\r\n"
263+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
264+ exit(0);
265+}
266+
267+/* ------------------------------------------------------------------ */
268+/* Path discipline */
269+/* ------------------------------------------------------------------ */
270+
271+typedef struct {
272+ char path[MAX_PATHQ];
273+ char label[32];
274+ int exists;
275+} sx_root_t;
276+
277+/*
278+ * The allowlist. $SQLITE_ALLOWED_ROOT is honoured first so a node owner can
279+ * point the plugin at a specific directory, and the three conventional roots
280+ * follow. Nothing outside these is ever opened, no matter what the query says.
281+ */
282+static int collect_roots(sx_root_t *out, int max)
283+{
284+ int n = 0;
285+ const char *extra = getenv("SQLITE_ALLOWED_ROOT");
286+ const char *home = getenv("HOME");
287+#if defined(_WIN32)
288+ if (!home || !*home) home = getenv("USERPROFILE");
289+#endif
290+ SX_STAT st;
291+
292+ memset(out, 0, (size_t)max * sizeof(out[0]));
293+
294+ if (extra && *extra && n < max) {
295+ copy_str(out[n].path, sizeof(out[n].path), extra);
296+ copy_str(out[n].label, sizeof(out[n].label), "allowed");
297+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
298+ n++;
299+ }
300+#if !defined(_WIN32)
301+ if (n < max) {
302+ copy_str(out[n].path, sizeof(out[n].path), "/workspace");
303+ copy_str(out[n].label, sizeof(out[n].label), "workspace");
304+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
305+ n++;
306+ }
307+ if (n < max) {
308+ copy_str(out[n].path, sizeof(out[n].path), "/codebases");
309+ copy_str(out[n].label, sizeof(out[n].label), "codebases");
310+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
311+ n++;
312+ }
313+#endif
314+ if (home && *home && n < max) {
315+ copy_str(out[n].path, sizeof(out[n].path), home);
316+ copy_str(out[n].label, sizeof(out[n].label), "home");
317+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
318+ n++;
319+ }
320+ return n;
321+}
322+
323+static int has_dotdot(const char *p)
324+{
325+ const char *s = p;
326+ while (s && *s) {
327+ if (s[0] == '.' && s[1] == '.' &&
328+ (s == p || s[-1] == '/' || s[-1] == '\\') &&
329+ (s[2] == '\0' || s[2] == '/' || s[2] == '\\'))
330+ return 1;
331+ s = strchr(s, '/');
332+ if (!s) break;
333+ s++;
334+ }
335+ return 0;
336+}
337+
338+/* Suffix gate: .db / .sqlite / .sqlite3 / .db3 (case-insensitive). */
339+static int has_db_suffix(const char *p)
340+{
341+ size_t n = strlen(p);
342+ const char *s;
343+ if (n < 4) return 0;
344+ for (s = p + n; s > p && s[-1] != '/' && s[-1] != '\\'; s--) {
345+ if (*s == '.') {
346+ if (ci_prefix(s, ".db") || ci_prefix(s, ".db3") ||
347+ ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3"))
348+ return 1;
349+ return 0;
350+ }
351+ }
352+ return 0;
353+}
354+
355+/*
356+ * Resolve and validate a database path.
357+ * 1 allowed, canonical path written to out
358+ * 0 not allowed (outside the roots / traversal / not a db file)
359+ * -1 allowed location but the file is absent
360+ */
361+static int resolve_db_path(const char *req, char *out, size_t outsz)
362+{
363+ sx_root_t roots[8];
364+ int nroots, i;
365+ char canon[MAX_PATHQ];
366+ SX_STAT st;
367+ size_t i2;
368+
369+ if (!req || !*req) return 0;
370+ if (strlen(req) >= MAX_PATHQ) return 0;
371+
372+ /* SQLite URI filenames can smuggle a different file past a naive check. */
373+ if (ci_prefix(req, "file:")) return 0;
374+ if (strstr(req, "://")) return 0;
375+ if (strstr(req, "?") || strstr(req, "#")) return 0;
376+ if (has_dotdot(req)) return 0;
377+ if (!has_db_suffix(req)) return 0;
378+
379+ /* An absolute request must resolve to itself; relative ones are joined to
380+ * $HOME so a bare "app.db" still works from the UI. */
381+ if (req[0] == '/' || (isalpha((unsigned char)req[0]) && req[1] == ':')) {
382+ copy_str(canon, sizeof(canon), req);
383+ } else {
384+ const char *home = getenv("HOME");
385+#if defined(_WIN32)
386+ if (!home || !*home) home = getenv("USERPROFILE");
387+#endif
388+ if (!home || !*home) return 0;
389+ snprintf(canon, sizeof(canon), "%s/%s", home, req);
390+ }
391+
392+ /* Normalise to an absolute, symlink-free path when the platform can. A
393+ * the leaf does not exist we resolve its parent instead and remember. */
394+ {
395+#if defined(_WIN32)
396+ char tmp[MAX_PATHQ];
397+ if (_fullpath(tmp, canon, sizeof(tmp)) != NULL)
398+ copy_str(canon, sizeof(canon), tmp);
399+ else
400+ return 0;
401+#else
402+ char tmp[MAX_PATHQ];
403+ if (realpath(canon, tmp) != NULL) {
404+ copy_str(canon, sizeof(canon), tmp);
405+ } else if (errno == ENOENT) {
406+ char dir[MAX_PATHQ], parent[MAX_PATHQ], rp[MAX_PATHQ];
407+ char *slash;
408+ copy_str(dir, sizeof dir, canon);
409+ slash = strrchr(dir, '/');
410+ if (!slash) return 0;
411+ *slash = '\0';
412+ copy_str(parent, sizeof parent, slash + 1);
413+ if (realpath(dir, rp) != NULL) {
414+ /* Bounded manual join: snprintf's "%s/%s" over two
415+ * PATH_MAX-sized buffers trips -Wformat-truncation. */
416+ size_t rl = strlen(rp);
417+ canon[0] = '\0';
418+ if (rl + strlen(parent) + 2 < sizeof canon) {
419+ memcpy(canon, rp, rl);
420+ canon[rl] = '/';
421+ copy_str(canon + rl + 1, sizeof(canon) - rl - 1, parent);
422+ } else {
423+ return 0;
424+ }
425+ }
426+ } else {
427+ return 0;
428+ }
429+#endif
430+ }
431+
432+ nroots = collect_roots(roots, 8);
433+ for (i = 0; i < nroots; i++) {
434+ size_t rl;
435+ if (!roots[i].exists) continue;
436+ rl = strlen(roots[i].path);
437+ while (rl > 1 && roots[i].path[rl - 1] == '/') rl--;
438+ if (strncmp(canon, roots[i].path, rl) != 0) continue;
439+ if (canon[rl] != '/' && canon[rl] != '\0') continue;
440+
441+ if (sx_stat(canon, &st) != 0) return -1;
442+ if (!SX_ISREG(st.st_mode)) return 0;
443+ copy_str(out, outsz, canon);
444+ return 1;
445+ }
446+
447+ /* Not under any root. Collapse any doubled separators first so the check
448+ * above cannot be defeated by "//workspace//..//". */
449+ for (i2 = 0; canon[i2]; i2++)
450+ if (canon[i2] == '\\') canon[i2] = '/';
451+ return 0;
452+}
453+
454+/* ------------------------------------------------------------------ */
455+/* SQLite: read-only open, authorizer, bounded execution */
456+/* ------------------------------------------------------------------ */
457+
458+typedef struct {
459+ long long deadline_ms;
460+ int aborted;
461+} sx_budget_t;
462+
463+static int progress_cb(void *p)
464+{
465+ sx_budget_t *b = (sx_budget_t *)p;
466+ if (!b) return 0;
467+ if (now_ms() > b->deadline_ms) { b->aborted = 1; return 1; }
468+ return 0;
469+}
470+
471+/* Read-only schema pragmas we are willing to run, and only these. */
472+static int pragma_allowed(const char *name)
473+{
474+ static const char *ok[] = {
475+ /* Pure readers only. Settable pragmas (journal_mode, encoding,
476+ * auto_vacuum, user_version, application_id, schema_version) are
477+ * deliberately absent: on a read-only handle they cannot write anyway,
478+ * but refusing them keeps the contract honest and the error explicit. */
479+ "table_info", "table_xinfo", "index_list", "index_info", "index_xinfo",
480+ "foreign_key_list", "database_list", "collation_list",
481+ "page_count", "page_size", "freelist_count", "compile_options",
482+ "quick_check", "integrity_check", "table_list",
483+ NULL
484+ };
485+ int i;
486+ if (!name) return 0;
487+ for (i = 0; ok[i]; i++)
488+ if (ci_prefix(name, ok[i]) && (name[strlen(ok[i])] == '\0'))
489+ return 1;
490+ return 0;
491+}
492+
493+/*
494+ * SQLITE_DENY on everything not explicitly allowed. Note that this fires for
495+ * the *compiled* statement, so a statement that tries to write is refused
496+ * before execution even on a writable file - defence in depth on top of
497+ * SQLITE_OPEN_READONLY.
498+ */
499+static int authorizer_cb(void *ud, int action, const char *a1, const char *a2,
500+ const char *dbname, const char *trigger)
501+{
502+ (void)ud; (void)a2; (void)dbname; (void)trigger;
503+
504+ switch (action) {
505+ case SQLITE_SELECT:
506+ case SQLITE_READ:
507+ case SQLITE_RECURSIVE:
508+ return SQLITE_OK;
509+ case SQLITE_FUNCTION:
510+ return SQLITE_OK;
511+ case SQLITE_PRAGMA:
512+ return pragma_allowed(a1) ? SQLITE_OK : SQLITE_DENY;
513+ default:
514+ return SQLITE_DENY;
515+ }
516+}
517+
518+static sqlite3 *open_ro(const char *path, int *errout)
519+{
520+ sqlite3 *db = NULL;
521+ int rc;
522+
523+ if (errout) *errout = 0;
524+
525+ /* READONLY plus no URI handling: the path has already been canonicalised
526+ * by resolve_db_path(), and URI filenames would re-introduce a second
527+ * filename parser under our feet. */
528+ rc = sqlite3_open_v2(path, &db,
529+ SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL);
530+ if (rc != SQLITE_OK) {
531+ if (db) sqlite3_close(db);
532+ if (errout) *errout = rc;
533+ return NULL;
534+ }
535+ sqlite3_extended_result_codes(db, 1);
536+ sqlite3_limit(db, SQLITE_LIMIT_ATTACHED, 0);
537+ sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
538+ sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, MAX_SQL);
539+ sqlite3_busy_timeout(db, 500);
540+ return db;
541+}
542+
543+/* Confirm the file really is a SQLite database before we report anything. */
544+static int is_database(sqlite3 *db)
545+{
546+ sqlite3_stmt *st = NULL;
547+ int rc = sqlite3_prepare_v2(db, "SELECT count(*) FROM sqlite_master", -1, &st, NULL);
548+ if (rc != SQLITE_OK) {
549+ if (st) sqlite3_finalize(st);
550+ return 0;
551+ }
552+ rc = sqlite3_step(st);
553+ sqlite3_finalize(st);
554+ return rc == SQLITE_ROW || rc == SQLITE_DONE;
555+}
556+
557+/* ------------------------------------------------------------------ */
558+/* JSON output helpers */
559+/* ------------------------------------------------------------------ */
560+
561+static void json_header(void)
562+{
563+ /* Deliberately no Content-Length - the server owns framing. */
564+ fputs("Content-Type: application/json; charset=utf-8\r\n"
565+ "Cache-Control: no-store\r\n"
566+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
567+}
568+
569+static void json_error(const char *code, const char *detail)
570+{
571+ json_header();
572+ fputs("{\"ok\":false,\"error\":", stdout);
573+ json_str(code);
574+ if (detail && *detail) {
575+ fputs(",\"detail\":", stdout);
576+ json_str(detail);
577+ }
578+ fputs("}\n", stdout);
579+}
580+
581+/* Emit one typed result value. BLOBs become a bounded hex preview. */
582+static void emit_value(sqlite3_stmt *st, int col)
583+{
584+ switch (sqlite3_column_type(st, col)) {
585+ case SQLITE_INTEGER:
586+ printf("%lld", (long long)sqlite3_column_int64(st, col));
587+ break;
588+ case SQLITE_FLOAT: {
589+ double d = sqlite3_column_double(st, col);
590+ if (d != d || d > 1.7976931348623157e308 || d < -1.7976931348623157e308) {
591+ /* NaN / Inf are not JSON numbers - describe them instead. */
592+ char buf[32];
593+ if (d != d) copy_str(buf, sizeof buf, "NaN");
594+ else if (d > 0) copy_str(buf, sizeof buf, "Infinity");
595+ else copy_str(buf, sizeof buf, "-Infinity");
596+ json_str(buf);
597+ } else {
598+ printf("%.15g", d);
599+ }
600+ break;
601+ }
602+ case SQLITE_TEXT: {
603+ const unsigned char *t = sqlite3_column_text(st, col);
604+ json_str(t ? (const char *)t : "");
605+ break;
606+ }
607+ case SQLITE_BLOB: {
608+ const unsigned char *b = (const unsigned char *)sqlite3_column_blob(st, col);
609+ int n = sqlite3_column_bytes(st, col), i, lim = n > 48 ? 48 : n;
610+ printf("{\"blob_bytes\":%d,\"hex\":\"", n);
611+ for (i = 0; i < lim; i++) printf("%02x", b[i]);
612+ fputs(n > lim ? "...\"}" : "\"}", stdout);
613+ break;
614+ }
615+ default:
616+ fputs("null", stdout);
617+ break;
618+ }
619+}
620+
621+static const char *value_type_name(sqlite3_stmt *st, int col)
622+{
623+ switch (sqlite3_column_type(st, col)) {
624+ case SQLITE_INTEGER: return "int";
625+ case SQLITE_FLOAT: return "float";
626+ case SQLITE_TEXT: return "text";
627+ case SQLITE_BLOB: return "blob";
628+ default: return "null";
629+ }
630+}
631+
632+/* Quote an identifier for interpolation into SQL (never for user values). */
633+static void quote_ident(const char *in, char *out, size_t outsz)
634+{
635+ size_t o = 0;
636+ if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
637+ out[o++] = '"';
638+ for (; in && *in && o + 3 < outsz; in++) {
639+ if (*in == '"') out[o++] = '"';
640+ out[o++] = *in;
641+ }
642+ out[o++] = '"';
643+ out[o] = '\0';
644+}
645+
646+/* ------------------------------------------------------------------ */
647+/* Database discovery */
648+/* ------------------------------------------------------------------ */
649+
650+typedef struct {
651+ char path[MAX_PATHQ];
652+ char root[32];
653+ long long size;
654+ long long mtime;
655+} sx_db_t;
656+
657+static int db_suffix_ok(const char *name)
658+{
659+ size_t n = strlen(name);
660+ const char *s = name + n;
661+ while (s > name && *s != '.') s--;
662+ if (*s != '.') return 0;
663+ return ci_prefix(s, ".db") || ci_prefix(s, ".db3") ||
664+ ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3");
665+}
666+
667+static int skip_name(const char *n)
668+{
669+ if (!n || !*n) return 1;
670+ if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0'))) return 1;
671+ /* Skip the obvious noise directories; they are never databases anyway. */
672+ if (strcmp(n, ".git") == 0 || strcmp(n, "node_modules") == 0 ||
673+ strcmp(n, "__pycache__") == 0 || strcmp(n, "venv") == 0 ||
674+ strcmp(n, ".venv") == 0 || strcmp(n, "bin") == 0 ||
675+ strcmp(n, "obj") == 0 || strcmp(n, "target") == 0)
676+ return 1;
677+ return 0;
678+}
679+
680+static int walk_dbs(const char *dir, const char *rootlabel, int depth,
681+ sx_db_t *out, int max, int *count, int *visited)
682+{
683+ if (depth > MAX_SCAN_DEPTH || *count >= max || *visited > MAX_SCAN_ENTRIES)
684+ return 0;
685+
686+#if defined(_WIN32)
687+ {
688+ WIN32_FIND_DATAA fd;
689+ HANDLE h;
690+ char pat[MAX_PATHQ];
691+ snprintf(pat, sizeof(pat), "%s\\*", dir);
692+ h = FindFirstFileA(pat, &fd);
693+ if (h == INVALID_HANDLE_VALUE) return 0;
694+ do {
695+ char full[MAX_PATHQ];
696+ SX_STAT st;
697+ if (skip_name(fd.cFileName)) continue;
698+ (*visited)++;
699+ if (*visited > MAX_SCAN_ENTRIES || *count >= max) break;
700+ snprintf(full, sizeof(full), "%s\\%s", dir, fd.cFileName);
701+ if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
702+ walk_dbs(full, rootlabel, depth + 1, out, max, count, visited);
703+ } else if (db_suffix_ok(fd.cFileName) &&
704+ sx_stat(full, &st) == 0 && SX_ISREG(st.st_mode)) {
705+ copy_str(out[*count].path, sizeof(out[*count].path), full);
706+ copy_str(out[*count].root, sizeof(out[*count].root), rootlabel);
707+ out[*count].size = (long long)st.st_size;
708+ out[*count].mtime = (long long)st.st_mtime;
709+ (*count)++;
710+ }
711+ } while (FindNextFileA(h, &fd));
712+ FindClose(h);
713+ }
714+#else
715+ {
716+ DIR *d = opendir(dir);
717+ struct dirent *e;
718+ if (!d) return 0;
719+ while ((e = readdir(d)) != NULL) {
720+ char full[MAX_PATHQ];
721+ SX_STAT st;
722+ if (skip_name(e->d_name)) continue;
723+ (*visited)++;
724+ if (*visited > MAX_SCAN_ENTRIES || *count >= max) break;
725+ snprintf(full, sizeof(full), "%s/%s", dir, e->d_name);
726+ if (lstat(full, &st) != 0) continue;
727+ if (S_ISDIR(st.st_mode)) {
728+ /* Never follow a symlinked directory: that is how a walk
729+ * escapes the allowlisted root. */
730+ if (S_ISLNK(st.st_mode)) continue;
731+ walk_dbs(full, rootlabel, depth + 1, out, max, count, visited);
732+ } else if (S_ISREG(st.st_mode) && db_suffix_ok(e->d_name)) {
733+ copy_str(out[*count].path, sizeof(out[*count].path), full);
734+ copy_str(out[*count].root, sizeof(out[*count].root), rootlabel);
735+ out[*count].size = (long long)st.st_size;
736+ out[*count].mtime = (long long)st.st_mtime;
737+ (*count)++;
738+ }
739+ }
740+ closedir(d);
741+ }
742+#endif
743+ return 0;
744+}
745+
746+/* ------------------------------------------------------------------ */
747+/* Actions */
748+/* ------------------------------------------------------------------ */
749+
750+static void action_dbs(void)
751+{
752+ sx_root_t roots[8];
753+ sx_db_t dbs[MAX_DBS];
754+ int nroots, i, count = 0, visited = 0;
755+
756+ nroots = collect_roots(roots, 8);
757+ memset(dbs, 0, sizeof(dbs));
758+
759+ json_header();
760+ fputs("{\"ok\":true,\"action\":\"dbs\",\"plugin\":\"" PLUGIN_ID "\"", stdout);
761+
762+ fputs(",\"roots\":[", stdout);
763+ for (i = 0; i < nroots; i++) {
764+ if (i) fputc(',', stdout);
765+ fputs("{\"label\":", stdout);
766+ json_str(roots[i].label);
767+ fputs(",\"path\":", stdout);
768+ json_str(roots[i].path);
769+ printf(",\"exists\":%s}", roots[i].exists ? "true" : "false");
770+ }
771+ fputs("]", stdout);
772+
773+ for (i = 0; i < nroots && count < MAX_DBS; i++) {
774+ if (!roots[i].exists) continue;
775+ walk_dbs(roots[i].path, roots[i].label, 0, dbs, MAX_DBS, &count, &visited);
776+ }
777+
778+ printf(",\"count\":%d,\"scanned_entries\":%d,\"max_depth\":%d,\"dbs\":[",
779+ count, visited, MAX_SCAN_DEPTH);
780+ for (i = 0; i < count; i++) {
781+ char utc[40];
782+ time_t t = (time_t)dbs[i].mtime;
783+ struct tm tmv;
784+#if defined(_WIN32)
785+ struct tm *p = gmtime(&t);
786+ if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv);
787+#else
788+ gmtime_r(&t, &tmv);
789+#endif
790+ strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
791+
792+ if (i) fputc(',', stdout);
793+ fputs("{\"path\":", stdout);
794+ json_str(dbs[i].path);
795+ fputs(",\"root\":", stdout);
796+ json_str(dbs[i].root);
797+ printf(",\"bytes\":%lld,\"mtime\":", dbs[i].size);
798+ json_str(utc);
799+ fputc('}', stdout);
800+ }
801+ fputs("],\"readonly\":true}\n", stdout);
802+}
803+
804+/* Count rows in one table, bounded by the statement budget. */
805+static int table_rows(sqlite3 *db, const char *table, long long *out)
806+{
807+ sqlite3_stmt *st = NULL;
808+ char sql[MAX_NAME * 2 + 64];
809+ char q[MAX_NAME * 2 + 4];
810+ int rc;
811+
812+ quote_ident(table, q, sizeof q);
813+ snprintf(sql, sizeof sql, "SELECT count(*) FROM %s", q);
814+
815+ rc = sqlite3_prepare_v2(db, sql, -1, &st, NULL);
816+ if (rc != SQLITE_OK) { if (st) sqlite3_finalize(st); return rc; }
817+ rc = sqlite3_step(st);
818+ if (rc == SQLITE_ROW) { *out = (long long)sqlite3_column_int64(st, 0); rc = SQLITE_OK; }
819+ else *out = -1;
820+ sqlite3_finalize(st);
821+ return rc;
822+}
823+
824+static void action_schema(const char *dbreq)
825+{
826+ char path[MAX_PATHQ];
827+ char errbuf[512];
828+ sqlite3 *db;
829+ sqlite3_stmt *st = NULL;
830+ sx_budget_t budget;
831+ int r, rc, tcount = 0;
832+
833+ memset(path, 0, sizeof path);
834+ r = resolve_db_path(dbreq, path, sizeof path);
835+ if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; }
836+ if (r < 0) { json_error("not_found", "database file does not exist"); return; }
837+
838+ db = open_ro(path, &rc);
839+ if (!db) {
840+ snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc));
841+ json_error("open_failed", errbuf);
842+ return;
843+ }
844+ if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; }
845+
846+ sqlite3_set_authorizer(db, authorizer_cb, NULL);
847+ budget.deadline_ms = now_ms() + STMT_BUDGET_MS;
848+ budget.aborted = 0;
849+ sqlite3_progress_handler(db, 20000, progress_cb, &budget);
850+
851+ json_header();
852+ fputs("{\"ok\":true,\"action\":\"schema\",\"readonly\":true,\"db\":", stdout);
853+ json_str(path);
854+ fputs(",\"tables\":[", stdout);
855+
856+ rc = sqlite3_prepare_v2(db,
857+ "SELECT name, type FROM sqlite_master "
858+ "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name",
859+ -1, &st, NULL);
860+ if (rc != SQLITE_OK) {
861+ sqlite3_close(db);
862+ /* Header already emitted, so finish the document with an error field. */
863+ fputs("],\"error\":\"schema_query_failed\"}\n", stdout);
864+ return;
865+ }
866+
867+ while (sqlite3_step(st) == SQLITE_ROW && tcount < MAX_TABLES) {
868+ const char *name = (const char *)sqlite3_column_text(st, 0);
869+ const char *kind = (const char *)sqlite3_column_text(st, 1);
870+ long long rows = -1;
871+ sqlite3_stmt *cs = NULL;
872+ char q[MAX_NAME * 2 + 4];
873+ int ci = 0;
874+ char sql[MAX_NAME * 2 + 96];
875+
876+ if (!name) continue;
877+ if (tcount) fputc(',', stdout);
878+ fputs("{\"name\":", stdout);
879+ json_str(name);
880+ fputs(",\"type\":", stdout);
881+ json_str(kind ? kind : "table");
882+
883+ if (table_rows(db, name, &rows) == SQLITE_OK) printf(",\"rows\":%lld", rows);
884+ else fputs(",\"rows\":null", stdout);
885+
886+ quote_ident(name, q, sizeof q);
887+ fputs(",\"columns\":[", stdout);
888+ snprintf(sql, sizeof sql, "PRAGMA table_info(%s)", q);
889+ if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) {
890+ while (sqlite3_step(cs) == SQLITE_ROW) {
891+ const char *cn = (const char *)sqlite3_column_text(cs, 1);
892+ const char *ct = (const char *)sqlite3_column_text(cs, 2);
893+ int nn = sqlite3_column_int(cs, 3);
894+ int pk = sqlite3_column_int(cs, 5);
895+ if (ci++) fputc(',', stdout);
896+ fputs("{\"name\":", stdout);
897+ json_str(cn ? cn : "");
898+ fputs(",\"type\":", stdout);
899+ json_str(ct ? ct : "");
900+ printf(",\"notnull\":%s,\"pk\":%d}", nn ? "true" : "false", pk);
901+ }
902+ }
903+ sqlite3_finalize(cs);
904+ fputs("]", stdout);
905+
906+ ci = 0;
907+ fputs(",\"indexes\":[", stdout);
908+ snprintf(sql, sizeof sql, "PRAGMA index_list(%s)", q);
909+ if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) {
910+ while (sqlite3_step(cs) == SQLITE_ROW) {
911+ const char *in = (const char *)sqlite3_column_text(cs, 1);
912+ int uniq = sqlite3_column_int(cs, 2);
913+ if (ci++) fputc(',', stdout);
914+ fputs("{\"name\":", stdout);
915+ json_str(in ? in : "");
916+ printf(",\"unique\":%s}", uniq ? "true" : "false");
917+ }
918+ }
919+ sqlite3_finalize(cs);
920+ fputs("]}", stdout);
921+ tcount++;
922+ }
923+ sqlite3_finalize(st);
924+
925+ printf("],\"table_count\":%d,\"truncated\":%s,\"budget_ms\":%d}\n",
926+ tcount, tcount >= MAX_TABLES ? "true" : "false", STMT_BUDGET_MS);
927+ sqlite3_close(db);
928+}
929+
930+/*
931+ * First keyword of the statement. The authorizer is the real gate; this check
932+ * only produces a friendlier error than "not authorized".
933+ */
934+static const char *first_keyword(const char *sql, char *out, size_t outsz)
935+{
936+ size_t i = 0;
937+ while (*sql && isspace((unsigned char)*sql)) sql++;
938+ while (*sql && (isalnum((unsigned char)*sql) || *sql == '_') && i + 1 < outsz)
939+ out[i++] = (char)tolower((unsigned char)*sql++);
940+ out[i] = '\0';
941+ return out;
942+}
943+
944+static int statement_allowed_shape(const char *kw)
945+{
946+ return strcmp(kw, "select") == 0 || strcmp(kw, "with") == 0 ||
947+ strcmp(kw, "pragma") == 0 || strcmp(kw, "explain") == 0 ||
948+ strcmp(kw, "values") == 0;
949+}
950+
951+static void action_query(const char *dbreq, const char *sql)
952+{
953+ char path[MAX_PATHQ];
954+ char errbuf[512];
955+ char kw[32];
956+ sqlite3 *db;
957+ sqlite3_stmt *st = NULL;
958+ sx_budget_t budget;
959+ int r, rc, ncols, nrows = 0, truncated = 0, i;
960+ char types[MAX_COLS][8];
961+ const char *tail = NULL;
962+ long long t0, t1;
963+
964+ if (!sql || !*sql) { json_error("missing_sql", "pass ?sql=SELECT ... or POST sql=..."); return; }
965+ if (strlen(sql) >= MAX_SQL) { json_error("sql_too_long", "statement exceeds the SQL length limit"); return; }
966+
967+ r = resolve_db_path(dbreq, path, sizeof path);
968+ if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; }
969+ if (r < 0) { json_error("not_found", "database file does not exist"); return; }
970+
971+ first_keyword(sql, kw, sizeof kw);
972+ if (!statement_allowed_shape(kw)) {
973+ json_error("read_only", "only SELECT / WITH / PRAGMA / EXPLAIN statements are accepted");
974+ return;
975+ }
976+
977+ db = open_ro(path, &rc);
978+ if (!db) {
979+ snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc));
980+ json_error("open_failed", errbuf);
981+ return;
982+ }
983+ if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; }
984+
985+ sqlite3_set_authorizer(db, authorizer_cb, NULL);
986+ budget.deadline_ms = now_ms() + STMT_BUDGET_MS;
987+ budget.aborted = 0;
988+ sqlite3_progress_handler(db, 20000, progress_cb, &budget);
989+
990+ t0 = now_ms();
991+ rc = sqlite3_prepare_v2(db, sql, -1, &st, &tail);
992+ if (rc != SQLITE_OK) {
993+ snprintf(errbuf, sizeof errbuf, "%s", sqlite3_errmsg(db));
994+ sqlite3_close(db);
995+ json_error("sql_error", errbuf);
996+ return;
997+ }
998+ /* Reject stacked statements: prepare() stops after the first one and the
999+ * tail would otherwise be silently dropped. */
1000+ while (tail && *tail && isspace((unsigned char)*tail)) tail++;
1001+ if (tail && *tail) {
1002+ sqlite3_finalize(st);
1003+ sqlite3_close(db);
1004+ json_error("multiple_statements", "submit one statement at a time");
1005+ return;
1006+ }
1007+
1008+ ncols = sqlite3_column_count(st);
1009+
1010+ json_header();
1011+ fputs("{\"ok\":true,\"action\":\"query\",\"readonly\":true,\"db\":", stdout);
1012+ json_str(path);
1013+ printf(",\"columns\":[");
1014+ for (i = 0; i < ncols; i++) {
1015+ const char *cn = sqlite3_column_name(st, i);
1016+ const char *dl = sqlite3_column_decltype(st, i);
1017+ if (i) fputc(',', stdout);
1018+ fputs("{\"name\":", stdout);
1019+ json_str(cn ? cn : "");
1020+ fputs(",\"decl\":", stdout);
1021+ json_str(dl ? dl : "");
1022+ fputc('}', stdout);
1023+ }
1024+ fputs("],\"rows\":[", stdout);
1025+
1026+ memset(types, 0, sizeof types);
1027+ while ((rc = sqlite3_step(st)) == SQLITE_ROW) {
1028+ if (nrows >= MAX_ROWS) { truncated = 1; break; }
1029+ if (nrows) fputc(',', stdout);
1030+ fputc('[', stdout);
1031+ for (i = 0; i < ncols; i++) {
1032+ if (i) fputc(',', stdout);
1033+ emit_value(st, i);
1034+ /* Column type is only meaningful while a row is positioned, so
1035+ * remember the first row's types for the summary block. */
1036+ if (nrows == 0 && i < MAX_COLS)
1037+ copy_str(types[i], sizeof types[i], value_type_name(st, i));
1038+ }
1039+ fputc(']', stdout);
1040+ nrows++;
1041+ }
1042+
1043+ if (rc == SQLITE_INTERRUPT || budget.aborted) {
1044+ /* Budget hit mid-scan: keep what we streamed and say so. */
1045+ truncated = 1;
1046+ } else if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
1047+ const char *m = sqlite3_errmsg(db);
1048+ fputs("],\"error\":", stdout);
1049+ json_str(m ? m : "statement failed");
1050+ printf(",\"aborted\":%s}\n", budget.aborted ? "true" : "false");
1051+ sqlite3_finalize(st);
1052+ sqlite3_close(db);
1053+ return;
1054+ }
1055+
1056+ t1 = now_ms();
1057+ printf("],\"row_count\":%d,\"truncated\":%s,\"limit\":%d,\"ms\":%lld,"
1058+ "\"aborted\":%s,\"types\":[",
1059+ nrows, truncated ? "true" : "false", MAX_ROWS, t1 - t0,
1060+ budget.aborted ? "true" : "false");
1061+ for (i = 0; i < ncols && nrows > 0 && i < MAX_COLS; i++) {
1062+ if (i) fputc(',', stdout);
1063+ json_str(types[i]);
1064+ }
1065+ fputs("]}\n", stdout);
1066+
1067+ sqlite3_finalize(st);
1068+ sqlite3_close(db);
1069+}
1070+
1071+static void action_info(void)
1072+{
1073+ char utc[40];
1074+ utc_now(utc, sizeof utc);
1075+
1076+ json_header();
1077+ fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\","
1078+ "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout);
1079+ json_str(platform_name());
1080+ fputs(",\"sqlite\":", stdout);
1081+ json_str(sqlite3_libversion());
1082+ printf(",\"pid\":%ld,\"utc\":", node_pid());
1083+ json_str(utc);
1084+ fputs(",\"node_auth\":", stdout);
1085+ {
1086+ const char *np = getenv("BOT_PASSWORD");
1087+ fputs((np && *np) ? "true" : "false", stdout);
1088+ }
1089+ fputs(",\"readonly\":true,\"zero_network\":true,\"threadsafe\":0,"
1090+ "\"load_extension\":false,"
1091+ "\"max_rows\":", stdout);
1092+ printf("%d", MAX_ROWS);
1093+ fputs(",\"budget_ms\":", stdout);
1094+ printf("%d", STMT_BUDGET_MS);
1095+ fputs(",\"allowed_roots\":[\"allowed\",\"workspace\",\"codebases\",\"home\"],"
1096+ "\"actions\":[\"dbs\",\"schema\",\"query\",\"info\"]}\n", stdout);
1097+}
1098+
1099+/* ------------------------------------------------------------------ */
1100+/* HTML UI */
1101+/* ------------------------------------------------------------------ */
1102+
1103+static int mode_html(int embed)
1104+{
1105+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1106+ "Cache-Control: no-store\r\n"
1107+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1108+
1109+ fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>"
1110+ "<meta name='viewport' content='width=device-width,initial-scale=1'>"
1111+ "<title>sqlite</title><style>", stdout);
1112+
1113+ fputs(
1114+":root{color-scheme:dark light;"
1115+ "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;"
1116+ "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;"
1117+ "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;"
1118+ "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}"
1119+"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;"
1120+ "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}"
1121+"*{box-sizing:border-box}"
1122+"body{margin:0;padding:16px;background:var(--bg);color:var(--text);"
1123+ "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;"
1124+ "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}"
1125+".wrap{max-width:1240px;margin:0 auto;min-width:0}"
1126+".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}"
1127+".title{font-size:20px;font-weight:700;margin:0}"
1128+".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow-wrap:anywhere}"
1129+".spacer{flex:1}"
1130+".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;"
1131+ "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}"
1132+".pill.ro{color:var(--ok);border-color:rgba(48,209,88,.4)}"
1133+".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1134+ "padding:16px;margin-bottom:14px;min-width:0}"
1135+".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;"
1136+ "text-transform:uppercase;color:var(--muted);font-weight:600}"
1137+"button{background:var(--accent);color:#fff;border:0;border-radius:999px;"
1138+ "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}"
1139+"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}"
1140+"button:active{transform:scale(.98)}"
1141+"button:disabled{opacity:.5;cursor:default}"
1142+"select,input,textarea{background:var(--surface2);color:var(--text);"
1143+ "border:1px solid var(--line);border-radius:9px;padding:8px 10px;"
1144+ "font-family:var(--mono);font-size:13px;width:100%}"
1145+"textarea{min-height:104px;resize:vertical;line-height:1.5}"
1146+"select{font-family:inherit}"
1147+".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}"
1148+".layout{display:grid;grid-template-columns:250px minmax(0,1fr);gap:14px;align-items:start}"
1149+"@media(max-width:860px){.layout{grid-template-columns:minmax(0,1fr)}}"
1150+".side{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1151+ "padding:12px;min-width:0}"
1152+".side h3{margin:0 0 8px;font-size:11px;letter-spacing:.06em;text-transform:uppercase;"
1153+ "color:var(--muted);font-weight:600}"
1154+".titem{display:block;width:100%;text-align:left;background:transparent;color:var(--text);"
1155+ "border:0;border-radius:8px;padding:6px 8px;font-size:12px;font-family:var(--mono);"
1156+ "cursor:pointer;overflow-wrap:anywhere}"
1157+".titem:hover{background:var(--surface2)}"
1158+".titem.on{background:var(--surface2);font-weight:700;color:var(--accent)}"
1159+".titem .n{color:var(--muted);font-weight:400}"
1160+".tblwrap{overflow:auto;max-height:60vh;border:1px solid var(--line);border-radius:10px}"
1161+"table{width:100%;border-collapse:collapse;font-size:12.5px;font-family:var(--mono)}"
1162+"th,td{text-align:left;padding:6px 9px;border-bottom:1px solid var(--line);"
1163+ "white-space:nowrap;max-width:340px;overflow:hidden;text-overflow:ellipsis}"
1164+"th{position:sticky;top:0;background:var(--surface2);cursor:pointer;"
1165+ "font-weight:700;user-select:none;z-index:1}"
1166+"th .dir{color:var(--accent);font-size:10px}"
1167+"td.null{color:var(--muted);font-style:italic}"
1168+"td.num{text-align:right}"
1169+"tbody tr:hover{background:var(--surface2)}"
1170+".empty{color:var(--muted);padding:14px 0;font-size:13px}"
1171+".err{color:var(--danger);font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}"
1172+".cols{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}"
1173+".chip{font-size:11px;font-family:var(--mono);color:var(--muted);"
1174+ "background:var(--surface2);border:1px solid var(--line);border-radius:7px;padding:2px 7px}"
1175+".hint{color:var(--muted);font-size:11.5px;margin-top:6px}"
1176+"kbd{font-family:var(--mono);font-size:11px;background:var(--surface2);"
1177+ "border:1px solid var(--line);border-radius:5px;padding:1px 5px}"
1178+"</style></head><body>", stdout);
1179+
1180+ fputs("<div class='wrap'>", stdout);
1181+
1182+ if (!embed) {
1183+ fputs("<div style='margin-bottom:12px'><a href='/' "
1184+ "style='color:var(--accent);text-decoration:none;font-weight:600'>"
1185+ "&larr; Back to Bot</a></div>", stdout);
1186+ }
1187+
1188+ fputs("<div class='top'><h2 class='title'>sqlite</h2>"
1189+ "<span class='pill ro'>read-only</span>"
1190+ "<span class='pill' id='dbcount'>&mdash;</span>"
1191+ "<span class='spacer'></span>"
1192+ "<button class='ghost' id='themebtn' type='button'>Theme</button>"
1193+ "</div>", stdout);
1194+
1195+ fputs("<div class='card'><h2>Database</h2>"
1196+ "<div class='row'><div style='flex:1 1 320px;min-width:0'>"
1197+ "<select id='dbsel'><option value=''>Loading databases...</option></select></div>"
1198+ "<button class='ghost' id='reloadbtn' type='button'>Rescan</button></div>"
1199+ "<div class='hint' id='dbhint'>Only .db / .sqlite / .sqlite3 files under the "
1200+ "allowlisted roots are listed.</div></div>", stdout);
1201+
1202+ fputs("<div class='layout'><div class='side'><h3>Tables</h3>"
1203+ "<div id='tables'><div class='empty'>Select a database.</div></div></div>", stdout);
1204+
1205+ fputs("<div style='min-width:0'><div class='card'><h2>SQL</h2>"
1206+ "<textarea id='sql' spellcheck='false'>SELECT name, type FROM sqlite_master LIMIT 50;</textarea>"
1207+ "<div class='row' style='margin-top:8px'>"
1208+ "<button id='runbtn' type='button'>Run</button>"
1209+ "<button class='ghost' id='csvbtn' type='button'>Copy CSV</button>"
1210+ "<button class='ghost' id='jsonbtn' type='button'>Copy JSON</button>"
1211+ "<span class='spacer'></span>"
1212+ "<span class='hint'><kbd>Ctrl</kbd>+<kbd>Enter</kbd> to run</span>"
1213+ "</div><div class='hint' id='qmeta'></div></div>", stdout);
1214+
1215+ fputs("<div class='card'><h2>Results</h2>"
1216+ "<div class='cols' id='cols'></div>"
1217+ "<div class='tblwrap' id='reswrap' style='margin-top:10px'>"
1218+ "<div class='empty'>No results yet.</div></div></div></div></div>", stdout);
1219+
1220+ fputs("<div class='card' id='infocard' style='display:none'><h2>Info</h2>"
1221+ "<div class='cols' id='info'></div></div></div>", stdout);
1222+
1223+ /* ---------------- client ---------------- */
1224+ fputs("<script>\n"
1225+"var Q = new URLSearchParams(location.search);\n"
1226+"var node = Q.get('node') || '';\n"
1227+"var sid = Q.get('id') || '';\n"
1228+"var HUB = Q.get('plugin') || '';\n"
1229+"var pwd = Q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) || localStorage.getItem('bot_active_pwd') || '';\n"
1230+"var currentDb = '';\n"
1231+"var lastData = null;\n"
1232+"\n"
1233+"function $(id){ return document.getElementById(id); }\n"
1234+"function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null) ? '' : v; }\n"
1235+"\n"
1236+"/* Two routes, and getting this wrong is the classic plugin bug:\n"
1237+" - served through the hub (bot.scorpiox.net/plugins?plugin=...&node=...)\n"
1238+" -> call the hub proxy back with /plugins?plugin=<id>&action=...\n"
1239+" - opened directly on the node -> the plugin IS the route: /plugin_sqlite?action=... */\n"
1240+"function apiUrl(action, extra){\n"
1241+" var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB)\n"
1242+" : '/plugin_sqlite?') +\n"
1243+" (HUB ? '&' : '') + 'action=' + encodeURIComponent(action);\n"
1244+" if (extra) u += '&' + extra;\n"
1245+" if (node) u += '&node=' + encodeURIComponent(node);\n"
1246+" if (sid) u += '&id=' + encodeURIComponent(sid);\n"
1247+" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n"
1248+" return u;\n"
1249+"}\n"
1250+"function api(action, extra){\n"
1251+" return fetch(apiUrl(action, extra), {headers: pwd ? {'X-Bot-Password': pwd} : {}})\n"
1252+" .then(function(r){ return r.json(); });\n"
1253+"}\n"
1254+"function apiPost(action, extra, body){\n"
1255+" return fetch(apiUrl(action, extra), {\n"
1256+" method: 'POST',\n"
1257+" headers: pwd ? {'X-Bot-Password': pwd, 'Content-Type': 'application/x-www-form-urlencoded'} : {'Content-Type': 'application/x-www-form-urlencoded'},\n"
1258+" body: body\n"
1259+" }).then(function(r){ return r.json(); });\n"
1260+"}\n"
1261+"\n"
1262+"function el(tag, c, t){\n"
1263+" var e = document.createElement(tag);\n"
1264+" if (c) e.className = c;\n"
1265+" if (t !== undefined) e.textContent = t;\n"
1266+" return e;\n"
1267+"}\n"
1268+"function bytes(n){\n"
1269+" if (n === null || n === undefined) return '\\u2014';\n"
1270+" var u = ['B','KB','MB','GB','TB'], i = 0, v = n;\n"
1271+" while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }\n"
1272+" return (i === 0 ? v.toFixed(0) : v.toFixed(v >= 100 ? 0 : 1)) + ' ' + u[i];\n"
1273+"}\n"
1274+"function err(msg){ var w = $('reswrap'); w.textContent = ''; w.appendChild(el('div','err', msg)); }\n"
1275+"\n"
1276+"/* ---- databases ---- */\n"
1277+"function loadDbs(){\n"
1278+" api('dbs').then(function(d){\n"
1279+" var sel = $('dbsel');\n"
1280+" sel.textContent = '';\n"
1281+" if (!d.ok) { err(d.error || 'failed to list databases'); return; }\n"
1282+" var list = d.dbs || [];\n"
1283+" txt('dbcount', list.length + (list.length === 1 ? ' database' : ' databases'));\n"
1284+" if (!list.length) {\n"
1285+" var o = el('option', null, 'No .db / .sqlite files found');\n"
1286+" o.value = ''; sel.appendChild(o);\n"
1287+" $('tables').textContent = '';\n"
1288+" $('tables').appendChild(el('div','empty','No database selected.'));\n"
1289+" return;\n"
1290+" }\n"
1291+" var ph = el('option', null, 'Choose a database (' + list.length + ')');\n"
1292+" ph.value = ''; sel.appendChild(ph);\n"
1293+" list.forEach(function(x){\n"
1294+" var o = el('option', null, x.path + ' \\u00b7 ' + bytes(x.bytes));\n"
1295+" o.value = x.path;\n"
1296+" sel.appendChild(o);\n"
1297+" });\n"
1298+" if (currentDb) sel.value = currentDb;\n"
1299+" if (!sel.value && list.length === 1) { sel.value = list[0].path; selectDb(list[0].path); }\n"
1300+" }).catch(function(e){ err('Error: ' + e); });\n"
1301+"}\n"
1302+"\n"
1303+"function selectDb(path){\n"
1304+" currentDb = path;\n"
1305+" var box = $('tables');\n"
1306+" box.textContent = '';\n"
1307+" if (!path) { box.appendChild(el('div','empty','Select a database.')); return; }\n"
1308+" box.appendChild(el('div','empty','Loading schema...'));\n"
1309+" api('schema', 'db=' + encodeURIComponent(path)).then(function(d){\n"
1310+" box.textContent = '';\n"
1311+" if (!d.ok) { box.appendChild(el('div','err', d.error + (d.detail ? ': ' + d.detail : ''))); return; }\n"
1312+" var list = d.tables || [];\n"
1313+" txt('dbhint', path + ' \\u00b7 ' + list.length + ' table' + (list.length === 1 ? '' : 's') + ' \\u00b7 read-only');\n"
1314+" if (!list.length) { box.appendChild(el('div','empty','No tables.')); return; }\n"
1315+" list.forEach(function(t){\n"
1316+" var b = el('button','titem');\n"
1317+" b.type = 'button';\n"
1318+" b.appendChild(document.createTextNode(t.name));\n"
1319+" var n = el('span','n', ' ' + (t.rows === null || t.rows === undefined ? '?' : t.rows)\n"
1320+" + (t.type === 'view' ? ' view' : ''));\n"
1321+" b.appendChild(n);\n"
1322+" b.title = (t.columns || []).map(function(c){ return c.name + ' ' + (c.type || ''); }).join('\\n');\n"
1323+" b.onclick = function(){\n"
1324+" Array.prototype.forEach.call(box.children, function(x){ x.classList.remove('on'); });\n"
1325+" b.classList.add('on');\n"
1326+" var q = 'SELECT * FROM \"' + String(t.name).replace(/\\\"/g, '\\\"\\\"') + '\" LIMIT 100;';\n"
1327+" $('sql').value = q;\n"
1328+" runQuery();\n"
1329+" };\n"
1330+" box.appendChild(b);\n"
1331+" });\n"
1332+" }).catch(function(e){ box.textContent = ''; box.appendChild(el('div','err','Error: ' + e)); });\n"
1333+"}\n"
1334+"\n"
1335+"/* ---- query ---- */\n"
1336+"function clearSorted(){ sortCol = -1; sortDir = 1; }\n"
1337+"var sortCol = -1, sortDir = 1;\n"
1338+"\n"
1339+"function runQuery(){\n"
1340+" var sql = $('sql').value;\n"
1341+" if (!currentDb) { err('Select a database first.'); return; }\n"
1342+" if (!sql.trim()) { err('Type a statement.'); return; }\n"
1343+" $('runbtn').disabled = true;\n"
1344+" txt('qmeta','Running...');\n"
1345+" clearSorted();\n"
1346+" apiPost('query', 'db=' + encodeURIComponent(currentDb),\n"
1347+" 'sql=' + encodeURIComponent(sql)).then(function(d){\n"
1348+" $('runbtn').disabled = false;\n"
1349+" lastData = d;\n"
1350+" if (!d.ok) { txt('qmeta',''); err((d.error || 'error') + (d.detail ? ': ' + d.detail : '')); $('cols').textContent=''; return; }\n"
1351+" if (d.error) { txt('qmeta',''); err(d.error); $('cols').textContent=''; return; }\n"
1352+" txt('qmeta', d.row_count + ' row' + (d.row_count === 1 ? '' : 's')\n"
1353+" + (d.truncated ? ' (truncated)' : '') + ' \\u00b7 ' + d.ms + ' ms'\n"
1354+" + (d.aborted ? ' \\u00b7 stopped at the time budget' : ''));\n"
1355+" renderTable(d);\n"
1356+" }).catch(function(e){\n"
1357+" $('runbtn').disabled = false;\n"
1358+" txt('qmeta',''); err('Request failed: ' + e);\n"
1359+" });\n"
1360+"}\n"
1361+"\n"
1362+"function renderTable(d){\n"
1363+" var wrap = $('reswrap');\n"
1364+" wrap.textContent = '';\n"
1365+" $('cols').textContent = '';\n"
1366+" var cols = d.columns || [], rows = d.rows || [];\n"
1367+" cols.forEach(function(c){\n"
1368+" $('cols').appendChild(el('span','chip', c.name + ' ' + (c.decl || '')));\n"
1369+" });\n"
1370+" if (!rows.length) { wrap.appendChild(el('div','empty','0 rows.')); return; }\n"
1371+" drawGrid(wrap, cols, rows);\n"
1372+"}\n"
1373+"\n"
1374+"function cellValue(v){\n"
1375+" if (v === null || v === undefined) return {t: 'NULL', cls: 'null'};\n"
1376+" if (typeof v === 'object') return {t: '[blob ' + v.blob_bytes + ']', cls: 'null'};\n"
1377+" if (typeof v === 'number') return {t: String(v), cls: 'num'};\n"
1378+" return {t: String(v), cls: ''};\n"
1379+"}\n"
1380+"\n"
1381+"function drawGrid(wrap, cols, rows){\n"
1382+" var tbl = el('table');\n"
1383+" var thead = el('thead'), tr = el('tr');\n"
1384+" cols.forEach(function(c, i){\n"
1385+" var th = el('th');\n"
1386+" th.appendChild(document.createTextNode(c.name));\n"
1387+" if (sortCol === i) {\n"
1388+" var dir = el('span','dir', sortDir > 0 ? ' \\u25b2' : ' \\u25bc');\n"
1389+" th.appendChild(dir);\n"
1390+" }\n"
1391+" th.title = c.decl || '';\n"
1392+" th.onclick = function(){\n"
1393+" if (sortCol === i) sortDir = -sortDir; else { sortCol = i; sortDir = 1; }\n"
1394+" var sorted = rows.slice().sort(function(a, b){\n"
1395+" var x = a[i], y = b[i];\n"
1396+" if (x === null || x === undefined) return 1;\n"
1397+" if (y === null || y === undefined) return -1;\n"
1398+" if (typeof x === 'number' && typeof y === 'number') return (x - y) * sortDir;\n"
1399+" return String(x).localeCompare(String(y)) * sortDir;\n"
1400+" });\n"
1401+" wrap.textContent = '';\n"
1402+" drawGrid(wrap, cols, sorted);\n"
1403+" };\n"
1404+" tr.appendChild(th);\n"
1405+" });\n"
1406+" thead.appendChild(tr);\n"
1407+" tbl.appendChild(thead);\n"
1408+" var tbody = el('tbody');\n"
1409+" rows.forEach(function(r){\n"
1410+" var row = el('tr');\n"
1411+" cols.forEach(function(c, i){\n"
1412+" var cv = cellValue(r[i]);\n"
1413+" var td = el('td', cv.cls, cv.t);\n"
1414+" td.title = cv.t;\n"
1415+" row.appendChild(td);\n"
1416+" });\n"
1417+" tbody.appendChild(row);\n"
1418+" });\n"
1419+" tbl.appendChild(tbody);\n"
1420+" wrap.appendChild(tbl);\n"
1421+"}\n"
1422+"\n"
1423+"/* ---- export ---- */\n"
1424+"function toCsv(d){\n"
1425+" var cols = (d.columns || []).map(function(c){ return c.name; });\n"
1426+" function q(v){\n"
1427+" if (v === null || v === undefined) return '';\n"
1428+" if (typeof v === 'object') return 'blob:' + v.blob_bytes;\n"
1429+" var s = String(v);\n"
1430+" return /[\",\\n\\r]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n"
1431+" }\n"
1432+" var out = [cols.map(q).join(',')];\n"
1433+" (d.rows || []).forEach(function(r){ out.push(r.map(q).join(',')); });\n"
1434+" return out.join('\\n');\n"
1435+"}\n"
1436+"function copy(text, label){\n"
1437+" var done = function(){ txt('qmeta', label + ' copied'); };\n"
1438+" if (navigator.clipboard && navigator.clipboard.writeText) {\n"
1439+" navigator.clipboard.writeText(text).then(done, function(){\n"
1440+" var ta = el('textarea'); ta.value = text; document.body.appendChild(ta);\n"
1441+" ta.select(); document.execCommand('copy'); document.body.removeChild(ta); done();\n"
1442+" });\n"
1443+" } else {\n"
1444+" var ta = el('textarea'); ta.value = text; document.body.appendChild(ta);\n"
1445+" ta.select(); document.execCommand('copy'); document.body.removeChild(ta); done();\n"
1446+" }\n"
1447+"}\n"
1448+"\n"
1449+"/* ---- theme ---- */\n"
1450+"function applyTheme(t){\n"
1451+" document.documentElement.setAttribute('data-theme', t);\n"
1452+" try { localStorage.setItem('sqlite_theme', t); } catch (e) {}\n"
1453+"}\n"
1454+"var savedTheme = null;\n"
1455+"try { savedTheme = localStorage.getItem('sqlite_theme'); } catch (e) {}\n"
1456+"applyTheme(savedTheme || (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));\n"
1457+"$('themebtn').onclick = function(){\n"
1458+" applyTheme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light');\n"
1459+"};\n"
1460+"\n"
1461+"/* ---- wiring ---- */\n"
1462+"$('dbsel').onchange = function(){ selectDb(this.value); };\n"
1463+"$('reloadbtn').onclick = function(){ loadDbs(); if (currentDb) selectDb(currentDb); };\n"
1464+"$('runbtn').onclick = runQuery;\n"
1465+"$('sql').addEventListener('keydown', function(e){\n"
1466+" if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); runQuery(); }\n"
1467+"});\n"
1468+"$('csvbtn').onclick = function(){ if (!lastData || !lastData.ok) { txt('qmeta','nothing to copy'); return; } copy(toCsv(lastData), 'CSV'); };\n"
1469+"$('jsonbtn').onclick = function(){ if (!lastData || !lastData.ok) { txt('qmeta','nothing to copy'); return; } copy(JSON.stringify(lastData.rows, null, 0), 'JSON'); };\n"
1470+"\n"
1471+"loadDbs();\n"
1472+"api('info').then(function(d){\n"
1473+" if (!d.ok) return;\n"
1474+" var box = $('info');\n"
1475+" $('infocard').style.display = '';\n"
1476+" [['plugin', d.plugin], ['version', d.version], ['sqlite', d.sqlite],\n"
1477+" ['platform', d.platform], ['max rows', d.max_rows], ['budget ms', d.budget_ms]].forEach(function(kv){\n"
1478+" box.appendChild(el('span','chip', kv[0] + ' ' + kv[1]));\n"
1479+" });\n"
1480+"}).catch(function(){});\n"
1481+"</script></body></html>\n", stdout);
1482+
1483+ return 0;
1484+}
1485+
1486+/* ------------------------------------------------------------------ */
1487+/* Main */
1488+/* ------------------------------------------------------------------ */
1489+
1490+int main(int argc, char **argv)
1491+{
1492+ const char *qs;
1493+ char action[64], db[512], sqlbuf[MAX_SQL], format[16];
1494+ int want_json = 0, embed = 0;
1495+
1496+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1497+ puts("{\"name\":\"sqlite\",\"desc\":\"SQLite viewer\"}");
1498+ return 0;
1499+ }
1500+ if (argc > 1 && strcmp(argv[1], "--version") == 0) {
1501+ printf("%s %s (sqlite %s)\n", PLUGIN_ID, PLUGIN_VER, sqlite3_libversion());
1502+ return 0;
1503+ }
1504+ if (argc > 1 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) {
1505+ fputs("usage: " PLUGIN_ID " [--meta|--version|--help]\n"
1506+ "\n"
1507+ "Run as a CGI-style executable. Modes:\n"
1508+ " --meta / SX_PLUGIN_META=1 discovery JSON\n"
1509+ " ?action=dbs list databases under the allowed roots\n"
1510+ " ?action=schema&db=<path> tables, columns, indexes, row counts\n"
1511+ " ?action=query&db=<path>&sql=<SELECT> bounded read-only query (GET or POST sql=)\n"
1512+ " ?action=info plugin build and limits\n"
1513+ " GET (default) HTML explorer (honours ?embed=1)\n"
1514+ "\n"
1515+ "Read-only: the authorizer allows SELECT/READ/FUNCTION/read-only PRAGMA only and\n"
1516+ "every database is opened with SQLITE_OPEN_READONLY. Rows are capped at 500.\n",
1517+ stdout);
1518+ return 0;
1519+ }
1520+
1521+ require_node_auth();
1522+
1523+ qs = getenv("QUERY_STRING");
1524+ if (!qs) qs = "";
1525+
1526+ action[0] = db[0] = sqlbuf[0] = format[0] = '\0';
1527+ get_query_val(qs, "action", action, sizeof action);
1528+ get_query_val(qs, "db", db, sizeof db);
1529+ get_query_val(qs, "sql", sqlbuf, sizeof sqlbuf);
1530+ get_query_val(qs, "format", format, sizeof format);
1531+
1532+ if (strstr(qs, "embed=1") || strstr(qs, "embed=true")) embed = 1;
1533+ if (ci_prefix(format, "json")) want_json = 1;
1534+
1535+ /* POST bodies arrive through the server's body file; read a plain
1536+ * urlencoded body and pull "sql" out of it. */
1537+ if (!sqlbuf[0]) {
1538+ const char *bodyfile = getenv("HTTP_BODY_FILE");
1539+ if (bodyfile && *bodyfile) {
1540+ FILE *f = fopen(bodyfile, "rb");
1541+ if (f) {
1542+ char body[MAX_SQL + 1024];
1543+ size_t n = fread(body, 1, sizeof(body) - 1, f);
1544+ body[n] = '\0';
1545+ fclose(f);
1546+ get_query_val(body, "sql", sqlbuf, sizeof sqlbuf);
1547+ if (!sqlbuf[0]) {
1548+ /* Some callers post the statement bare. */
1549+ copy_str(sqlbuf, sizeof sqlbuf, body);
1550+ }
1551+ }
1552+ }
1553+ }
1554+
1555+ if (!action[0] && want_json) copy_str(action, sizeof action, "dbs");
1556+
1557+ if (action[0]) {
1558+ if (strcmp(action, "dbs") == 0) { action_dbs(); return 0; }
1559+ if (strcmp(action, "schema") == 0) { action_schema(db); return 0; }
1560+ if (strcmp(action, "query") == 0) { action_query(db, sqlbuf); return 0; }
1561+ if (strcmp(action, "info") == 0) { action_info(); return 0; }
1562+ json_error("unknown_action", "supported actions: dbs, schema, query, info");
1563+ return 0;
1564+ }
1565+
1566+ mode_html(embed);
1567+ return 0;
1568+}
tests/run.sh+427−0■■■■■
11new file mode 100755
index 0000000..13c8788
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,427 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_sqlite across all 3 modes.
3+#
4+# Builds a throwaway SQLite database in a temp directory, points the plugin at
5+# it with SQLITE_ALLOWED_ROOT, and proves:
6+# * discovery, schema and query all answer with well-formed JSON
7+# * the read-only contract holds (INSERT/UPDATE/DELETE/DROP/ALTER/ATTACH/
8+# CREATE are refused, both by the statement guard and by the authorizer)
9+# * path traversal, system paths and SQLite URI filenames are refused
10+# * the row cap and the statement time budget actually bite
11+# * node auth (401 / X-Bot-Password / Bearer / ?pwd=) behaves
12+# * the musl static build and the Windows PE are the right kind of file
13+# * the whole git history carries no secret and no LAN IP
14+#
15+# If musl / arm64 / Win64 artifacts are present they are checked too.
16+# Exit code 0 = everything passed.
17+
18+set -u
19+
20+ROOT=$(cd "$(dirname "$0")/.." && pwd)
21+cd "$ROOT" || exit 1
22+
23+BIN=./plugin_sqlite
24+PASS=0
25+FAIL=0
26+
27+if [ -t 1 ]; then
28+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
29+else
30+ C_OK=; C_BAD=; C_B=; C_0=
31+fi
32+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
33+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
34+
35+check() { # check <desc> <expected-substring> <actual>
36+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
37+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)"
38+ fi
39+}
40+
41+check_not() { # check_not <desc> <forbidden-substring> <actual>
42+ if printf '%s' "$3" | grep -F -q -- "$2"; then
43+ fail "$1 (must NOT contain: $2)"; else pass "$1"
44+ fi
45+}
46+
47+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
48+
49+# Strip the CGI header block, leaving the body.
50+body() { printf '%s' "$1" | sed '1,/^\r$/d'; }
51+
52+[ -x "$BIN" ] || { printf '%smissing %s - run make first%s\n' "$C_BAD" "$BIN" "$C_0" >&2; exit 1; }
53+
54+TMP=$(mktemp -d 2>/dev/null || echo "/tmp/plugin_sqlite_test.$$")
55+mkdir -p "$TMP"
56+trap 'rm -rf "$TMP"' EXIT 2>/dev/null || true
57+
58+# Export so every invocation below sees a narrow, predictable allowlist.
59+SQLITE_ALLOWED_ROOT="$TMP"; export SQLITE_ALLOWED_ROOT
60+
61+# ---------------------------------------------------------------- fixture
62+section "fixture"
63+if ! command -v python3 >/dev/null 2>&1; then
64+ printf '%sFAIL%s python3 is required to build the test database\n' "$C_BAD" "$C_0" >&2
65+ exit 1
66+fi
67+
68+python3 - "$TMP" <<'PY' || exit 1
69+import sqlite3, sys, os
70+tmp = sys.argv[1]
71+db = os.path.join(tmp, "shop.sqlite")
72+if os.path.exists(db):
73+ os.remove(db)
74+c = sqlite3.connect(db)
75+c.executescript("""
76+CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
77+CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id),
78+ total REAL, note BLOB, created TEXT);
79+CREATE INDEX idx_orders_cust ON orders(customer_id);
80+CREATE VIEW big_orders AS SELECT * FROM orders WHERE total > 100;
81+INSERT INTO customers(name,email) VALUES ('Ada','ada@example.com'),('Bo',NULL);
82+""")
83+for i in range(1200):
84+ c.execute("INSERT INTO orders(customer_id,total,note,created) VALUES(?,?,?,?)",
85+ (1 + (i % 2), (i % 500) + 0.5, b"\x01\x02", "2026-03-%02d" % (i % 28 + 1)))
86+c.commit()
87+c.close()
88+open(os.path.join(tmp, "notes.txt"), "w").write("not a database\n")
89+open(os.path.join(tmp, "fake.db"), "w").write("this is definitely not sqlite\n")
90+print(" fixture: %s (%d bytes)" % (db, os.path.getsize(db)))
91+PY
92+[ -f "$TMP/shop.sqlite" ] && pass "test database created" || { fail "test database missing"; exit 1; }
93+
94+DB="$TMP/shop.sqlite"
95+
96+# ---------------------------------------------------------------- mode 1
97+section "mode 1 --meta"
98+META=$("$BIN" --meta)
99+check "meta emits name sqlite" '"name":"sqlite"' "$META"
100+check "meta emits desc SQLite viewer" '"desc":"SQLite viewer"' "$META"
101+METAENV=$(SX_PLUGIN_META=1 "$BIN")
102+check "SX_PLUGIN_META=1 yields same meta" '"name":"sqlite"' "$METAENV"
103+LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
104+[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
105+printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
106+ && pass "meta is valid JSON" || fail "meta is not valid JSON"
107+DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
108+[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
109+NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
110+[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
111+check "--version prints version" '1.0.0' "$("$BIN" --version)"
112+check "--version names the sqlite lib" 'sqlite 3.' "$("$BIN" --version)"
113+check "--help is available" 'usage:' "$("$BIN" --help)"
114+META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
115+check "meta still works when BOT_PASSWORD is set" '"name":"sqlite"' "$META_AUTH"
116+
117+# ---------------------------------------------------------------- auth
118+section "node auth"
119+AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
120+check "no credentials -> 401" 'Status: 401' "$AUTHNONE"
121+check "401 body is json" 'invalid node password' "$AUTHNONE"
122+AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
123+check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")"
124+AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=info' "$BIN")
125+check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")"
126+AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=info&pwd=testpw' "$BIN")
127+check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")"
128+AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=info' "$BIN")
129+check "wrong password -> 401" 'Status: 401' "$AUTHBAD"
130+HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
131+check "html mode is also gated" 'Status: 401' "$HTMLAUTH"
132+
133+# ---------------------------------------------------------------- dbs
134+section "mode 2 action=dbs"
135+DBS=$(body "$(QUERY_STRING='action=dbs' "$BIN")")
136+printf '%s' "$DBS" > "$TMP/dbs.json"
137+check "dbs ok:true" '"ok":true' "$DBS"
138+check "dbs names the plugin" '"plugin":"plugin_sqlite"' "$DBS"
139+check "dbs declares read-only" '"readonly":true' "$DBS"
140+check "dbs carries the allowed root" "$TMP" "$DBS"
141+check "dbs finds our database" 'shop.sqlite' "$DBS"
142+check "dbs reports a count" '"count":' "$DBS"
143+printf '%s' "$DBS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
144+ && pass "dbs body is valid JSON" || fail "dbs body JSON invalid"
145+python3 - "$TMP/dbs.json" <<'PYEOF' && pass "dbs rows are well formed" || fail "dbs rows malformed"
146+import json, sys
147+d = json.load(open(sys.argv[1]))
148+assert d["ok"] is True
149+assert d["count"] == len(d["dbs"])
150+assert d["count"] >= 1
151+names = [x["path"] for x in d["dbs"]]
152+assert any(p.endswith("shop.sqlite") for p in names), names
153+assert not any(p.endswith("notes.txt") for p in names), names
154+for x in d["dbs"]:
155+ assert x["bytes"] > 0
156+ assert x["root"]
157+ assert x["mtime"].endswith("Z")
158+PYEOF
159+check_not "dbs ignores non-db files" 'notes.txt' "$DBS"
160+
161+# ---------------------------------------------------------------- schema
162+section "mode 2 action=schema"
163+SCHEMA=$(body "$(QUERY_STRING="action=schema&db=$DB" "$BIN")")
164+printf '%s' "$SCHEMA" > "$TMP/schema.json"
165+check "schema ok:true" '"ok":true' "$SCHEMA"
166+check "schema names the database" "$DB" "$SCHEMA"
167+check "schema lists customers" '"name":"customers"' "$SCHEMA"
168+check "schema lists orders" '"name":"orders"' "$SCHEMA"
169+check "schema marks the view" '"type":"view"' "$SCHEMA"
170+check "schema reports the index" 'idx_orders_cust' "$SCHEMA"
171+check "schema has column detail" '"notnull":true' "$SCHEMA"
172+python3 - "$TMP/schema.json" <<'PYEOF' && pass "schema rows are well formed" || fail "schema malformed"
173+import json, sys
174+d = json.load(open(sys.argv[1]))
175+assert d["ok"] is True and d["readonly"] is True
176+tables = {t["name"]: t for t in d["tables"]}
177+assert "customers" in tables and "orders" in tables and "big_orders" in tables
178+assert tables["orders"]["rows"] == 1200, tables["orders"]["rows"]
179+assert tables["customers"]["rows"] == 2
180+cols = {c["name"]: c for c in tables["orders"]["columns"]}
181+assert cols["customer_id"]["type"] == "INTEGER"
182+assert [i["name"] for i in tables["orders"]["indexes"]] == ["idx_orders_cust"]
183+assert tables["customers"]["type"] == "table"
184+assert tables["big_orders"]["type"] == "view"
185+PYEOF
186+SCHEMA_MISS=$(body "$(QUERY_STRING="action=schema&db=$TMP/nope.sqlite" "$BIN")")
187+SCHEMA_FAKE=$(body "$(QUERY_STRING="action=schema&db=$TMP/fake.db" "$BIN")")
188+check "non-sqlite file -> not_a_database" 'not_a_database' "$SCHEMA_FAKE"
189+
190+# ---------------------------------------------------------------- query
191+section "mode 2 action=query (allowed)"
192+Q1=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
193+check "count(*) works" '[[1200]]' "$Q1"
194+check "query reports row_count" '"row_count":1' "$Q1"
195+check "query reports elapsed ms" '"ms":' "$Q1"
196+check "query reports column types" '"types":["int"]' "$Q1"
197+
198+Q2=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+name,email+from+customers+order+by+id" "$BIN")")
199+check "text values are quoted" '"Ada"' "$Q2"
200+check "NULL becomes json null" 'null' "$Q2"
201+
202+Q3=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+total,note+from+orders+limit+1" "$BIN")")
203+check "real numbers are emitted" '"total"' "$Q3"
204+check "blobs become a hex preview" '"blob_bytes":2' "$Q3"
205+check "blob hex is the real bytes" '"hex":"0102"' "$Q3"
206+
207+Q4=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+table_info(orders)" "$BIN")")
208+check "read-only pragma runs" '"customer_id"' "$Q4"
209+
210+Q5=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+integrity_check" "$BIN")")
211+check "integrity_check runs" '"ok"' "$Q5"
212+
213+Q6=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+o+AS+(SELECT+id+FROM+orders)+SELECT+count(*)+FROM+o" "$BIN")")
214+check "WITH / CTE select works" '[[1200]]' "$Q6"
215+
216+Q7=$(body "$(QUERY_STRING="action=query&db=$DB&sql=explain+select+1" "$BIN")")
217+check "EXPLAIN works" '"ok":true' "$Q7"
218+
219+# POST-style body parsing
220+printf 'sql=select+42+as+answer' > "$TMP/body.txt"
221+Q8=$(body "$(HTTP_BODY_FILE="$TMP/body.txt" QUERY_STRING="action=query&db=$DB" "$BIN")")
222+check "POST body sql= is parsed" '[[42]]' "$Q8"
223+
224+# ---------------------------------------------------------------- row cap
225+section "row cap and time budget"
226+CAP=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+*+from+orders" "$BIN")")
227+check "unbounded select is capped" '"row_count":500' "$CAP"
228+check "cap is flagged as truncated" '"truncated":true' "$CAP"
229+check "cap declares the limit" '"limit":500' "$CAP"
230+printf '%s' "$CAP" | python3 -c '
231+import json,sys
232+d = json.load(sys.stdin)
233+assert len(d["rows"]) == 500, len(d["rows"])
234+assert d["row_count"] == 500
235+' 2>/dev/null && pass "exactly 500 rows were streamed" || fail "row cap did not produce 500 rows"
236+
237+BUDGET=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+RECURSIVE+c(i)+AS(SELECT+1+UNION+ALL+SELECT+i%2B1+FROM+c+WHERE+i%3C30000000)+SELECT+count(*)+FROM+c" "$BIN")")
238+check "runaway recursion is stopped" '"aborted":true' "$BUDGET"
239+
240+# ---------------------------------------------------------------- read-only
241+section "read-only enforcement"
242+deny() { # deny <desc> <sql>
243+ local out
244+ out=$(body "$(QUERY_STRING="action=query&db=$DB&sql=$2" "$BIN")")
245+ case "$out" in
246+ *'"ok":false'*) pass "$1 rejected" ;;
247+ *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
248+ esac
249+}
250+deny "INSERT" "insert+into+customers(name)+values('x')"
251+deny "UPDATE" "update+customers+set+name='x'"
252+deny "DELETE" "delete+from+customers"
253+deny "DROP TABLE" "drop+table+orders"
254+deny "ALTER TABLE" "alter+table+orders+add+column+x+int"
255+deny "CREATE TABLE" "create+table+x(a)"
256+deny "CREATE VIEW" "create+view+v+as+select+1"
257+deny "ATTACH" "attach+%27$TMP%2Fevil.db%27+as+evil"
258+deny "DETACH" "detach+main"
259+deny "REINDEX" "reindex"
260+deny "VACUUM" "vacuum"
261+deny "BEGIN" "begin"
262+deny "PRAGMA write" "pragma+user_version%3D5"
263+deny "stacked stmt" "select+1%3B+drop+table+orders"
264+deny "WITH-DELETE" "WITH+x+AS(SELECT+1)+DELETE+FROM+customers"
265+
266+# Row-count evidence that nothing above actually mutated the file.
267+AFTER=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
268+check "orders still has 1200 rows" '[[1200]]' "$AFTER"
269+AFTER_C=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+customers" "$BIN")")
270+check "customers still has 2 rows" '[[2]]' "$AFTER_C"
271+[ ! -f "$TMP/evil.db" ] && pass "ATTACH created no file" || fail "ATTACH created $TMP/evil.db"
272+
273+# The authorizer is the second line of defence; prove it fires directly.
274+python3 - "$DB" <<'PY' && pass "on-disk mtime proves no write happened" || fail "database file changed"
275+import os, sqlite3, sys, time
276+db = sys.argv[1]
277+before = os.stat(db).st_mtime
278+c = sqlite3.connect(db)
279+c.execute("SELECT count(*) FROM orders").fetchone()
280+c.close()
281+assert os.stat(db).st_mtime == before
282+PY
283+
284+# ---------------------------------------------------------------- paths
285+section "path discipline"
286+bad_path() { # bad_path <desc> <db-query-value>
287+ local out
288+ out=$(body "$(QUERY_STRING="action=query&db=$2&sql=select+1" "$BIN")")
289+ case "$out" in
290+ *forbidden_path*) pass "$1 rejected" ;;
291+ *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
292+ esac
293+}
294+bad_path "/etc/passwd" "/etc/passwd"
295+bad_path "../ traversal" "$TMP/../../etc/passwd"
296+bad_path "encoded traversal" "$TMP/%2e%2e/%2e%2e/etc/passwd"
297+bad_path "SQLite URI filename" "file:$DB"
298+bad_path "URI with mode=rwc" "file:$DB%3Fmode%3Drwc"
299+bad_path "http scheme" "http://example.com/x.db"
300+bad_path "non-db suffix" "$TMP/notes.txt"
301+bad_path "arbitrary root" "/etc/hosts.db"
302+
303+MISSING=$(body "$(QUERY_STRING="action=query&db=$TMP/absent.sqlite&sql=select+1" "$BIN")")
304+check "allowed location, missing file -> not_found" 'not_found' "$MISSING"
305+
306+# ---------------------------------------------------------------- misc
307+section "mode 2 misc"
308+INFO=$(body "$(QUERY_STRING='action=info' "$BIN")")
309+check "info names the plugin" '"plugin":"plugin_sqlite"' "$INFO"
310+check "info names the sqlite version" '"sqlite":"3.' "$INFO"
311+check "info declares read-only" '"readonly":true' "$INFO"
312+check "info declares zero_network" '"zero_network":true' "$INFO"
313+check "info declares no extension load" '"load_extension":false' "$INFO"
314+check "info lists the actions" '"dbs","schema","query","info"' "$INFO"
315+check "info declares max_rows" '"max_rows":500' "$INFO"
316+
317+UNK=$(body "$(QUERY_STRING='action=nope' "$BIN")")
318+check "unknown action is refused" 'unknown_action' "$UNK"
319+JSONF=$(body "$(QUERY_STRING='format=json' "$BIN")")
320+check "format=json falls back to dbs" '"action":"dbs"' "$JSONF"
321+NOSQL=$(body "$(QUERY_STRING="action=query&db=$DB" "$BIN")")
322+check "query without sql -> missing_sql" 'missing_sql' "$NOSQL"
323+
324+# ---------------------------------------------------------------- mode 3
325+section "mode 3 html"
326+HTML=$("$BIN")
327+check "html content type" 'Content-Type: text/html' "$HTML"
328+check "html has a doctype" '<!DOCTYPE html>' "$HTML"
329+check "html titles the tool" '<title>sqlite</title>' "$HTML"
330+check "html ships the sql editor" "id='sql'" "$HTML"
331+check "html ships the db picker" "id='dbsel'" "$HTML"
332+check "html ships the result grid" "id='reswrap'" "$HTML"
333+check "html supports ctrl+enter" 'Ctrl' "$HTML"
334+check "html offers CSV copy" 'Copy CSV' "$HTML"
335+check "html offers JSON copy" 'Copy JSON' "$HTML"
336+check "html declares the node route" '/plugin_sqlite?action=' "$HTML"
337+check "html declares the hub route" "/plugins?plugin=" "$HTML"
338+check "html honours embed" "/plugin_sqlite?action=" "$HTML"
339+check "html supports light theme" "data-theme=light" "$HTML"
340+check_not "html has no CDN script" '<script src=' "$HTML"
341+check_not "html has no cdnjs" 'cdnjs' "$HTML"
342+check_not "html emits no Content-Length" 'Content-Length' "$HTML"
343+EMBED=$("$BIN" </dev/null 2>/dev/null | head -1)
344+EMBEDQ=$(QUERY_STRING='embed=1' "$BIN")
345+check_not "embed=1 drops the back link" 'Back to Bot' "$EMBEDQ"
346+check "non-embed keeps the back link" 'Back to Bot' "$HTML"
347+
348+# ---------------------------------------------------------------- artifacts
349+section "cross builds"
350+if [ -f plugin_sqlite.musl ]; then
351+ MAGIC=$(od -An -tx1 -N4 plugin_sqlite.musl | tr -d ' \n')
352+ [ "$MAGIC" = "7f454c46" ] && pass "musl artifact is an ELF" || fail "musl artifact is not ELF ($MAGIC)"
353+ python3 - plugin_sqlite.musl <<'PY' && pass "musl artifact is x86_64 (EM_X86_64=62)" || fail "musl artifact wrong machine"
354+import sys, struct
355+d = open(sys.argv[1], "rb").read(20)
356+assert d[4] == 2, "not 64-bit"
357+assert d[5] == 1, "not little-endian"
358+assert struct.unpack("<H", d[18:20])[0] == 62
359+PY
360+ if command -v readelf >/dev/null 2>&1; then
361+ readelf -d plugin_sqlite.musl 2>/dev/null | grep -q NEEDED \
362+ && fail "musl artifact is dynamically linked" || pass "musl artifact is fully static"
363+ fi
364+else
365+ printf ' skip musl artifact (not built)\n'
366+fi
367+
368+if [ -f plugin_sqlite.arm64 ]; then
369+ python3 - plugin_sqlite.arm64 <<'PY' && pass "arm64 artifact is EM_AARCH64 (183)" || fail "arm64 artifact wrong machine"
370+import sys, struct
371+d = open(sys.argv[1], "rb").read(20)
372+assert d[4] == 2, "not 64-bit"
373+assert d[5] == 1, "not little-endian"
374+assert struct.unpack("<H", d[18:20])[0] == 183
375+PY
376+else
377+ printf ' skip arm64 artifact (not built)\n'
378+fi
379+
380+if [ -f plugin_sqlite.exe ]; then
381+ MZ=$(head -c 2 plugin_sqlite.exe)
382+ [ "$MZ" = "MZ" ] && pass "windows artifact starts with MZ" || fail "windows artifact is not a PE"
383+ SZ=$(wc -c < plugin_sqlite.exe | tr -d ' ')
384+ [ "$SZ" -gt 200000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
385+else
386+ printf ' skip windows artifact (not built)\n'
387+fi
388+
389+# ---------------------------------------------------------------- history
390+section "git history audit"
391+if [ -d .git ]; then
392+ SCAN="$TMP/history.txt"
393+ P_ROOT=$(pwd); P_WT=$(pwd)
394+ git log -p --all 2>/dev/null \
395+ | grep -v '^Author: ' \
396+ | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
397+ > "$SCAN" || : > "$SCAN"
398+ HITS=0
399+ scan() { # scan <label> <regex>
400+ out=$(grep -Eo "$2" "$SCAN" 2>/dev/null | sort -u | head -5 || true)
401+ if [ -n "$out" ]; then
402+ printf ' %sHIT%s %s\n %s\n' "$C_BAD" "$C_0" "$1" "$(printf '%s' "$out" | tr '\n' ' ')"
403+ HITS=$((HITS + 1))
404+ else
405+ pass "no $1 in history"
406+ fi
407+ }
408+ scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
409+ scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
410+ scan "private 172.16-31.x.x" '\b172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
411+ scan "GitHub tokens" 'ghp_[A-Za-z0-9]{20,}'
412+ scan "HuggingFace tokens" 'hf_[A-Za-z0-9]{20,}'
413+ scan "AWS access keys" 'AKIA[0-9A-Z]{16}'
414+ scan "OpenAI keys" 'sk-[A-Za-z0-9]{32,}'
415+ scan "private keys" 'BEGIN (RSA|OPENSSH|EC|PGP) PRIVATE KEY'
416+ scan "passwords in source" '(password|passwd|secret)[[:space:]]*=[[:space:]]*"[^"]{4,}"'
417+ [ "$HITS" -eq 0 ] && pass "history audit clean (0 hits)" || fail "history audit found $HITS category(ies)"
418+else
419+ printf ' skip history audit (not a git repo)\n'
420+fi
421+
422+# ---------------------------------------------------------------- summary
423+printf '\n%s----------------------------------------%s\n' "$C_B" "$C_0"
424+printf ' %spass %d%s %sfail %d%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
425+[ "$FAIL" -eq 0 ] && { printf ' %sALL PASS%s\n' "$C_OK" "$C_0"; exit 0; }
426+printf ' %sFAILURES%s\n' "$C_BAD" "$C_0"
427+exit 1
vendor/sqlite3.c+1674−0■■■■■
11new file mode 100644
index 0000000..0644a39
--- /dev/null
+++ b/vendor/sqlite3.c
@@ -0,0 +1,269649 @@
1+/******************************************************************************
2+** This file is an amalgamation of many separate C source files from SQLite
3+** version 3.53.4. By combining all the individual C code files into this
4+** single large file, the entire code can be compiled as a single translation
5+** unit. This allows many compilers to do optimizations that would not be
6+** possible if the files were compiled separately. Performance improvements
7+** of 5% or more are commonly seen when SQLite is compiled as a single
8+** translation unit.
9+**
10+** This file is all you need to compile SQLite. To use SQLite in other
11+** programs, you need this file and the "sqlite3.h" header file that defines
12+** the programming interface to the SQLite library. (If you do not have
13+** the "sqlite3.h" header file at hand, you will find a copy embedded within
14+** the text of this file. Search for "Begin file sqlite3.h" to find the start
15+** of the embedded sqlite3.h header file.) Additional code files may be needed
16+** if you want a wrapper to interface SQLite with your choice of programming
17+** language. The code for the "sqlite3" command-line shell is also in a
18+** separate file. This file contains only code for the core SQLite library.
19+**
20+** The content in this amalgamation comes from Fossil check-in
21+** bf7c7f30031888f4e796e429ab3978879485 with changes in files:
22+**
23+**
24+*/
25+#ifndef SQLITE_AMALGAMATION
26+#define SQLITE_CORE 1
27+#define SQLITE_AMALGAMATION 1
28+#ifndef SQLITE_PRIVATE
29+# define SQLITE_PRIVATE static
30+#endif
31+/************** Begin file sqliteInt.h ***************************************/
32+/*
33+** 2001 September 15
34+**
35+** The author disclaims copyright to this source code. In place of
36+** a legal notice, here is a blessing:
37+**
38+** May you do good and not evil.
39+** May you find forgiveness for yourself and forgive others.
40+** May you share freely, never taking more than you give.
41+**
42+*************************************************************************
43+** Internal interface definitions for SQLite.
44+**
45+*/
46+#ifndef SQLITEINT_H
47+#define SQLITEINT_H
48+
49+/* Special Comments:
50+**
51+** Some comments have special meaning to the tools that measure test
52+** coverage:
53+**
54+** NO_TEST - The branches on this line are not
55+** measured by branch coverage. This is
56+** used on lines of code that actually
57+** implement parts of coverage testing.
58+**
59+** OPTIMIZATION-IF-TRUE - This branch is allowed to always be false
60+** and the correct answer is still obtained,
61+** though perhaps more slowly.
62+**
63+** OPTIMIZATION-IF-FALSE - This branch is allowed to always be true
64+** and the correct answer is still obtained,
65+** though perhaps more slowly.
66+**
67+** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
68+** that would be harmless and undetectable
69+** if it did occur.
70+**
71+** In all cases, the special comment must be enclosed in the usual
72+** slash-asterisk...asterisk-slash comment marks, with no spaces between the
73+** asterisks and the comment text.
74+*/
75+
76+/*
77+** Make sure the Tcl calling convention macro is defined. This macro is
78+** only used by test code and Tcl integration code.
79+*/
80+#ifndef SQLITE_TCLAPI
81+# define SQLITE_TCLAPI
82+#endif
83+
84+/*
85+** Include the header file used to customize the compiler options for MSVC.
86+** This should be done first so that it can successfully prevent spurious
87+** compiler warnings due to subsequent content in this file and other files
88+** that are included by this file.
89+*/
90+/************** Include msvc.h in the middle of sqliteInt.h ******************/
91+/************** Begin file msvc.h ********************************************/
92+/*
93+** 2015 January 12
94+**
95+** The author disclaims copyright to this source code. In place of
96+** a legal notice, here is a blessing:
97+**
98+** May you do good and not evil.
99+** May you find forgiveness for yourself and forgive others.
100+** May you share freely, never taking more than you give.
101+**
102+******************************************************************************
103+**
104+** This file contains code that is specific to MSVC.
105+*/
106+#ifndef SQLITE_MSVC_H
107+#define SQLITE_MSVC_H
108+
109+#if defined(_MSC_VER)
110+#pragma warning(disable : 4054)
111+#pragma warning(disable : 4055)
112+#pragma warning(disable : 4100)
113+#pragma warning(disable : 4127)
114+#pragma warning(disable : 4130)
115+#pragma warning(disable : 4152)
116+#pragma warning(disable : 4189)
117+#pragma warning(disable : 4206)
118+#pragma warning(disable : 4210)
119+#pragma warning(disable : 4232)
120+#pragma warning(disable : 4244)
121+#pragma warning(disable : 4305)
122+#pragma warning(disable : 4306)
123+#pragma warning(disable : 4702)
124+#pragma warning(disable : 4706)
125+#endif /* defined(_MSC_VER) */
126+
127+#if defined(_MSC_VER) && !defined(_WIN64)
128+#undef SQLITE_4_BYTE_ALIGNED_MALLOC
129+#define SQLITE_4_BYTE_ALIGNED_MALLOC
130+#endif /* defined(_MSC_VER) && !defined(_WIN64) */
131+
132+#if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800
133+#define HAVE_LOG2 0
134+#endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */
135+
136+#endif /* SQLITE_MSVC_H */
137+
138+/************** End of msvc.h ************************************************/
139+/************** Continuing where we left off in sqliteInt.h ******************/
140+
141+/*
142+** Special setup for VxWorks
143+*/
144+/************** Include vxworks.h in the middle of sqliteInt.h ***************/
145+/************** Begin file vxworks.h *****************************************/
146+/*
147+** 2015-03-02
148+**
149+** The author disclaims copyright to this source code. In place of
150+** a legal notice, here is a blessing:
151+**
152+** May you do good and not evil.
153+** May you find forgiveness for yourself and forgive others.
154+** May you share freely, never taking more than you give.
155+**
156+******************************************************************************
157+**
158+** This file contains code that is specific to Wind River's VxWorks
159+*/
160+#if defined(__RTP__) || defined(_WRS_KERNEL)
161+/* This is VxWorks. Set up things specially for that OS
162+*/
163+#include <vxWorks.h>
164+#include <pthread.h> /* amalgamator: dontcache */
165+#define OS_VXWORKS 1
166+#define SQLITE_OS_OTHER 0
167+#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
168+#define SQLITE_OMIT_LOAD_EXTENSION 1
169+#define SQLITE_ENABLE_LOCKING_STYLE 0
170+#define HAVE_UTIME 1
171+#else
172+/* This is not VxWorks. */
173+#ifndef OS_VXWORKS
174+# define OS_VXWORKS 0
175+#endif
176+#define HAVE_FCHOWN 1
177+#define HAVE_READLINK 1
178+#define HAVE_LSTAT 1
179+#endif /* defined(_WRS_KERNEL) */
180+
181+/************** End of vxworks.h *********************************************/
182+/************** Continuing where we left off in sqliteInt.h ******************/
183+
184+/*
185+** These #defines should enable >2GB file support on POSIX if the
186+** underlying operating system supports it. If the OS lacks
187+** large file support, or if the OS is windows, these should be no-ops.
188+**
189+** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
190+** system #includes. Hence, this block of code must be the very first
191+** code in all source files.
192+**
193+** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
194+** on the compiler command line. This is necessary if you are compiling
195+** on a recent machine (ex: Red Hat 7.2) but you want your code to work
196+** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
197+** without this option, LFS is enable. But LFS does not exist in the kernel
198+** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
199+** portability you should omit LFS.
200+**
201+** The previous paragraph was written in 2005. (This paragraph is written
202+** on 2008-11-28.) These days, all Linux kernels support large files, so
203+** you should probably leave LFS enabled. But some embedded platforms might
204+** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
205+**
206+** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
207+*/
208+#ifndef SQLITE_DISABLE_LFS
209+# define _LARGE_FILE 1
210+# ifndef _FILE_OFFSET_BITS
211+# define _FILE_OFFSET_BITS 64
212+# endif
213+# define _LARGEFILE_SOURCE 1
214+#endif
215+
216+/* The GCC_VERSION and MSVC_VERSION macros are used to
217+** conditionally include optimizations for each of these compilers. A
218+** value of 0 means that compiler is not being used. The
219+** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
220+** optimizations, and hence set all compiler macros to 0
221+**
222+** There was once also a CLANG_VERSION macro. However, we learn that the
223+** version numbers in clang are for "marketing" only and are inconsistent
224+** and unreliable. Fortunately, all versions of clang also recognize the
225+** gcc version numbers and have reasonable settings for gcc version numbers,
226+** so the GCC_VERSION macro will be set to a correct non-zero value even
227+** when compiling with clang.
228+*/
229+#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
230+# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
231+#else
232+# define GCC_VERSION 0
233+#endif
234+#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
235+# define MSVC_VERSION _MSC_VER
236+#else
237+# define MSVC_VERSION 0
238+#endif
239+
240+/*
241+** Some C99 functions in "math.h" are only present for MSVC when its version
242+** is associated with Visual Studio 2013 or higher.
243+*/
244+#ifndef SQLITE_HAVE_C99_MATH_FUNCS
245+# if MSVC_VERSION==0 || MSVC_VERSION>=1800
246+# define SQLITE_HAVE_C99_MATH_FUNCS (1)
247+# else
248+# define SQLITE_HAVE_C99_MATH_FUNCS (0)
249+# endif
250+#endif
251+
252+/* Needed for various definitions... */
253+#if defined(__GNUC__) && !defined(_GNU_SOURCE)
254+# define _GNU_SOURCE
255+#endif
256+
257+#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
258+# define _BSD_SOURCE
259+#endif
260+
261+/*
262+** Macro to disable warnings about missing "break" at the end of a "case".
263+*/
264+#if defined(__has_attribute)
265+# if __has_attribute(fallthrough)
266+# define deliberate_fall_through __attribute__((fallthrough));
267+# endif
268+#endif
269+#if !defined(deliberate_fall_through)
270+# define deliberate_fall_through
271+#endif
272+
273+/*
274+** For MinGW, check to see if we can include the header file containing its
275+** version information, among other things. Normally, this internal MinGW
276+** header file would [only] be included automatically by other MinGW header
277+** files; however, the contained version information is now required by this
278+** header file to work around binary compatibility issues (see below) and
279+** this is the only known way to reliably obtain it. This entire #if block
280+** would be completely unnecessary if there was any other way of detecting
281+** MinGW via their preprocessor (e.g. if they customized their GCC to define
282+** some MinGW-specific macros). When compiling for MinGW, either the
283+** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
284+** defined; otherwise, detection of conditions specific to MinGW will be
285+** disabled.
286+*/
287+#if defined(_HAVE_MINGW_H)
288+# include "mingw.h"
289+#elif defined(_HAVE__MINGW_H)
290+# include "_mingw.h"
291+#endif
292+
293+/*
294+** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
295+** define is required to maintain binary compatibility with the MSVC runtime
296+** library in use (e.g. for Windows XP).
297+*/
298+#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
299+ defined(_WIN32) && !defined(_WIN64) && \
300+ defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
301+ defined(__MSVCRT__)
302+# define _USE_32BIT_TIME_T
303+#endif
304+
305+/* Optionally #include a user-defined header, whereby compilation options
306+** may be set prior to where they take effect, but after platform setup.
307+** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
308+** file.
309+*/
310+#ifdef SQLITE_CUSTOM_INCLUDE
311+# define INC_STRINGIFY_(f) #f
312+# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
313+# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
314+#endif
315+
316+/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
317+** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
318+** MinGW.
319+*/
320+/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
321+/************** Begin file sqlite3.h *****************************************/
322+/*
323+** 2001-09-15
324+**
325+** The author disclaims copyright to this source code. In place of
326+** a legal notice, here is a blessing:
327+**
328+** May you do good and not evil.
329+** May you find forgiveness for yourself and forgive others.
330+** May you share freely, never taking more than you give.
331+**
332+*************************************************************************
333+** This header file defines the interface that the SQLite library
334+** presents to client programs. If a C-function, structure, datatype,
335+** or constant definition does not appear in this file, then it is
336+** not a published API of SQLite, is subject to change without
337+** notice, and should not be referenced by programs that use SQLite.
338+**
339+** Some of the definitions that are in this file are marked as
340+** "experimental". Experimental interfaces are normally new
341+** features recently added to SQLite. We do not anticipate changes
342+** to experimental interfaces but reserve the right to make minor changes
343+** if experience from use "in the wild" suggest such changes are prudent.
344+**
345+** The official C-language API documentation for SQLite is derived
346+** from comments in this file. This file is the authoritative source
347+** on how SQLite interfaces are supposed to operate.
348+**
349+** The name of this file under configuration management is "sqlite.h.in".
350+** The makefile makes some minor changes to this file (such as inserting
351+** the version number) and changes its name to "sqlite3.h" as
352+** part of the build process.
353+*/
354+#ifndef SQLITE3_H
355+#define SQLITE3_H
356+#include <stdarg.h> /* Needed for the definition of va_list */
357+
358+/*
359+** Make sure we can call this stuff from C++.
360+*/
361+#if 0
362+extern "C" {
363+#endif
364+
365+
366+/*
367+** Facilitate override of interface linkage and calling conventions.
368+** Be aware that these macros may not be used within this particular
369+** translation of the amalgamation and its associated header file.
370+**
371+** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
372+** compiler that the target identifier should have external linkage.
373+**
374+** The SQLITE_CDECL macro is used to set the calling convention for
375+** public functions that accept a variable number of arguments.
376+**
377+** The SQLITE_APICALL macro is used to set the calling convention for
378+** public functions that accept a fixed number of arguments.
379+**
380+** The SQLITE_STDCALL macro is no longer used and is now deprecated.
381+**
382+** The SQLITE_CALLBACK macro is used to set the calling convention for
383+** function pointers.
384+**
385+** The SQLITE_SYSAPI macro is used to set the calling convention for
386+** functions provided by the operating system.
387+**
388+** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
389+** SQLITE_SYSAPI macros are used only when building for environments
390+** that require non-default calling conventions.
391+*/
392+#ifndef SQLITE_EXTERN
393+# define SQLITE_EXTERN extern
394+#endif
395+#ifndef SQLITE_API
396+# define SQLITE_API
397+#endif
398+#ifndef SQLITE_CDECL
399+# define SQLITE_CDECL
400+#endif
401+#ifndef SQLITE_APICALL
402+# define SQLITE_APICALL
403+#endif
404+#ifndef SQLITE_STDCALL
405+# define SQLITE_STDCALL SQLITE_APICALL
406+#endif
407+#ifndef SQLITE_CALLBACK
408+# define SQLITE_CALLBACK
409+#endif
410+#ifndef SQLITE_SYSAPI
411+# define SQLITE_SYSAPI
412+#endif
413+
414+/*
415+** These no-op macros are used in front of interfaces to mark those
416+** interfaces as either deprecated or experimental. New applications
417+** should not use deprecated interfaces - they are supported for backwards
418+** compatibility only. Application writers should be aware that
419+** experimental interfaces are subject to change in point releases.
420+**
421+** These macros used to resolve to various kinds of compiler magic that
422+** would generate warning messages when they were used. But that
423+** compiler magic ended up generating such a flurry of bug reports
424+** that we have taken it all out and gone back to using simple
425+** noop macros.
426+*/
427+#define SQLITE_DEPRECATED
428+#define SQLITE_EXPERIMENTAL
429+
430+/*
431+** Ensure these symbols were not defined by some previous header file.
432+*/
433+#ifdef SQLITE_VERSION
434+# undef SQLITE_VERSION
435+#endif
436+#ifdef SQLITE_VERSION_NUMBER
437+# undef SQLITE_VERSION_NUMBER
438+#endif
439+
440+/*
441+** CAPI3REF: Compile-Time Library Version Numbers
442+**
443+** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
444+** evaluates to a string literal that is the SQLite version in the
445+** format "X.Y.Z" where X is the major version number (always 3 for
446+** SQLite3) and Y is the minor version number and Z is the release number.)^
447+** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
448+** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
449+** numbers used in [SQLITE_VERSION].)^
450+** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
451+** be larger than the release from which it is derived. Either Y will
452+** be held constant and Z will be incremented or else Y will be incremented
453+** and Z will be reset to zero.
454+**
455+** Since [version 3.6.18] ([dateof:3.6.18]),
456+** SQLite source code has been stored in the
457+** <a href="http://fossil-scm.org/">Fossil configuration management
458+** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
459+** a string which identifies a particular check-in of SQLite
460+** within its configuration management system. ^The SQLITE_SOURCE_ID
461+** string contains the date and time of the check-in (UTC) and a SHA1
462+** or SHA3-256 hash of the entire source tree. If the source code has
463+** been edited in any way since it was last checked in, then the last
464+** four hexadecimal digits of the hash may be modified.
465+**
466+** See also: [sqlite3_libversion()],
467+** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468+** [sqlite_version()] and [sqlite_source_id()].
469+*/
470+#define SQLITE_VERSION "3.53.4"
471+#define SQLITE_VERSION_NUMBER 3053004
472+#define SQLITE_SOURCE_ID "2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc"
473+#define SQLITE_SCM_BRANCH "branch-3.53"
474+#define SQLITE_SCM_TAGS "release version-3.53.4"
475+#define SQLITE_SCM_DATETIME "2026-07-24T19:02:57.525Z"
476+
477+/*
478+** CAPI3REF: Run-Time Library Version Numbers
479+** KEYWORDS: sqlite3_version sqlite3_sourceid
480+**
481+** These interfaces provide the same information as the [SQLITE_VERSION],
482+** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
483+** but are associated with the library instead of the header file. ^(Cautious
484+** programmers might include assert() statements in their application to
485+** verify that values returned by these interfaces match the macros in
486+** the header, and thus ensure that the application is
487+** compiled with matching library and header files.
488+**
489+** <blockquote><pre>
490+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
491+** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
492+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
493+** </pre></blockquote>)^
494+**
495+** ^The sqlite3_version[] string constant contains the text of the
496+** [SQLITE_VERSION] macro. ^The sqlite3_libversion() function returns a
497+** pointer to the sqlite3_version[] string constant. The sqlite3_libversion()
498+** function is provided for use in DLLs since DLL users usually do not have
499+** direct access to string constants within the DLL. ^The
500+** sqlite3_libversion_number() function returns an integer equal to
501+** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
502+** a pointer to a string constant whose value is the same as the
503+** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
504+** using an edited copy of [the amalgamation], then the last four characters
505+** of the hash might be different from [SQLITE_SOURCE_ID].)^
506+**
507+** See also: [sqlite_version()] and [sqlite_source_id()].
508+*/
509+SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
510+SQLITE_API const char *sqlite3_libversion(void);
511+SQLITE_API const char *sqlite3_sourceid(void);
512+SQLITE_API int sqlite3_libversion_number(void);
513+
514+/*
515+** CAPI3REF: Run-Time Library Compilation Options Diagnostics
516+**
517+** ^The sqlite3_compileoption_used() function returns 0 or 1
518+** indicating whether the specified option was defined at
519+** compile time. ^The SQLITE_ prefix may be omitted from the
520+** option name passed to sqlite3_compileoption_used().
521+**
522+** ^The sqlite3_compileoption_get() function allows iterating
523+** over the list of options that were defined at compile time by
524+** returning the N-th compile time option string. ^If N is out of range,
525+** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
526+** prefix is omitted from any strings returned by
527+** sqlite3_compileoption_get().
528+**
529+** ^Support for the diagnostic functions sqlite3_compileoption_used()
530+** and sqlite3_compileoption_get() may be omitted by specifying the
531+** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
532+**
533+** See also: SQL functions [sqlite_compileoption_used()] and
534+** [sqlite_compileoption_get()] and the [compile_options pragma].
535+*/
536+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
537+SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
538+SQLITE_API const char *sqlite3_compileoption_get(int N);
539+#else
540+# define sqlite3_compileoption_used(X) 0
541+# define sqlite3_compileoption_get(X) ((void*)0)
542+#endif
543+
544+/*
545+** CAPI3REF: Test To See If The Library Is Threadsafe
546+**
547+** ^The sqlite3_threadsafe() function returns zero if and only if
548+** SQLite was compiled with mutexing code omitted due to the
549+** [SQLITE_THREADSAFE] compile-time option being set to 0.
550+**
551+** SQLite can be compiled with or without mutexes. When
552+** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
553+** are enabled and SQLite is threadsafe. When the
554+** [SQLITE_THREADSAFE] macro is 0,
555+** the mutexes are omitted. Without the mutexes, it is not safe
556+** to use SQLite concurrently from more than one thread.
557+**
558+** Enabling mutexes incurs a measurable performance penalty.
559+** So if speed is of utmost importance, it makes sense to disable
560+** the mutexes. But for maximum safety, mutexes should be enabled.
561+** ^The default behavior is for mutexes to be enabled.
562+**
563+** This interface can be used by an application to make sure that the
564+** version of SQLite that it is linking against was compiled with
565+** the desired setting of the [SQLITE_THREADSAFE] macro.
566+**
567+** This interface only reports on the compile-time mutex setting
568+** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
569+** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
570+** can be fully or partially disabled using a call to [sqlite3_config()]
571+** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
572+** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
573+** sqlite3_threadsafe() function shows only the compile-time setting of
574+** thread safety, not any run-time changes to that setting made by
575+** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
576+** is unchanged by calls to sqlite3_config().)^
577+**
578+** See the [threading mode] documentation for additional information.
579+*/
580+SQLITE_API int sqlite3_threadsafe(void);
581+
582+/*
583+** CAPI3REF: Database Connection Handle
584+** KEYWORDS: {database connection} {database connections}
585+**
586+** Each open SQLite database is represented by a pointer to an instance of
587+** the opaque structure named "sqlite3". It is useful to think of an sqlite3
588+** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
589+** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
590+** and [sqlite3_close_v2()] are its destructors. There are many other
591+** interfaces (such as
592+** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
593+** [sqlite3_busy_timeout()] to name but three) that are methods on an
594+** sqlite3 object.
595+*/
596+typedef struct sqlite3 sqlite3;
597+
598+/*
599+** CAPI3REF: 64-Bit Integer Types
600+** KEYWORDS: sqlite_int64 sqlite_uint64
601+**
602+** Because there is no cross-platform way to specify 64-bit integer types
603+** SQLite includes typedefs for 64-bit signed and unsigned integers.
604+**
605+** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
606+** The sqlite_int64 and sqlite_uint64 types are supported for backwards
607+** compatibility only.
608+**
609+** ^The sqlite3_int64 and sqlite_int64 types can store integer values
610+** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
611+** sqlite3_uint64 and sqlite_uint64 types can store integer values
612+** between 0 and +18446744073709551615 inclusive.
613+*/
614+#ifdef SQLITE_INT64_TYPE
615+ typedef SQLITE_INT64_TYPE sqlite_int64;
616+# ifdef SQLITE_UINT64_TYPE
617+ typedef SQLITE_UINT64_TYPE sqlite_uint64;
618+# else
619+ typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
620+# endif
621+#elif defined(_MSC_VER) || defined(__BORLANDC__)
622+ typedef __int64 sqlite_int64;
623+ typedef unsigned __int64 sqlite_uint64;
624+#else
625+ typedef long long int sqlite_int64;
626+ typedef unsigned long long int sqlite_uint64;
627+#endif
628+typedef sqlite_int64 sqlite3_int64;
629+typedef sqlite_uint64 sqlite3_uint64;
630+
631+/*
632+** If compiling for a processor that lacks floating point support,
633+** substitute integer for floating-point.
634+*/
635+#ifdef SQLITE_OMIT_FLOATING_POINT
636+# define double sqlite3_int64
637+#endif
638+
639+/*
640+** CAPI3REF: Closing A Database Connection
641+** DESTRUCTOR: sqlite3
642+**
643+** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
644+** for the [sqlite3] object.
645+** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
646+** the [sqlite3] object is successfully destroyed and all associated
647+** resources are deallocated.
648+**
649+** Ideally, applications should [sqlite3_finalize | finalize] all
650+** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
651+** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
652+** with the [sqlite3] object prior to attempting to close the object.
653+** ^If the database connection is associated with unfinalized prepared
654+** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
655+** sqlite3_close() will leave the database connection open and return
656+** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
657+** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
658+** it returns [SQLITE_OK] regardless, but instead of deallocating the database
659+** connection immediately, it marks the database connection as an unusable
660+** "zombie" and makes arrangements to automatically deallocate the database
661+** connection after all prepared statements are finalized, all BLOB handles
662+** are closed, and all backups have finished. The sqlite3_close_v2() interface
663+** is intended for use with host languages that are garbage collected, and
664+** where the order in which destructors are called is arbitrary.
665+**
666+** ^If an [sqlite3] object is destroyed while a transaction is open,
667+** the transaction is automatically rolled back.
668+**
669+** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
670+** must be either a NULL
671+** pointer or an [sqlite3] object pointer obtained
672+** from [sqlite3_open()], [sqlite3_open16()], or
673+** [sqlite3_open_v2()], and not previously closed.
674+** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
675+** argument is a harmless no-op.
676+*/
677+SQLITE_API int sqlite3_close(sqlite3*);
678+SQLITE_API int sqlite3_close_v2(sqlite3*);
679+
680+/*
681+** The type for a callback function.
682+** This is legacy and deprecated. It is included for historical
683+** compatibility and is not documented.
684+*/
685+typedef int (*sqlite3_callback)(void*,int,char**, char**);
686+
687+/*
688+** CAPI3REF: One-Step Query Execution Interface
689+** METHOD: sqlite3
690+**
691+** The sqlite3_exec() interface is a convenience wrapper around
692+** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
693+** that allows an application to run multiple statements of SQL
694+** without having to use a lot of C code.
695+**
696+** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
697+** semicolon-separated SQL statements passed into its 2nd argument,
698+** in the context of the [database connection] passed in as its 1st
699+** argument. ^If the callback function of the 3rd argument to
700+** sqlite3_exec() is not NULL, then it is invoked for each result row
701+** coming out of the evaluated SQL statements. ^The 4th argument to
702+** sqlite3_exec() is relayed through to the 1st argument of each
703+** callback invocation. ^If the callback pointer to sqlite3_exec()
704+** is NULL, then no callback is ever invoked and result rows are
705+** ignored.
706+**
707+** ^If an error occurs while evaluating the SQL statements passed into
708+** sqlite3_exec(), then execution of the current statement stops and
709+** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
710+** is not NULL then any error message is written into memory obtained
711+** from [sqlite3_malloc()] and passed back through the 5th parameter.
712+** To avoid memory leaks, the application should invoke [sqlite3_free()]
713+** on error message strings returned through the 5th parameter of
714+** sqlite3_exec() after the error message string is no longer needed.
715+** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
716+** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
717+** NULL before returning.
718+**
719+** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
720+** routine returns SQLITE_ABORT without invoking the callback again and
721+** without running any subsequent SQL statements.
722+**
723+** ^The 2nd argument to the sqlite3_exec() callback function is the
724+** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
725+** callback is an array of pointers to strings obtained as if from
726+** [sqlite3_column_text()], one for each column. ^If an element of a
727+** result row is NULL then the corresponding string pointer for the
728+** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
729+** sqlite3_exec() callback is an array of pointers to strings where each
730+** entry represents the name of a corresponding result column as obtained
731+** from [sqlite3_column_name()].
732+**
733+** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
734+** to an empty string, or a pointer that contains only whitespace and/or
735+** SQL comments, then no SQL statements are evaluated and the database
736+** is not changed.
737+**
738+** Restrictions:
739+**
740+** <ul>
741+** <li> The application must ensure that the 1st parameter to sqlite3_exec()
742+** is a valid and open [database connection].
743+** <li> The application must not close the [database connection] specified by
744+** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
745+** <li> The application must not modify the SQL statement text passed into
746+** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
747+** <li> The application must not dereference the arrays or string pointers
748+** passed as the 3rd and 4th callback parameters after it returns.
749+** </ul>
750+*/
751+SQLITE_API int sqlite3_exec(
752+ sqlite3*, /* An open database */
753+ const char *sql, /* SQL to be evaluated */
754+ int (*callback)(void*,int,char**,char**), /* Callback function */
755+ void *, /* 1st argument to callback */
756+ char **errmsg /* Error msg written here */
757+);
758+
759+/*
760+** CAPI3REF: Result Codes
761+** KEYWORDS: {result code definitions}
762+**
763+** Many SQLite functions return an integer result code from the set shown
764+** here in order to indicate success or failure.
765+**
766+** New error codes may be added in future versions of SQLite.
767+**
768+** See also: [extended result code definitions]
769+*/
770+#define SQLITE_OK 0 /* Successful result */
771+/* beginning-of-error-codes */
772+#define SQLITE_ERROR 1 /* Generic error */
773+#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
774+#define SQLITE_PERM 3 /* Access permission denied */
775+#define SQLITE_ABORT 4 /* Callback routine requested an abort */
776+#define SQLITE_BUSY 5 /* The database file is locked */
777+#define SQLITE_LOCKED 6 /* A table in the database is locked */
778+#define SQLITE_NOMEM 7 /* A malloc() failed */
779+#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
780+#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
781+#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
782+#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
783+#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
784+#define SQLITE_FULL 13 /* Insertion failed because database is full */
785+#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
786+#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
787+#define SQLITE_EMPTY 16 /* Internal use only */
788+#define SQLITE_SCHEMA 17 /* The database schema changed */
789+#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
790+#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
791+#define SQLITE_MISMATCH 20 /* Data type mismatch */
792+#define SQLITE_MISUSE 21 /* Library used incorrectly */
793+#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
794+#define SQLITE_AUTH 23 /* Authorization denied */
795+#define SQLITE_FORMAT 24 /* Not used */
796+#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
797+#define SQLITE_NOTADB 26 /* File opened that is not a database file */
798+#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
799+#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
800+#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
801+#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
802+/* end-of-error-codes */
803+
804+/*
805+** CAPI3REF: Extended Result Codes
806+** KEYWORDS: {extended result code definitions}
807+**
808+** In its default configuration, SQLite API routines return one of 30 integer
809+** [result codes]. However, experience has shown that many of
810+** these result codes are too coarse-grained. They do not provide as
811+** much information about problems as programmers might like. In an effort to
812+** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
813+** and later) include
814+** support for additional result codes that provide more detailed information
815+** about errors. These [extended result codes] are enabled or disabled
816+** on a per database connection basis using the
817+** [sqlite3_extended_result_codes()] API. Or, the extended code for
818+** the most recent error can be obtained using
819+** [sqlite3_extended_errcode()].
820+*/
821+#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
822+#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
823+#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
824+#define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8))
825+#define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8))
826+#define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8))
827+#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
828+#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
829+#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
830+#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
831+#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
832+#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
833+#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
834+#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
835+#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
836+#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
837+#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
838+#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
839+#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
840+#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
841+#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
842+#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
843+#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
844+#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
845+#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
846+#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
847+#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
848+#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
849+#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
850+#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
851+#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
852+#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
853+#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
854+#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
855+#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
856+#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
857+#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
858+#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))
859+#define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8))
860+#define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8))
861+#define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8))
862+#define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8))
863+#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
864+#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
865+#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
866+#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
867+#define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8))
868+#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
869+#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
870+#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
871+#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
872+#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
873+#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8))
874+#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
875+#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
876+#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8))
877+#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
878+#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
879+#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
880+#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
881+#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
882+#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
883+#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
884+#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
885+#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
886+#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
887+#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
888+#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
889+#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
890+#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
891+#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
892+#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
893+#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
894+#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8))
895+#define SQLITE_CONSTRAINT_DATATYPE (SQLITE_CONSTRAINT |(12<<8))
896+#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
897+#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
898+#define SQLITE_NOTICE_RBU (SQLITE_NOTICE | (3<<8))
899+#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
900+#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
901+#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
902+#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal only */
903+
904+/*
905+** CAPI3REF: Flags For File Open Operations
906+**
907+** These bit values are intended for use in the
908+** 3rd parameter to the [sqlite3_open_v2()] interface and
909+** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
910+**
911+** Only those flags marked as "Ok for sqlite3_open_v2()" may be
912+** used as the third argument to the [sqlite3_open_v2()] interface.
913+** The other flags have historically been ignored by sqlite3_open_v2(),
914+** though future versions of SQLite might change so that an error is
915+** raised if any of the disallowed bits are passed into sqlite3_open_v2().
916+** Applications should not depend on the historical behavior.
917+**
918+** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
919+** [sqlite3_open_v2()] does *not* cause the underlying database file
920+** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into
921+** [sqlite3_open_v2()] has historically been a no-op and might become an
922+** error in future versions of SQLite.
923+*/
924+#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
925+#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
926+#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
927+#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
928+#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
929+#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
930+#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
931+#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
932+#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
933+#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
934+#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
935+#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
936+#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
937+#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
938+#define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */
939+#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
940+#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
941+#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
942+#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
943+#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
944+#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */
945+#define SQLITE_OPEN_EXRESCODE 0x02000000 /* Extended result codes */
946+
947+/* Reserved: 0x00F00000 */
948+/* Legacy compatibility: */
949+#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
950+
951+
952+/*
953+** CAPI3REF: Device Characteristics
954+**
955+** The xDeviceCharacteristics method of the [sqlite3_io_methods]
956+** object returns an integer which is a vector of these
957+** bit values expressing I/O characteristics of the mass storage
958+** device that holds the file that the [sqlite3_io_methods]
959+** refers to.
960+**
961+** The SQLITE_IOCAP_ATOMIC property means that all writes of
962+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
963+** mean that writes of blocks that are nnn bytes in size and
964+** are aligned to an address which is an integer multiple of
965+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
966+** that when data is appended to a file, the data is appended
967+** first then the size of the file is extended, never the other
968+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
969+** information is written to disk in the same order as calls
970+** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
971+** after reboot following a crash or power loss, the only bytes in a
972+** file that were written at the application level might have changed
973+** and that adjacent bytes, even bytes within the same sector are
974+** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
975+** flag indicates that a file cannot be deleted when open. The
976+** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
977+** read-only media and cannot be changed even by processes with
978+** elevated privileges.
979+**
980+** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
981+** filesystem supports doing multiple write operations atomically when those
982+** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
983+** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
984+**
985+** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read
986+** from the database file in amounts that are not a multiple of the
987+** page size and that do not begin at a page boundary. Without this
988+** property, SQLite is careful to only do full-page reads and write
989+** on aligned pages, with the one exception that it will do a sub-page
990+** read of the first page to access the database header.
991+*/
992+#define SQLITE_IOCAP_ATOMIC 0x00000001
993+#define SQLITE_IOCAP_ATOMIC512 0x00000002
994+#define SQLITE_IOCAP_ATOMIC1K 0x00000004
995+#define SQLITE_IOCAP_ATOMIC2K 0x00000008
996+#define SQLITE_IOCAP_ATOMIC4K 0x00000010
997+#define SQLITE_IOCAP_ATOMIC8K 0x00000020
998+#define SQLITE_IOCAP_ATOMIC16K 0x00000040
999+#define SQLITE_IOCAP_ATOMIC32K 0x00000080
1000+#define SQLITE_IOCAP_ATOMIC64K 0x00000100
1001+#define SQLITE_IOCAP_SAFE_APPEND 0x00000200
1002+#define SQLITE_IOCAP_SEQUENTIAL 0x00000400
1003+#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
1004+#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
1005+#define SQLITE_IOCAP_IMMUTABLE 0x00002000
1006+#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
1007+#define SQLITE_IOCAP_SUBPAGE_READ 0x00008000
1008+
1009+/*
1010+** CAPI3REF: File Locking Levels
1011+**
1012+** SQLite uses one of these integer values as the second
1013+** argument to calls it makes to the xLock() and xUnlock() methods
1014+** of an [sqlite3_io_methods] object. These values are ordered from
1015+** least restrictive to most restrictive.
1016+**
1017+** The argument to xLock() is always SHARED or higher. The argument to
1018+** xUnlock is either SHARED or NONE.
1019+*/
1020+#define SQLITE_LOCK_NONE 0 /* xUnlock() only */
1021+#define SQLITE_LOCK_SHARED 1 /* xLock() or xUnlock() */
1022+#define SQLITE_LOCK_RESERVED 2 /* xLock() only */
1023+#define SQLITE_LOCK_PENDING 3 /* xLock() only */
1024+#define SQLITE_LOCK_EXCLUSIVE 4 /* xLock() only */
1025+
1026+/*
1027+** CAPI3REF: Synchronization Type Flags
1028+**
1029+** When SQLite invokes the xSync() method of an
1030+** [sqlite3_io_methods] object it uses a combination of
1031+** these integer values as the second argument.
1032+**
1033+** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1034+** sync operation only needs to flush data to mass storage. Inode
1035+** information need not be flushed. If the lower four bits of the flag
1036+** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1037+** If the lower four bits equal SQLITE_SYNC_FULL, that means
1038+** to use Mac OS X style fullsync instead of fsync().
1039+**
1040+** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1041+** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1042+** settings. The [synchronous pragma] determines when calls to the
1043+** xSync VFS method occur and applies uniformly across all platforms.
1044+** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1045+** energetic or rigorous or forceful the sync operations are and
1046+** only make a difference on Mac OSX for the default SQLite code.
1047+** (Third-party VFS implementations might also make the distinction
1048+** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1049+** operating systems natively supported by SQLite, only Mac OSX
1050+** cares about the difference.)
1051+*/
1052+#define SQLITE_SYNC_NORMAL 0x00002
1053+#define SQLITE_SYNC_FULL 0x00003
1054+#define SQLITE_SYNC_DATAONLY 0x00010
1055+
1056+/*
1057+** CAPI3REF: OS Interface Open File Handle
1058+**
1059+** An [sqlite3_file] object represents an open file in the
1060+** [sqlite3_vfs | OS interface layer]. Individual OS interface
1061+** implementations will
1062+** want to subclass this object by appending additional fields
1063+** for their own use. The pMethods entry is a pointer to an
1064+** [sqlite3_io_methods] object that defines methods for performing
1065+** I/O operations on the open file.
1066+*/
1067+typedef struct sqlite3_file sqlite3_file;
1068+struct sqlite3_file {
1069+ const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1070+};
1071+
1072+/*
1073+** CAPI3REF: OS Interface File Virtual Methods Object
1074+**
1075+** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1076+** [sqlite3_file] object (or, more commonly, a subclass of the
1077+** [sqlite3_file] object) with a pointer to an instance of this object.
1078+** This object defines the methods used to perform various operations
1079+** against the open file represented by the [sqlite3_file] object.
1080+**
1081+** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1082+** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1083+** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1084+** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1085+** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1086+** to NULL.
1087+**
1088+** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1089+** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1090+** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1091+** flag may be ORed in to indicate that only the data of the file
1092+** and not its inode needs to be synced.
1093+**
1094+** The integer values to xLock() and xUnlock() are one of
1095+** <ul>
1096+** <li> [SQLITE_LOCK_NONE],
1097+** <li> [SQLITE_LOCK_SHARED],
1098+** <li> [SQLITE_LOCK_RESERVED],
1099+** <li> [SQLITE_LOCK_PENDING], or
1100+** <li> [SQLITE_LOCK_EXCLUSIVE].
1101+** </ul>
1102+** xLock() upgrades the database file lock. In other words, xLock() moves the
1103+** database file lock in the direction NONE toward EXCLUSIVE. The argument to
1104+** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never
1105+** SQLITE_LOCK_NONE. If the database file lock is already at or above the
1106+** requested lock, then the call to xLock() is a no-op.
1107+** xUnlock() downgrades the database file lock to either SHARED or NONE.
1108+** If the lock is already at or below the requested lock state, then the call
1109+** to xUnlock() is a no-op.
1110+** The xCheckReservedLock() method checks whether any database connection,
1111+** either in this process or in some other process, is holding a RESERVED,
1112+** PENDING, or EXCLUSIVE lock on the file. It returns, via its output
1113+** pointer parameter, true if such a lock exists and false otherwise.
1114+**
1115+** The xFileControl() method is a generic interface that allows custom
1116+** VFS implementations to directly control an open file using the
1117+** [sqlite3_file_control()] interface. The second "op" argument is an
1118+** integer opcode. The third argument is a generic pointer intended to
1119+** point to a structure that may contain arguments or space in which to
1120+** write return values. Potential uses for xFileControl() might be
1121+** functions to enable blocking locks with timeouts, to change the
1122+** locking strategy (for example to use dot-file locks), to inquire
1123+** about the status of a lock, or to break stale locks. The SQLite
1124+** core reserves all opcodes less than 100 for its own use.
1125+** A [file control opcodes | list of opcodes] less than 100 is available.
1126+** Applications that define a custom xFileControl method should use opcodes
1127+** greater than 100 to avoid conflicts. VFS implementations should
1128+** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1129+** recognize.
1130+**
1131+** The xSectorSize() method returns the sector size of the
1132+** device that underlies the file. The sector size is the
1133+** minimum write that can be performed without disturbing
1134+** other bytes in the file. The xDeviceCharacteristics()
1135+** method returns a bit vector describing behaviors of the
1136+** underlying device:
1137+**
1138+** <ul>
1139+** <li> [SQLITE_IOCAP_ATOMIC]
1140+** <li> [SQLITE_IOCAP_ATOMIC512]
1141+** <li> [SQLITE_IOCAP_ATOMIC1K]
1142+** <li> [SQLITE_IOCAP_ATOMIC2K]
1143+** <li> [SQLITE_IOCAP_ATOMIC4K]
1144+** <li> [SQLITE_IOCAP_ATOMIC8K]
1145+** <li> [SQLITE_IOCAP_ATOMIC16K]
1146+** <li> [SQLITE_IOCAP_ATOMIC32K]
1147+** <li> [SQLITE_IOCAP_ATOMIC64K]
1148+** <li> [SQLITE_IOCAP_SAFE_APPEND]
1149+** <li> [SQLITE_IOCAP_SEQUENTIAL]
1150+** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1151+** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1152+** <li> [SQLITE_IOCAP_IMMUTABLE]
1153+** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
1154+** <li> [SQLITE_IOCAP_SUBPAGE_READ]
1155+** </ul>
1156+**
1157+** The SQLITE_IOCAP_ATOMIC property means that all writes of
1158+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1159+** mean that writes of blocks that are nnn bytes in size and
1160+** are aligned to an address which is an integer multiple of
1161+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1162+** that when data is appended to a file, the data is appended
1163+** first then the size of the file is extended, never the other
1164+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1165+** information is written to disk in the same order as calls
1166+** to xWrite().
1167+**
1168+** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1169+** in the unread portions of the buffer with zeros. A VFS that
1170+** fails to zero-fill short reads might seem to work. However,
1171+** failure to zero-fill short reads will eventually lead to
1172+** database corruption.
1173+*/
1174+typedef struct sqlite3_io_methods sqlite3_io_methods;
1175+struct sqlite3_io_methods {
1176+ int iVersion;
1177+ int (*xClose)(sqlite3_file*);
1178+ int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1179+ int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1180+ int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1181+ int (*xSync)(sqlite3_file*, int flags);
1182+ int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1183+ int (*xLock)(sqlite3_file*, int);
1184+ int (*xUnlock)(sqlite3_file*, int);
1185+ int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1186+ int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1187+ int (*xSectorSize)(sqlite3_file*);
1188+ int (*xDeviceCharacteristics)(sqlite3_file*);
1189+ /* Methods above are valid for version 1 */
1190+ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1191+ int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1192+ void (*xShmBarrier)(sqlite3_file*);
1193+ int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1194+ /* Methods above are valid for version 2 */
1195+ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1196+ int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1197+ /* Methods above are valid for version 3 */
1198+ /* Additional methods may be added in future releases */
1199+};
1200+
1201+/*
1202+** CAPI3REF: Standard File Control Opcodes
1203+** KEYWORDS: {file control opcodes} {file control opcode}
1204+**
1205+** These integer constants are opcodes for the xFileControl method
1206+** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1207+** interface.
1208+**
1209+** <ul>
1210+** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1211+** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1212+** opcode causes the xFileControl method to write the current state of
1213+** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1214+** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1215+** into an integer that the pArg argument points to.
1216+** This capability is only available if SQLite is compiled with [SQLITE_DEBUG].
1217+**
1218+** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1219+** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1220+** layer a hint of how large the database file will grow to be during the
1221+** current transaction. This hint is not guaranteed to be accurate but it
1222+** is often close. The underlying VFS might choose to preallocate database
1223+** file space based on this hint in order to help writes to the database
1224+** file run faster.
1225+**
1226+** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
1227+** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1228+** implements [sqlite3_deserialize()] to set an upper bound on the size
1229+** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
1230+** If the integer pointed to is negative, then it is filled in with the
1231+** current limit. Otherwise the limit is set to the larger of the value
1232+** of the integer pointed to and the current database size. The integer
1233+** pointed to is set to the new limit.
1234+**
1235+** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1236+** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1237+** extends and truncates the database file in chunks of a size specified
1238+** by the user. The fourth argument to [sqlite3_file_control()] should
1239+** point to an integer (type int) containing the new chunk-size to use
1240+** for the nominated database. Allocating database file space in large
1241+** chunks (say 1MB at a time), may reduce file-system fragmentation and
1242+** improve performance on some systems.
1243+**
1244+** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1245+** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1246+** to the [sqlite3_file] object associated with a particular database
1247+** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1248+**
1249+** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1250+** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1251+** to the [sqlite3_file] object associated with the journal file (either
1252+** the [rollback journal] or the [write-ahead log]) for a particular database
1253+** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1254+**
1255+** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1256+** The SQLITE_FCNTL_SYNC_OMITTED file-control is no longer used.
1257+**
1258+** <li>[[SQLITE_FCNTL_SYNC]]
1259+** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1260+** sent to the VFS immediately before the xSync method is invoked on a
1261+** database file descriptor. Or, if the xSync method is not invoked
1262+** because the user has configured SQLite with
1263+** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1264+** of the xSync method. In most cases, the pointer argument passed with
1265+** this file-control is NULL. However, if the database file is being synced
1266+** as part of a multi-database commit, the argument points to a nul-terminated
1267+** string containing the transactions super-journal file name. VFSes that
1268+** do not need this signal should silently ignore this opcode. Applications
1269+** should not call [sqlite3_file_control()] with this opcode as doing so may
1270+** disrupt the operation of the specialized VFSes that do require it.
1271+**
1272+** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1273+** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1274+** and sent to the VFS after a transaction has been committed immediately
1275+** but before the database is unlocked. VFSes that do not need this signal
1276+** should silently ignore this opcode. Applications should not call
1277+** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1278+** operation of the specialized VFSes that do require it.
1279+**
1280+** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1281+** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1282+** retry counts and intervals for certain disk I/O operations for the
1283+** windows [VFS] in order to provide robustness in the presence of
1284+** anti-virus programs. By default, the windows VFS will retry file read,
1285+** file write, and file delete operations up to 10 times, with a delay
1286+** of 25 milliseconds before the first retry and with the delay increasing
1287+** by an additional 25 milliseconds with each subsequent retry. This
1288+** opcode allows these two values (10 retries and 25 milliseconds of delay)
1289+** to be adjusted. The values are changed for all database connections
1290+** within the same process. The argument is a pointer to an array of two
1291+** integers where the first integer is the new retry count and the second
1292+** integer is the delay. If either integer is negative, then the setting
1293+** is not changed but instead the prior value of that setting is written
1294+** into the array entry, allowing the current retry settings to be
1295+** interrogated. The zDbName parameter is ignored.
1296+**
1297+** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1298+** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1299+** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1300+** write ahead log ([WAL file]) and shared memory
1301+** files used for transaction control
1302+** are automatically deleted when the latest connection to the database
1303+** closes. Setting persistent WAL mode causes those files to persist after
1304+** close. Persisting the files is useful when other processes that do not
1305+** have write permission on the directory containing the database file want
1306+** to read the database file, as the WAL and shared memory files must exist
1307+** in order for the database to be readable. The fourth parameter to
1308+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1309+** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1310+** WAL mode. If the integer is -1, then it is overwritten with the current
1311+** WAL persistence setting.
1312+**
1313+** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1314+** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1315+** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1316+** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1317+** xDeviceCharacteristics methods. The fourth parameter to
1318+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1319+** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1320+** mode. If the integer is -1, then it is overwritten with the current
1321+** zero-damage mode setting.
1322+**
1323+** <li>[[SQLITE_FCNTL_OVERWRITE]]
1324+** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1325+** a write transaction to indicate that, unless it is rolled back for some
1326+** reason, the entire database file will be overwritten by the current
1327+** transaction. This is used by VACUUM operations.
1328+**
1329+** <li>[[SQLITE_FCNTL_VFSNAME]]
1330+** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1331+** all [VFSes] in the VFS stack. The names of all VFS shims and the
1332+** final bottom-level VFS are written into memory obtained from
1333+** [sqlite3_malloc()] and the result is stored in the char* variable
1334+** that the fourth parameter of [sqlite3_file_control()] points to.
1335+** The caller is responsible for freeing the memory when done. As with
1336+** all file-control actions, there is no guarantee that this will actually
1337+** do anything. Callers should initialize the char* variable to a NULL
1338+** pointer in case this file-control is not implemented. This file-control
1339+** is intended for diagnostic use only.
1340+**
1341+** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1342+** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1343+** [VFSes] currently in use. ^(The argument X in
1344+** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1345+** of type "[sqlite3_vfs] **". This opcode will set *X
1346+** to a pointer to the top-level VFS.)^
1347+** ^When there are multiple VFS shims in the stack, this opcode finds the
1348+** upper-most shim only.
1349+**
1350+** <li>[[SQLITE_FCNTL_PRAGMA]]
1351+** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1352+** file control is sent to the open [sqlite3_file] object corresponding
1353+** to the database file to which the pragma statement refers. ^The argument
1354+** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1355+** pointers to strings (char**) in which the second element of the array
1356+** is the name of the pragma and the third element is the argument to the
1357+** pragma or NULL if the pragma has no argument. ^The handler for an
1358+** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1359+** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1360+** or the equivalent and that string will become the result of the pragma or
1361+** the error message if the pragma fails. ^If the
1362+** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1363+** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1364+** file control returns [SQLITE_OK], then the parser assumes that the
1365+** VFS has handled the PRAGMA itself and the parser generates a no-op
1366+** prepared statement if result string is NULL, or that returns a copy
1367+** of the result string if the string is non-NULL.
1368+** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1369+** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1370+** that the VFS encountered an error while handling the [PRAGMA] and the
1371+** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1372+** file control occurs at the beginning of pragma statement analysis and so
1373+** it is able to override built-in [PRAGMA] statements.
1374+**
1375+** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1376+** ^The [SQLITE_FCNTL_BUSYHANDLER]
1377+** file-control may be invoked by SQLite on the database file handle
1378+** shortly after it is opened in order to provide a custom VFS with access
1379+** to the connection's busy-handler callback. The argument is of type (void**)
1380+** - an array of two (void *) values. The first (void *) actually points
1381+** to a function of type (int (*)(void *)). In order to invoke the connection's
1382+** busy-handler, this function should be invoked with the second (void *) in
1383+** the array as the only argument. If it returns non-zero, then the operation
1384+** should be retried. If it returns zero, the custom VFS should abandon the
1385+** current operation.
1386+**
1387+** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1388+** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1389+** to have SQLite generate a
1390+** temporary filename using the same algorithm that is followed to generate
1391+** temporary filenames for TEMP tables and other internal uses. The
1392+** argument should be a char** which will be filled with the filename
1393+** written into memory obtained from [sqlite3_malloc()]. The caller should
1394+** invoke [sqlite3_free()] on the result to avoid a memory leak.
1395+**
1396+** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1397+** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1398+** maximum number of bytes that will be used for memory-mapped I/O.
1399+** The argument is a pointer to a value of type sqlite3_int64 that
1400+** is an advisory maximum number of bytes in the file to memory map. The
1401+** pointer is overwritten with the old value. The limit is not changed if
1402+** the value originally pointed to is negative, and so the current limit
1403+** can be queried by passing in a pointer to a negative number. This
1404+** file-control is used internally to implement [PRAGMA mmap_size].
1405+**
1406+** <li>[[SQLITE_FCNTL_TRACE]]
1407+** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1408+** to the VFS about what the higher layers of the SQLite stack are doing.
1409+** This file control is used by some VFS activity tracing [shims].
1410+** The argument is a zero-terminated string. Higher layers in the
1411+** SQLite stack may generate instances of this file control if
1412+** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1413+**
1414+** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1415+** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1416+** pointer to an integer and it writes a boolean into that integer depending
1417+** on whether or not the file has been renamed, moved, or deleted since it
1418+** was first opened.
1419+**
1420+** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1421+** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1422+** underlying native file handle associated with a file handle. This file
1423+** control interprets its argument as a pointer to a native file handle and
1424+** writes the resulting value there.
1425+**
1426+** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1427+** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1428+** opcode causes the xFileControl method to swap the file handle with the one
1429+** pointed to by the pArg argument. This capability is used during testing
1430+** and only needs to be supported when SQLITE_TEST is defined.
1431+**
1432+** <li>[[SQLITE_FCNTL_NULL_IO]]
1433+** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor
1434+** or file handle for the [sqlite3_file] object such that it will no longer
1435+** read or write to the database file.
1436+**
1437+** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1438+** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1439+** be advantageous to block on the next WAL lock if the lock is not immediately
1440+** available. The WAL subsystem issues this signal during rare
1441+** circumstances in order to fix a problem with priority inversion.
1442+** Applications should <em>not</em> use this file-control.
1443+**
1444+** <li>[[SQLITE_FCNTL_ZIPVFS]]
1445+** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1446+** VFS should return SQLITE_NOTFOUND for this opcode.
1447+**
1448+** <li>[[SQLITE_FCNTL_RBU]]
1449+** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1450+** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1451+** this opcode.
1452+**
1453+** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
1454+** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
1455+** the file descriptor is placed in "batch write mode", which
1456+** means all subsequent write operations will be deferred and done
1457+** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
1458+** that do not support batch atomic writes will return SQLITE_NOTFOUND.
1459+** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
1460+** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
1461+** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
1462+** no VFS interface calls on the same [sqlite3_file] file descriptor
1463+** except for calls to the xWrite method and the xFileControl method
1464+** with [SQLITE_FCNTL_SIZE_HINT].
1465+**
1466+** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
1467+** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
1468+** operations since the previous successful call to
1469+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
1470+** This file control returns [SQLITE_OK] if and only if the writes were
1471+** all performed successfully and have been committed to persistent storage.
1472+** ^Regardless of whether or not it is successful, this file control takes
1473+** the file descriptor out of batch write mode so that all subsequent
1474+** write operations are independent.
1475+** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
1476+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1477+**
1478+** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
1479+** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
1480+** operations since the previous successful call to
1481+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
1482+** ^This file control takes the file descriptor out of batch write mode
1483+** so that all subsequent write operations are independent.
1484+** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
1485+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1486+**
1487+** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
1488+** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
1489+** to block for up to M milliseconds before failing when attempting to
1490+** obtain a file lock using the xLock or xShmLock methods of the VFS.
1491+** The parameter is a pointer to a 32-bit signed integer that contains
1492+** the value that M is to be set to. Before returning, the 32-bit signed
1493+** integer is overwritten with the previous value of M.
1494+**
1495+** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]]
1496+** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the
1497+** VFS to block when taking a SHARED lock to connect to a wal mode database.
1498+** This is used to implement the functionality associated with
1499+** SQLITE_SETLK_BLOCK_ON_CONNECT.
1500+**
1501+** <li>[[SQLITE_FCNTL_DATA_VERSION]]
1502+** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
1503+** a database file. The argument is a pointer to a 32-bit unsigned integer.
1504+** The "data version" for the pager is written into the pointer. The
1505+** "data version" changes whenever any change occurs to the corresponding
1506+** database file, either through SQL statements on the same database
1507+** connection or through transactions committed by separate database
1508+** connections possibly in other processes. The [sqlite3_total_changes()]
1509+** interface can be used to find if any database on the connection has changed,
1510+** but that interface responds to changes on TEMP as well as MAIN and does
1511+** not provide a mechanism to detect changes to MAIN only. Also, the
1512+** [sqlite3_total_changes()] interface responds to internal changes only and
1513+** omits changes made by other database connections. The
1514+** [PRAGMA data_version] command provides a mechanism to detect changes to
1515+** a single attached database that occur due to other database connections,
1516+** but omits changes implemented by the database connection on which it is
1517+** called. This file control is the only mechanism to detect changes that
1518+** happen either internally or externally and that are associated with
1519+** a particular attached database.
1520+**
1521+** <li>[[SQLITE_FCNTL_CKPT_START]]
1522+** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
1523+** in wal mode before the client starts to copy pages from the wal
1524+** file to the database file.
1525+**
1526+** <li>[[SQLITE_FCNTL_CKPT_DONE]]
1527+** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
1528+** in wal mode after the client has finished copying pages from the wal
1529+** file to the database file, but before the *-shm file is updated to
1530+** record the fact that the pages have been checkpointed.
1531+**
1532+** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
1533+** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
1534+** whether or not there is a database client in another process with a wal-mode
1535+** transaction open on the database or not. It is only available on unix. The
1536+** (void*) argument passed with this file-control should be a pointer to a
1537+** value of type (int). The integer value is set to 1 if the database is a wal
1538+** mode database and there exists at least one client in another process that
1539+** currently has an SQL transaction open on the database. It is set to 0 if
1540+** the database is not a wal-mode db, or if there is no such connection in any
1541+** other process. This opcode cannot be used to detect transactions opened
1542+** by clients within the current process, only within other processes.
1543+**
1544+** <li>[[SQLITE_FCNTL_CKSM_FILE]]
1545+** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the
1546+** [checksum VFS shim] only.
1547+**
1548+** <li>[[SQLITE_FCNTL_RESET_CACHE]]
1549+** If there is currently no transaction open on the database, and the
1550+** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control
1551+** purges the contents of the in-memory page cache. If there is an open
1552+** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.
1553+**
1554+** <li>[[SQLITE_FCNTL_FILESTAT]]
1555+** The [SQLITE_FCNTL_FILESTAT] opcode returns low-level diagnostic information
1556+** about the [sqlite3_file] objects used access the database and journal files
1557+** for the given schema. The fourth parameter to [sqlite3_file_control()]
1558+** should be an initialized [sqlite3_str] pointer. JSON text describing
1559+** various aspects of the sqlite3_file object is appended to the sqlite3_str.
1560+** The SQLITE_FCNTL_FILESTAT opcode is usually a no-op, unless compile-time
1561+** options are used to enable it.
1562+** </ul>
1563+*/
1564+#define SQLITE_FCNTL_LOCKSTATE 1
1565+#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1566+#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1567+#define SQLITE_FCNTL_LAST_ERRNO 4
1568+#define SQLITE_FCNTL_SIZE_HINT 5
1569+#define SQLITE_FCNTL_CHUNK_SIZE 6
1570+#define SQLITE_FCNTL_FILE_POINTER 7
1571+#define SQLITE_FCNTL_SYNC_OMITTED 8
1572+#define SQLITE_FCNTL_WIN32_AV_RETRY 9
1573+#define SQLITE_FCNTL_PERSIST_WAL 10
1574+#define SQLITE_FCNTL_OVERWRITE 11
1575+#define SQLITE_FCNTL_VFSNAME 12
1576+#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1577+#define SQLITE_FCNTL_PRAGMA 14
1578+#define SQLITE_FCNTL_BUSYHANDLER 15
1579+#define SQLITE_FCNTL_TEMPFILENAME 16
1580+#define SQLITE_FCNTL_MMAP_SIZE 18
1581+#define SQLITE_FCNTL_TRACE 19
1582+#define SQLITE_FCNTL_HAS_MOVED 20
1583+#define SQLITE_FCNTL_SYNC 21
1584+#define SQLITE_FCNTL_COMMIT_PHASETWO 22
1585+#define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1586+#define SQLITE_FCNTL_WAL_BLOCK 24
1587+#define SQLITE_FCNTL_ZIPVFS 25
1588+#define SQLITE_FCNTL_RBU 26
1589+#define SQLITE_FCNTL_VFS_POINTER 27
1590+#define SQLITE_FCNTL_JOURNAL_POINTER 28
1591+#define SQLITE_FCNTL_WIN32_GET_HANDLE 29
1592+#define SQLITE_FCNTL_PDB 30
1593+#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
1594+#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
1595+#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
1596+#define SQLITE_FCNTL_LOCK_TIMEOUT 34
1597+#define SQLITE_FCNTL_DATA_VERSION 35
1598+#define SQLITE_FCNTL_SIZE_LIMIT 36
1599+#define SQLITE_FCNTL_CKPT_DONE 37
1600+#define SQLITE_FCNTL_RESERVE_BYTES 38
1601+#define SQLITE_FCNTL_CKPT_START 39
1602+#define SQLITE_FCNTL_EXTERNAL_READER 40
1603+#define SQLITE_FCNTL_CKSM_FILE 41
1604+#define SQLITE_FCNTL_RESET_CACHE 42
1605+#define SQLITE_FCNTL_NULL_IO 43
1606+#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44
1607+#define SQLITE_FCNTL_FILESTAT 45
1608+
1609+/* deprecated names */
1610+#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1611+#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1612+#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1613+
1614+/* reserved file-control numbers:
1615+** 101
1616+** 102
1617+** 103
1618+*/
1619+
1620+
1621+/*
1622+** CAPI3REF: Mutex Handle
1623+**
1624+** The mutex module within SQLite defines [sqlite3_mutex] to be an
1625+** abstract type for a mutex object. The SQLite core never looks
1626+** at the internal representation of an [sqlite3_mutex]. It only
1627+** deals with pointers to the [sqlite3_mutex] object.
1628+**
1629+** Mutexes are created using [sqlite3_mutex_alloc()].
1630+*/
1631+typedef struct sqlite3_mutex sqlite3_mutex;
1632+
1633+/*
1634+** CAPI3REF: Loadable Extension Thunk
1635+**
1636+** A pointer to the opaque sqlite3_api_routines structure is passed as
1637+** the third parameter to entry points of [loadable extensions]. This
1638+** structure must be typedefed in order to work around compiler warnings
1639+** on some platforms.
1640+*/
1641+typedef struct sqlite3_api_routines sqlite3_api_routines;
1642+
1643+/*
1644+** CAPI3REF: File Name
1645+**
1646+** Type [sqlite3_filename] is used by SQLite to pass filenames to the
1647+** xOpen method of a [VFS]. It may be cast to (const char*) and treated
1648+** as a normal, nul-terminated, UTF-8 buffer containing the filename, but
1649+** may also be passed to special APIs such as:
1650+**
1651+** <ul>
1652+** <li> sqlite3_filename_database()
1653+** <li> sqlite3_filename_journal()
1654+** <li> sqlite3_filename_wal()
1655+** <li> sqlite3_uri_parameter()
1656+** <li> sqlite3_uri_boolean()
1657+** <li> sqlite3_uri_int64()
1658+** <li> sqlite3_uri_key()
1659+** </ul>
1660+*/
1661+typedef const char *sqlite3_filename;
1662+
1663+/*
1664+** CAPI3REF: OS Interface Object
1665+**
1666+** An instance of the sqlite3_vfs object defines the interface between
1667+** the SQLite core and the underlying operating system. The "vfs"
1668+** in the name of the object stands for "virtual file system". See
1669+** the [VFS | VFS documentation] for further information.
1670+**
1671+** The VFS interface is sometimes extended by adding new methods onto
1672+** the end. Each time such an extension occurs, the iVersion field
1673+** is incremented. The iVersion value started out as 1 in
1674+** SQLite [version 3.5.0] on [dateof:3.
.gitignore+12−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..e94beb9index 0000000..e94beb9
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,12 @@@@ -0,0 +1,12 @@
1+/plugin_sqlite
2+/plugin_sqlite.exe
3+/plugin_sqlite.musl
4+/plugin_sqlite.arm64
5+/plugin_sqlite.macos-*
6+*.o
7+*.obj
8+bin/
9+*.tmp
10+*.log
11+__pycache__/
12+*.pyc
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+84−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..f8af03dindex 0000000..f8af03d
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,84 @@@@ -0,0 +1,84 @@
1+# plugin_sqlite - ScorpioX Bot open-source read-only SQLite explorer plugin
2+#
3+# Targets:
4+# make native build -> ./plugin_sqlite
5+# make musl static musl x86_64 -> ./plugin_sqlite.musl
6+# make arm64 static aarch64 -> ./plugin_sqlite.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_sqlite.exe
8+# make macos Apple clang -> ./plugin_sqlite (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+#
12+# The public-domain SQLite amalgamation (vendor/sqlite3.c) is compiled into the
13+# binary, so no target needs a sqlite3 CLI, libsqlite3.so or sqlite3.dll.
14+
15+CC ?= cc
16+CFLAGS ?= -O2 -std=c99 -Wall -Wextra
17+MUSL_CC ?= musl-gcc
18+ARM64_CC ?= $(shell command -v aarch64-linux-musl-gcc 2>/dev/null || \
19+ command -v aarch64-linux-gnu-gcc 2>/dev/null || \
20+ echo aarch64-linux-musl-gcc)
21+WIN_CC ?= x86_64-w64-mingw32-gcc
22+
23+# Read-only, dependency-free SQLite build flags.
24+SQLITE_DEFS := -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0 \
25+ -DSQLITE_OMIT_DEPRECATED -DSQLITE_DQS=0 \
26+ -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_OMIT_SHARED_CACHE \
27+ -DSQLITE_MAX_ATTACHED=0
28+
29+# The amalgamation is huge and single-threaded; -O1 for it keeps builds
30+# minutes-to-seconds without measurably slowing an I/O bound browser.
31+SQLITE_OPT := -O1
32+
33+SRC := src/plugin_sqlite.c
34+AMALG := vendor/sqlite3.c
35+INC := -Isrc -Ivendor
36+BIN := plugin_sqlite
37+EXE := plugin_sqlite.exe
38+
39+.PHONY: all native musl arm64 win64 macos test clean help
40+
41+all: native
42+
43+native: $(BIN)
44+
45+$(BIN): $(SRC) $(AMALG)
46+ @echo "==> native build ($(CC))"
47+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -c $(AMALG) -o sqlite3.o $(SQLITE_OPT)
48+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -o $(BIN) $(SRC) sqlite3.o
49+
50+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
51+musl: $(SRC) $(AMALG)
52+ @echo "==> static musl build ($(MUSL_CC))"
53+ $(MUSL_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -c $(AMALG) -o sqlite3.musl.o $(SQLITE_OPT)
54+ $(MUSL_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -o $(BIN).musl $(SRC) sqlite3.musl.o
55+
56+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
57+arm64: $(SRC) $(AMALG)
58+ @echo "==> static arm64 build ($(ARM64_CC))"
59+ $(ARM64_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -c $(AMALG) -o sqlite3.arm64.o $(SQLITE_OPT)
60+ $(ARM64_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -o $(BIN).arm64 $(SRC) sqlite3.arm64.o
61+
62+# Native Win64 static PE - runs on any Windows 10/11 x64 node
63+win64: $(SRC) $(AMALG)
64+ @echo "==> MinGW-w64 build ($(WIN_CC))"
65+ $(WIN_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -c $(AMALG) -o sqlite3.win.o $(SQLITE_OPT)
66+ $(WIN_CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -static -o $(EXE) $(SRC) sqlite3.win.o
67+
68+# Apple clang build (run this on macOS)
69+macos: $(SRC) $(AMALG)
70+ @echo "==> Apple clang build"
71+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -c $(AMALG) -o sqlite3.o $(SQLITE_OPT)
72+ $(CC) $(CFLAGS) $(SQLITE_DEFS) $(INC) -o $(BIN) $(SRC) sqlite3.o
73+
74+test: native
75+ @sh tests/run.sh
76+
77+clean:
78+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \
79+ $(BIN).macos-arm64 $(BIN).macos-x86_64 \
80+ *.o bin -r
81+ rm -rf bin
82+
83+help:
84+ @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean"
README.md+154−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ac42d83index 0000000..ac42d83
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,154 @@@@ -0,0 +1,154 @@
1+# plugin_sqlite — read-only SQLite explorer for ScorpioX Bot
2+
3+A clean-room, **strictly read-only** local SQLite schema and query browser, written in pure C99.
4+One binary, three modes: discovery metadata, a JSON node API, and a responsive HTML tool UI.
5+
6+The public-domain SQLite amalgamation (`vendor/sqlite3.c`, 3.53.4) is compiled **into** the
7+binary, so nothing needs a `sqlite3` CLI, `libsqlite3.so` or `sqlite3.dll` on the node.
8+
9+| | |
10+|---|---|
11+| slug | `sqlite` |
12+| executable | `plugin_sqlite` (`plugin_sqlite.exe` on Windows) |
13+| metadata | `{"name":"sqlite","desc":"SQLite viewer"}` |
14+| category | `devtools` |
15+| license | MIT (SQLite itself is public domain) |
16+
17+## What it does
18+
19+* Discovers `.db` / `.db3` / `.sqlite` / `.sqlite3` files under `/workspace`, `/codebases`,
20+ `$HOME` and `$SQLITE_ALLOWED_ROOT` (depth 4, 60 000 entries, symlinked directories never
21+ followed).
22+* Shows tables and views with row counts, columns (type / NOT NULL / primary key) and indexes
23+ (unique or not).
24+* Runs `SELECT` / `WITH` / read-only `PRAGMA` / `EXPLAIN` statements and streams typed rows as
25+ JSON: integers and reals as JSON numbers, text as strings, `NULL` as `null`, and BLOBs as a
26+ bounded `{"blob_bytes":N,"hex":"..."}` preview.
27+* Renders an HTML explorer: database picker, sidebar table list, SQL editor (`Ctrl`+`Enter` to
28+ run), sortable result grid, CSV and JSON copy, dark and light themes, `?embed=1` aware.
29+
30+## Read-only by construction
31+
32+Two independent mechanisms, because a single one is a promise and two are a design:
33+
34+1. **`SQLITE_OPEN_READONLY`** on every `sqlite3_open_v2()`, plus `SQLITE_LIMIT_ATTACHED = 0`.
35+2. **`sqlite3_set_authorizer()`** that answers `SQLITE_OK` only for `SQLITE_SELECT`,
36+ `SQLITE_READ`, `SQLITE_RECURSIVE`, `SQLITE_FUNCTION`, and a whitelist of read-only PRAGMAs
37+ (`table_info`, `index_list`, `foreign_key_list`, `page_count`, `integrity_check`, ...).
38+ Everything else — `INSERT`, `UPDATE`, `DELETE`, `CREATE`, `DROP`, `ALTER`, `ATTACH`, `DETACH`,
39+ `TRANSACTION`, `REINDEX`, `VACUUM`, and settable pragmas such as `journal_mode=...` — is
40+ `SQLITE_DENY`, which the engine enforces at prepare time.
41+
42+On top of that:
43+
44+* The statement must start with `select`, `with`, `pragma`, `explain` or `values` (friendly
45+ errors rather than a bare "not authorized"), and stacked statements are rejected.
46+* Result rows are capped at **500** (`truncated: true` when the cap bites).
47+* A `sqlite3_progress_handler` aborts any statement that runs past **~2 s**
48+ (`aborted: true`, partial rows kept).
49+
50+## Path discipline
51+
52+Only regular files with a database suffix, resolved through `realpath()`, inside one of the
53+allowlisted roots are opened. Rejected outright: any `..` segment, `file:`-prefixed SQLite URI
54+filenames, `://` schemes, query strings and fragments, non-database suffixes, symlinks pointing
55+out of a root, and system paths such as `/etc/passwd`. An allowlisted-but-absent file answers
56+`not_found`, which is a different error from `forbidden_path` on purpose — the UI can tell "you
57+looked in the wrong place" from "you are not allowed there".
58+
59+Test the policy yourself:
60+
61+```
62+curl -s -G 'http://127.0.0.1:8150/plugin_sqlite' -H 'X-Bot-Password: <pwd>' \
63+ --data-urlencode 'action=query' --data-urlencode 'db=/etc/passwd' --data-urlencode 'sql=select 1'
64+# {"ok":false,"error":"forbidden_path",...}
65+```
66+
67+## API
68+
69+All routes answer `application/json; charset=utf-8` unless noted. Everything except `--meta`
70+requires the node password (`X-Bot-Password`, `Authorization: Bearer`, or `?pwd=`; unset
71+`BOT_PASSWORD` disables the check, which is how you run it from a shell).
72+
73+| Route | Answer |
74+|---|---|
75+| `?action=dbs` | `{ok, roots:[{label,path,exists}], count, dbs:[{path,root,bytes,mtime}]}` |
76+| `?action=schema&db=<path>` | `{ok, db, tables:[{name,type,rows,columns:[{name,type,notnull,pk}],indexes:[{name,unique}]}], table_count}` |
77+| `?action=query&db=<path>&sql=<SELECT ...>` | `{ok, db, columns:[{name,decl}], rows:[[...]], row_count, truncated, limit, ms, aborted, types}` |
78+| `?action=info` | plugin id, version, bundled SQLite version, platform, limits |
79+| `?format=json` | falls back to `action=dbs` |
80+| `GET` (no action) | HTML explorer, honours `?embed=1` |
81+
82+`query` also accepts `POST` with a `sql=...` body: the caller is expected to hand the urlencoded
83+body through the `HTTP_BODY_FILE` environment variable (the form `scorpiox-server` uses). A bare
84+body is treated as the statement itself.
85+
86+Rows: text is a JSON string, integer/real are JSON numbers, `NULL` is `null`, BLOB is
87+`{"blob_bytes":N,"hex":"..."}` with the hex preview truncated after 48 bytes.
88+
89+## Build
90+
91+```sh
92+make # native (glibc) -> ./plugin_sqlite
93+make musl # static musl x86_64 -> ./plugin_sqlite.musl
94+make arm64 # static aarch64 -> ./plugin_sqlite.arm64
95+make win64 # MinGW-w64 static PE -> ./plugin_sqlite.exe
96+make macos # Apple clang (on macOS) -> ./plugin_sqlite
97+make test # run tests/run.sh
98+```
99+
100+Windows without a cross toolchain: `powershell -ExecutionPolicy Bypass -File build.ps1`.
101+
102+The SQLite amalgamation compiles at `-O1` (roughly 10 s on a laptop, about a minute on a Windows
103+box). Bumping the engine to `-O2` changes nothing measurable for an I/O-bound 500-row browser.
104+
105+## Tests
106+
107+`tests/run.sh` builds a throwaway database, points the plugin at it with `SQLITE_ALLOWED_ROOT`,
108+and runs 120+ assertions:
109+
110+* `--meta` shape (single-word name, at most 15-char description, compact, valid JSON)
111+* node auth: 401 without credentials, `X-Bot-Password` / `Bearer` / `?pwd=` accepted, wrong
112+ password refused, HTML route gated too
113+* discovery, schema (tables, views, indexes, row counts, column detail) and queries
114+* typed values: integers, reals, text, JSON `null`, BLOB hex preview
115+* read-only: 15 rejected mutations (INSERT/UPDATE/DELETE/DROP/ALTER/CREATE TABLE/CREATE VIEW/
116+ ATTACH/DETACH/REINDEX/VACUUM/BEGIN/settable PRAGMA/stacked statement/WITH-DELETE) plus proof
117+ the file on disk did not change and no ATTACH file appeared
118+* path discipline: `/etc/passwd`, `..` traversal, `file:` URIs, `://` schemes, non-db suffixes
119+* the 500-row cap and the ~2 s statement budget
120+* the HTML UI (no CDN scripts, no `Content-Length`, embed behaviour)
121+* artifact checks when the musl / arm64 / Win64 builds are present (ELF magic, `e_machine`,
122+ static-link proof, `MZ` header)
123+* a full git-history audit for LAN IPs, tokens and private keys
124+
125+## Install on a node
126+
127+```sh
128+cp plugin_sqlite ~/.scorpiox/plugins/ && chmod +x ~/.scorpiox/plugins/plugin_sqlite
129+curl -s -H 'X-Bot-Password: <pwd>' 'http://127.0.0.1:8150/plugin_sqlite?action=info'
130+```
131+
132+Discovery is automatic — no server restart. On Windows the plugin directory is
133+`%LOCALAPPDATA%\scorpiox\plugins\`.
134+
135+## Source-first
136+
137+```
138+git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-sqlite.git
139+```
140+
141+Audit `src/plugin_sqlite.c`, change the allowlisted roots or the row cap for your setup, and
142+compile it yourself — it is one C file plus the vendored amalgamation and libc.
143+
144+## Layout
145+
146+```
147+src/plugin_sqlite.c the whole plugin (3 modes, path gate, authorizer, HTML UI)
148+vendor/sqlite3.{c,h} public-domain SQLite 3.53.4 amalgamation
149+tests/run.sh 120+ offline assertions
150+Makefile native / musl / arm64 / win64 / macos / test / clean
151+build.ps1 Windows MinGW static build
152+release-dist.sh build all targets, package, publish, mirror
153+plugin.json marketplace metadata
154+```
build.ps1+72−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..a04d0b0index 0000000..a04d0b0
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,72 @@@@ -0,0 +1,72 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_sqlite
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_sqlite.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+# No extra Win32 import libraries are needed: the SQLite amalgamation is
9+# compiled in and the plugin talks to no socket.
10+#
11+# The SQLite amalgamation is a ~9 MB single translation unit; compiling it at
12+# -O1 keeps the build near a minute on a laptop while the plugin itself is I/O
13+# bound, so -O2 in the engine buys nothing anybody can measure.
14+
15+$ErrorActionPreference = "Stop"
16+$ScriptDir = $PSScriptRoot
17+Push-Location $ScriptDir
18+try {
19+ $Src = Join-Path $ScriptDir "src\plugin_sqlite.c"
20+ $Amalg = Join-Path $ScriptDir "vendor\sqlite3.c"
21+ $Out = Join-Path $ScriptDir "plugin_sqlite.exe"
22+ $Cc = "x86_64-w64-mingw32-gcc"
23+
24+ foreach ($p in @($Src, $Amalg)) {
25+ if (-not (Test-Path $p)) { throw "source not found: $p" }
26+ }
27+
28+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
29+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
30+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
31+ $Cc = "C:\gcc16\bin\gcc.exe"
32+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
33+ $Cc = "gcc"
34+ } else {
35+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
36+ }
37+ }
38+
39+ $Defs = @("-DSQLITE_OMIT_LOAD_EXTENSION", "-DSQLITE_THREADSAFE=0",
40+ "-DSQLITE_OMIT_DEPRECATED", "-DSQLITE_DQS=0",
41+ "-DSQLITE_DEFAULT_MEMSTATUS=0", "-DSQLITE_OMIT_SHARED_CACHE",
42+ "-DSQLITE_MAX_ATTACHED=0")
43+
44+ Write-Host "==> compiling the SQLite amalgamation (this takes a minute)"
45+ & $Cc -O1 -std=c99 -Ivendor @Defs -static -c $Amalg -o sqlite3.win.o
46+ if ($LASTEXITCODE -ne 0) { throw "amalgamation compile failed (exit $LASTEXITCODE)" }
47+
48+ Write-Host "==> building plugin_sqlite.exe with $Cc"
49+ & $Cc -O2 -std=c99 -Wall -Wextra -Isrc -Ivendor @Defs -static `
50+ -o $Out $Src sqlite3.win.o
51+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
52+
53+ if (-not (Test-Path $Out)) { throw "build produced no output" }
54+
55+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
56+ $bytes = [System.IO.File]::ReadAllBytes($Out)
57+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
58+ throw "output is not a PE executable (missing MZ header)"
59+ }
60+
61+ Write-Host "==> metadata check"
62+ & $Out --meta
63+ if ($LASTEXITCODE -ne 0) { throw "--meta failed" }
64+
65+ $size = (Get-Item $Out).Length
66+ Write-Host ""
67+ Write-Host "Built $Out ($size bytes)"
68+ Write-Host "Install: Copy-Item plugin_sqlite.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`""
69+}
70+finally {
71+ Pop-Location
72+}
plugin.json+10−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ce389d0index 0000000..ce389d0
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,10 @@@@ -0,0 +1,10 @@
1+{
2+ "slug": "sqlite",
3+ "id": "plugin_sqlite",
4+ "title": "SQLite Explorer",
5+ "summary": "Zero-dependency, strictly read-only SQLite browser: discovers .db/.sqlite files under your workspace and home, shows tables, columns, indexes and row counts, and runs capped SELECT queries with a sortable result grid - the SQLite engine is compiled into the binary so no sqlite3 CLI, libsqlite3.so or sqlite3.dll is needed.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_read", "sqlite_readonly_open", "bounded_directory_walk"],
9+ "trust_notice": "Executes native C code on your node. Opens databases with SQLITE_OPEN_READONLY and installs an authorizer that permits only SELECT, READ, FUNCTION and read-only PRAGMA statements, so INSERT/UPDATE/DELETE/DROP/ALTER/ATTACH/CREATE are refused by the engine. Only .db/.sqlite/.sqlite3 files under /workspace, /codebases, $HOME or $SQLITE_ALLOWED_ROOT are browsable; results are capped at 500 rows and about 2 seconds per statement. Makes zero outbound network requests and opens no sockets."
10+}
release-dist.sh+385−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..99d851eindex 0000000..99d851e
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,385 @@@@ -0,0 +1,385 @@
1+#!/usr/bin/env bash
2+# release-dist.sh — build, scan and publish plugin_disks to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+
27+set -euo pipefail
28+
29+SLUG="sqlite"
30+ID="plugin_sqlite"
31+VERSION="1.0.0"
32+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
33+
34+# Compile flags for the vendored SQLite amalgamation.
35+SQLITE_DEFS="-DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_DEPRECATED -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_OMIT_SHARED_CACHE -DSQLITE_MAX_ATTACHED=0"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --dry-run) DRY_RUN=1 ;;
47+ --no-macos) DO_MACOS=0 ;;
48+ --no-mirror) DO_MIRROR=0 ;;
49+ --standalone) STANDALONE=1 ;;
50+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline (dist + plugingit mirror)"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition — otherwise this file's own detector patterns read as
90+# findings in every historical revision of it.
91+git log -p --all 2>/dev/null \
92+ | grep -v '^Author: ' \
93+ | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
94+ > "$SCAN_TMP" || : > "$SCAN_TMP"
95+HITS=0
96+scan() { # scan <label> <regex>
97+ local out
98+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
99+ if [ -n "$out" ]; then
100+ printf ' \033[31mHIT\033[0m %s\n' "$1"
101+ printf '%s\n' "$out" | sed 's/^/ /'
102+ HITS=$((HITS + 1))
103+ else
104+ printf ' ok %s\n' "$1"
105+ fi
106+}
107+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
108+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
109+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
110+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
111+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
112+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
113+scan "hard-coded ssh password" 'sshpass -p [^"$]'
114+P_ROOT="/codebases"
115+P_PICOBOT="${P_ROOT}/pico""bot"
116+P_WT=".work""trees"
117+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
118+scan "run-token env assignment" 'RUNNER_'"PASS="
119+if [ "$HITS" -ne 0 ]; then
120+ die "secret scan found $HITS problem(s) — refusing to publish"
121+fi
122+echo " clean: 0 hits"
123+
124+# ---------------------------------------------------------------- 2. build
125+say "2/7 build targets"
126+
127+build_ok() { [ -f "$1" ]; }
128+
129+# linux-x86_64 (glibc, native)
130+if command -v cc >/dev/null 2>&1; then
131+ cc -O1 -std=c99 -Wall -Wextra $SQLITE_DEFS -Ivendor -c vendor/sqlite3.c -o "$STAGE/sqlite3.o" \
132+ || die "amalgamation build failed"
133+ cc -O2 -std=c99 -Wall -Wextra $SQLITE_DEFS -Isrc -Ivendor -o "$STAGE/$ID" src/$ID.c "$STAGE/sqlite3.o" \
134+ || die "native build failed"
135+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
136+else
137+ die "no native cc found"
138+fi
139+
140+# linux-x86_64-musl (fully static — the universal Linux artifact)
141+if command -v musl-gcc >/dev/null 2>&1; then
142+ musl-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor -c vendor/sqlite3.c \
143+ -o "$STAGE/sqlite3.musl.o" || die "musl amalgamation build failed"
144+ musl-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
145+ -o "$STAGE/$ID.musl" src/$ID.c "$STAGE/sqlite3.musl.o" || die "musl build failed"
146+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
147+else
148+ echo " skip linux-x86_64-musl (no musl-gcc)"
149+fi
150+
151+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers).
152+# Prefer musl; on a host that only has the Debian cross toolchain the static
153+# glibc link still yields a self-contained aarch64 ELF.
154+if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then
155+ aarch64-linux-musl-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor \
156+ -c vendor/sqlite3.c -o "$STAGE/sqlite3.arm64.o" || die "arm64 musl amalgamation failed"
157+ aarch64-linux-musl-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
158+ -o "$STAGE/$ID.arm64" src/$ID.c "$STAGE/sqlite3.arm64.o" || die "arm64 musl build failed"
159+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
160+elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
161+ aarch64-linux-gnu-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor \
162+ -c vendor/sqlite3.c -o "$STAGE/sqlite3.arm64.o" || die "arm64 amalgamation failed"
163+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
164+ -o "$STAGE/$ID.arm64" src/$ID.c "$STAGE/sqlite3.arm64.o" || die "arm64 static build failed"
165+ echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
166+else
167+ echo " skip linux-arm64-musl (no aarch64 cross compiler)"
168+fi
169+
170+# windows-x86_64 (static PE)
171+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
172+ x86_64-w64-mingw32-gcc -O1 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Ivendor \
173+ -c vendor/sqlite3.c -o "$STAGE/sqlite3.win.o" || die "MinGW amalgamation build failed"
174+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static $SQLITE_DEFS -Isrc -Ivendor \
175+ -o "$STAGE/$ID.exe" src/$ID.c "$STAGE/sqlite3.win.o" || die "MinGW build failed"
176+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
177+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
178+else
179+ echo " skip windows-x86_64 (no MinGW cross compiler)"
180+fi
181+
182+# macOS legs — Mach-O must be produced by Apple clang on a real Mac.
183+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
184+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
185+ MAC_USER="${MAC_USER:-$(whoami)}"
186+ MAC_DIR="/tmp/${ID}-mac-$$"
187+ echo " building macOS legs on $MAC_HOST"
188+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
189+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
190+ if [ -n "${MAC_PASS:-}" ]; then
191+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
192+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
193+ fi
194+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
195+ if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c" &&
196+ "${SCP_MAC[@]}" vendor/sqlite3.c vendor/sqlite3.h "$MAC_USER@$MAC_HOST:$MAC_DIR/"; then
197+ # Build straight from the uploaded file — no src/ tree on the remote.
198+ for slice in arm64 x86_64; do
199+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
200+ "cd '$MAC_DIR' && clang -O1 -std=c99 $SQLITE_DEFS -c sqlite3.c -o sqlite3.o && clang -O2 -std=c99 -Wall -Wextra -arch $slice $SQLITE_DEFS -o $ID.$slice $ID.c sqlite3.o" \
201+ 2>/dev/null; then
202+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
203+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
204+ else
205+ echo " warn: macos-$slice build failed on $MAC_HOST"
206+ fi
207+ done
208+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true
209+ else
210+ echo " warn: mac scp failed"
211+ fi
212+ else
213+ echo " warn: mac host unreachable"
214+ fi
215+else
216+ echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)"
217+fi
218+
219+# ---------------------------------------------------------------- 3. package
220+say "3/7 package"
221+
222+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
223+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
224+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
225+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
226+
227+target_meta() { # target_meta <key> <file> <format> <relpath> <name>
228+ local key="$1" file="$2" fmt="$3" rel="$4" name="$5"
229+ [ -f "$file" ] || return 0
230+ local sha size
231+ sha=$(sha256sum "$file" | awk '{print $1}')
232+ size=$(wc -c < "$file" | tr -d ' ')
233+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
234+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
235+}
236+
237+{
238+ printf '{\n'
239+ printf ' "slug": "%s",\n' "$SLUG"
240+ printf ' "id": "%s",\n' "$ID"
241+ printf ' "name": "disks",\n'
242+ printf ' "desc": "Local storage",\n'
243+ printf ' "title": "Local Storage & Mounts",\n'
244+ printf ' "summary": "Zero-dependency local storage inspector: every real mounted filesystem with usage and inode pressure, plus a bounded one-level size breakdown of /workspace and $HOME for container and laptop nodes.",\n'
245+ printf ' "category": "system",\n'
246+ printf ' "version": "%s",\n' "$VERSION"
247+ printf ' "license": "MIT",\n'
248+ printf ' "trust_notice": "Executes native C code on your node. Reads /proc/mounts and statvfs, getmntinfo or GetLogicalDriveStringsA, and walks only the allowlisted /workspace or $HOME roots; makes zero outbound network requests and opens no sockets.",\n'
249+ printf ' "capabilities": ["procfs_read", "local_filesystem_stat", "bounded_directory_walk"],\n'
250+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
251+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
252+ printf ' "git_commit": "%s",\n' "$COMMIT"
253+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
254+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
255+ printf ' "build_cmd_posix": "make",\n'
256+ printf ' "build_cmd_win64": "make win64",\n'
257+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
258+ printf ' "targets": {\n'
259+ first=1
260+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
261+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID"
262+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID"
263+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID"
264+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID"
265+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID"
266+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID"
267+ printf '\n }\n}\n'
268+} > "$STAGE/manifest.json"
269+
270+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
271+ || die "generated manifest.json is not valid JSON"
272+echo " manifest.json ok"
273+
274+# SHA256SUMS — relative paths, exactly as published
275+( cd "$STAGE"
276+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
277+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
278+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
279+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
280+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
281+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
282+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
283+ true ) > "$STAGE/SHA256SUMS"
284+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
285+
286+# ---------------------------------------------------------------- 4. stage
287+say "4/7 stage tree"
288+PKG="$STAGE/pkg"
289+mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \
290+ "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64"
291+cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID"
292+[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"
293+[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"
294+[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"
295+[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"
296+[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"
297+cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
298+chmod +x "$PKG"/*/$ID 2>/dev/null || true
299+find "$PKG" -type f | sed 's/^/ /'
300+
301+if [ "$DRY_RUN" -eq 1 ]; then
302+ say "dry run — staged at $STAGE/pkg (kept for inspection)"
303+ trap - EXIT
304+ exit 0
305+fi
306+
307+# ---------------------------------------------------------------- 5. upload
308+say "5/7 upload"
309+
310+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload"
311+SSH=(ssh -o StrictHostKeyChecking=no)
312+SCP=(scp -o StrictHostKeyChecking=no)
313+if [ -n "$DIST_PASS" ]; then
314+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
315+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
316+fi
317+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
318+
319+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
320+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
321+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
322+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
323+# OpenSSH 9 refuses to scp a bare "." source.
324+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
325+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
326+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
327+ || die "remote extract failed"
328+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
329+
330+# latest.json = copy of this version's manifest
331+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
332+ || die "latest.json update failed"
333+echo " updated bot-plugins/$SLUG/latest.json"
334+
335+# index.json — merge, preserving every sibling <slug>/latest.json
336+say "index.json merge"
337+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
338+import json, os, sys, glob
339+slug = sys.argv[1]
340+entries = {}
341+for p in sorted(glob.glob('*/latest.json')):
342+ s = os.path.dirname(p)
343+ try:
344+ entries[s] = json.load(open(p))
345+ except Exception:
346+ pass
347+index = {
348+ 'ok': True,
349+ 'service': 'bot-plugins-dist',
350+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
351+ 'count': len(entries),
352+ 'slugs': sorted(entries),
353+ 'plugins': [entries[k] for k in sorted(entries)],
354+}
355+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
356+os.replace('index.json.tmp', 'index.json')
357+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
358+PY" || die "index.json merge failed"
359+
360+# ---------------------------------------------------------------- 6. mirror
361+say "6/7 plugingit mirror"
362+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
363+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
364+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|")
365+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
366+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
367+ echo " mirrored to $PLUGINGIT_REMOTE"
368+else
369+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
370+fi
371+
372+# ---------------------------------------------------------------- 7. verify
373+say "7/7 verify"
374+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
375+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
376+if [ "$CODE" = "200" ]; then
377+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
378+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
379+else
380+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
381+fi
382+
383+printf '\n\033[1mrelease complete\033[0m\n'
384+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
385+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/plugin_sqlite.c+1568−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..01c8ec9index 0000000..01c8ec9
--- /dev/null--- /dev/null
+++ b/src/plugin_sqlite.c+++ b/src/plugin_sqlite.c
@@ -0,0 +1,1568 @@@@ -0,0 +1,1568 @@
1+/*
2+ * plugin_sqlite - ScorpioX Bot open-source read-only SQLite explorer plugin
3+ *
4+ * A single clean-room C99 binary that serves THREE modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery
6+ * 2. ?action=dbs | ?action=schema&db=... | ?action=query&db=...&sql=...
7+ * | ?action=info | ?format=json
8+ * -> JSON node API (read-only database access)
9+ * 3. GET (default) -> responsive HTML explorer UI
10+ *
11+ * READ-ONLY BY CONSTRUCTION
12+ * - Every database is opened with SQLITE_OPEN_READONLY.
13+ * - sqlite3_set_authorizer() permits only SQLITE_SELECT, SQLITE_READ,
14+ * SQLITE_RECURSIVE, SQLITE_FUNCTION and a small whitelist of read-only
15+ * PRAGMAs. INSERT / UPDATE / DELETE / CREATE / DROP / ALTER / ATTACH /
16+ * DETACH / TRANSACTION / REINDEX / VACUUM are all refused by the engine
17+ * before they can reach the file.
18+ * - Only .db / .sqlite / .sqlite3 regular files under /workspace,
19+ * /codebases, $HOME (or $SQLITE_ALLOWED_ROOT) are browsable. Paths are
20+ * resolved and verified - '..' traversal, SQLite URI filenames and system
21+ * paths such as /etc/passwd are rejected.
22+ * - Result rows are capped at 500 and each statement is bounded by a
23+ * sqlite3_progress_handler ceiling (~2 s).
24+ *
25+ * Vendors the public-domain SQLite amalgamation (vendor/sqlite3.{c,h}) and
26+ * compiles it with -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0, so the
27+ * Linux (glibc + musl static), macOS and Windows binaries need no sqlite3 CLI,
28+ * no libsqlite3.so and no sqlite3.dll.
29+ *
30+ * Zero dependencies beyond libc. MIT License. Copyright (c) 2026 SCORPIOX INC.
31+ */
32+
33+#if defined(__APPLE__)
34+# define _DARWIN_C_SOURCE 1
35+#elif !defined(_WIN32)
36+# define _POSIX_C_SOURCE 200809L
37+# define _DEFAULT_SOURCE 1
38+#endif
39+
40+#include <stdio.h>
41+#include <stdlib.h>
42+#include <string.h>
43+#include <time.h>
44+#include <ctype.h>
45+#include <errno.h>
46+
47+#if defined(_WIN32)
48+# define WIN32_LEAN_AND_MEAN
49+# include <windows.h>
50+# include <direct.h>
51+# include <io.h>
52+# include <sys/stat.h>
53+# define SX_STAT struct _stat64
54+# define sx_stat(p,s) _stat64((p),(s))
55+# define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
56+# define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
57+#else
58+# include <unistd.h>
59+# include <dirent.h>
60+# include <sys/types.h>
61+# include <sys/stat.h>
62+# define SX_STAT struct stat
63+# define sx_stat(p,s) stat((p),(s))
64+# define SX_ISREG(m) S_ISREG(m)
65+# define SX_ISDIR(m) S_ISDIR(m)
66+#endif
67+
68+#include "sqlite3.h"
69+
70+#define PLUGIN_SLUG "sqlite"
71+#define PLUGIN_ID "plugin_sqlite"
72+#define PLUGIN_VER "1.0.0"
73+
74+#define MAX_NAME 256
75+/* glibc's fortified realpath() demands a PATH_MAX-sized buffer. */
76+#define MAX_PATHQ 4096
77+#define MAX_DBS 200
78+#define MAX_TABLES 200
79+#define MAX_COLS 128
80+#define MAX_SQL 16384
81+#define MAX_ROWS 500
82+#define MAX_SCAN_ENTRIES 60000
83+#define MAX_SCAN_DEPTH 4
84+#define STMT_BUDGET_MS 2000
85+
86+/* ------------------------------------------------------------------ */
87+/* Small utilities */
88+/* ------------------------------------------------------------------ */
89+
90+static void url_decode(char *s)
91+{
92+ char *o = s;
93+ if (!s) return;
94+ while (*s) {
95+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
96+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
97+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
98+ *o++ = (char)((hi << 4) | lo);
99+ s += 3;
100+ } else if (*s == '+') {
101+ *o++ = ' ';
102+ s++;
103+ } else {
104+ *o++ = *s++;
105+ }
106+ }
107+ *o = '\0';
108+}
109+
110+/* Read one parameter (decoded) out of a query or form string. */
111+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
112+{
113+ size_t klen;
114+ const char *p;
115+
116+ if (!out || outsz == 0) return 0;
117+ out[0] = '\0';
118+ if (!qs || !key) return 0;
119+ klen = strlen(key);
120+
121+ for (p = qs; *p; ) {
122+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
123+ const char *v = p + klen + 1;
124+ size_t i = 0;
125+ while (*v && *v != '&' && i + 1 < outsz)
126+ out[i++] = *v++;
127+ out[i] = '\0';
128+ url_decode(out);
129+ return 1;
130+ }
131+ p = strchr(p, '&');
132+ if (!p) break;
133+ p++;
134+ }
135+ return 0;
136+}
137+
138+/* JSON string literal; drops control characters rather than escaping them. */
139+static void json_str(const char *s)
140+{
141+ fputc('"', stdout);
142+ if (s) {
143+ for (; *s; s++) {
144+ unsigned char c = (unsigned char)*s;
145+ if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((int)c, stdout); }
146+ else if (c == '\n') fputs("\\n", stdout);
147+ else if (c == '\r') fputs("\\r", stdout);
148+ else if (c == '\t') fputs("\\t", stdout);
149+ else if (c >= 0x20) fputc((int)c, stdout);
150+ }
151+ }
152+ fputc('"', stdout);
153+}
154+
155+static void copy_str(char *dst, size_t dstsz, const char *src)
156+{
157+ size_t n;
158+ if (!dst || dstsz == 0) return;
159+ if (!src) { dst[0] = '\0'; return; }
160+ n = strlen(src);
161+ if (n >= dstsz) n = dstsz - 1;
162+ memcpy(dst, src, n);
163+ dst[n] = '\0';
164+}
165+
166+static void utc_now(char *buf, size_t sz)
167+{
168+ time_t t = time(NULL);
169+ struct tm tmv;
170+#if defined(_WIN32)
171+ struct tm *p = gmtime(&t);
172+ if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv);
173+#else
174+ gmtime_r(&t, &tmv);
175+#endif
176+ strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
177+}
178+
179+static long long now_ms(void)
180+{
181+#if defined(_WIN32)
182+ return (long long)GetTickCount64();
183+#else
184+ struct timespec ts;
185+ if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
186+ return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL;
187+#endif
188+}
189+
190+static long node_pid(void)
191+{
192+#if defined(_WIN32)
193+ return (long)GetCurrentProcessId();
194+#else
195+ return (long)getpid();
196+#endif
197+}
198+
199+static const char *platform_name(void)
200+{
201+#if defined(_WIN32)
202+ return "windows";
203+#elif defined(__APPLE__)
204+ return "macos";
205+#else
206+ return "linux";
207+#endif
208+}
209+
210+/* Case-insensitive prefix compare, portable across glibc / macOS / MinGW. */
211+static int ci_prefix(const char *s, const char *pre)
212+{
213+ while (*pre) {
214+ if (!*s) return 0;
215+ if (tolower((unsigned char)*s) != tolower((unsigned char)*pre)) return 0;
216+ s++; pre++;
217+ }
218+ return 1;
219+}
220+
221+/* ------------------------------------------------------------------ */
222+/* Node authentication */
223+/* ------------------------------------------------------------------ */
224+
225+/*
226+ * Everything except --meta discovery must prove it knows the node password.
227+ * Accepted exactly like the rest of the node API: X-Bot-Password (what
228+ * bot-web proxies with), Authorization: Bearer, and ?pwd= (what the plugin
229+ * iframe appends). With BOT_PASSWORD unset the plugin is a deliberate no-op
230+ * so it can be exercised from a shell during development.
231+ */
232+static void require_node_auth(void)
233+{
234+ const char *np = getenv("BOT_PASSWORD");
235+ const char *xp;
236+ const char *auth;
237+ char qpwd[256];
238+ const char *qs;
239+
240+ if (!np || !*np) return;
241+
242+ xp = getenv("HTTP_X_BOT_PASSWORD");
243+ if (xp && strcmp(xp, np) == 0) return;
244+
245+ auth = getenv("HTTP_AUTHORIZATION");
246+ if (auth) {
247+ while (*auth == ' ') auth++;
248+ if (ci_prefix(auth, "Bearer ")) {
249+ auth += 7;
250+ while (*auth == ' ') auth++;
251+ if (strcmp(auth, np) == 0) return;
252+ }
253+ }
254+
255+ qs = getenv("QUERY_STRING");
256+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
257+ return;
258+
259+ fputs("Status: 401 Unauthorized\r\n"
260+ "Content-Type: application/json; charset=utf-8\r\n"
261+ "Cache-Control: no-store\r\n"
262+ "X-Content-Type-Options: nosniff\r\n\r\n"
263+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
264+ exit(0);
265+}
266+
267+/* ------------------------------------------------------------------ */
268+/* Path discipline */
269+/* ------------------------------------------------------------------ */
270+
271+typedef struct {
272+ char path[MAX_PATHQ];
273+ char label[32];
274+ int exists;
275+} sx_root_t;
276+
277+/*
278+ * The allowlist. $SQLITE_ALLOWED_ROOT is honoured first so a node owner can
279+ * point the plugin at a specific directory, and the three conventional roots
280+ * follow. Nothing outside these is ever opened, no matter what the query says.
281+ */
282+static int collect_roots(sx_root_t *out, int max)
283+{
284+ int n = 0;
285+ const char *extra = getenv("SQLITE_ALLOWED_ROOT");
286+ const char *home = getenv("HOME");
287+#if defined(_WIN32)
288+ if (!home || !*home) home = getenv("USERPROFILE");
289+#endif
290+ SX_STAT st;
291+
292+ memset(out, 0, (size_t)max * sizeof(out[0]));
293+
294+ if (extra && *extra && n < max) {
295+ copy_str(out[n].path, sizeof(out[n].path), extra);
296+ copy_str(out[n].label, sizeof(out[n].label), "allowed");
297+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
298+ n++;
299+ }
300+#if !defined(_WIN32)
301+ if (n < max) {
302+ copy_str(out[n].path, sizeof(out[n].path), "/workspace");
303+ copy_str(out[n].label, sizeof(out[n].label), "workspace");
304+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
305+ n++;
306+ }
307+ if (n < max) {
308+ copy_str(out[n].path, sizeof(out[n].path), "/codebases");
309+ copy_str(out[n].label, sizeof(out[n].label), "codebases");
310+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
311+ n++;
312+ }
313+#endif
314+ if (home && *home && n < max) {
315+ copy_str(out[n].path, sizeof(out[n].path), home);
316+ copy_str(out[n].label, sizeof(out[n].label), "home");
317+ out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode));
318+ n++;
319+ }
320+ return n;
321+}
322+
323+static int has_dotdot(const char *p)
324+{
325+ const char *s = p;
326+ while (s && *s) {
327+ if (s[0] == '.' && s[1] == '.' &&
328+ (s == p || s[-1] == '/' || s[-1] == '\\') &&
329+ (s[2] == '\0' || s[2] == '/' || s[2] == '\\'))
330+ return 1;
331+ s = strchr(s, '/');
332+ if (!s) break;
333+ s++;
334+ }
335+ return 0;
336+}
337+
338+/* Suffix gate: .db / .sqlite / .sqlite3 / .db3 (case-insensitive). */
339+static int has_db_suffix(const char *p)
340+{
341+ size_t n = strlen(p);
342+ const char *s;
343+ if (n < 4) return 0;
344+ for (s = p + n; s > p && s[-1] != '/' && s[-1] != '\\'; s--) {
345+ if (*s == '.') {
346+ if (ci_prefix(s, ".db") || ci_prefix(s, ".db3") ||
347+ ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3"))
348+ return 1;
349+ return 0;
350+ }
351+ }
352+ return 0;
353+}
354+
355+/*
356+ * Resolve and validate a database path.
357+ * 1 allowed, canonical path written to out
358+ * 0 not allowed (outside the roots / traversal / not a db file)
359+ * -1 allowed location but the file is absent
360+ */
361+static int resolve_db_path(const char *req, char *out, size_t outsz)
362+{
363+ sx_root_t roots[8];
364+ int nroots, i;
365+ char canon[MAX_PATHQ];
366+ SX_STAT st;
367+ size_t i2;
368+
369+ if (!req || !*req) return 0;
370+ if (strlen(req) >= MAX_PATHQ) return 0;
371+
372+ /* SQLite URI filenames can smuggle a different file past a naive check. */
373+ if (ci_prefix(req, "file:")) return 0;
374+ if (strstr(req, "://")) return 0;
375+ if (strstr(req, "?") || strstr(req, "#")) return 0;
376+ if (has_dotdot(req)) return 0;
377+ if (!has_db_suffix(req)) return 0;
378+
379+ /* An absolute request must resolve to itself; relative ones are joined to
380+ * $HOME so a bare "app.db" still works from the UI. */
381+ if (req[0] == '/' || (isalpha((unsigned char)req[0]) && req[1] == ':')) {
382+ copy_str(canon, sizeof(canon), req);
383+ } else {
384+ const char *home = getenv("HOME");
385+#if defined(_WIN32)
386+ if (!home || !*home) home = getenv("USERPROFILE");
387+#endif
388+ if (!home || !*home) return 0;
389+ snprintf(canon, sizeof(canon), "%s/%s", home, req);
390+ }
391+
392+ /* Normalise to an absolute, symlink-free path when the platform can. A
393+ * the leaf does not exist we resolve its parent instead and remember. */
394+ {
395+#if defined(_WIN32)
396+ char tmp[MAX_PATHQ];
397+ if (_fullpath(tmp, canon, sizeof(tmp)) != NULL)
398+ copy_str(canon, sizeof(canon), tmp);
399+ else
400+ return 0;
401+#else
402+ char tmp[MAX_PATHQ];
403+ if (realpath(canon, tmp) != NULL) {
404+ copy_str(canon, sizeof(canon), tmp);
405+ } else if (errno == ENOENT) {
406+ char dir[MAX_PATHQ], parent[MAX_PATHQ], rp[MAX_PATHQ];
407+ char *slash;
408+ copy_str(dir, sizeof dir, canon);
409+ slash = strrchr(dir, '/');
410+ if (!slash) return 0;
411+ *slash = '\0';
412+ copy_str(parent, sizeof parent, slash + 1);
413+ if (realpath(dir, rp) != NULL) {
414+ /* Bounded manual join: snprintf's "%s/%s" over two
415+ * PATH_MAX-sized buffers trips -Wformat-truncation. */
416+ size_t rl = strlen(rp);
417+ canon[0] = '\0';
418+ if (rl + strlen(parent) + 2 < sizeof canon) {
419+ memcpy(canon, rp, rl);
420+ canon[rl] = '/';
421+ copy_str(canon + rl + 1, sizeof(canon) - rl - 1, parent);
422+ } else {
423+ return 0;
424+ }
425+ }
426+ } else {
427+ return 0;
428+ }
429+#endif
430+ }
431+
432+ nroots = collect_roots(roots, 8);
433+ for (i = 0; i < nroots; i++) {
434+ size_t rl;
435+ if (!roots[i].exists) continue;
436+ rl = strlen(roots[i].path);
437+ while (rl > 1 && roots[i].path[rl - 1] == '/') rl--;
438+ if (strncmp(canon, roots[i].path, rl) != 0) continue;
439+ if (canon[rl] != '/' && canon[rl] != '\0') continue;
440+
441+ if (sx_stat(canon, &st) != 0) return -1;
442+ if (!SX_ISREG(st.st_mode)) return 0;
443+ copy_str(out, outsz, canon);
444+ return 1;
445+ }
446+
447+ /* Not under any root. Collapse any doubled separators first so the check
448+ * above cannot be defeated by "//workspace//..//". */
449+ for (i2 = 0; canon[i2]; i2++)
450+ if (canon[i2] == '\\') canon[i2] = '/';
451+ return 0;
452+}
453+
454+/* ------------------------------------------------------------------ */
455+/* SQLite: read-only open, authorizer, bounded execution */
456+/* ------------------------------------------------------------------ */
457+
458+typedef struct {
459+ long long deadline_ms;
460+ int aborted;
461+} sx_budget_t;
462+
463+static int progress_cb(void *p)
464+{
465+ sx_budget_t *b = (sx_budget_t *)p;
466+ if (!b) return 0;
467+ if (now_ms() > b->deadline_ms) { b->aborted = 1; return 1; }
468+ return 0;
469+}
470+
471+/* Read-only schema pragmas we are willing to run, and only these. */
472+static int pragma_allowed(const char *name)
473+{
474+ static const char *ok[] = {
475+ /* Pure readers only. Settable pragmas (journal_mode, encoding,
476+ * auto_vacuum, user_version, application_id, schema_version) are
477+ * deliberately absent: on a read-only handle they cannot write anyway,
478+ * but refusing them keeps the contract honest and the error explicit. */
479+ "table_info", "table_xinfo", "index_list", "index_info", "index_xinfo",
480+ "foreign_key_list", "database_list", "collation_list",
481+ "page_count", "page_size", "freelist_count", "compile_options",
482+ "quick_check", "integrity_check", "table_list",
483+ NULL
484+ };
485+ int i;
486+ if (!name) return 0;
487+ for (i = 0; ok[i]; i++)
488+ if (ci_prefix(name, ok[i]) && (name[strlen(ok[i])] == '\0'))
489+ return 1;
490+ return 0;
491+}
492+
493+/*
494+ * SQLITE_DENY on everything not explicitly allowed. Note that this fires for
495+ * the *compiled* statement, so a statement that tries to write is refused
496+ * before execution even on a writable file - defence in depth on top of
497+ * SQLITE_OPEN_READONLY.
498+ */
499+static int authorizer_cb(void *ud, int action, const char *a1, const char *a2,
500+ const char *dbname, const char *trigger)
501+{
502+ (void)ud; (void)a2; (void)dbname; (void)trigger;
503+
504+ switch (action) {
505+ case SQLITE_SELECT:
506+ case SQLITE_READ:
507+ case SQLITE_RECURSIVE:
508+ return SQLITE_OK;
509+ case SQLITE_FUNCTION:
510+ return SQLITE_OK;
511+ case SQLITE_PRAGMA:
512+ return pragma_allowed(a1) ? SQLITE_OK : SQLITE_DENY;
513+ default:
514+ return SQLITE_DENY;
515+ }
516+}
517+
518+static sqlite3 *open_ro(const char *path, int *errout)
519+{
520+ sqlite3 *db = NULL;
521+ int rc;
522+
523+ if (errout) *errout = 0;
524+
525+ /* READONLY plus no URI handling: the path has already been canonicalised
526+ * by resolve_db_path(), and URI filenames would re-introduce a second
527+ * filename parser under our feet. */
528+ rc = sqlite3_open_v2(path, &db,
529+ SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL);
530+ if (rc != SQLITE_OK) {
531+ if (db) sqlite3_close(db);
532+ if (errout) *errout = rc;
533+ return NULL;
534+ }
535+ sqlite3_extended_result_codes(db, 1);
536+ sqlite3_limit(db, SQLITE_LIMIT_ATTACHED, 0);
537+ sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
538+ sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, MAX_SQL);
539+ sqlite3_busy_timeout(db, 500);
540+ return db;
541+}
542+
543+/* Confirm the file really is a SQLite database before we report anything. */
544+static int is_database(sqlite3 *db)
545+{
546+ sqlite3_stmt *st = NULL;
547+ int rc = sqlite3_prepare_v2(db, "SELECT count(*) FROM sqlite_master", -1, &st, NULL);
548+ if (rc != SQLITE_OK) {
549+ if (st) sqlite3_finalize(st);
550+ return 0;
551+ }
552+ rc = sqlite3_step(st);
553+ sqlite3_finalize(st);
554+ return rc == SQLITE_ROW || rc == SQLITE_DONE;
555+}
556+
557+/* ------------------------------------------------------------------ */
558+/* JSON output helpers */
559+/* ------------------------------------------------------------------ */
560+
561+static void json_header(void)
562+{
563+ /* Deliberately no Content-Length - the server owns framing. */
564+ fputs("Content-Type: application/json; charset=utf-8\r\n"
565+ "Cache-Control: no-store\r\n"
566+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
567+}
568+
569+static void json_error(const char *code, const char *detail)
570+{
571+ json_header();
572+ fputs("{\"ok\":false,\"error\":", stdout);
573+ json_str(code);
574+ if (detail && *detail) {
575+ fputs(",\"detail\":", stdout);
576+ json_str(detail);
577+ }
578+ fputs("}\n", stdout);
579+}
580+
581+/* Emit one typed result value. BLOBs become a bounded hex preview. */
582+static void emit_value(sqlite3_stmt *st, int col)
583+{
584+ switch (sqlite3_column_type(st, col)) {
585+ case SQLITE_INTEGER:
586+ printf("%lld", (long long)sqlite3_column_int64(st, col));
587+ break;
588+ case SQLITE_FLOAT: {
589+ double d = sqlite3_column_double(st, col);
590+ if (d != d || d > 1.7976931348623157e308 || d < -1.7976931348623157e308) {
591+ /* NaN / Inf are not JSON numbers - describe them instead. */
592+ char buf[32];
593+ if (d != d) copy_str(buf, sizeof buf, "NaN");
594+ else if (d > 0) copy_str(buf, sizeof buf, "Infinity");
595+ else copy_str(buf, sizeof buf, "-Infinity");
596+ json_str(buf);
597+ } else {
598+ printf("%.15g", d);
599+ }
600+ break;
601+ }
602+ case SQLITE_TEXT: {
603+ const unsigned char *t = sqlite3_column_text(st, col);
604+ json_str(t ? (const char *)t : "");
605+ break;
606+ }
607+ case SQLITE_BLOB: {
608+ const unsigned char *b = (const unsigned char *)sqlite3_column_blob(st, col);
609+ int n = sqlite3_column_bytes(st, col), i, lim = n > 48 ? 48 : n;
610+ printf("{\"blob_bytes\":%d,\"hex\":\"", n);
611+ for (i = 0; i < lim; i++) printf("%02x", b[i]);
612+ fputs(n > lim ? "...\"}" : "\"}", stdout);
613+ break;
614+ }
615+ default:
616+ fputs("null", stdout);
617+ break;
618+ }
619+}
620+
621+static const char *value_type_name(sqlite3_stmt *st, int col)
622+{
623+ switch (sqlite3_column_type(st, col)) {
624+ case SQLITE_INTEGER: return "int";
625+ case SQLITE_FLOAT: return "float";
626+ case SQLITE_TEXT: return "text";
627+ case SQLITE_BLOB: return "blob";
628+ default: return "null";
629+ }
630+}
631+
632+/* Quote an identifier for interpolation into SQL (never for user values). */
633+static void quote_ident(const char *in, char *out, size_t outsz)
634+{
635+ size_t o = 0;
636+ if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
637+ out[o++] = '"';
638+ for (; in && *in && o + 3 < outsz; in++) {
639+ if (*in == '"') out[o++] = '"';
640+ out[o++] = *in;
641+ }
642+ out[o++] = '"';
643+ out[o] = '\0';
644+}
645+
646+/* ------------------------------------------------------------------ */
647+/* Database discovery */
648+/* ------------------------------------------------------------------ */
649+
650+typedef struct {
651+ char path[MAX_PATHQ];
652+ char root[32];
653+ long long size;
654+ long long mtime;
655+} sx_db_t;
656+
657+static int db_suffix_ok(const char *name)
658+{
659+ size_t n = strlen(name);
660+ const char *s = name + n;
661+ while (s > name && *s != '.') s--;
662+ if (*s != '.') return 0;
663+ return ci_prefix(s, ".db") || ci_prefix(s, ".db3") ||
664+ ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3");
665+}
666+
667+static int skip_name(const char *n)
668+{
669+ if (!n || !*n) return 1;
670+ if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0'))) return 1;
671+ /* Skip the obvious noise directories; they are never databases anyway. */
672+ if (strcmp(n, ".git") == 0 || strcmp(n, "node_modules") == 0 ||
673+ strcmp(n, "__pycache__") == 0 || strcmp(n, "venv") == 0 ||
674+ strcmp(n, ".venv") == 0 || strcmp(n, "bin") == 0 ||
675+ strcmp(n, "obj") == 0 || strcmp(n, "target") == 0)
676+ return 1;
677+ return 0;
678+}
679+
680+static int walk_dbs(const char *dir, const char *rootlabel, int depth,
681+ sx_db_t *out, int max, int *count, int *visited)
682+{
683+ if (depth > MAX_SCAN_DEPTH || *count >= max || *visited > MAX_SCAN_ENTRIES)
684+ return 0;
685+
686+#if defined(_WIN32)
687+ {
688+ WIN32_FIND_DATAA fd;
689+ HANDLE h;
690+ char pat[MAX_PATHQ];
691+ snprintf(pat, sizeof(pat), "%s\\*", dir);
692+ h = FindFirstFileA(pat, &fd);
693+ if (h == INVALID_HANDLE_VALUE) return 0;
694+ do {
695+ char full[MAX_PATHQ];
696+ SX_STAT st;
697+ if (skip_name(fd.cFileName)) continue;
698+ (*visited)++;
699+ if (*visited > MAX_SCAN_ENTRIES || *count >= max) break;
700+ snprintf(full, sizeof(full), "%s\\%s", dir, fd.cFileName);
701+ if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
702+ walk_dbs(full, rootlabel, depth + 1, out, max, count, visited);
703+ } else if (db_suffix_ok(fd.cFileName) &&
704+ sx_stat(full, &st) == 0 && SX_ISREG(st.st_mode)) {
705+ copy_str(out[*count].path, sizeof(out[*count].path), full);
706+ copy_str(out[*count].root, sizeof(out[*count].root), rootlabel);
707+ out[*count].size = (long long)st.st_size;
708+ out[*count].mtime = (long long)st.st_mtime;
709+ (*count)++;
710+ }
711+ } while (FindNextFileA(h, &fd));
712+ FindClose(h);
713+ }
714+#else
715+ {
716+ DIR *d = opendir(dir);
717+ struct dirent *e;
718+ if (!d) return 0;
719+ while ((e = readdir(d)) != NULL) {
720+ char full[MAX_PATHQ];
721+ SX_STAT st;
722+ if (skip_name(e->d_name)) continue;
723+ (*visited)++;
724+ if (*visited > MAX_SCAN_ENTRIES || *count >= max) break;
725+ snprintf(full, sizeof(full), "%s/%s", dir, e->d_name);
726+ if (lstat(full, &st) != 0) continue;
727+ if (S_ISDIR(st.st_mode)) {
728+ /* Never follow a symlinked directory: that is how a walk
729+ * escapes the allowlisted root. */
730+ if (S_ISLNK(st.st_mode)) continue;
731+ walk_dbs(full, rootlabel, depth + 1, out, max, count, visited);
732+ } else if (S_ISREG(st.st_mode) && db_suffix_ok(e->d_name)) {
733+ copy_str(out[*count].path, sizeof(out[*count].path), full);
734+ copy_str(out[*count].root, sizeof(out[*count].root), rootlabel);
735+ out[*count].size = (long long)st.st_size;
736+ out[*count].mtime = (long long)st.st_mtime;
737+ (*count)++;
738+ }
739+ }
740+ closedir(d);
741+ }
742+#endif
743+ return 0;
744+}
745+
746+/* ------------------------------------------------------------------ */
747+/* Actions */
748+/* ------------------------------------------------------------------ */
749+
750+static void action_dbs(void)
751+{
752+ sx_root_t roots[8];
753+ sx_db_t dbs[MAX_DBS];
754+ int nroots, i, count = 0, visited = 0;
755+
756+ nroots = collect_roots(roots, 8);
757+ memset(dbs, 0, sizeof(dbs));
758+
759+ json_header();
760+ fputs("{\"ok\":true,\"action\":\"dbs\",\"plugin\":\"" PLUGIN_ID "\"", stdout);
761+
762+ fputs(",\"roots\":[", stdout);
763+ for (i = 0; i < nroots; i++) {
764+ if (i) fputc(',', stdout);
765+ fputs("{\"label\":", stdout);
766+ json_str(roots[i].label);
767+ fputs(",\"path\":", stdout);
768+ json_str(roots[i].path);
769+ printf(",\"exists\":%s}", roots[i].exists ? "true" : "false");
770+ }
771+ fputs("]", stdout);
772+
773+ for (i = 0; i < nroots && count < MAX_DBS; i++) {
774+ if (!roots[i].exists) continue;
775+ walk_dbs(roots[i].path, roots[i].label, 0, dbs, MAX_DBS, &count, &visited);
776+ }
777+
778+ printf(",\"count\":%d,\"scanned_entries\":%d,\"max_depth\":%d,\"dbs\":[",
779+ count, visited, MAX_SCAN_DEPTH);
780+ for (i = 0; i < count; i++) {
781+ char utc[40];
782+ time_t t = (time_t)dbs[i].mtime;
783+ struct tm tmv;
784+#if defined(_WIN32)
785+ struct tm *p = gmtime(&t);
786+ if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv);
787+#else
788+ gmtime_r(&t, &tmv);
789+#endif
790+ strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
791+
792+ if (i) fputc(',', stdout);
793+ fputs("{\"path\":", stdout);
794+ json_str(dbs[i].path);
795+ fputs(",\"root\":", stdout);
796+ json_str(dbs[i].root);
797+ printf(",\"bytes\":%lld,\"mtime\":", dbs[i].size);
798+ json_str(utc);
799+ fputc('}', stdout);
800+ }
801+ fputs("],\"readonly\":true}\n", stdout);
802+}
803+
804+/* Count rows in one table, bounded by the statement budget. */
805+static int table_rows(sqlite3 *db, const char *table, long long *out)
806+{
807+ sqlite3_stmt *st = NULL;
808+ char sql[MAX_NAME * 2 + 64];
809+ char q[MAX_NAME * 2 + 4];
810+ int rc;
811+
812+ quote_ident(table, q, sizeof q);
813+ snprintf(sql, sizeof sql, "SELECT count(*) FROM %s", q);
814+
815+ rc = sqlite3_prepare_v2(db, sql, -1, &st, NULL);
816+ if (rc != SQLITE_OK) { if (st) sqlite3_finalize(st); return rc; }
817+ rc = sqlite3_step(st);
818+ if (rc == SQLITE_ROW) { *out = (long long)sqlite3_column_int64(st, 0); rc = SQLITE_OK; }
819+ else *out = -1;
820+ sqlite3_finalize(st);
821+ return rc;
822+}
823+
824+static void action_schema(const char *dbreq)
825+{
826+ char path[MAX_PATHQ];
827+ char errbuf[512];
828+ sqlite3 *db;
829+ sqlite3_stmt *st = NULL;
830+ sx_budget_t budget;
831+ int r, rc, tcount = 0;
832+
833+ memset(path, 0, sizeof path);
834+ r = resolve_db_path(dbreq, path, sizeof path);
835+ if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; }
836+ if (r < 0) { json_error("not_found", "database file does not exist"); return; }
837+
838+ db = open_ro(path, &rc);
839+ if (!db) {
840+ snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc));
841+ json_error("open_failed", errbuf);
842+ return;
843+ }
844+ if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; }
845+
846+ sqlite3_set_authorizer(db, authorizer_cb, NULL);
847+ budget.deadline_ms = now_ms() + STMT_BUDGET_MS;
848+ budget.aborted = 0;
849+ sqlite3_progress_handler(db, 20000, progress_cb, &budget);
850+
851+ json_header();
852+ fputs("{\"ok\":true,\"action\":\"schema\",\"readonly\":true,\"db\":", stdout);
853+ json_str(path);
854+ fputs(",\"tables\":[", stdout);
855+
856+ rc = sqlite3_prepare_v2(db,
857+ "SELECT name, type FROM sqlite_master "
858+ "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name",
859+ -1, &st, NULL);
860+ if (rc != SQLITE_OK) {
861+ sqlite3_close(db);
862+ /* Header already emitted, so finish the document with an error field. */
863+ fputs("],\"error\":\"schema_query_failed\"}\n", stdout);
864+ return;
865+ }
866+
867+ while (sqlite3_step(st) == SQLITE_ROW && tcount < MAX_TABLES) {
868+ const char *name = (const char *)sqlite3_column_text(st, 0);
869+ const char *kind = (const char *)sqlite3_column_text(st, 1);
870+ long long rows = -1;
871+ sqlite3_stmt *cs = NULL;
872+ char q[MAX_NAME * 2 + 4];
873+ int ci = 0;
874+ char sql[MAX_NAME * 2 + 96];
875+
876+ if (!name) continue;
877+ if (tcount) fputc(',', stdout);
878+ fputs("{\"name\":", stdout);
879+ json_str(name);
880+ fputs(",\"type\":", stdout);
881+ json_str(kind ? kind : "table");
882+
883+ if (table_rows(db, name, &rows) == SQLITE_OK) printf(",\"rows\":%lld", rows);
884+ else fputs(",\"rows\":null", stdout);
885+
886+ quote_ident(name, q, sizeof q);
887+ fputs(",\"columns\":[", stdout);
888+ snprintf(sql, sizeof sql, "PRAGMA table_info(%s)", q);
889+ if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) {
890+ while (sqlite3_step(cs) == SQLITE_ROW) {
891+ const char *cn = (const char *)sqlite3_column_text(cs, 1);
892+ const char *ct = (const char *)sqlite3_column_text(cs, 2);
893+ int nn = sqlite3_column_int(cs, 3);
894+ int pk = sqlite3_column_int(cs, 5);
895+ if (ci++) fputc(',', stdout);
896+ fputs("{\"name\":", stdout);
897+ json_str(cn ? cn : "");
898+ fputs(",\"type\":", stdout);
899+ json_str(ct ? ct : "");
900+ printf(",\"notnull\":%s,\"pk\":%d}", nn ? "true" : "false", pk);
901+ }
902+ }
903+ sqlite3_finalize(cs);
904+ fputs("]", stdout);
905+
906+ ci = 0;
907+ fputs(",\"indexes\":[", stdout);
908+ snprintf(sql, sizeof sql, "PRAGMA index_list(%s)", q);
909+ if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) {
910+ while (sqlite3_step(cs) == SQLITE_ROW) {
911+ const char *in = (const char *)sqlite3_column_text(cs, 1);
912+ int uniq = sqlite3_column_int(cs, 2);
913+ if (ci++) fputc(',', stdout);
914+ fputs("{\"name\":", stdout);
915+ json_str(in ? in : "");
916+ printf(",\"unique\":%s}", uniq ? "true" : "false");
917+ }
918+ }
919+ sqlite3_finalize(cs);
920+ fputs("]}", stdout);
921+ tcount++;
922+ }
923+ sqlite3_finalize(st);
924+
925+ printf("],\"table_count\":%d,\"truncated\":%s,\"budget_ms\":%d}\n",
926+ tcount, tcount >= MAX_TABLES ? "true" : "false", STMT_BUDGET_MS);
927+ sqlite3_close(db);
928+}
929+
930+/*
931+ * First keyword of the statement. The authorizer is the real gate; this check
932+ * only produces a friendlier error than "not authorized".
933+ */
934+static const char *first_keyword(const char *sql, char *out, size_t outsz)
935+{
936+ size_t i = 0;
937+ while (*sql && isspace((unsigned char)*sql)) sql++;
938+ while (*sql && (isalnum((unsigned char)*sql) || *sql == '_') && i + 1 < outsz)
939+ out[i++] = (char)tolower((unsigned char)*sql++);
940+ out[i] = '\0';
941+ return out;
942+}
943+
944+static int statement_allowed_shape(const char *kw)
945+{
946+ return strcmp(kw, "select") == 0 || strcmp(kw, "with") == 0 ||
947+ strcmp(kw, "pragma") == 0 || strcmp(kw, "explain") == 0 ||
948+ strcmp(kw, "values") == 0;
949+}
950+
951+static void action_query(const char *dbreq, const char *sql)
952+{
953+ char path[MAX_PATHQ];
954+ char errbuf[512];
955+ char kw[32];
956+ sqlite3 *db;
957+ sqlite3_stmt *st = NULL;
958+ sx_budget_t budget;
959+ int r, rc, ncols, nrows = 0, truncated = 0, i;
960+ char types[MAX_COLS][8];
961+ const char *tail = NULL;
962+ long long t0, t1;
963+
964+ if (!sql || !*sql) { json_error("missing_sql", "pass ?sql=SELECT ... or POST sql=..."); return; }
965+ if (strlen(sql) >= MAX_SQL) { json_error("sql_too_long", "statement exceeds the SQL length limit"); return; }
966+
967+ r = resolve_db_path(dbreq, path, sizeof path);
968+ if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; }
969+ if (r < 0) { json_error("not_found", "database file does not exist"); return; }
970+
971+ first_keyword(sql, kw, sizeof kw);
972+ if (!statement_allowed_shape(kw)) {
973+ json_error("read_only", "only SELECT / WITH / PRAGMA / EXPLAIN statements are accepted");
974+ return;
975+ }
976+
977+ db = open_ro(path, &rc);
978+ if (!db) {
979+ snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc));
980+ json_error("open_failed", errbuf);
981+ return;
982+ }
983+ if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; }
984+
985+ sqlite3_set_authorizer(db, authorizer_cb, NULL);
986+ budget.deadline_ms = now_ms() + STMT_BUDGET_MS;
987+ budget.aborted = 0;
988+ sqlite3_progress_handler(db, 20000, progress_cb, &budget);
989+
990+ t0 = now_ms();
991+ rc = sqlite3_prepare_v2(db, sql, -1, &st, &tail);
992+ if (rc != SQLITE_OK) {
993+ snprintf(errbuf, sizeof errbuf, "%s", sqlite3_errmsg(db));
994+ sqlite3_close(db);
995+ json_error("sql_error", errbuf);
996+ return;
997+ }
998+ /* Reject stacked statements: prepare() stops after the first one and the
999+ * tail would otherwise be silently dropped. */
1000+ while (tail && *tail && isspace((unsigned char)*tail)) tail++;
1001+ if (tail && *tail) {
1002+ sqlite3_finalize(st);
1003+ sqlite3_close(db);
1004+ json_error("multiple_statements", "submit one statement at a time");
1005+ return;
1006+ }
1007+
1008+ ncols = sqlite3_column_count(st);
1009+
1010+ json_header();
1011+ fputs("{\"ok\":true,\"action\":\"query\",\"readonly\":true,\"db\":", stdout);
1012+ json_str(path);
1013+ printf(",\"columns\":[");
1014+ for (i = 0; i < ncols; i++) {
1015+ const char *cn = sqlite3_column_name(st, i);
1016+ const char *dl = sqlite3_column_decltype(st, i);
1017+ if (i) fputc(',', stdout);
1018+ fputs("{\"name\":", stdout);
1019+ json_str(cn ? cn : "");
1020+ fputs(",\"decl\":", stdout);
1021+ json_str(dl ? dl : "");
1022+ fputc('}', stdout);
1023+ }
1024+ fputs("],\"rows\":[", stdout);
1025+
1026+ memset(types, 0, sizeof types);
1027+ while ((rc = sqlite3_step(st)) == SQLITE_ROW) {
1028+ if (nrows >= MAX_ROWS) { truncated = 1; break; }
1029+ if (nrows) fputc(',', stdout);
1030+ fputc('[', stdout);
1031+ for (i = 0; i < ncols; i++) {
1032+ if (i) fputc(',', stdout);
1033+ emit_value(st, i);
1034+ /* Column type is only meaningful while a row is positioned, so
1035+ * remember the first row's types for the summary block. */
1036+ if (nrows == 0 && i < MAX_COLS)
1037+ copy_str(types[i], sizeof types[i], value_type_name(st, i));
1038+ }
1039+ fputc(']', stdout);
1040+ nrows++;
1041+ }
1042+
1043+ if (rc == SQLITE_INTERRUPT || budget.aborted) {
1044+ /* Budget hit mid-scan: keep what we streamed and say so. */
1045+ truncated = 1;
1046+ } else if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
1047+ const char *m = sqlite3_errmsg(db);
1048+ fputs("],\"error\":", stdout);
1049+ json_str(m ? m : "statement failed");
1050+ printf(",\"aborted\":%s}\n", budget.aborted ? "true" : "false");
1051+ sqlite3_finalize(st);
1052+ sqlite3_close(db);
1053+ return;
1054+ }
1055+
1056+ t1 = now_ms();
1057+ printf("],\"row_count\":%d,\"truncated\":%s,\"limit\":%d,\"ms\":%lld,"
1058+ "\"aborted\":%s,\"types\":[",
1059+ nrows, truncated ? "true" : "false", MAX_ROWS, t1 - t0,
1060+ budget.aborted ? "true" : "false");
1061+ for (i = 0; i < ncols && nrows > 0 && i < MAX_COLS; i++) {
1062+ if (i) fputc(',', stdout);
1063+ json_str(types[i]);
1064+ }
1065+ fputs("]}\n", stdout);
1066+
1067+ sqlite3_finalize(st);
1068+ sqlite3_close(db);
1069+}
1070+
1071+static void action_info(void)
1072+{
1073+ char utc[40];
1074+ utc_now(utc, sizeof utc);
1075+
1076+ json_header();
1077+ fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\","
1078+ "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout);
1079+ json_str(platform_name());
1080+ fputs(",\"sqlite\":", stdout);
1081+ json_str(sqlite3_libversion());
1082+ printf(",\"pid\":%ld,\"utc\":", node_pid());
1083+ json_str(utc);
1084+ fputs(",\"node_auth\":", stdout);
1085+ {
1086+ const char *np = getenv("BOT_PASSWORD");
1087+ fputs((np && *np) ? "true" : "false", stdout);
1088+ }
1089+ fputs(",\"readonly\":true,\"zero_network\":true,\"threadsafe\":0,"
1090+ "\"load_extension\":false,"
1091+ "\"max_rows\":", stdout);
1092+ printf("%d", MAX_ROWS);
1093+ fputs(",\"budget_ms\":", stdout);
1094+ printf("%d", STMT_BUDGET_MS);
1095+ fputs(",\"allowed_roots\":[\"allowed\",\"workspace\",\"codebases\",\"home\"],"
1096+ "\"actions\":[\"dbs\",\"schema\",\"query\",\"info\"]}\n", stdout);
1097+}
1098+
1099+/* ------------------------------------------------------------------ */
1100+/* HTML UI */
1101+/* ------------------------------------------------------------------ */
1102+
1103+static int mode_html(int embed)
1104+{
1105+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1106+ "Cache-Control: no-store\r\n"
1107+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1108+
1109+ fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>"
1110+ "<meta name='viewport' content='width=device-width,initial-scale=1'>"
1111+ "<title>sqlite</title><style>", stdout);
1112+
1113+ fputs(
1114+":root{color-scheme:dark light;"
1115+ "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;"
1116+ "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;"
1117+ "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;"
1118+ "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}"
1119+"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;"
1120+ "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}"
1121+"*{box-sizing:border-box}"
1122+"body{margin:0;padding:16px;background:var(--bg);color:var(--text);"
1123+ "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;"
1124+ "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}"
1125+".wrap{max-width:1240px;margin:0 auto;min-width:0}"
1126+".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}"
1127+".title{font-size:20px;font-weight:700;margin:0}"
1128+".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow-wrap:anywhere}"
1129+".spacer{flex:1}"
1130+".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;"
1131+ "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}"
1132+".pill.ro{color:var(--ok);border-color:rgba(48,209,88,.4)}"
1133+".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1134+ "padding:16px;margin-bottom:14px;min-width:0}"
1135+".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;"
1136+ "text-transform:uppercase;color:var(--muted);font-weight:600}"
1137+"button{background:var(--accent);color:#fff;border:0;border-radius:999px;"
1138+ "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}"
1139+"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}"
1140+"button:active{transform:scale(.98)}"
1141+"button:disabled{opacity:.5;cursor:default}"
1142+"select,input,textarea{background:var(--surface2);color:var(--text);"
1143+ "border:1px solid var(--line);border-radius:9px;padding:8px 10px;"
1144+ "font-family:var(--mono);font-size:13px;width:100%}"
1145+"textarea{min-height:104px;resize:vertical;line-height:1.5}"
1146+"select{font-family:inherit}"
1147+".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}"
1148+".layout{display:grid;grid-template-columns:250px minmax(0,1fr);gap:14px;align-items:start}"
1149+"@media(max-width:860px){.layout{grid-template-columns:minmax(0,1fr)}}"
1150+".side{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1151+ "padding:12px;min-width:0}"
1152+".side h3{margin:0 0 8px;font-size:11px;letter-spacing:.06em;text-transform:uppercase;"
1153+ "color:var(--muted);font-weight:600}"
1154+".titem{display:block;width:100%;text-align:left;background:transparent;color:var(--text);"
1155+ "border:0;border-radius:8px;padding:6px 8px;font-size:12px;font-family:var(--mono);"
1156+ "cursor:pointer;overflow-wrap:anywhere}"
1157+".titem:hover{background:var(--surface2)}"
1158+".titem.on{background:var(--surface2);font-weight:700;color:var(--accent)}"
1159+".titem .n{color:var(--muted);font-weight:400}"
1160+".tblwrap{overflow:auto;max-height:60vh;border:1px solid var(--line);border-radius:10px}"
1161+"table{width:100%;border-collapse:collapse;font-size:12.5px;font-family:var(--mono)}"
1162+"th,td{text-align:left;padding:6px 9px;border-bottom:1px solid var(--line);"
1163+ "white-space:nowrap;max-width:340px;overflow:hidden;text-overflow:ellipsis}"
1164+"th{position:sticky;top:0;background:var(--surface2);cursor:pointer;"
1165+ "font-weight:700;user-select:none;z-index:1}"
1166+"th .dir{color:var(--accent);font-size:10px}"
1167+"td.null{color:var(--muted);font-style:italic}"
1168+"td.num{text-align:right}"
1169+"tbody tr:hover{background:var(--surface2)}"
1170+".empty{color:var(--muted);padding:14px 0;font-size:13px}"
1171+".err{color:var(--danger);font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}"
1172+".cols{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}"
1173+".chip{font-size:11px;font-family:var(--mono);color:var(--muted);"
1174+ "background:var(--surface2);border:1px solid var(--line);border-radius:7px;padding:2px 7px}"
1175+".hint{color:var(--muted);font-size:11.5px;margin-top:6px}"
1176+"kbd{font-family:var(--mono);font-size:11px;background:var(--surface2);"
1177+ "border:1px solid var(--line);border-radius:5px;padding:1px 5px}"
1178+"</style></head><body>", stdout);
1179+
1180+ fputs("<div class='wrap'>", stdout);
1181+
1182+ if (!embed) {
1183+ fputs("<div style='margin-bottom:12px'><a href='/' "
1184+ "style='color:var(--accent);text-decoration:none;font-weight:600'>"
1185+ "&larr; Back to Bot</a></div>", stdout);
1186+ }
1187+
1188+ fputs("<div class='top'><h2 class='title'>sqlite</h2>"
1189+ "<span class='pill ro'>read-only</span>"
1190+ "<span class='pill' id='dbcount'>&mdash;</span>"
1191+ "<span class='spacer'></span>"
1192+ "<button class='ghost' id='themebtn' type='button'>Theme</button>"
1193+ "</div>", stdout);
1194+
1195+ fputs("<div class='card'><h2>Database</h2>"
1196+ "<div class='row'><div style='flex:1 1 320px;min-width:0'>"
1197+ "<select id='dbsel'><option value=''>Loading databases...</option></select></div>"
1198+ "<button class='ghost' id='reloadbtn' type='button'>Rescan</button></div>"
1199+ "<div class='hint' id='dbhint'>Only .db / .sqlite / .sqlite3 files under the "
1200+ "allowlisted roots are listed.</div></div>", stdout);
1201+
1202+ fputs("<div class='layout'><div class='side'><h3>Tables</h3>"
1203+ "<div id='tables'><div class='empty'>Select a database.</div></div></div>", stdout);
1204+
1205+ fputs("<div style='min-width:0'><div class='card'><h2>SQL</h2>"
1206+ "<textarea id='sql' spellcheck='false'>SELECT name, type FROM sqlite_master LIMIT 50;</textarea>"
1207+ "<div class='row' style='margin-top:8px'>"
1208+ "<button id='runbtn' type='button'>Run</button>"
1209+ "<button class='ghost' id='csvbtn' type='button'>Copy CSV</button>"
1210+ "<button class='ghost' id='jsonbtn' type='button'>Copy JSON</button>"
1211+ "<span class='spacer'></span>"
1212+ "<span class='hint'><kbd>Ctrl</kbd>+<kbd>Enter</kbd> to run</span>"
1213+ "</div><div class='hint' id='qmeta'></div></div>", stdout);
1214+
1215+ fputs("<div class='card'><h2>Results</h2>"
1216+ "<div class='cols' id='cols'></div>"
1217+ "<div class='tblwrap' id='reswrap' style='margin-top:10px'>"
1218+ "<div class='empty'>No results yet.</div></div></div></div></div>", stdout);
1219+
1220+ fputs("<div class='card' id='infocard' style='display:none'><h2>Info</h2>"
1221+ "<div class='cols' id='info'></div></div></div>", stdout);
1222+
1223+ /* ---------------- client ---------------- */
1224+ fputs("<script>\n"
1225+"var Q = new URLSearchParams(location.search);\n"
1226+"var node = Q.get('node') || '';\n"
1227+"var sid = Q.get('id') || '';\n"
1228+"var HUB = Q.get('plugin') || '';\n"
1229+"var pwd = Q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) || localStorage.getItem('bot_active_pwd') || '';\n"
1230+"var currentDb = '';\n"
1231+"var lastData = null;\n"
1232+"\n"
1233+"function $(id){ return document.getElementById(id); }\n"
1234+"function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null) ? '' : v; }\n"
1235+"\n"
1236+"/* Two routes, and getting this wrong is the classic plugin bug:\n"
1237+" - served through the hub (bot.scorpiox.net/plugins?plugin=...&node=...)\n"
1238+" -> call the hub proxy back with /plugins?plugin=<id>&action=...\n"
1239+" - opened directly on the node -> the plugin IS the route: /plugin_sqlite?action=... */\n"
1240+"function apiUrl(action, extra){\n"
1241+" var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB)\n"
1242+" : '/plugin_sqlite?') +\n"
1243+" (HUB ? '&' : '') + 'action=' + encodeURIComponent(action);\n"
1244+" if (extra) u += '&' + extra;\n"
1245+" if (node) u += '&node=' + encodeURIComponent(node);\n"
1246+" if (sid) u += '&id=' + encodeURIComponent(sid);\n"
1247+" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n"
1248+" return u;\n"
1249+"}\n"
1250+"function api(action, extra){\n"
1251+" return fetch(apiUrl(action, extra), {headers: pwd ? {'X-Bot-Password': pwd} : {}})\n"
1252+" .then(function(r){ return r.json(); });\n"
1253+"}\n"
1254+"function apiPost(action, extra, body){\n"
1255+" return fetch(apiUrl(action, extra), {\n"
1256+" method: 'POST',\n"
1257+" headers: pwd ? {'X-Bot-Password': pwd, 'Content-Type': 'application/x-www-form-urlencoded'} : {'Content-Type': 'application/x-www-form-urlencoded'},\n"
1258+" body: body\n"
1259+" }).then(function(r){ return r.json(); });\n"
1260+"}\n"
1261+"\n"
1262+"function el(tag, c, t){\n"
1263+" var e = document.createElement(tag);\n"
1264+" if (c) e.className = c;\n"
1265+" if (t !== undefined) e.textContent = t;\n"
1266+" return e;\n"
1267+"}\n"
1268+"function bytes(n){\n"
1269+" if (n === null || n === undefined) return '\\u2014';\n"
1270+" var u = ['B','KB','MB','GB','TB'], i = 0, v = n;\n"
1271+" while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }\n"
1272+" return (i === 0 ? v.toFixed(0) : v.toFixed(v >= 100 ? 0 : 1)) + ' ' + u[i];\n"
1273+"}\n"
1274+"function err(msg){ var w = $('reswrap'); w.textContent = ''; w.appendChild(el('div','err', msg)); }\n"
1275+"\n"
1276+"/* ---- databases ---- */\n"
1277+"function loadDbs(){\n"
1278+" api('dbs').then(function(d){\n"
1279+" var sel = $('dbsel');\n"
1280+" sel.textContent = '';\n"
1281+" if (!d.ok) { err(d.error || 'failed to list databases'); return; }\n"
1282+" var list = d.dbs || [];\n"
1283+" txt('dbcount', list.length + (list.length === 1 ? ' database' : ' databases'));\n"
1284+" if (!list.length) {\n"
1285+" var o = el('option', null, 'No .db / .sqlite files found');\n"
1286+" o.value = ''; sel.appendChild(o);\n"
1287+" $('tables').textContent = '';\n"
1288+" $('tables').appendChild(el('div','empty','No database selected.'));\n"
1289+" return;\n"
1290+" }\n"
1291+" var ph = el('option', null, 'Choose a database (' + list.length + ')');\n"
1292+" ph.value = ''; sel.appendChild(ph);\n"
1293+" list.forEach(function(x){\n"
1294+" var o = el('option', null, x.path + ' \\u00b7 ' + bytes(x.bytes));\n"
1295+" o.value = x.path;\n"
1296+" sel.appendChild(o);\n"
1297+" });\n"
1298+" if (currentDb) sel.value = currentDb;\n"
1299+" if (!sel.value && list.length === 1) { sel.value = list[0].path; selectDb(list[0].path); }\n"
1300+" }).catch(function(e){ err('Error: ' + e); });\n"
1301+"}\n"
1302+"\n"
1303+"function selectDb(path){\n"
1304+" currentDb = path;\n"
1305+" var box = $('tables');\n"
1306+" box.textContent = '';\n"
1307+" if (!path) { box.appendChild(el('div','empty','Select a database.')); return; }\n"
1308+" box.appendChild(el('div','empty','Loading schema...'));\n"
1309+" api('schema', 'db=' + encodeURIComponent(path)).then(function(d){\n"
1310+" box.textContent = '';\n"
1311+" if (!d.ok) { box.appendChild(el('div','err', d.error + (d.detail ? ': ' + d.detail : ''))); return; }\n"
1312+" var list = d.tables || [];\n"
1313+" txt('dbhint', path + ' \\u00b7 ' + list.length + ' table' + (list.length === 1 ? '' : 's') + ' \\u00b7 read-only');\n"
1314+" if (!list.length) { box.appendChild(el('div','empty','No tables.')); return; }\n"
1315+" list.forEach(function(t){\n"
1316+" var b = el('button','titem');\n"
1317+" b.type = 'button';\n"
1318+" b.appendChild(document.createTextNode(t.name));\n"
1319+" var n = el('span','n', ' ' + (t.rows === null || t.rows === undefined ? '?' : t.rows)\n"
1320+" + (t.type === 'view' ? ' view' : ''));\n"
1321+" b.appendChild(n);\n"
1322+" b.title = (t.columns || []).map(function(c){ return c.name + ' ' + (c.type || ''); }).join('\\n');\n"
1323+" b.onclick = function(){\n"
1324+" Array.prototype.forEach.call(box.children, function(x){ x.classList.remove('on'); });\n"
1325+" b.classList.add('on');\n"
1326+" var q = 'SELECT * FROM \"' + String(t.name).replace(/\\\"/g, '\\\"\\\"') + '\" LIMIT 100;';\n"
1327+" $('sql').value = q;\n"
1328+" runQuery();\n"
1329+" };\n"
1330+" box.appendChild(b);\n"
1331+" });\n"
1332+" }).catch(function(e){ box.textContent = ''; box.appendChild(el('div','err','Error: ' + e)); });\n"
1333+"}\n"
1334+"\n"
1335+"/* ---- query ---- */\n"
1336+"function clearSorted(){ sortCol = -1; sortDir = 1; }\n"
1337+"var sortCol = -1, sortDir = 1;\n"
1338+"\n"
1339+"function runQuery(){\n"
1340+" var sql = $('sql').value;\n"
1341+" if (!currentDb) { err('Select a database first.'); return; }\n"
1342+" if (!sql.trim()) { err('Type a statement.'); return; }\n"
1343+" $('runbtn').disabled = true;\n"
1344+" txt('qmeta','Running...');\n"
1345+" clearSorted();\n"
1346+" apiPost('query', 'db=' + encodeURIComponent(currentDb),\n"
1347+" 'sql=' + encodeURIComponent(sql)).then(function(d){\n"
1348+" $('runbtn').disabled = false;\n"
1349+" lastData = d;\n"
1350+" if (!d.ok) { txt('qmeta',''); err((d.error || 'error') + (d.detail ? ': ' + d.detail : '')); $('cols').textContent=''; return; }\n"
1351+" if (d.error) { txt('qmeta',''); err(d.error); $('cols').textContent=''; return; }\n"
1352+" txt('qmeta', d.row_count + ' row' + (d.row_count === 1 ? '' : 's')\n"
1353+" + (d.truncated ? ' (truncated)' : '') + ' \\u00b7 ' + d.ms + ' ms'\n"
1354+" + (d.aborted ? ' \\u00b7 stopped at the time budget' : ''));\n"
1355+" renderTable(d);\n"
1356+" }).catch(function(e){\n"
1357+" $('runbtn').disabled = false;\n"
1358+" txt('qmeta',''); err('Request failed: ' + e);\n"
1359+" });\n"
1360+"}\n"
1361+"\n"
1362+"function renderTable(d){\n"
1363+" var wrap = $('reswrap');\n"
1364+" wrap.textContent = '';\n"
1365+" $('cols').textContent = '';\n"
1366+" var cols = d.columns || [], rows = d.rows || [];\n"
1367+" cols.forEach(function(c){\n"
1368+" $('cols').appendChild(el('span','chip', c.name + ' ' + (c.decl || '')));\n"
1369+" });\n"
1370+" if (!rows.length) { wrap.appendChild(el('div','empty','0 rows.')); return; }\n"
1371+" drawGrid(wrap, cols, rows);\n"
1372+"}\n"
1373+"\n"
1374+"function cellValue(v){\n"
1375+" if (v === null || v === undefined) return {t: 'NULL', cls: 'null'};\n"
1376+" if (typeof v === 'object') return {t: '[blob ' + v.blob_bytes + ']', cls: 'null'};\n"
1377+" if (typeof v === 'number') return {t: String(v), cls: 'num'};\n"
1378+" return {t: String(v), cls: ''};\n"
1379+"}\n"
1380+"\n"
1381+"function drawGrid(wrap, cols, rows){\n"
1382+" var tbl = el('table');\n"
1383+" var thead = el('thead'), tr = el('tr');\n"
1384+" cols.forEach(function(c, i){\n"
1385+" var th = el('th');\n"
1386+" th.appendChild(document.createTextNode(c.name));\n"
1387+" if (sortCol === i) {\n"
1388+" var dir = el('span','dir', sortDir > 0 ? ' \\u25b2' : ' \\u25bc');\n"
1389+" th.appendChild(dir);\n"
1390+" }\n"
1391+" th.title = c.decl || '';\n"
1392+" th.onclick = function(){\n"
1393+" if (sortCol === i) sortDir = -sortDir; else { sortCol = i; sortDir = 1; }\n"
1394+" var sorted = rows.slice().sort(function(a, b){\n"
1395+" var x = a[i], y = b[i];\n"
1396+" if (x === null || x === undefined) return 1;\n"
1397+" if (y === null || y === undefined) return -1;\n"
1398+" if (typeof x === 'number' && typeof y === 'number') return (x - y) * sortDir;\n"
1399+" return String(x).localeCompare(String(y)) * sortDir;\n"
1400+" });\n"
1401+" wrap.textContent = '';\n"
1402+" drawGrid(wrap, cols, sorted);\n"
1403+" };\n"
1404+" tr.appendChild(th);\n"
1405+" });\n"
1406+" thead.appendChild(tr);\n"
1407+" tbl.appendChild(thead);\n"
1408+" var tbody = el('tbody');\n"
1409+" rows.forEach(function(r){\n"
1410+" var row = el('tr');\n"
1411+" cols.forEach(function(c, i){\n"
1412+" var cv = cellValue(r[i]);\n"
1413+" var td = el('td', cv.cls, cv.t);\n"
1414+" td.title = cv.t;\n"
1415+" row.appendChild(td);\n"
1416+" });\n"
1417+" tbody.appendChild(row);\n"
1418+" });\n"
1419+" tbl.appendChild(tbody);\n"
1420+" wrap.appendChild(tbl);\n"
1421+"}\n"
1422+"\n"
1423+"/* ---- export ---- */\n"
1424+"function toCsv(d){\n"
1425+" var cols = (d.columns || []).map(function(c){ return c.name; });\n"
1426+" function q(v){\n"
1427+" if (v === null || v === undefined) return '';\n"
1428+" if (typeof v === 'object') return 'blob:' + v.blob_bytes;\n"
1429+" var s = String(v);\n"
1430+" return /[\",\\n\\r]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n"
1431+" }\n"
1432+" var out = [cols.map(q).join(',')];\n"
1433+" (d.rows || []).forEach(function(r){ out.push(r.map(q).join(',')); });\n"
1434+" return out.join('\\n');\n"
1435+"}\n"
1436+"function copy(text, label){\n"
1437+" var done = function(){ txt('qmeta', label + ' copied'); };\n"
1438+" if (navigator.clipboard && navigator.clipboard.writeText) {\n"
1439+" navigator.clipboard.writeText(text).then(done, function(){\n"
1440+" var ta = el('textarea'); ta.value = text; document.body.appendChild(ta);\n"
1441+" ta.select(); document.execCommand('copy'); document.body.removeChild(ta); done();\n"
1442+" });\n"
1443+" } else {\n"
1444+" var ta = el('textarea'); ta.value = text; document.body.appendChild(ta);\n"
1445+" ta.select(); document.execCommand('copy'); document.body.removeChild(ta); done();\n"
1446+" }\n"
1447+"}\n"
1448+"\n"
1449+"/* ---- theme ---- */\n"
1450+"function applyTheme(t){\n"
1451+" document.documentElement.setAttribute('data-theme', t);\n"
1452+" try { localStorage.setItem('sqlite_theme', t); } catch (e) {}\n"
1453+"}\n"
1454+"var savedTheme = null;\n"
1455+"try { savedTheme = localStorage.getItem('sqlite_theme'); } catch (e) {}\n"
1456+"applyTheme(savedTheme || (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));\n"
1457+"$('themebtn').onclick = function(){\n"
1458+" applyTheme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light');\n"
1459+"};\n"
1460+"\n"
1461+"/* ---- wiring ---- */\n"
1462+"$('dbsel').onchange = function(){ selectDb(this.value); };\n"
1463+"$('reloadbtn').onclick = function(){ loadDbs(); if (currentDb) selectDb(currentDb); };\n"
1464+"$('runbtn').onclick = runQuery;\n"
1465+"$('sql').addEventListener('keydown', function(e){\n"
1466+" if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); runQuery(); }\n"
1467+"});\n"
1468+"$('csvbtn').onclick = function(){ if (!lastData || !lastData.ok) { txt('qmeta','nothing to copy'); return; } copy(toCsv(lastData), 'CSV'); };\n"
1469+"$('jsonbtn').onclick = function(){ if (!lastData || !lastData.ok) { txt('qmeta','nothing to copy'); return; } copy(JSON.stringify(lastData.rows, null, 0), 'JSON'); };\n"
1470+"\n"
1471+"loadDbs();\n"
1472+"api('info').then(function(d){\n"
1473+" if (!d.ok) return;\n"
1474+" var box = $('info');\n"
1475+" $('infocard').style.display = '';\n"
1476+" [['plugin', d.plugin], ['version', d.version], ['sqlite', d.sqlite],\n"
1477+" ['platform', d.platform], ['max rows', d.max_rows], ['budget ms', d.budget_ms]].forEach(function(kv){\n"
1478+" box.appendChild(el('span','chip', kv[0] + ' ' + kv[1]));\n"
1479+" });\n"
1480+"}).catch(function(){});\n"
1481+"</script></body></html>\n", stdout);
1482+
1483+ return 0;
1484+}
1485+
1486+/* ------------------------------------------------------------------ */
1487+/* Main */
1488+/* ------------------------------------------------------------------ */
1489+
1490+int main(int argc, char **argv)
1491+{
1492+ const char *qs;
1493+ char action[64], db[512], sqlbuf[MAX_SQL], format[16];
1494+ int want_json = 0, embed = 0;
1495+
1496+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1497+ puts("{\"name\":\"sqlite\",\"desc\":\"SQLite viewer\"}");
1498+ return 0;
1499+ }
1500+ if (argc > 1 && strcmp(argv[1], "--version") == 0) {
1501+ printf("%s %s (sqlite %s)\n", PLUGIN_ID, PLUGIN_VER, sqlite3_libversion());
1502+ return 0;
1503+ }
1504+ if (argc > 1 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) {
1505+ fputs("usage: " PLUGIN_ID " [--meta|--version|--help]\n"
1506+ "\n"
1507+ "Run as a CGI-style executable. Modes:\n"
1508+ " --meta / SX_PLUGIN_META=1 discovery JSON\n"
1509+ " ?action=dbs list databases under the allowed roots\n"
1510+ " ?action=schema&db=<path> tables, columns, indexes, row counts\n"
1511+ " ?action=query&db=<path>&sql=<SELECT> bounded read-only query (GET or POST sql=)\n"
1512+ " ?action=info plugin build and limits\n"
1513+ " GET (default) HTML explorer (honours ?embed=1)\n"
1514+ "\n"
1515+ "Read-only: the authorizer allows SELECT/READ/FUNCTION/read-only PRAGMA only and\n"
1516+ "every database is opened with SQLITE_OPEN_READONLY. Rows are capped at 500.\n",
1517+ stdout);
1518+ return 0;
1519+ }
1520+
1521+ require_node_auth();
1522+
1523+ qs = getenv("QUERY_STRING");
1524+ if (!qs) qs = "";
1525+
1526+ action[0] = db[0] = sqlbuf[0] = format[0] = '\0';
1527+ get_query_val(qs, "action", action, sizeof action);
1528+ get_query_val(qs, "db", db, sizeof db);
1529+ get_query_val(qs, "sql", sqlbuf, sizeof sqlbuf);
1530+ get_query_val(qs, "format", format, sizeof format);
1531+
1532+ if (strstr(qs, "embed=1") || strstr(qs, "embed=true")) embed = 1;
1533+ if (ci_prefix(format, "json")) want_json = 1;
1534+
1535+ /* POST bodies arrive through the server's body file; read a plain
1536+ * urlencoded body and pull "sql" out of it. */
1537+ if (!sqlbuf[0]) {
1538+ const char *bodyfile = getenv("HTTP_BODY_FILE");
1539+ if (bodyfile && *bodyfile) {
1540+ FILE *f = fopen(bodyfile, "rb");
1541+ if (f) {
1542+ char body[MAX_SQL + 1024];
1543+ size_t n = fread(body, 1, sizeof(body) - 1, f);
1544+ body[n] = '\0';
1545+ fclose(f);
1546+ get_query_val(body, "sql", sqlbuf, sizeof sqlbuf);
1547+ if (!sqlbuf[0]) {
1548+ /* Some callers post the statement bare. */
1549+ copy_str(sqlbuf, sizeof sqlbuf, body);
1550+ }
1551+ }
1552+ }
1553+ }
1554+
1555+ if (!action[0] && want_json) copy_str(action, sizeof action, "dbs");
1556+
1557+ if (action[0]) {
1558+ if (strcmp(action, "dbs") == 0) { action_dbs(); return 0; }
1559+ if (strcmp(action, "schema") == 0) { action_schema(db); return 0; }
1560+ if (strcmp(action, "query") == 0) { action_query(db, sqlbuf); return 0; }
1561+ if (strcmp(action, "info") == 0) { action_info(); return 0; }
1562+ json_error("unknown_action", "supported actions: dbs, schema, query, info");
1563+ return 0;
1564+ }
1565+
1566+ mode_html(embed);
1567+ return 0;
1568+}
tests/run.sh+427−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..13c8788index 0000000..13c8788
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,427 @@@@ -0,0 +1,427 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_sqlite across all 3 modes.
3+#
4+# Builds a throwaway SQLite database in a temp directory, points the plugin at
5+# it with SQLITE_ALLOWED_ROOT, and proves:
6+# * discovery, schema and query all answer with well-formed JSON
7+# * the read-only contract holds (INSERT/UPDATE/DELETE/DROP/ALTER/ATTACH/
8+# CREATE are refused, both by the statement guard and by the authorizer)
9+# * path traversal, system paths and SQLite URI filenames are refused
10+# * the row cap and the statement time budget actually bite
11+# * node auth (401 / X-Bot-Password / Bearer / ?pwd=) behaves
12+# * the musl static build and the Windows PE are the right kind of file
13+# * the whole git history carries no secret and no LAN IP
14+#
15+# If musl / arm64 / Win64 artifacts are present they are checked too.
16+# Exit code 0 = everything passed.
17+
18+set -u
19+
20+ROOT=$(cd "$(dirname "$0")/.." && pwd)
21+cd "$ROOT" || exit 1
22+
23+BIN=./plugin_sqlite
24+PASS=0
25+FAIL=0
26+
27+if [ -t 1 ]; then
28+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
29+else
30+ C_OK=; C_BAD=; C_B=; C_0=
31+fi
32+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
33+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
34+
35+check() { # check <desc> <expected-substring> <actual>
36+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
37+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)"
38+ fi
39+}
40+
41+check_not() { # check_not <desc> <forbidden-substring> <actual>
42+ if printf '%s' "$3" | grep -F -q -- "$2"; then
43+ fail "$1 (must NOT contain: $2)"; else pass "$1"
44+ fi
45+}
46+
47+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
48+
49+# Strip the CGI header block, leaving the body.
50+body() { printf '%s' "$1" | sed '1,/^\r$/d'; }
51+
52+[ -x "$BIN" ] || { printf '%smissing %s - run make first%s\n' "$C_BAD" "$BIN" "$C_0" >&2; exit 1; }
53+
54+TMP=$(mktemp -d 2>/dev/null || echo "/tmp/plugin_sqlite_test.$$")
55+mkdir -p "$TMP"
56+trap 'rm -rf "$TMP"' EXIT 2>/dev/null || true
57+
58+# Export so every invocation below sees a narrow, predictable allowlist.
59+SQLITE_ALLOWED_ROOT="$TMP"; export SQLITE_ALLOWED_ROOT
60+
61+# ---------------------------------------------------------------- fixture
62+section "fixture"
63+if ! command -v python3 >/dev/null 2>&1; then
64+ printf '%sFAIL%s python3 is required to build the test database\n' "$C_BAD" "$C_0" >&2
65+ exit 1
66+fi
67+
68+python3 - "$TMP" <<'PY' || exit 1
69+import sqlite3, sys, os
70+tmp = sys.argv[1]
71+db = os.path.join(tmp, "shop.sqlite")
72+if os.path.exists(db):
73+ os.remove(db)
74+c = sqlite3.connect(db)
75+c.executescript("""
76+CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
77+CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id),
78+ total REAL, note BLOB, created TEXT);
79+CREATE INDEX idx_orders_cust ON orders(customer_id);
80+CREATE VIEW big_orders AS SELECT * FROM orders WHERE total > 100;
81+INSERT INTO customers(name,email) VALUES ('Ada','ada@example.com'),('Bo',NULL);
82+""")
83+for i in range(1200):
84+ c.execute("INSERT INTO orders(customer_id,total,note,created) VALUES(?,?,?,?)",
85+ (1 + (i % 2), (i % 500) + 0.5, b"\x01\x02", "2026-03-%02d" % (i % 28 + 1)))
86+c.commit()
87+c.close()
88+open(os.path.join(tmp, "notes.txt"), "w").write("not a database\n")
89+open(os.path.join(tmp, "fake.db"), "w").write("this is definitely not sqlite\n")
90+print(" fixture: %s (%d bytes)" % (db, os.path.getsize(db)))
91+PY
92+[ -f "$TMP/shop.sqlite" ] && pass "test database created" || { fail "test database missing"; exit 1; }
93+
94+DB="$TMP/shop.sqlite"
95+
96+# ---------------------------------------------------------------- mode 1
97+section "mode 1 --meta"
98+META=$("$BIN" --meta)
99+check "meta emits name sqlite" '"name":"sqlite"' "$META"
100+check "meta emits desc SQLite viewer" '"desc":"SQLite viewer"' "$META"
101+METAENV=$(SX_PLUGIN_META=1 "$BIN")
102+check "SX_PLUGIN_META=1 yields same meta" '"name":"sqlite"' "$METAENV"
103+LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
104+[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
105+printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
106+ && pass "meta is valid JSON" || fail "meta is not valid JSON"
107+DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
108+[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
109+NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
110+[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
111+check "--version prints version" '1.0.0' "$("$BIN" --version)"
112+check "--version names the sqlite lib" 'sqlite 3.' "$("$BIN" --version)"
113+check "--help is available" 'usage:' "$("$BIN" --help)"
114+META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
115+check "meta still works when BOT_PASSWORD is set" '"name":"sqlite"' "$META_AUTH"
116+
117+# ---------------------------------------------------------------- auth
118+section "node auth"
119+AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
120+check "no credentials -> 401" 'Status: 401' "$AUTHNONE"
121+check "401 body is json" 'invalid node password' "$AUTHNONE"
122+AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
123+check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")"
124+AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=info' "$BIN")
125+check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")"
126+AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=info&pwd=testpw' "$BIN")
127+check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")"
128+AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=info' "$BIN")
129+check "wrong password -> 401" 'Status: 401' "$AUTHBAD"
130+HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
131+check "html mode is also gated" 'Status: 401' "$HTMLAUTH"
132+
133+# ---------------------------------------------------------------- dbs
134+section "mode 2 action=dbs"
135+DBS=$(body "$(QUERY_STRING='action=dbs' "$BIN")")
136+printf '%s' "$DBS" > "$TMP/dbs.json"
137+check "dbs ok:true" '"ok":true' "$DBS"
138+check "dbs names the plugin" '"plugin":"plugin_sqlite"' "$DBS"
139+check "dbs declares read-only" '"readonly":true' "$DBS"
140+check "dbs carries the allowed root" "$TMP" "$DBS"
141+check "dbs finds our database" 'shop.sqlite' "$DBS"
142+check "dbs reports a count" '"count":' "$DBS"
143+printf '%s' "$DBS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
144+ && pass "dbs body is valid JSON" || fail "dbs body JSON invalid"
145+python3 - "$TMP/dbs.json" <<'PYEOF' && pass "dbs rows are well formed" || fail "dbs rows malformed"
146+import json, sys
147+d = json.load(open(sys.argv[1]))
148+assert d["ok"] is True
149+assert d["count"] == len(d["dbs"])
150+assert d["count"] >= 1
151+names = [x["path"] for x in d["dbs"]]
152+assert any(p.endswith("shop.sqlite") for p in names), names
153+assert not any(p.endswith("notes.txt") for p in names), names
154+for x in d["dbs"]:
155+ assert x["bytes"] > 0
156+ assert x["root"]
157+ assert x["mtime"].endswith("Z")
158+PYEOF
159+check_not "dbs ignores non-db files" 'notes.txt' "$DBS"
160+
161+# ---------------------------------------------------------------- schema
162+section "mode 2 action=schema"
163+SCHEMA=$(body "$(QUERY_STRING="action=schema&db=$DB" "$BIN")")
164+printf '%s' "$SCHEMA" > "$TMP/schema.json"
165+check "schema ok:true" '"ok":true' "$SCHEMA"
166+check "schema names the database" "$DB" "$SCHEMA"
167+check "schema lists customers" '"name":"customers"' "$SCHEMA"
168+check "schema lists orders" '"name":"orders"' "$SCHEMA"
169+check "schema marks the view" '"type":"view"' "$SCHEMA"
170+check "schema reports the index" 'idx_orders_cust' "$SCHEMA"
171+check "schema has column detail" '"notnull":true' "$SCHEMA"
172+python3 - "$TMP/schema.json" <<'PYEOF' && pass "schema rows are well formed" || fail "schema malformed"
173+import json, sys
174+d = json.load(open(sys.argv[1]))
175+assert d["ok"] is True and d["readonly"] is True
176+tables = {t["name"]: t for t in d["tables"]}
177+assert "customers" in tables and "orders" in tables and "big_orders" in tables
178+assert tables["orders"]["rows"] == 1200, tables["orders"]["rows"]
179+assert tables["customers"]["rows"] == 2
180+cols = {c["name"]: c for c in tables["orders"]["columns"]}
181+assert cols["customer_id"]["type"] == "INTEGER"
182+assert [i["name"] for i in tables["orders"]["indexes"]] == ["idx_orders_cust"]
183+assert tables["customers"]["type"] == "table"
184+assert tables["big_orders"]["type"] == "view"
185+PYEOF
186+SCHEMA_MISS=$(body "$(QUERY_STRING="action=schema&db=$TMP/nope.sqlite" "$BIN")")
187+SCHEMA_FAKE=$(body "$(QUERY_STRING="action=schema&db=$TMP/fake.db" "$BIN")")
188+check "non-sqlite file -> not_a_database" 'not_a_database' "$SCHEMA_FAKE"
189+
190+# ---------------------------------------------------------------- query
191+section "mode 2 action=query (allowed)"
192+Q1=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
193+check "count(*) works" '[[1200]]' "$Q1"
194+check "query reports row_count" '"row_count":1' "$Q1"
195+check "query reports elapsed ms" '"ms":' "$Q1"
196+check "query reports column types" '"types":["int"]' "$Q1"
197+
198+Q2=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+name,email+from+customers+order+by+id" "$BIN")")
199+check "text values are quoted" '"Ada"' "$Q2"
200+check "NULL becomes json null" 'null' "$Q2"
201+
202+Q3=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+total,note+from+orders+limit+1" "$BIN")")
203+check "real numbers are emitted" '"total"' "$Q3"
204+check "blobs become a hex preview" '"blob_bytes":2' "$Q3"
205+check "blob hex is the real bytes" '"hex":"0102"' "$Q3"
206+
207+Q4=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+table_info(orders)" "$BIN")")
208+check "read-only pragma runs" '"customer_id"' "$Q4"
209+
210+Q5=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+integrity_check" "$BIN")")
211+check "integrity_check runs" '"ok"' "$Q5"
212+
213+Q6=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+o+AS+(SELECT+id+FROM+orders)+SELECT+count(*)+FROM+o" "$BIN")")
214+check "WITH / CTE select works" '[[1200]]' "$Q6"
215+
216+Q7=$(body "$(QUERY_STRING="action=query&db=$DB&sql=explain+select+1" "$BIN")")
217+check "EXPLAIN works" '"ok":true' "$Q7"
218+
219+# POST-style body parsing
220+printf 'sql=select+42+as+answer' > "$TMP/body.txt"
221+Q8=$(body "$(HTTP_BODY_FILE="$TMP/body.txt" QUERY_STRING="action=query&db=$DB" "$BIN")")
222+check "POST body sql= is parsed" '[[42]]' "$Q8"
223+
224+# ---------------------------------------------------------------- row cap
225+section "row cap and time budget"
226+CAP=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+*+from+orders" "$BIN")")
227+check "unbounded select is capped" '"row_count":500' "$CAP"
228+check "cap is flagged as truncated" '"truncated":true' "$CAP"
229+check "cap declares the limit" '"limit":500' "$CAP"
230+printf '%s' "$CAP" | python3 -c '
231+import json,sys
232+d = json.load(sys.stdin)
233+assert len(d["rows"]) == 500, len(d["rows"])
234+assert d["row_count"] == 500
235+' 2>/dev/null && pass "exactly 500 rows were streamed" || fail "row cap did not produce 500 rows"
236+
237+BUDGET=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+RECURSIVE+c(i)+AS(SELECT+1+UNION+ALL+SELECT+i%2B1+FROM+c+WHERE+i%3C30000000)+SELECT+count(*)+FROM+c" "$BIN")")
238+check "runaway recursion is stopped" '"aborted":true' "$BUDGET"
239+
240+# ---------------------------------------------------------------- read-only
241+section "read-only enforcement"
242+deny() { # deny <desc> <sql>
243+ local out
244+ out=$(body "$(QUERY_STRING="action=query&db=$DB&sql=$2" "$BIN")")
245+ case "$out" in
246+ *'"ok":false'*) pass "$1 rejected" ;;
247+ *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
248+ esac
249+}
250+deny "INSERT" "insert+into+customers(name)+values('x')"
251+deny "UPDATE" "update+customers+set+name='x'"
252+deny "DELETE" "delete+from+customers"
253+deny "DROP TABLE" "drop+table+orders"
254+deny "ALTER TABLE" "alter+table+orders+add+column+x+int"
255+deny "CREATE TABLE" "create+table+x(a)"
256+deny "CREATE VIEW" "create+view+v+as+select+1"
257+deny "ATTACH" "attach+%27$TMP%2Fevil.db%27+as+evil"
258+deny "DETACH" "detach+main"
259+deny "REINDEX" "reindex"
260+deny "VACUUM" "vacuum"
261+deny "BEGIN" "begin"
262+deny "PRAGMA write" "pragma+user_version%3D5"
263+deny "stacked stmt" "select+1%3B+drop+table+orders"
264+deny "WITH-DELETE" "WITH+x+AS(SELECT+1)+DELETE+FROM+customers"
265+
266+# Row-count evidence that nothing above actually mutated the file.
267+AFTER=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
268+check "orders still has 1200 rows" '[[1200]]' "$AFTER"
269+AFTER_C=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+customers" "$BIN")")
270+check "customers still has 2 rows" '[[2]]' "$AFTER_C"
271+[ ! -f "$TMP/evil.db" ] && pass "ATTACH created no file" || fail "ATTACH created $TMP/evil.db"
272+
273+# The authorizer is the second line of defence; prove it fires directly.
274+python3 - "$DB" <<'PY' && pass "on-disk mtime proves no write happened" || fail "database file changed"
275+import os, sqlite3, sys, time
276+db = sys.argv[1]
277+before = os.stat(db).st_mtime
278+c = sqlite3.connect(db)
279+c.execute("SELECT count(*) FROM orders").fetchone()
280+c.close()
281+assert os.stat(db).st_mtime == before
282+PY
283+
284+# ---------------------------------------------------------------- paths
285+section "path discipline"
286+bad_path() { # bad_path <desc> <db-query-value>
287+ local out
288+ out=$(body "$(QUERY_STRING="action=query&db=$2&sql=select+1" "$BIN")")
289+ case "$out" in
290+ *forbidden_path*) pass "$1 rejected" ;;
291+ *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
292+ esac
293+}
294+bad_path "/etc/passwd" "/etc/passwd"
295+bad_path "../ traversal" "$TMP/../../etc/passwd"
296+bad_path "encoded traversal" "$TMP/%2e%2e/%2e%2e/etc/passwd"
297+bad_path "SQLite URI filename" "file:$DB"
298+bad_path "URI with mode=rwc" "file:$DB%3Fmode%3Drwc"
299+bad_path "http scheme" "http://example.com/x.db"
300+bad_path "non-db suffix" "$TMP/notes.txt"
301+bad_path "arbitrary root" "/etc/hosts.db"
302+
303+MISSING=$(body "$(QUERY_STRING="action=query&db=$TMP/absent.sqlite&sql=select+1" "$BIN")")
304+check "allowed location, missing file -> not_found" 'not_found' "$MISSING"
305+
306+# ---------------------------------------------------------------- misc
307+section "mode 2 misc"
308+INFO=$(body "$(QUERY_STRING='action=info' "$BIN")")
309+check "info names the plugin" '"plugin":"plugin_sqlite"' "$INFO"
310+check "info names the sqlite version" '"sqlite":"3.' "$INFO"
311+check "info declares read-only" '"readonly":true' "$INFO"
312+check "info declares zero_network" '"zero_network":true' "$INFO"
313+check "info declares no extension load" '"load_extension":false' "$INFO"
314+check "info lists the actions" '"dbs","schema","query","info"' "$INFO"
315+check "info declares max_rows" '"max_rows":500' "$INFO"
316+
317+UNK=$(body "$(QUERY_STRING='action=nope' "$BIN")")
318+check "unknown action is refused" 'unknown_action' "$UNK"
319+JSONF=$(body "$(QUERY_STRING='format=json' "$BIN")")
320+check "format=json falls back to dbs" '"action":"dbs"' "$JSONF"
321+NOSQL=$(body "$(QUERY_STRING="action=query&db=$DB" "$BIN")")
322+check "query without sql -> missing_sql" 'missing_sql' "$NOSQL"
323+
324+# ---------------------------------------------------------------- mode 3
325+section "mode 3 html"
326+HTML=$("$BIN")
327+check "html content type" 'Content-Type: text/html' "$HTML"
328+check "html has a doctype" '<!DOCTYPE html>' "$HTML"
329+check "html titles the tool" '<title>sqlite</title>' "$HTML"
330+check "html ships the sql editor" "id='sql'" "$HTML"
331+check "html ships the db picker" "id='dbsel'" "$HTML"
332+check "html ships the result grid" "id='reswrap'" "$HTML"
333+check "html supports ctrl+enter" 'Ctrl' "$HTML"
334+check "html offers CSV copy" 'Copy CSV' "$HTML"
335+check "html offers JSON copy" 'Copy JSON' "$HTML"
336+check "html declares the node route" '/plugin_sqlite?action=' "$HTML"
337+check "html declares the hub route" "/plugins?plugin=" "$HTML"
338+check "html honours embed" "/plugin_sqlite?action=" "$HTML"
339+check "html supports light theme" "data-theme=light" "$HTML"
340+check_not "html has no CDN script" '<script src=' "$HTML"
341+check_not "html has no cdnjs" 'cdnjs' "$HTML"
342+check_not "html emits no Content-Length" 'Content-Length' "$HTML"
343+EMBED=$("$BIN" </dev/null 2>/dev/null | head -1)
344+EMBEDQ=$(QUERY_STRING='embed=1' "$BIN")
345+check_not "embed=1 drops the back link" 'Back to Bot' "$EMBEDQ"
346+check "non-embed keeps the back link" 'Back to Bot' "$HTML"
347+
348+# ---------------------------------------------------------------- artifacts
349+section "cross builds"
350+if [ -f plugin_sqlite.musl ]; then
351+ MAGIC=$(od -An -tx1 -N4 plugin_sqlite.musl | tr -d ' \n')
352+ [ "$MAGIC" = "7f454c46" ] && pass "musl artifact is an ELF" || fail "musl artifact is not ELF ($MAGIC)"
353+ python3 - plugin_sqlite.musl <<'PY' && pass "musl artifact is x86_64 (EM_X86_64=62)" || fail "musl artifact wrong machine"
354+import sys, struct
355+d = open(sys.argv[1], "rb").read(20)
356+assert d[4] == 2, "not 64-bit"
357+assert d[5] == 1, "not little-endian"
358+assert struct.unpack("<H", d[18:20])[0] == 62
359+PY
360+ if command -v readelf >/dev/null 2>&1; then
361+ readelf -d plugin_sqlite.musl 2>/dev/null | grep -q NEEDED \
362+ && fail "musl artifact is dynamically linked" || pass "musl artifact is fully static"
363+ fi
364+else
365+ printf ' skip musl artifact (not built)\n'
366+fi
367+
368+if [ -f plugin_sqlite.arm64 ]; then
369+ python3 - plugin_sqlite.arm64 <<'PY' && pass "arm64 artifact is EM_AARCH64 (183)" || fail "arm64 artifact wrong machine"
370+import sys, struct
371+d = open(sys.argv[1], "rb").read(20)
372+assert d[4] == 2, "not 64-bit"
373+assert d[5] == 1, "not little-endian"
374+assert struct.unpack("<H", d[18:20])[0] == 183
375+PY
376+else
377+ printf ' skip arm64 artifact (not built)\n'
378+fi
379+
380+if [ -f plugin_sqlite.exe ]; then
381+ MZ=$(head -c 2 plugin_sqlite.exe)
382+ [ "$MZ" = "MZ" ] && pass "windows artifact starts with MZ" || fail "windows artifact is not a PE"
383+ SZ=$(wc -c < plugin_sqlite.exe | tr -d ' ')
384+ [ "$SZ" -gt 200000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
385+else
386+ printf ' skip windows artifact (not built)\n'
387+fi
388+
389+# ---------------------------------------------------------------- history
390+section "git history audit"
391+if [ -d .git ]; then
392+ SCAN="$TMP/history.txt"
393+ P_ROOT=$(pwd); P_WT=$(pwd)
394+ git log -p --all 2>/dev/null \
395+ | grep -v '^Author: ' \
396+ | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
397+ > "$SCAN" || : > "$SCAN"
398+ HITS=0
399+ scan() { # scan <label> <regex>
400+ out=$(grep -Eo "$2" "$SCAN" 2>/dev/null | sort -u | head -5 || true)
401+ if [ -n "$out" ]; then
402+ printf ' %sHIT%s %s\n %s\n' "$C_BAD" "$C_0" "$1" "$(printf '%s' "$out" | tr '\n' ' ')"
403+ HITS=$((HITS + 1))
404+ else
405+ pass "no $1 in history"
406+ fi
407+ }
408+ scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
409+ scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
410+ scan "private 172.16-31.x.x" '\b172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
411+ scan "GitHub tokens" 'ghp_[A-Za-z0-9]{20,}'
412+ scan "HuggingFace tokens" 'hf_[A-Za-z0-9]{20,}'
413+ scan "AWS access keys" 'AKIA[0-9A-Z]{16}'
414+ scan "OpenAI keys" 'sk-[A-Za-z0-9]{32,}'
415+ scan "private keys" 'BEGIN (RSA|OPENSSH|EC|PGP) PRIVATE KEY'
416+ scan "passwords in source" '(password|passwd|secret)[[:space:]]*=[[:space:]]*"[^"]{4,}"'
417+ [ "$HITS" -eq 0 ] && pass "history audit clean (0 hits)" || fail "history audit found $HITS category(ies)"
418+else
419+ printf ' skip history audit (not a git repo)\n'
420+fi
421+
422+# ---------------------------------------------------------------- summary
423+printf '\n%s----------------------------------------%s\n' "$C_B" "$C_0"
424+printf ' %spass %d%s %sfail %d%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
425+[ "$FAIL" -eq 0 ] && { printf ' %sALL PASS%s\n' "$C_OK" "$C_0"; exit 0; }
426+printf ' %sFAILURES%s\n' "$C_BAD" "$C_0"
427+exit 1
vendor/sqlite3.c+1674−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0644a39index 0000000..0644a39
--- /dev/null--- /dev/null
+++ b/vendor/sqlite3.c+++ b/vendor/sqlite3.c
@@ -0,0 +1,269649 @@@@ -0,0 +1,269649 @@
1+/******************************************************************************
2+** This file is an amalgamation of many separate C source files from SQLite
3+** version 3.53.4. By combining all the individual C code files into this
4+** single large file, the entire code can be compiled as a single translation
5+** unit. This allows many compilers to do optimizations that would not be
6+** possible if the files were compiled separately. Performance improvements
7+** of 5% or more are commonly seen when SQLite is compiled as a single
8+** translation unit.
9+**
10+** This file is all you need to compile SQLite. To use SQLite in other
11+** programs, you need this file and the "sqlite3.h" header file that defines
12+** the programming interface to the SQLite library. (If you do not have
13+** the "sqlite3.h" header file at hand, you will find a copy embedded within
14+** the text of this file. Search for "Begin file sqlite3.h" to find the start
15+** of the embedded sqlite3.h header file.) Additional code files may be needed
16+** if you want a wrapper to interface SQLite with your choice of programming
17+** language. The code for the "sqlite3" command-line shell is also in a
18+** separate file. This file contains only code for the core SQLite library.
19+**
20+** The content in this amalgamation comes from Fossil check-in
21+** bf7c7f30031888f4e796e429ab3978879485 with changes in files:
22+**
23+**
24+*/
25+#ifndef SQLITE_AMALGAMATION
26+#define SQLITE_CORE 1
27+#define SQLITE_AMALGAMATION 1
28+#ifndef SQLITE_PRIVATE
29+# define SQLITE_PRIVATE static
30+#endif
31+/************** Begin file sqliteInt.h ***************************************/
32+/*
33+** 2001 September 15
34+**
35+** The author disclaims copyright to this source code. In place of
36+** a legal notice, here is a blessing:
37+**
38+** May you do good and not evil.
39+** May you find forgiveness for yourself and forgive others.
40+** May you share freely, never taking more than you give.
41+**
42+*************************************************************************
43+** Internal interface definitions for SQLite.
44+**
45+*/
46+#ifndef SQLITEINT_H
47+#define SQLITEINT_H
48+
49+/* Special Comments:
50+**
51+** Some comments have special meaning to the tools that measure test
52+** coverage:
53+**
54+** NO_TEST - The branches on this line are not
55+** measured by branch coverage. This is
56+** used on lines of code that actually
57+** implement parts of coverage testing.
58+**
59+** OPTIMIZATION-IF-TRUE - This branch is allowed to always be false
60+** and the correct answer is still obtained,
61+** though perhaps more slowly.
62+**
63+** OPTIMIZATION-IF-FALSE - This branch is allowed to always be true
64+** and the correct answer is still obtained,
65+** though perhaps more slowly.
66+**
67+** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
68+** that would be harmless and undetectable
69+** if it did occur.
70+**
71+** In all cases, the special comment must be enclosed in the usual
72+** slash-asterisk...asterisk-slash comment marks, with no spaces between the
73+** asterisks and the comment text.
74+*/
75+
76+/*
77+** Make sure the Tcl calling convention macro is defined. This macro is
78+** only used by test code and Tcl integration code.
79+*/
80+#ifndef SQLITE_TCLAPI
81+# define SQLITE_TCLAPI
82+#endif
83+
84+/*
85+** Include the header file used to customize the compiler options for MSVC.
86+** This should be done first so that it can successfully prevent spurious
87+** compiler warnings due to subsequent content in this file and other files
88+** that are included by this file.
89+*/
90+/************** Include msvc.h in the middle of sqliteInt.h ******************/
91+/************** Begin file msvc.h ********************************************/
92+/*
93+** 2015 January 12
94+**
95+** The author disclaims copyright to this source code. In place of
96+** a legal notice, here is a blessing:
97+**
98+** May you do good and not evil.
99+** May you find forgiveness for yourself and forgive others.
100+** May you share freely, never taking more than you give.
101+**
102+******************************************************************************
103+**
104+** This file contains code that is specific to MSVC.
105+*/
106+#ifndef SQLITE_MSVC_H
107+#define SQLITE_MSVC_H
108+
109+#if defined(_MSC_VER)
110+#pragma warning(disable : 4054)
111+#pragma warning(disable : 4055)
112+#pragma warning(disable : 4100)
113+#pragma warning(disable : 4127)
114+#pragma warning(disable : 4130)
115+#pragma warning(disable : 4152)
116+#pragma warning(disable : 4189)
117+#pragma warning(disable : 4206)
118+#pragma warning(disable : 4210)
119+#pragma warning(disable : 4232)
120+#pragma warning(disable : 4244)
121+#pragma warning(disable : 4305)
122+#pragma warning(disable : 4306)
123+#pragma warning(disable : 4702)
124+#pragma warning(disable : 4706)
125+#endif /* defined(_MSC_VER) */
126+
127+#if defined(_MSC_VER) && !defined(_WIN64)
128+#undef SQLITE_4_BYTE_ALIGNED_MALLOC
129+#define SQLITE_4_BYTE_ALIGNED_MALLOC
130+#endif /* defined(_MSC_VER) && !defined(_WIN64) */
131+
132+#if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800
133+#define HAVE_LOG2 0
134+#endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */
135+
136+#endif /* SQLITE_MSVC_H */
137+
138+/************** End of msvc.h ************************************************/
139+/************** Continuing where we left off in sqliteInt.h ******************/
140+
141+/*
142+** Special setup for VxWorks
143+*/
144+/************** Include vxworks.h in the middle of sqliteInt.h ***************/
145+/************** Begin file vxworks.h *****************************************/
146+/*
147+** 2015-03-02
148+**
149+** The author disclaims copyright to this source code. In place of
150+** a legal notice, here is a blessing:
151+**
152+** May you do good and not evil.
153+** May you find forgiveness for yourself and forgive others.
154+** May you share freely, never taking more than you give.
155+**
156+******************************************************************************
157+**
158+** This file contains code that is specific to Wind River's VxWorks
159+*/
160+#if defined(__RTP__) || defined(_WRS_KERNEL)
161+/* This is VxWorks. Set up things specially for that OS
162+*/
163+#include <vxWorks.h>
164+#include <pthread.h> /* amalgamator: dontcache */
165+#define OS_VXWORKS 1
166+#define SQLITE_OS_OTHER 0
167+#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
168+#define SQLITE_OMIT_LOAD_EXTENSION 1
169+#define SQLITE_ENABLE_LOCKING_STYLE 0
170+#define HAVE_UTIME 1
171+#else
172+/* This is not VxWorks. */
173+#ifndef OS_VXWORKS
174+# define OS_VXWORKS 0
175+#endif
176+#define HAVE_FCHOWN 1
177+#define HAVE_READLINK 1
178+#define HAVE_LSTAT 1
179+#endif /* defined(_WRS_KERNEL) */
180+
181+/************** End of vxworks.h *********************************************/
182+/************** Continuing where we left off in sqliteInt.h ******************/
183+
184+/*
185+** These #defines should enable >2GB file support on POSIX if the
186+** underlying operating system supports it. If the OS lacks
187+** large file support, or if the OS is windows, these should be no-ops.
188+**
189+** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
190+** system #includes. Hence, this block of code must be the very first
191+** code in all source files.
192+**
193+** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
194+** on the compiler command line. This is necessary if you are compiling
195+** on a recent machine (ex: Red Hat 7.2) but you want your code to work
196+** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
197+** without this option, LFS is enable. But LFS does not exist in the kernel
198+** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
199+** portability you should omit LFS.
200+**
201+** The previous paragraph was written in 2005. (This paragraph is written
202+** on 2008-11-28.) These days, all Linux kernels support large files, so
203+** you should probably leave LFS enabled. But some embedded platforms might
204+** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
205+**
206+** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
207+*/
208+#ifndef SQLITE_DISABLE_LFS
209+# define _LARGE_FILE 1
210+# ifndef _FILE_OFFSET_BITS
211+# define _FILE_OFFSET_BITS 64
212+# endif
213+# define _LARGEFILE_SOURCE 1
214+#endif
215+
216+/* The GCC_VERSION and MSVC_VERSION macros are used to
217+** conditionally include optimizations for each of these compilers. A
218+** value of 0 means that compiler is not being used. The
219+** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
220+** optimizations, and hence set all compiler macros to 0
221+**
222+** There was once also a CLANG_VERSION macro. However, we learn that the
223+** version numbers in clang are for "marketing" only and are inconsistent
224+** and unreliable. Fortunately, all versions of clang also recognize the
225+** gcc version numbers and have reasonable settings for gcc version numbers,
226+** so the GCC_VERSION macro will be set to a correct non-zero value even
227+** when compiling with clang.
228+*/
229+#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
230+# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
231+#else
232+# define GCC_VERSION 0
233+#endif
234+#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
235+# define MSVC_VERSION _MSC_VER
236+#else
237+# define MSVC_VERSION 0
238+#endif
239+
240+/*
241+** Some C99 functions in "math.h" are only present for MSVC when its version
242+** is associated with Visual Studio 2013 or higher.
243+*/
244+#ifndef SQLITE_HAVE_C99_MATH_FUNCS
245+# if MSVC_VERSION==0 || MSVC_VERSION>=1800
246+# define SQLITE_HAVE_C99_MATH_FUNCS (1)
247+# else
248+# define SQLITE_HAVE_C99_MATH_FUNCS (0)
249+# endif
250+#endif
251+
252+/* Needed for various definitions... */
253+#if defined(__GNUC__) && !defined(_GNU_SOURCE)
254+# define _GNU_SOURCE
255+#endif
256+
257+#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
258+# define _BSD_SOURCE
259+#endif
260+
261+/*
262+** Macro to disable warnings about missing "break" at the end of a "case".
263+*/
264+#if defined(__has_attribute)
265+# if __has_attribute(fallthrough)
266+# define deliberate_fall_through __attribute__((fallthrough));
267+# endif
268+#endif
269+#if !defined(deliberate_fall_through)
270+# define deliberate_fall_through
271+#endif
272+
273+/*
274+** For MinGW, check to see if we can include the header file containing its
275+** version information, among other things. Normally, this internal MinGW
276+** header file would [only] be included automatically by other MinGW header
277+** files; however, the contained version information is now required by this
278+** header file to work around binary compatibility issues (see below) and
279+** this is the only known way to reliably obtain it. This entire #if block
280+** would be completely unnecessary if there was any other way of detecting
281+** MinGW via their preprocessor (e.g. if they customized their GCC to define
282+** some MinGW-specific macros). When compiling for MinGW, either the
283+** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
284+** defined; otherwise, detection of conditions specific to MinGW will be
285+** disabled.
286+*/
287+#if defined(_HAVE_MINGW_H)
288+# include "mingw.h"
289+#elif defined(_HAVE__MINGW_H)
290+# include "_mingw.h"
291+#endif
292+
293+/*
294+** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
295+** define is required to maintain binary compatibility with the MSVC runtime
296+** library in use (e.g. for Windows XP).
297+*/
298+#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
299+ defined(_WIN32) && !defined(_WIN64) && \
300+ defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
301+ defined(__MSVCRT__)
302+# define _USE_32BIT_TIME_T
303+#endif
304+
305+/* Optionally #include a user-defined header, whereby compilation options
306+** may be set prior to where they take effect, but after platform setup.
307+** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
308+** file.
309+*/
310+#ifdef SQLITE_CUSTOM_INCLUDE
311+# define INC_STRINGIFY_(f) #f
312+# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
313+# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
314+#endif
315+
316+/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
317+** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
318+** MinGW.
319+*/
320+/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
321+/************** Begin file sqlite3.h *****************************************/
322+/*
323+** 2001-09-15
324+**
325+** The author disclaims copyright to this source code. In place of
326+** a legal notice, here is a blessing:
327+**
328+** May you do good and not evil.
329+** May you find forgiveness for yourself and forgive others.
330+** May you share freely, never taking more than you give.
331+**
332+*************************************************************************
333+** This header file defines the interface that the SQLite library
334+** presents to client programs. If a C-function, structure, datatype,
335+** or constant definition does not appear in this file, then it is
336+** not a published API of SQLite, is subject to change without
337+** notice, and should not be referenced by programs that use SQLite.
338+**
339+** Some of the definitions that are in this file are marked as
340+** "experimental". Experimental interfaces are normally new
341+** features recently added to SQLite. We do not anticipate changes
342+** to experimental interfaces but reserve the right to make minor changes
343+** if experience from use "in the wild" suggest such changes are prudent.
344+**
345+** The official C-language API documentation for SQLite is derived
346+** from comments in this file. This file is the authoritative source
347+** on how SQLite interfaces are supposed to operate.
348+**
349+** The name of this file under configuration management is "sqlite.h.in".
350+** The makefile makes some minor changes to this file (such as inserting
351+** the version number) and changes its name to "sqlite3.h" as
352+** part of the build process.
353+*/
354+#ifndef SQLITE3_H
355+#define SQLITE3_H
356+#include <stdarg.h> /* Needed for the definition of va_list */
357+
358+/*
359+** Make sure we can call this stuff from C++.
360+*/
361+#if 0
362+extern "C" {
363+#endif
364+
365+
366+/*
367+** Facilitate override of interface linkage and calling conventions.
368+** Be aware that these macros may not be used within this particular
369+** translation of the amalgamation and its associated header file.
370+**
371+** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
372+** compiler that the target identifier should have external linkage.
373+**
374+** The SQLITE_CDECL macro is used to set the calling convention for
375+** public functions that accept a variable number of arguments.
376+**
377+** The SQLITE_APICALL macro is used to set the calling convention for
378+** public functions that accept a fixed number of arguments.
379+**
380+** The SQLITE_STDCALL macro is no longer used and is now deprecated.
381+**
382+** The SQLITE_CALLBACK macro is used to set the calling convention for
383+** function pointers.
384+**
385+** The SQLITE_SYSAPI macro is used to set the calling convention for
386+** functions provided by the operating system.
387+**
388+** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
389+** SQLITE_SYSAPI macros are used only when building for environments
390+** that require non-default calling conventions.
391+*/
392+#ifndef SQLITE_EXTERN
393+# define SQLITE_EXTERN extern
394+#endif
395+#ifndef SQLITE_API
396+# define SQLITE_API
397+#endif
398+#ifndef SQLITE_CDECL
399+# define SQLITE_CDECL
400+#endif
401+#ifndef SQLITE_APICALL
402+# define SQLITE_APICALL
403+#endif
404+#ifndef SQLITE_STDCALL
405+# define SQLITE_STDCALL SQLITE_APICALL
406+#endif
407+#ifndef SQLITE_CALLBACK
408+# define SQLITE_CALLBACK
409+#endif
410+#ifndef SQLITE_SYSAPI
411+# define SQLITE_SYSAPI
412+#endif
413+
414+/*
415+** These no-op macros are used in front of interfaces to mark those
416+** interfaces as either deprecated or experimental. New applications
417+** should not use deprecated interfaces - they are supported for backwards
418+** compatibility only. Application writers should be aware that
419+** experimental interfaces are subject to change in point releases.
420+**
421+** These macros used to resolve to various kinds of compiler magic that
422+** would generate warning messages when they were used. But that
423+** compiler magic ended up generating such a flurry of bug reports
424+** that we have taken it all out and gone back to using simple
425+** noop macros.
426+*/
427+#define SQLITE_DEPRECATED
428+#define SQLITE_EXPERIMENTAL
429+
430+/*
431+** Ensure these symbols were not defined by some previous header file.
432+*/
433+#ifdef SQLITE_VERSION
434+# undef SQLITE_VERSION
435+#endif
436+#ifdef SQLITE_VERSION_NUMBER
437+# undef SQLITE_VERSION_NUMBER
438+#endif
439+
440+/*
441+** CAPI3REF: Compile-Time Library Version Numbers
442+**
443+** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
444+** evaluates to a string literal that is the SQLite version in the
445+** format "X.Y.Z" where X is the major version number (always 3 for
446+** SQLite3) and Y is the minor version number and Z is the release number.)^
447+** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
448+** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
449+** numbers used in [SQLITE_VERSION].)^
450+** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
451+** be larger than the release from which it is derived. Either Y will
452+** be held constant and Z will be incremented or else Y will be incremented
453+** and Z will be reset to zero.
454+**
455+** Since [version 3.6.18] ([dateof:3.6.18]),
456+** SQLite source code has been stored in the
457+** <a href="http://fossil-scm.org/">Fossil configuration management
458+** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
459+** a string which identifies a particular check-in of SQLite
460+** within its configuration management system. ^The SQLITE_SOURCE_ID
461+** string contains the date and time of the check-in (UTC) and a SHA1
462+** or SHA3-256 hash of the entire source tree. If the source code has
463+** been edited in any way since it was last checked in, then the last
464+** four hexadecimal digits of the hash may be modified.
465+**
466+** See also: [sqlite3_libversion()],
467+** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468+** [sqlite_version()] and [sqlite_source_id()].
469+*/
470+#define SQLITE_VERSION "3.53.4"
471+#define SQLITE_VERSION_NUMBER 3053004
472+#define SQLITE_SOURCE_ID "2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc"
473+#define SQLITE_SCM_BRANCH "branch-3.53"
474+#define SQLITE_SCM_TAGS "release version-3.53.4"
475+#define SQLITE_SCM_DATETIME "2026-07-24T19:02:57.525Z"
476+
477+/*
478+** CAPI3REF: Run-Time Library Version Numbers
479+** KEYWORDS: sqlite3_version sqlite3_sourceid
480+**
481+** These interfaces provide the same information as the [SQLITE_VERSION],
482+** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
483+** but are associated with the library instead of the header file. ^(Cautious
484+** programmers might include assert() statements in their application to
485+** verify that values returned by these interfaces match the macros in
486+** the header, and thus ensure that the application is
487+** compiled with matching library and header files.
488+**
489+** <blockquote><pre>
490+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
491+** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
492+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
493+** </pre></blockquote>)^
494+**
495+** ^The sqlite3_version[] string constant contains the text of the
496+** [SQLITE_VERSION] macro. ^The sqlite3_libversion() function returns a
497+** pointer to the sqlite3_version[] string constant. The sqlite3_libversion()
498+** function is provided for use in DLLs since DLL users usually do not have
499+** direct access to string constants within the DLL. ^The
500+** sqlite3_libversion_number() function returns an integer equal to
501+** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
502+** a pointer to a string constant whose value is the same as the
503+** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
504+** using an edited copy of [the amalgamation], then the last four characters
505+** of the hash might be different from [SQLITE_SOURCE_ID].)^
506+**
507+** See also: [sqlite_version()] and [sqlite_source_id()].
508+*/
509+SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
510+SQLITE_API const char *sqlite3_libversion(void);
511+SQLITE_API const char *sqlite3_sourceid(void);
512+SQLITE_API int sqlite3_libversion_number(void);
513+
514+/*
515+** CAPI3REF: Run-Time Library Compilation Options Diagnostics
516+**
517+** ^The sqlite3_compileoption_used() function returns 0 or 1
518+** indicating whether the specified option was defined at
519+** compile time. ^The SQLITE_ prefix may be omitted from the
520+** option name passed to sqlite3_compileoption_used().
521+**
522+** ^The sqlite3_compileoption_get() function allows iterating
523+** over the list of options that were defined at compile time by
524+** returning the N-th compile time option string. ^If N is out of range,
525+** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
526+** prefix is omitted from any strings returned by
527+** sqlite3_compileoption_get().
528+**
529+** ^Support for the diagnostic functions sqlite3_compileoption_used()
530+** and sqlite3_compileoption_get() may be omitted by specifying the
531+** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
532+**
533+** See also: SQL functions [sqlite_compileoption_used()] and
534+** [sqlite_compileoption_get()] and the [compile_options pragma].
535+*/
536+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
537+SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
538+SQLITE_API const char *sqlite3_compileoption_get(int N);
539+#else
540+# define sqlite3_compileoption_used(X) 0
541+# define sqlite3_compileoption_get(X) ((void*)0)
542+#endif
543+
544+/*
545+** CAPI3REF: Test To See If The Library Is Threadsafe
546+**
547+** ^The sqlite3_threadsafe() function returns zero if and only if
548+** SQLite was compiled with mutexing code omitted due to the
549+** [SQLITE_THREADSAFE] compile-time option being set to 0.
550+**
551+** SQLite can be compiled with or without mutexes. When
552+** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
553+** are enabled and SQLite is threadsafe. When the
554+** [SQLITE_THREADSAFE] macro is 0,
555+** the mutexes are omitted. Without the mutexes, it is not safe
556+** to use SQLite concurrently from more than one thread.
557+**
558+** Enabling mutexes incurs a measurable performance penalty.
559+** So if speed is of utmost importance, it makes sense to disable
560+** the mutexes. But for maximum safety, mutexes should be enabled.
561+** ^The default behavior is for mutexes to be enabled.
562+**
563+** This interface can be used by an application to make sure that the
564+** version of SQLite that it is linking against was compiled with
565+** the desired setting of the [SQLITE_THREADSAFE] macro.
566+**
567+** This interface only reports on the compile-time mutex setting
568+** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
569+** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
570+** can be fully or partially disabled using a call to [sqlite3_config()]
571+** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
572+** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
573+** sqlite3_threadsafe() function shows only the compile-time setting of
574+** thread safety, not any run-time changes to that setting made by
575+** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
576+** is unchanged by calls to sqlite3_config().)^
577+**
578+** See the [threading mode] documentation for additional information.
579+*/
580+SQLITE_API int sqlite3_threadsafe(void);
581+
582+/*
583+** CAPI3REF: Database Connection Handle
584+** KEYWORDS: {database connection} {database connections}
585+**
586+** Each open SQLite database is represented by a pointer to an instance of
587+** the opaque structure named "sqlite3". It is useful to think of an sqlite3
588+** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
589+** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
590+** and [sqlite3_close_v2()] are its destructors. There are many other
591+** interfaces (such as
592+** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
593+** [sqlite3_busy_timeout()] to name but three) that are methods on an
594+** sqlite3 object.
595+*/
596+typedef struct sqlite3 sqlite3;
597+
598+/*
599+** CAPI3REF: 64-Bit Integer Types
600+** KEYWORDS: sqlite_int64 sqlite_uint64
601+**
602+** Because there is no cross-platform way to specify 64-bit integer types
603+** SQLite includes typedefs for 64-bit signed and unsigned integers.
604+**
605+** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
606+** The sqlite_int64 and sqlite_uint64 types are supported for backwards
607+** compatibility only.
608+**
609+** ^The sqlite3_int64 and sqlite_int64 types can store integer values
610+** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
611+** sqlite3_uint64 and sqlite_uint64 types can store integer values
612+** between 0 and +18446744073709551615 inclusive.
613+*/
614+#ifdef SQLITE_INT64_TYPE
615+ typedef SQLITE_INT64_TYPE sqlite_int64;
616+# ifdef SQLITE_UINT64_TYPE
617+ typedef SQLITE_UINT64_TYPE sqlite_uint64;
618+# else
619+ typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
620+# endif
621+#elif defined(_MSC_VER) || defined(__BORLANDC__)
622+ typedef __int64 sqlite_int64;
623+ typedef unsigned __int64 sqlite_uint64;
624+#else
625+ typedef long long int sqlite_int64;
626+ typedef unsigned long long int sqlite_uint64;
627+#endif
628+typedef sqlite_int64 sqlite3_int64;
629+typedef sqlite_uint64 sqlite3_uint64;
630+
631+/*
632+** If compiling for a processor that lacks floating point support,
633+** substitute integer for floating-point.
634+*/
635+#ifdef SQLITE_OMIT_FLOATING_POINT
636+# define double sqlite3_int64
637+#endif
638+
639+/*
640+** CAPI3REF: Closing A Database Connection
641+** DESTRUCTOR: sqlite3
642+**
643+** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
644+** for the [sqlite3] object.
645+** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
646+** the [sqlite3] object is successfully destroyed and all associated
647+** resources are deallocated.
648+**
649+** Ideally, applications should [sqlite3_finalize | finalize] all
650+** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
651+** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
652+** with the [sqlite3] object prior to attempting to close the object.
653+** ^If the database connection is associated with unfinalized prepared
654+** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
655+** sqlite3_close() will leave the database connection open and return
656+** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
657+** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
658+** it returns [SQLITE_OK] regardless, but instead of deallocating the database
659+** connection immediately, it marks the database connection as an unusable
660+** "zombie" and makes arrangements to automatically deallocate the database
661+** connection after all prepared statements are finalized, all BLOB handles
662+** are closed, and all backups have finished. The sqlite3_close_v2() interface
663+** is intended for use with host languages that are garbage collected, and
664+** where the order in which destructors are called is arbitrary.
665+**
666+** ^If an [sqlite3] object is destroyed while a transaction is open,
667+** the transaction is automatically rolled back.
668+**
669+** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
670+** must be either a NULL
671+** pointer or an [sqlite3] object pointer obtained
672+** from [sqlite3_open()], [sqlite3_open16()], or
673+** [sqlite3_open_v2()], and not previously closed.
674+** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
675+** argument is a harmless no-op.
676+*/
677+SQLITE_API int sqlite3_close(sqlite3*);
678+SQLITE_API int sqlite3_close_v2(sqlite3*);
679+
680+/*
681+** The type for a callback function.
682+** This is legacy and deprecated. It is included for historical
683+** compatibility and is not documented.
684+*/
685+typedef int (*sqlite3_callback)(void*,int,char**, char**);
686+
687+/*
688+** CAPI3REF: One-Step Query Execution Interface
689+** METHOD: sqlite3
690+**
691+** The sqlite3_exec() interface is a convenience wrapper around
692+** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
693+** that allows an application to run multiple statements of SQL
694+** without having to use a lot of C code.
695+**
696+** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
697+** semicolon-separated SQL statements passed into its 2nd argument,
698+** in the context of the [database connection] passed in as its 1st
699+** argument. ^If the callback function of the 3rd argument to
700+** sqlite3_exec() is not NULL, then it is invoked for each result row
701+** coming out of the evaluated SQL statements. ^The 4th argument to
702+** sqlite3_exec() is relayed through to the 1st argument of each
703+** callback invocation. ^If the callback pointer to sqlite3_exec()
704+** is NULL, then no callback is ever invoked and result rows are
705+** ignored.
706+**
707+** ^If an error occurs while evaluating the SQL statements passed into
708+** sqlite3_exec(), then execution of the current statement stops and
709+** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
710+** is not NULL then any error message is written into memory obtained
711+** from [sqlite3_malloc()] and passed back through the 5th parameter.
712+** To avoid memory leaks, the application should invoke [sqlite3_free()]
713+** on error message strings returned through the 5th parameter of
714+** sqlite3_exec() after the error message string is no longer needed.
715+** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
716+** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
717+** NULL before returning.
718+**
719+** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
720+** routine returns SQLITE_ABORT without invoking the callback again and
721+** without running any subsequent SQL statements.
722+**
723+** ^The 2nd argument to the sqlite3_exec() callback function is the
724+** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
725+** callback is an array of pointers to strings obtained as if from
726+** [sqlite3_column_text()], one for each column. ^If an element of a
727+** result row is NULL then the corresponding string pointer for the
728+** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
729+** sqlite3_exec() callback is an array of pointers to strings where each
730+** entry represents the name of a corresponding result column as obtained
731+** from [sqlite3_column_name()].
732+**
733+** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
734+** to an empty string, or a pointer that contains only whitespace and/or
735+** SQL comments, then no SQL statements are evaluated and the database
736+** is not changed.
737+**
738+** Restrictions:
739+**
740+** <ul>
741+** <li> The application must ensure that the 1st parameter to sqlite3_exec()
742+** is a valid and open [database connection].
743+** <li> The application must not close the [database connection] specified by
744+** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
745+** <li> The application must not modify the SQL statement text passed into
746+** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
747+** <li> The application must not dereference the arrays or string pointers
748+** passed as the 3rd and 4th callback parameters after it returns.
749+** </ul>
750+*/
751+SQLITE_API int sqlite3_exec(
752+ sqlite3*, /* An open database */
753+ const char *sql, /* SQL to be evaluated */
754+ int (*callback)(void*,int,char**,char**), /* Callback function */
755+ void *, /* 1st argument to callback */
756+ char **errmsg /* Error msg written here */
757+);
758+
759+/*
760+** CAPI3REF: Result Codes
761+** KEYWORDS: {result code definitions}
762+**
763+** Many SQLite functions return an integer result code from the set shown
764+** here in order to indicate success or failure.
765+**
766+** New error codes may be added in future versions of SQLite.
767+**
768+** See also: [extended result code definitions]
769+*/
770+#define SQLITE_OK 0 /* Successful result */
771+/* beginning-of-error-codes */
772+#define SQLITE_ERROR 1 /* Generic error */
773+#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
774+#define SQLITE_PERM 3 /* Access permission denied */
775+#define SQLITE_ABORT 4 /* Callback routine requested an abort */
776+#define SQLITE_BUSY 5 /* The database file is locked */
777+#define SQLITE_LOCKED 6 /* A table in the database is locked */
778+#define SQLITE_NOMEM 7 /* A malloc() failed */
779+#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
780+#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
781+#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
782+#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
783+#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
784+#define SQLITE_FULL 13 /* Insertion failed because database is full */
785+#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
786+#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
787+#define SQLITE_EMPTY 16 /* Internal use only */
788+#define SQLITE_SCHEMA 17 /* The database schema changed */
789+#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
790+#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
791+#define SQLITE_MISMATCH 20 /* Data type mismatch */
792+#define SQLITE_MISUSE 21 /* Library used incorrectly */
793+#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
794+#define SQLITE_AUTH 23 /* Authorization denied */
795+#define SQLITE_FORMAT 24 /* Not used */
796+#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
797+#define SQLITE_NOTADB 26 /* File opened that is not a database file */
798+#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
799+#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
800+#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
801+#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
802+/* end-of-error-codes */
803+
804+/*
805+** CAPI3REF: Extended Result Codes
806+** KEYWORDS: {extended result code definitions}
807+**
808+** In its default configuration, SQLite API routines return one of 30 integer
809+** [result codes]. However, experience has shown that many of
810+** these result codes are too coarse-grained. They do not provide as
811+** much information about problems as programmers might like. In an effort to
812+** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
813+** and later) include
814+** support for additional result codes that provide more detailed information
815+** about errors. These [extended result codes] are enabled or disabled
816+** on a per database connection basis using the
817+** [sqlite3_extended_result_codes()] API. Or, the extended code for
818+** the most recent error can be obtained using
819+** [sqlite3_extended_errcode()].
820+*/
821+#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
822+#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
823+#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
824+#define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8))
825+#define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8))
826+#define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8))
827+#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
828+#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
829+#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
830+#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
831+#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
832+#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
833+#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
834+#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
835+#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
836+#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
837+#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
838+#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
839+#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
840+#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
841+#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
842+#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
843+#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
844+#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
845+#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
846+#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
847+#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
848+#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
849+#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
850+#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
851+#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
852+#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
853+#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
854+#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
855+#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
856+#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
857+#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
858+#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))
859+#define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8))
860+#define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8))
861+#define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8))
862+#define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8))
863+#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
864+#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
865+#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
866+#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
867+#define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8))
868+#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
869+#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
870+#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
871+#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
872+#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
873+#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8))
874+#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
875+#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
876+#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8))
877+#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
878+#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
879+#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
880+#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
881+#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
882+#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
883+#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
884+#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
885+#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
886+#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
887+#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
888+#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
889+#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
890+#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
891+#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
892+#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
893+#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
894+#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8))
895+#define SQLITE_CONSTRAINT_DATATYPE (SQLITE_CONSTRAINT |(12<<8))
896+#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
897+#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
898+#define SQLITE_NOTICE_RBU (SQLITE_NOTICE | (3<<8))
899+#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
900+#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
901+#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
902+#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal only */
903+
904+/*
905+** CAPI3REF: Flags For File Open Operations
906+**
907+** These bit values are intended for use in the
908+** 3rd parameter to the [sqlite3_open_v2()] interface and
909+** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
910+**
911+** Only those flags marked as "Ok for sqlite3_open_v2()" may be
912+** used as the third argument to the [sqlite3_open_v2()] interface.
913+** The other flags have historically been ignored by sqlite3_open_v2(),
914+** though future versions of SQLite might change so that an error is
915+** raised if any of the disallowed bits are passed into sqlite3_open_v2().
916+** Applications should not depend on the historical behavior.
917+**
918+** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
919+** [sqlite3_open_v2()] does *not* cause the underlying database file
920+** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into
921+** [sqlite3_open_v2()] has historically been a no-op and might become an
922+** error in future versions of SQLite.
923+*/
924+#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
925+#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
926+#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
927+#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
928+#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
929+#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
930+#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
931+#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
932+#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
933+#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
934+#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
935+#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
936+#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
937+#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
938+#define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */
939+#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
940+#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
941+#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
942+#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
943+#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
944+#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */
945+#define SQLITE_OPEN_EXRESCODE 0x02000000 /* Extended result codes */
946+
947+/* Reserved: 0x00F00000 */
948+/* Legacy compatibility: */
949+#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
950+
951+
952+/*
953+** CAPI3REF: Device Characteristics
954+**
955+** The xDeviceCharacteristics method of the [sqlite3_io_methods]
956+** object returns an integer which is a vector of these
957+** bit values expressing I/O characteristics of the mass storage
958+** device that holds the file that the [sqlite3_io_methods]
959+** refers to.
960+**
961+** The SQLITE_IOCAP_ATOMIC property means that all writes of
962+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
963+** mean that writes of blocks that are nnn bytes in size and
964+** are aligned to an address which is an integer multiple of
965+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
966+** that when data is appended to a file, the data is appended
967+** first then the size of the file is extended, never the other
968+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
969+** information is written to disk in the same order as calls
970+** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
971+** after reboot following a crash or power loss, the only bytes in a
972+** file that were written at the application level might have changed
973+** and that adjacent bytes, even bytes within the same sector are
974+** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
975+** flag indicates that a file cannot be deleted when open. The
976+** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
977+** read-only media and cannot be changed even by processes with
978+** elevated privileges.
979+**
980+** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
981+** filesystem supports doing multiple write operations atomically when those
982+** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
983+** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
984+**
985+** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read
986+** from the database file in amounts that are not a multiple of the
987+** page size and that do not begin at a page boundary. Without this
988+** property, SQLite is careful to only do full-page reads and write
989+** on aligned pages, with the one exception that it will do a sub-page
990+** read of the first page to access the database header.
991+*/
992+#define SQLITE_IOCAP_ATOMIC 0x00000001
993+#define SQLITE_IOCAP_ATOMIC512 0x00000002
994+#define SQLITE_IOCAP_ATOMIC1K 0x00000004
995+#define SQLITE_IOCAP_ATOMIC2K 0x00000008
996+#define SQLITE_IOCAP_ATOMIC4K 0x00000010
997+#define SQLITE_IOCAP_ATOMIC8K 0x00000020
998+#define SQLITE_IOCAP_ATOMIC16K 0x00000040
999+#define SQLITE_IOCAP_ATOMIC32K 0x00000080
1000+#define SQLITE_IOCAP_ATOMIC64K 0x00000100
1001+#define SQLITE_IOCAP_SAFE_APPEND 0x00000200
1002+#define SQLITE_IOCAP_SEQUENTIAL 0x00000400
1003+#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
1004+#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
1005+#define SQLITE_IOCAP_IMMUTABLE 0x00002000
1006+#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
1007+#define SQLITE_IOCAP_SUBPAGE_READ 0x00008000
1008+
1009+/*
1010+** CAPI3REF: File Locking Levels
1011+**
1012+** SQLite uses one of these integer values as the second
1013+** argument to calls it makes to the xLock() and xUnlock() methods
1014+** of an [sqlite3_io_methods] object. These values are ordered from
1015+** least restrictive to most restrictive.
1016+**
1017+** The argument to xLock() is always SHARED or higher. The argument to
1018+** xUnlock is either SHARED or NONE.
1019+*/
1020+#define SQLITE_LOCK_NONE 0 /* xUnlock() only */
1021+#define SQLITE_LOCK_SHARED 1 /* xLock() or xUnlock() */
1022+#define SQLITE_LOCK_RESERVED 2 /* xLock() only */
1023+#define SQLITE_LOCK_PENDING 3 /* xLock() only */
1024+#define SQLITE_LOCK_EXCLUSIVE 4 /* xLock() only */
1025+
1026+/*
1027+** CAPI3REF: Synchronization Type Flags
1028+**
1029+** When SQLite invokes the xSync() method of an
1030+** [sqlite3_io_methods] object it uses a combination of
1031+** these integer values as the second argument.
1032+**
1033+** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1034+** sync operation only needs to flush data to mass storage. Inode
1035+** information need not be flushed. If the lower four bits of the flag
1036+** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1037+** If the lower four bits equal SQLITE_SYNC_FULL, that means
1038+** to use Mac OS X style fullsync instead of fsync().
1039+**
1040+** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1041+** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1042+** settings. The [synchronous pragma] determines when calls to the
1043+** xSync VFS method occur and applies uniformly across all platforms.
1044+** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1045+** energetic or rigorous or forceful the sync operations are and
1046+** only make a difference on Mac OSX for the default SQLite code.
1047+** (Third-party VFS implementations might also make the distinction
1048+** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1049+** operating systems natively supported by SQLite, only Mac OSX
1050+** cares about the difference.)
1051+*/
1052+#define SQLITE_SYNC_NORMAL 0x00002
1053+#define SQLITE_SYNC_FULL 0x00003
1054+#define SQLITE_SYNC_DATAONLY 0x00010
1055+
1056+/*
1057+** CAPI3REF: OS Interface Open File Handle
1058+**
1059+** An [sqlite3_file] object represents an open file in the
1060+** [sqlite3_vfs | OS interface layer]. Individual OS interface
1061+** implementations will
1062+** want to subclass this object by appending additional fields
1063+** for their own use. The pMethods entry is a pointer to an
1064+** [sqlite3_io_methods] object that defines methods for performing
1065+** I/O operations on the open file.
1066+*/
1067+typedef struct sqlite3_file sqlite3_file;
1068+struct sqlite3_file {
1069+ const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1070+};
1071+
1072+/*
1073+** CAPI3REF: OS Interface File Virtual Methods Object
1074+**
1075+** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1076+** [sqlite3_file] object (or, more commonly, a subclass of the
1077+** [sqlite3_file] object) with a pointer to an instance of this object.
1078+** This object defines the methods used to perform various operations
1079+** against the open file represented by the [sqlite3_file] object.
1080+**
1081+** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1082+** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1083+** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1084+** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1085+** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1086+** to NULL.
1087+**
1088+** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1089+** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1090+** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1091+** flag may be ORed in to indicate that only the data of the file
1092+** and not its inode needs to be synced.
1093+**
1094+** The integer values to xLock() and xUnlock() are one of
1095+** <ul>
1096+** <li> [SQLITE_LOCK_NONE],
1097+** <li> [SQLITE_LOCK_SHARED],
1098+** <li> [SQLITE_LOCK_RESERVED],
1099+** <li> [SQLITE_LOCK_PENDING], or
1100+** <li> [SQLITE_LOCK_EXCLUSIVE].
1101+** </ul>
1102+** xLock() upgrades the database file lock. In other words, xLock() moves the
1103+** database file lock in the direction NONE toward EXCLUSIVE. The argument to
1104+** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never
1105+** SQLITE_LOCK_NONE. If the database file lock is already at or above the
1106+** requested lock, then the call to xLock() is a no-op.
1107+** xUnlock() downgrades the database file lock to either SHARED or NONE.
1108+** If the lock is already at or below the requested lock state, then the call
1109+** to xUnlock() is a no-op.
1110+** The xCheckReservedLock() method checks whether any database connection,
1111+** either in this process or in some other process, is holding a RESERVED,
1112+** PENDING, or EXCLUSIVE lock on the file. It returns, via its output
1113+** pointer parameter, true if such a lock exists and false otherwise.
1114+**
1115+** The xFileControl() method is a generic interface that allows custom
1116+** VFS implementations to directly control an open file using the
1117+** [sqlite3_file_control()] interface. The second "op" argument is an
1118+** integer opcode. The third argument is a generic pointer intended to
1119+** point to a structure that may contain arguments or space in which to
1120+** write return values. Potential uses for xFileControl() might be
1121+** functions to enable blocking locks with timeouts, to change the
1122+** locking strategy (for example to use dot-file locks), to inquire
1123+** about the status of a lock, or to break stale locks. The SQLite
1124+** core reserves all opcodes less than 100 for its own use.
1125+** A [file control opcodes | list of opcodes] less than 100 is available.
1126+** Applications that define a custom xFileControl method should use opcodes
1127+** greater than 100 to avoid conflicts. VFS implementations should
1128+** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1129+** recognize.
1130+**
1131+** The xSectorSize() method returns the sector size of the
1132+** device that underlies the file. The sector size is the
1133+** minimum write that can be performed without disturbing
1134+** other bytes in the file. The xDeviceCharacteristics()
1135+** method returns a bit vector describing behaviors of the
1136+** underlying device:
1137+**
1138+** <ul>
1139+** <li> [SQLITE_IOCAP_ATOMIC]
1140+** <li> [SQLITE_IOCAP_ATOMIC512]
1141+** <li> [SQLITE_IOCAP_ATOMIC1K]
1142+** <li> [SQLITE_IOCAP_ATOMIC2K]
1143+** <li> [SQLITE_IOCAP_ATOMIC4K]
1144+** <li> [SQLITE_IOCAP_ATOMIC8K]
1145+** <li> [SQLITE_IOCAP_ATOMIC16K]
1146+** <li> [SQLITE_IOCAP_ATOMIC32K]
1147+** <li> [SQLITE_IOCAP_ATOMIC64K]
1148+** <li> [SQLITE_IOCAP_SAFE_APPEND]
1149+** <li> [SQLITE_IOCAP_SEQUENTIAL]
1150+** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1151+** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1152+** <li> [SQLITE_IOCAP_IMMUTABLE]
1153+** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
1154+** <li> [SQLITE_IOCAP_SUBPAGE_READ]
1155+** </ul>
1156+**
1157+** The SQLITE_IOCAP_ATOMIC property means that all writes of
1158+** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1159+** mean that writes of blocks that are nnn bytes in size and
1160+** are aligned to an address which is an integer multiple of
1161+** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1162+** that when data is appended to a file, the data is appended
1163+** first then the size of the file is extended, never the other
1164+** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1165+** information is written to disk in the same order as calls
1166+** to xWrite().
1167+**
1168+** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1169+** in the unread portions of the buffer with zeros. A VFS that
1170+** fails to zero-fill short reads might seem to work. However,
1171+** failure to zero-fill short reads will eventually lead to
1172+** database corruption.
1173+*/
1174+typedef struct sqlite3_io_methods sqlite3_io_methods;
1175+struct sqlite3_io_methods {
1176+ int iVersion;
1177+ int (*xClose)(sqlite3_file*);
1178+ int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1179+ int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1180+ int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1181+ int (*xSync)(sqlite3_file*, int flags);
1182+ int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1183+ int (*xLock)(sqlite3_file*, int);
1184+ int (*xUnlock)(sqlite3_file*, int);
1185+ int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1186+ int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1187+ int (*xSectorSize)(sqlite3_file*);
1188+ int (*xDeviceCharacteristics)(sqlite3_file*);
1189+ /* Methods above are valid for version 1 */
1190+ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1191+ int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1192+ void (*xShmBarrier)(sqlite3_file*);
1193+ int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1194+ /* Methods above are valid for version 2 */
1195+ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1196+ int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1197+ /* Methods above are valid for version 3 */
1198+ /* Additional methods may be added in future releases */
1199+};
1200+
1201+/*
1202+** CAPI3REF: Standard File Control Opcodes
1203+** KEYWORDS: {file control opcodes} {file control opcode}
1204+**
1205+** These integer constants are opcodes for the xFileControl method
1206+** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1207+** interface.
1208+**
1209+** <ul>
1210+** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1211+** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1212+** opcode causes the xFileControl method to write the current state of
1213+** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1214+** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1215+** into an integer that the pArg argument points to.
1216+** This capability is only available if SQLite is compiled with [SQLITE_DEBUG].
1217+**
1218+** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1219+** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1220+** layer a hint of how large the database file will grow to be during the
1221+** current transaction. This hint is not guaranteed to be accurate but it
1222+** is often close. The underlying VFS might choose to preallocate database
1223+** file space based on this hint in order to help writes to the database
1224+** file run faster.
1225+**
1226+** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
1227+** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1228+** implements [sqlite3_deserialize()] to set an upper bound on the size
1229+** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
1230+** If the integer pointed to is negative, then it is filled in with the
1231+** current limit. Otherwise the limit is set to the larger of the value
1232+** of the integer pointed to and the current database size. The integer
1233+** pointed to is set to the new limit.
1234+**
1235+** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1236+** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1237+** extends and truncates the database file in chunks of a size specified
1238+** by the user. The fourth argument to [sqlite3_file_control()] should
1239+** point to an integer (type int) containing the new chunk-size to use
1240+** for the nominated database. Allocating database file space in large
1241+** chunks (say 1MB at a time), may reduce file-system fragmentation and
1242+** improve performance on some systems.
1243+**
1244+** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1245+** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1246+** to the [sqlite3_file] object associated with a particular database
1247+** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1248+**
1249+** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1250+** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1251+** to the [sqlite3_file] object associated with the journal file (either
1252+** the [rollback journal] or the [write-ahead log]) for a particular database
1253+** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1254+**
1255+** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1256+** The SQLITE_FCNTL_SYNC_OMITTED file-control is no longer used.
1257+**
1258+** <li>[[SQLITE_FCNTL_SYNC]]
1259+** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1260+** sent to the VFS immediately before the xSync method is invoked on a
1261+** database file descriptor. Or, if the xSync method is not invoked
1262+** because the user has configured SQLite with
1263+** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1264+** of the xSync method. In most cases, the pointer argument passed with
1265+** this file-control is NULL. However, if the database file is being synced
1266+** as part of a multi-database commit, the argument points to a nul-terminated
1267+** string containing the transactions super-journal file name. VFSes that
1268+** do not need this signal should silently ignore this opcode. Applications
1269+** should not call [sqlite3_file_control()] with this opcode as doing so may
1270+** disrupt the operation of the specialized VFSes that do require it.
1271+**
1272+** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1273+** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1274+** and sent to the VFS after a transaction has been committed immediately
1275+** but before the database is unlocked. VFSes that do not need this signal
1276+** should silently ignore this opcode. Applications should not call
1277+** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1278+** operation of the specialized VFSes that do require it.
1279+**
1280+** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1281+** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1282+** retry counts and intervals for certain disk I/O operations for the
1283+** windows [VFS] in order to provide robustness in the presence of
1284+** anti-virus programs. By default, the windows VFS will retry file read,
1285+** file write, and file delete operations up to 10 times, with a delay
1286+** of 25 milliseconds before the first retry and with the delay increasing
1287+** by an additional 25 milliseconds with each subsequent retry. This
1288+** opcode allows these two values (10 retries and 25 milliseconds of delay)
1289+** to be adjusted. The values are changed for all database connections
1290+** within the same process. The argument is a pointer to an array of two
1291+** integers where the first integer is the new retry count and the second
1292+** integer is the delay. If either integer is negative, then the setting
1293+** is not changed but instead the prior value of that setting is written
1294+** into the array entry, allowing the current retry settings to be
1295+** interrogated. The zDbName parameter is ignored.
1296+**
1297+** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1298+** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1299+** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1300+** write ahead log ([WAL file]) and shared memory
1301+** files used for transaction control
1302+** are automatically deleted when the latest connection to the database
1303+** closes. Setting persistent WAL mode causes those files to persist after
1304+** close. Persisting the files is useful when other processes that do not
1305+** have write permission on the directory containing the database file want
1306+** to read the database file, as the WAL and shared memory files must exist
1307+** in order for the database to be readable. The fourth parameter to
1308+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1309+** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1310+** WAL mode. If the integer is -1, then it is overwritten with the current
1311+** WAL persistence setting.
1312+**
1313+** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1314+** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1315+** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1316+** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1317+** xDeviceCharacteristics methods. The fourth parameter to
1318+** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1319+** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1320+** mode. If the integer is -1, then it is overwritten with the current
1321+** zero-damage mode setting.
1322+**
1323+** <li>[[SQLITE_FCNTL_OVERWRITE]]
1324+** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1325+** a write transaction to indicate that, unless it is rolled back for some
1326+** reason, the entire database file will be overwritten by the current
1327+** transaction. This is used by VACUUM operations.
1328+**
1329+** <li>[[SQLITE_FCNTL_VFSNAME]]
1330+** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1331+** all [VFSes] in the VFS stack. The names of all VFS shims and the
1332+** final bottom-level VFS are written into memory obtained from
1333+** [sqlite3_malloc()] and the result is stored in the char* variable
1334+** that the fourth parameter of [sqlite3_file_control()] points to.
1335+** The caller is responsible for freeing the memory when done. As with
1336+** all file-control actions, there is no guarantee that this will actually
1337+** do anything. Callers should initialize the char* variable to a NULL
1338+** pointer in case this file-control is not implemented. This file-control
1339+** is intended for diagnostic use only.
1340+**
1341+** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1342+** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1343+** [VFSes] currently in use. ^(The argument X in
1344+** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1345+** of type "[sqlite3_vfs] **". This opcode will set *X
1346+** to a pointer to the top-level VFS.)^
1347+** ^When there are multiple VFS shims in the stack, this opcode finds the
1348+** upper-most shim only.
1349+**
1350+** <li>[[SQLITE_FCNTL_PRAGMA]]
1351+** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1352+** file control is sent to the open [sqlite3_file] object corresponding
1353+** to the database file to which the pragma statement refers. ^The argument
1354+** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1355+** pointers to strings (char**) in which the second element of the array
1356+** is the name of the pragma and the third element is the argument to the
1357+** pragma or NULL if the pragma has no argument. ^The handler for an
1358+** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1359+** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1360+** or the equivalent and that string will become the result of the pragma or
1361+** the error message if the pragma fails. ^If the
1362+** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1363+** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1364+** file control returns [SQLITE_OK], then the parser assumes that the
1365+** VFS has handled the PRAGMA itself and the parser generates a no-op
1366+** prepared statement if result string is NULL, or that returns a copy
1367+** of the result string if the string is non-NULL.
1368+** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1369+** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1370+** that the VFS encountered an error while handling the [PRAGMA] and the
1371+** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1372+** file control occurs at the beginning of pragma statement analysis and so
1373+** it is able to override built-in [PRAGMA] statements.
1374+**
1375+** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1376+** ^The [SQLITE_FCNTL_BUSYHANDLER]
1377+** file-control may be invoked by SQLite on the database file handle
1378+** shortly after it is opened in order to provide a custom VFS with access
1379+** to the connection's busy-handler callback. The argument is of type (void**)
1380+** - an array of two (void *) values. The first (void *) actually points
1381+** to a function of type (int (*)(void *)). In order to invoke the connection's
1382+** busy-handler, this function should be invoked with the second (void *) in
1383+** the array as the only argument. If it returns non-zero, then the operation
1384+** should be retried. If it returns zero, the custom VFS should abandon the
1385+** current operation.
1386+**
1387+** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1388+** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1389+** to have SQLite generate a
1390+** temporary filename using the same algorithm that is followed to generate
1391+** temporary filenames for TEMP tables and other internal uses. The
1392+** argument should be a char** which will be filled with the filename
1393+** written into memory obtained from [sqlite3_malloc()]. The caller should
1394+** invoke [sqlite3_free()] on the result to avoid a memory leak.
1395+**
1396+** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1397+** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1398+** maximum number of bytes that will be used for memory-mapped I/O.
1399+** The argument is a pointer to a value of type sqlite3_int64 that
1400+** is an advisory maximum number of bytes in the file to memory map. The
1401+** pointer is overwritten with the old value. The limit is not changed if
1402+** the value originally pointed to is negative, and so the current limit
1403+** can be queried by passing in a pointer to a negative number. This
1404+** file-control is used internally to implement [PRAGMA mmap_size].
1405+**
1406+** <li>[[SQLITE_FCNTL_TRACE]]
1407+** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1408+** to the VFS about what the higher layers of the SQLite stack are doing.
1409+** This file control is used by some VFS activity tracing [shims].
1410+** The argument is a zero-terminated string. Higher layers in the
1411+** SQLite stack may generate instances of this file control if
1412+** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1413+**
1414+** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1415+** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1416+** pointer to an integer and it writes a boolean into that integer depending
1417+** on whether or not the file has been renamed, moved, or deleted since it
1418+** was first opened.
1419+**
1420+** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1421+** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1422+** underlying native file handle associated with a file handle. This file
1423+** control interprets its argument as a pointer to a native file handle and
1424+** writes the resulting value there.
1425+**
1426+** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1427+** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1428+** opcode causes the xFileControl method to swap the file handle with the one
1429+** pointed to by the pArg argument. This capability is used during testing
1430+** and only needs to be supported when SQLITE_TEST is defined.
1431+**
1432+** <li>[[SQLITE_FCNTL_NULL_IO]]
1433+** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor
1434+** or file handle for the [sqlite3_file] object such that it will no longer
1435+** read or write to the database file.
1436+**
1437+** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1438+** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1439+** be advantageous to block on the next WAL lock if the lock is not immediately
1440+** available. The WAL subsystem issues this signal during rare
1441+** circumstances in order to fix a problem with priority inversion.
1442+** Applications should <em>not</em> use this file-control.
1443+**
1444+** <li>[[SQLITE_FCNTL_ZIPVFS]]
1445+** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1446+** VFS should return SQLITE_NOTFOUND for this opcode.
1447+**
1448+** <li>[[SQLITE_FCNTL_RBU]]
1449+** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1450+** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1451+** this opcode.
1452+**
1453+** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
1454+** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
1455+** the file descriptor is placed in "batch write mode", which
1456+** means all subsequent write operations will be deferred and done
1457+** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
1458+** that do not support batch atomic writes will return SQLITE_NOTFOUND.
1459+** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
1460+** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
1461+** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
1462+** no VFS interface calls on the same [sqlite3_file] file descriptor
1463+** except for calls to the xWrite method and the xFileControl method
1464+** with [SQLITE_FCNTL_SIZE_HINT].
1465+**
1466+** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
1467+** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
1468+** operations since the previous successful call to
1469+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
1470+** This file control returns [SQLITE_OK] if and only if the writes were
1471+** all performed successfully and have been committed to persistent storage.
1472+** ^Regardless of whether or not it is successful, this file control takes
1473+** the file descriptor out of batch write mode so that all subsequent
1474+** write operations are independent.
1475+** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
1476+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1477+**
1478+** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
1479+** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
1480+** operations since the previous successful call to
1481+** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
1482+** ^This file control takes the file descriptor out of batch write mode
1483+** so that all subsequent write operations are independent.
1484+** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
1485+** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
1486+**
1487+** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
1488+** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
1489+** to block for up to M milliseconds before failing when attempting to
1490+** obtain a file lock using the xLock or xShmLock methods of the VFS.
1491+** The parameter is a pointer to a 32-bit signed integer that contains
1492+** the value that M is to be set to. Before returning, the 32-bit signed
1493+** integer is overwritten with the previous value of M.
1494+**
1495+** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]]
1496+** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the
1497+** VFS to block when taking a SHARED lock to connect to a wal mode database.
1498+** This is used to implement the functionality associated with
1499+** SQLITE_SETLK_BLOCK_ON_CONNECT.
1500+**
1501+** <li>[[SQLITE_FCNTL_DATA_VERSION]]
1502+** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
1503+** a database file. The argument is a pointer to a 32-bit unsigned integer.
1504+** The "data version" for the pager is written into the pointer. The
1505+** "data version" changes whenever any change occurs to the corresponding
1506+** database file, either through SQL statements on the same database
1507+** connection or through transactions committed by separate database
1508+** connections possibly in other processes. The [sqlite3_total_changes()]
1509+** interface can be used to find if any database on the connection has changed,
1510+** but that interface responds to changes on TEMP as well as MAIN and does
1511+** not provide a mechanism to detect changes to MAIN only. Also, the
1512+** [sqlite3_total_changes()] interface responds to internal changes only and
1513+** omits changes made by other database connections. The
1514+** [PRAGMA data_version] command provides a mechanism to detect changes to
1515+** a single attached database that occur due to other database connections,
1516+** but omits changes implemented by the database connection on which it is
1517+** called. This file control is the only mechanism to detect changes that
1518+** happen either internally or externally and that are associated with
1519+** a particular attached database.
1520+**
1521+** <li>[[SQLITE_FCNTL_CKPT_START]]
1522+** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
1523+** in wal mode before the client starts to copy pages from the wal
1524+** file to the database file.
1525+**
1526+** <li>[[SQLITE_FCNTL_CKPT_DONE]]
1527+** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
1528+** in wal mode after the client has finished copying pages from the wal
1529+** file to the database file, but before the *-shm file is updated to
1530+** record the fact that the pages have been checkpointed.
1531+**
1532+** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
1533+** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
1534+** whether or not there is a database client in another process with a wal-mode
1535+** transaction open on the database or not. It is only available on unix. The
1536+** (void*) argument passed with this file-control should be a pointer to a
1537+** value of type (int). The integer value is set to 1 if the database is a wal
1538+** mode database and there exists at least one client in another process that
1539+** currently has an SQL transaction open on the database. It is set to 0 if
1540+** the database is not a wal-mode db, or if there is no such connection in any
1541+** other process. This opcode cannot be used to detect transactions opened
1542+** by clients within the current process, only within other processes.
1543+**
1544+** <li>[[SQLITE_FCNTL_CKSM_FILE]]
1545+** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the
1546+** [checksum VFS shim] only.
1547+**
1548+** <li>[[SQLITE_FCNTL_RESET_CACHE]]
1549+** If there is currently no transaction open on the database, and the
1550+** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control
1551+** purges the contents of the in-memory page cache. If there is an open
1552+** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.
1553+**
1554+** <li>[[SQLITE_FCNTL_FILESTAT]]
1555+** The [SQLITE_FCNTL_FILESTAT] opcode returns low-level diagnostic information
1556+** about the [sqlite3_file] objects used access the database and journal files
1557+** for the given schema. The fourth parameter to [sqlite3_file_control()]
1558+** should be an initialized [sqlite3_str] pointer. JSON text describing
1559+** various aspects of the sqlite3_file object is appended to the sqlite3_str.
1560+** The SQLITE_FCNTL_FILESTAT opcode is usually a no-op, unless compile-time
1561+** options are used to enable it.
1562+** </ul>
1563+*/
1564+#define SQLITE_FCNTL_LOCKSTATE 1
1565+#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1566+#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1567+#define SQLITE_FCNTL_LAST_ERRNO 4
1568+#define SQLITE_FCNTL_SIZE_HINT 5
1569+#define SQLITE_FCNTL_CHUNK_SIZE 6
1570+#define SQLITE_FCNTL_FILE_POINTER 7
1571+#define SQLITE_FCNTL_SYNC_OMITTED 8
1572+#define SQLITE_FCNTL_WIN32_AV_RETRY 9
1573+#define SQLITE_FCNTL_PERSIST_WAL 10
1574+#define SQLITE_FCNTL_OVERWRITE 11
1575+#define SQLITE_FCNTL_VFSNAME 12
1576+#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1577+#define SQLITE_FCNTL_PRAGMA 14
1578+#define SQLITE_FCNTL_BUSYHANDLER 15
1579+#define SQLITE_FCNTL_TEMPFILENAME 16
1580+#define SQLITE_FCNTL_MMAP_SIZE 18
1581+#define SQLITE_FCNTL_TRACE 19
1582+#define SQLITE_FCNTL_HAS_MOVED 20
1583+#define SQLITE_FCNTL_SYNC 21
1584+#define SQLITE_FCNTL_COMMIT_PHASETWO 22
1585+#define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1586+#define SQLITE_FCNTL_WAL_BLOCK 24
1587+#define SQLITE_FCNTL_ZIPVFS 25
1588+#define SQLITE_FCNTL_RBU 26
1589+#define SQLITE_FCNTL_VFS_POINTER 27
1590+#define SQLITE_FCNTL_JOURNAL_POINTER 28
1591+#define SQLITE_FCNTL_WIN32_GET_HANDLE 29
1592+#define SQLITE_FCNTL_PDB 30
1593+#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
1594+#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
1595+#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
1596+#define SQLITE_FCNTL_LOCK_TIMEOUT 34
1597+#define SQLITE_FCNTL_DATA_VERSION 35
1598+#define SQLITE_FCNTL_SIZE_LIMIT 36
1599+#define SQLITE_FCNTL_CKPT_DONE 37
1600+#define SQLITE_FCNTL_RESERVE_BYTES 38
1601+#define SQLITE_FCNTL_CKPT_START 39
1602+#define SQLITE_FCNTL_EXTERNAL_READER 40
1603+#define SQLITE_FCNTL_CKSM_FILE 41
1604+#define SQLITE_FCNTL_RESET_CACHE 42
1605+#define SQLITE_FCNTL_NULL_IO 43
1606+#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44
1607+#define SQLITE_FCNTL_FILESTAT 45
1608+
1609+/* deprecated names */
1610+#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1611+#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1612+#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1613+
1614+/* reserved file-control numbers:
1615+** 101
1616+** 102
1617+** 103
1618+*/
1619+
1620+
1621+/*
1622+** CAPI3REF: Mutex Handle
1623+**
1624+** The mutex module within SQLite defines [sqlite3_mutex] to be an
1625+** abstract type for a mutex object. The SQLite core never looks
1626+** at the internal representation of an [sqlite3_mutex]. It only
1627+** deals with pointers to the [sqlite3_mutex] object.
1628+**
1629+** Mutexes are created using [sqlite3_mutex_alloc()].
1630+*/
1631+typedef struct sqlite3_mutex sqlite3_mutex;
1632+
1633+/*
1634+** CAPI3REF: Loadable Extension Thunk
1635+**
1636+** A pointer to the opaque sqlite3_api_routines structure is passed as
1637+** the third parameter to entry points of [loadable extensions]. This
1638+** structure must be typedefed in order to work around compiler warnings
1639+** on some platforms.
1640+*/
1641+typedef struct sqlite3_api_routines sqlite3_api_routines;
1642+
1643+/*
1644+** CAPI3REF: File Name
1645+**
1646+** Type [sqlite3_filename] is used by SQLite to pass filenames to the
1647+** xOpen method of a [VFS]. It may be cast to (const char*) and treated
1648+** as a normal, nul-terminated, UTF-8 buffer containing the filename, but
1649+** may also be passed to special APIs such as:
1650+**
1651+** <ul>
1652+** <li> sqlite3_filename_database()
1653+** <li> sqlite3_filename_journal()
1654+** <li> sqlite3_filename_wal()
1655+** <li> sqlite3_uri_parameter()
1656+** <li> sqlite3_uri_boolean()
1657+** <li> sqlite3_uri_int64()
1658+** <li> sqlite3_uri_key()
1659+** </ul>
1660+*/
1661+typedef const char *sqlite3_filename;
1662+
1663+/*
1664+** CAPI3REF: OS Interface Object
1665+**
1666+** An instance of the sqlite3_vfs object defines the interface between
1667+** the SQLite core and the underlying operating system. The "vfs"
1668+** in the name of the object stands for "virtual file system". See
1669+** the [VFS | VFS documentation] for further information.
1670+**
1671+** The VFS interface is sometimes extended by adding new methods onto
1672+** the end. Each time such an extension occurs, the iVersion field
1673+** is incremented. The iVersion value started out as 1 in
1674+** SQLite [version 3.5.0] on [dateof:3.