From 01be5b8d987c8af5e2df9c66cfc24da677ebd38b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:52:18 +0000 Subject: [PATCH 01/16] ADFA-7301 SQLite debugger: sqlite3 shell tools (suggest_indexes, lint_foreign_keys, dump, export, .dbinfo) Phase 2, P2-6 (ADFA-7131 comments 41477, 41489). On P2-2 (ADFA-7297). All new tools are read-only, with readOnlyHint. - suggest_indexes (.expert): SQLite's ext/expert, vendored unchanged from 3.49.1 (src/main/cpp/expert, public domain), compiled into libsqlitedbg.so by sqlitedbg_expert.c through the api table. It runs on the read-only server connection. Expert's two in-memory connections open inside sqlitedbg_private_open, so they are neither listed nor traced. Sampling is off: no row of the app's data is read and nothing is added to the server connection, so suggestions rest on SQLite's default estimates. Deadline: progress handler on expert's connections plus a check between its steps. JNI suggestIndexes. - lint_foreign_keys (.lint fkey-indexes): the shell's query-plan globs, in Kotlin. Limit: no COLLATE clause for a child column whose collation differs from its parent key's. - dump (.dump): the shell's order (foreign_keys=OFF, BEGIN, tables and rows, sqlite_sequence, indexes/triggers/views, COMMIT), virtual tables through writable_schema, rows by quote() in rowid order, generated columns left out. Paged by cursor: 1000 statements, about 4 MiB; a statement over 4 MiB is cut and listed. - export (.mode csv, .mode insert): RFC 4180 CSV; INSERT literals that read back the same. Values cut at 64 KiB. - get_stats (.dbinfo): PRAGMA values, schema object counts and size, and header fields through sqlite_dbpage when SQLite has it (else header_unavailable). Never reads the file itself: closing a descriptor would drop the app's POSIX locks. - ShellFormat (CSV, SQL literals, glob, header) is pure and tested alone. README updated. The ticket's UNVERIFIED item: ext/expert builds against the 3.49 headers through sqlite3ext.h with no warning, and runs on a read-only server connection with its authorizer (C and JNI tests). Not yet on requery's libsqlite3x.so on a device. Size (estimate, clang 18 -Os with host headers, not the NDK): expert adds about 22 KB of code on arm64 and 15 KB on armv7 (Thumb-2). Tests: test.sh passes (ASan+UBSan, TSan, JNI 324 checks, including the SQL every new tool sends). DatabaseToolsTest, ShellToolsTest, McpProtocolTest and EventDecoderTest pass (134), compiled with the Kotlin compiler outside Gradle. Revert proofs: no private open fails the C test (3 connections listed, 67 statements traced); sampling on fails "no row of the app's data was read" (3 sampling queries); no INTEGER PRIMARY KEY glob fails "an INTEGER PRIMARY KEY covers it"; an unquoted empty string fails both CSV tests. Not run here: Gradle, spotlessCheck, a device, the real .so sizes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 37 +- .../src/main/cpp/CMakeLists.txt | 3 +- .../src/main/cpp/expert/sqlite3expert.c | 2234 +++++++++++++++++ .../src/main/cpp/expert/sqlite3expert.h | 168 ++ .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 2 + .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 15 + .../src/main/cpp/sqlitedbg_expert.c | 34 + .../src/main/cpp/sqlitedbg_jni.c | 58 + .../sqlitedebugger/engine/DebugEngine.kt | 26 + .../sqlitedebugger/engine/NativeBridge.kt | 12 + .../engine/NativeDebugEngine.kt | 10 + .../sqlitedebugger/mcp/DatabaseTools.kt | 485 +++- .../sqlitedebugger/mcp/ShellFormat.kt | 89 + .../src/test/c/sqlitedbg_test.c | 88 + .../sqlitedebugger/engine/FakeDebugEngine.kt | 11 + .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 32 +- .../sqlitedebugger/mcp/ShellToolsTest.kt | 449 ++++ .../src/test/jni/JniQueryTest.java | 53 + .../sqlitedebugger/engine/NativeBridge.java | 2 + subprojects/sqlite-debugger/test.sh | 4 +- 20 files changed, 3802 insertions(+), 10 deletions(-) create mode 100644 subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.c create mode 100644 subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.h create mode 100644 subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c create mode 100644 subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt create mode 100644 subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index a3970161f3..f0a8b80a12 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -20,7 +20,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `sqlitedbg.c` is a SQLite extension. `sqlitedbg_install` registers it with `sqlite3_auto_extension`, so it runs on every connection the app opens afterwards. It keeps the list of app connections and a ring buffer of statement events (trace: statement, profile, row, close), and opens connections for the server (`sqlitedbg_open_server`). - `sqlitedbg_jni.c` finds `sqlite3_auto_extension` in requery's `libsqlite3x.so` with `dlopen(RTLD_NOLOAD)` and `dlsym`, so no SQLite is compiled or linked here (CMake takes only the headers from `../sqlite-js/upstream/libs`). Its version script exports only `JNI_OnLoad`; the functions of `NativeBridge` are registered there by name, and `consumer-rules.pro` keeps them. - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. -- `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. +- `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `suggest_indexes`, `lint_foreign_keys`, `dump`, `export`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. - On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory); (f) an install by the intent-based fallback installer, used on MIUI or when `debugFallbackInstaller` is set, Run installs included, which never calls `beforeCommit` and has no session or result, so nothing clears or pairs. Only the Launch action (`LaunchAppAction`) pairs an unpaired app installed by (a) to (f), at the next launch from a project, through `insertPairingIfAbsent`, which keeps an already-paired app's stored values; the automatic post-install launch (`BaseEditorActivity.doLaunchApp`, in debug mode too), `RestartVmAction` and Quick Build's launch of the proxy app never call `recordLaunched`. An app whose old process is gone stays unreachable until its new process reports. Other installs keep the old values too: `recordInstalled` returns false and keeps them when the project has no recent-project row or the write fails; a result that names a different package is dropped without clearing; a `beforeCommit` that throws is logged and the install goes on with no note; and an install not made from a project (the file tab's Install action, or adb) leaves an already-paired app listed with its dead token and port, and does not pair an unpaired app; the Launch action pairs that app at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). @@ -47,6 +47,38 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. - **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. +### sqlite3 shell tools (ADFA-7301) + +Capabilities of the sqlite3 shell, in the server so every client has them. All are read-only. +- **`suggest_indexes` (`.expert`).** SQLite's `ext/expert`, vendored unchanged from 3.49.1 in `src/main/cpp/expert/` (public domain, like SQLite), is compiled into `libsqlitedbg.so` through `sqlitedbg_expert.c`. That file includes it in a translation unit that reaches SQLite through the api table, like `sqlitedbg.c`. + - Expert copies the schema of the server connection into two in-memory connections of its own. It opens them inside `sqlitedbg_private_open`, so the extension neither lists nor traces them, and it only prepares the client's SQL on the server connection. + - Sampling is off (`EXPERT_CONFIG_SAMPLE` 0). With sampling on, expert reads every row of every indexed table on the server connection, and adds functions and a temp table to it. So the suggestions rest on SQLite's default estimates, and the description says to check them with `explain_query_plan`. + - The time limit runs through a progress handler on expert's connections and a check between its steps. + - Code size: about 22 KB on arm64 and 15 KB on armv7 (Thumb-2) at `-Os`, estimated with clang 18 and host headers, not the NDK. `sqlitedbg.c` is about 6 KB. +- **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one. + - Limit: the shell adds a COLLATE clause when a child column's collation differs from its parent key's (`fkey_collate_clause`, through `sqlite3_table_column_metadata` and a function registered on the connection). This check doesn't. +- **`dump` (`.dump`).** The shell's order: + 1. `PRAGMA foreign_keys=OFF`, then `BEGIN TRANSACTION`; + 2. each table's CREATE and its rows; + 3. `sqlite_sequence` last, with `DELETE FROM sqlite_sequence`; + 4. the indexes, triggers and views; + 5. `COMMIT`. + + Details: + - Other `sqlite_` tables are skipped, except that `sqlite_stat1` gets `ANALYZE sqlite_schema`. + - A virtual table goes into `sqlite_schema` under `PRAGMA writable_schema`, and its shadow tables are dumped as tables. + - Rows are written by `quote()` in SQL, which round-trips REALs (checked in the JNI test). They come in rowid order, so paging is stable. + - Generated columns are left out, with a column list. + - Paged by a cursor (`unit.offset`, rebuilt from the schema on each call): at most 1000 statements and about 4 MiB a page. A statement over 4 MiB is cut and listed. +- **`export` (`.mode csv`, `.mode insert`).** + - CSV is RFC 4180 with CRLF line ends. NULL is an empty field, the empty string is `""`, and a BLOB is hex. + - `insert` writes literals that read back the same (`X'..'`, an infinity as `1e999`, NaN as NULL). + - A value is cut at 64 KiB, higher than `query`'s limit, since a cut value is wrong data in an export. +- **`get_stats` (`.dbinfo`).** + - It adds `schema_version`, `user_version`, `application_id`, `encoding`, `auto_vacuum`, `journal_mode`, the schema object counts and the schema size. + - The header fields no PRAGMA reads come from page 1 through `sqlite_dbpage`, when SQLite has it; otherwise `header_unavailable` says why. The host SQLite in `test.sh` has no `sqlite_dbpage`; whether requery's has it is unchecked. + - Never from the file itself: closing any descriptor to it would drop the app's POSIX locks. + ## Decisions that shape it - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. @@ -67,7 +99,8 @@ What the server gives a client so it can format results as the sqlite3 shell wou - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. - **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. -- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. +- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`), the sqlite3 shell tools (`ShellToolsTest`) and `EndpointBroadcast`, its announce receiver included. +- **Expert:** the C test runs `sqlitedbg_expert_run` on a read-only server connection. It checks that expert suggests the index, lists nothing, traces nothing, and leaves nothing on the server connection, and that no sampling query runs on it. The JNI test runs `suggestIndexes` and the SQL the other shell tools send, against the real SQLite. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt index 779767a2bb..f2488fc367 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt +++ b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt @@ -8,7 +8,8 @@ set(SQLITE_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/../../../../sqlite-js/upstream/li add_library(sqlitedbg SHARED sqlitedbg.c - sqlitedbg_jni.c) + sqlitedbg_jni.c + sqlitedbg_expert.c) target_include_directories(sqlitedbg PRIVATE ${SQLITE_HEADERS} ${CMAKE_CURRENT_SOURCE_DIR}) target_compile_options(sqlitedbg PRIVATE -Wall -Wextra -fvisibility=hidden) diff --git a/subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.c b/subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.c new file mode 100644 index 0000000000..93693cfae9 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.c @@ -0,0 +1,2234 @@ +/* +** 2017 April 09 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ +#include "sqlite3expert.h" +#include +#include +#include + +#if !defined(SQLITE_AMALGAMATION) +#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) +# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1 +#endif +#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif +#endif /* !defined(SQLITE_AMALGAMATION) */ + + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef sqlite3_int64 i64; +typedef sqlite3_uint64 u64; + +typedef struct IdxColumn IdxColumn; +typedef struct IdxConstraint IdxConstraint; +typedef struct IdxScan IdxScan; +typedef struct IdxStatement IdxStatement; +typedef struct IdxTable IdxTable; +typedef struct IdxWrite IdxWrite; + +#define STRLEN (int)strlen + +/* +** A temp table name that we assume no user database will actually use. +** If this assumption proves incorrect triggers on the table with the +** conflicting name will be ignored. +*/ +#define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776" + +/* +** A single constraint. Equivalent to either "col = ?" or "col < ?" (or +** any other type of single-ended range constraint on a column). +** +** pLink: +** Used to temporarily link IdxConstraint objects into lists while +** creating candidate indexes. +*/ +struct IdxConstraint { + char *zColl; /* Collation sequence */ + int bRange; /* True for range, false for eq */ + int iCol; /* Constrained table column */ + int bFlag; /* Used by idxFindCompatible() */ + int bDesc; /* True if ORDER BY DESC */ + IdxConstraint *pNext; /* Next constraint in pEq or pRange list */ + IdxConstraint *pLink; /* See above */ +}; + +/* +** A single scan of a single table. +*/ +struct IdxScan { + IdxTable *pTab; /* Associated table object */ + int iDb; /* Database containing table zTable */ + i64 covering; /* Mask of columns required for cov. index */ + IdxConstraint *pOrder; /* ORDER BY columns */ + IdxConstraint *pEq; /* List of == constraints */ + IdxConstraint *pRange; /* List of < constraints */ + IdxScan *pNextScan; /* Next IdxScan object for same analysis */ +}; + +/* +** Information regarding a single database table. Extracted from +** "PRAGMA table_info" by function idxGetTableInfo(). +*/ +struct IdxColumn { + char *zName; + char *zColl; + int iPk; +}; +struct IdxTable { + int nCol; + char *zName; /* Table name */ + IdxColumn *aCol; + IdxTable *pNext; /* Next table in linked list of all tables */ +}; + +/* +** An object of the following type is created for each unique table/write-op +** seen. The objects are stored in a singly-linked list beginning at +** sqlite3expert.pWrite. +*/ +struct IdxWrite { + IdxTable *pTab; + int eOp; /* SQLITE_UPDATE, DELETE or INSERT */ + IdxWrite *pNext; +}; + +/* +** Each statement being analyzed is represented by an instance of this +** structure. +*/ +struct IdxStatement { + int iId; /* Statement number */ + char *zSql; /* SQL statement */ + char *zIdx; /* Indexes */ + char *zEQP; /* Plan */ + IdxStatement *pNext; +}; + + +/* +** A hash table for storing strings. With space for a payload string +** with each entry. Methods are: +** +** idxHashInit() +** idxHashClear() +** idxHashAdd() +** idxHashSearch() +*/ +#define IDX_HASH_SIZE 1023 +typedef struct IdxHashEntry IdxHashEntry; +typedef struct IdxHash IdxHash; +struct IdxHashEntry { + char *zKey; /* nul-terminated key */ + char *zVal; /* nul-terminated value string */ + char *zVal2; /* nul-terminated value string 2 */ + IdxHashEntry *pHashNext; /* Next entry in same hash bucket */ + IdxHashEntry *pNext; /* Next entry in hash */ +}; +struct IdxHash { + IdxHashEntry *pFirst; + IdxHashEntry *aHash[IDX_HASH_SIZE]; +}; + +/* +** sqlite3expert object. +*/ +struct sqlite3expert { + int iSample; /* Percentage of tables to sample for stat1 */ + sqlite3 *db; /* User database */ + sqlite3 *dbm; /* In-memory db for this analysis */ + sqlite3 *dbv; /* Vtab schema for this analysis */ + IdxTable *pTable; /* List of all IdxTable objects */ + IdxScan *pScan; /* List of scan objects */ + IdxWrite *pWrite; /* List of write objects */ + IdxStatement *pStatement; /* List of IdxStatement objects */ + int bRun; /* True once analysis has run */ + char **pzErrmsg; + int rc; /* Error code from whereinfo hook */ + IdxHash hIdx; /* Hash containing all candidate indexes */ + char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */ +}; + + +/* +** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). +** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL. +*/ +static void *idxMalloc(int *pRc, int nByte){ + void *pRet; + assert( *pRc==SQLITE_OK ); + assert( nByte>0 ); + pRet = sqlite3_malloc(nByte); + if( pRet ){ + memset(pRet, 0, nByte); + }else{ + *pRc = SQLITE_NOMEM; + } + return pRet; +} + +/* +** Initialize an IdxHash hash table. +*/ +static void idxHashInit(IdxHash *pHash){ + memset(pHash, 0, sizeof(IdxHash)); +} + +/* +** Reset an IdxHash hash table. +*/ +static void idxHashClear(IdxHash *pHash){ + int i; + for(i=0; iaHash[i]; pEntry; pEntry=pNext){ + pNext = pEntry->pHashNext; + sqlite3_free(pEntry->zVal2); + sqlite3_free(pEntry); + } + } + memset(pHash, 0, sizeof(IdxHash)); +} + +/* +** Return the index of the hash bucket that the string specified by the +** arguments to this function belongs. +*/ +static int idxHashString(const char *z, int n){ + unsigned int ret = 0; + int i; + for(i=0; i=0 ); + for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ + if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ + return 1; + } + } + pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1); + if( pEntry ){ + pEntry->zKey = (char*)&pEntry[1]; + memcpy(pEntry->zKey, zKey, nKey); + if( zVal ){ + pEntry->zVal = &pEntry->zKey[nKey+1]; + memcpy(pEntry->zVal, zVal, nVal); + } + pEntry->pHashNext = pHash->aHash[iHash]; + pHash->aHash[iHash] = pEntry; + + pEntry->pNext = pHash->pFirst; + pHash->pFirst = pEntry; + } + return 0; +} + +/* +** If zKey/nKey is present in the hash table, return a pointer to the +** hash-entry object. +*/ +static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){ + int iHash; + IdxHashEntry *pEntry; + if( nKey<0 ) nKey = STRLEN(zKey); + iHash = idxHashString(zKey, nKey); + assert( iHash>=0 ); + for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ + if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ + return pEntry; + } + } + return 0; +} + +/* +** If the hash table contains an entry with a key equal to the string +** passed as the final two arguments to this function, return a pointer +** to the payload string. Otherwise, if zKey/nKey is not present in the +** hash table, return NULL. +*/ +static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){ + IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey); + if( pEntry ) return pEntry->zVal; + return 0; +} + +/* +** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl +** variable to point to a copy of nul-terminated string zColl. +*/ +static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){ + IdxConstraint *pNew; + int nColl = STRLEN(zColl); + + assert( *pRc==SQLITE_OK ); + pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1); + if( pNew ){ + pNew->zColl = (char*)&pNew[1]; + memcpy(pNew->zColl, zColl, nColl+1); + } + return pNew; +} + +/* +** An error associated with database handle db has just occurred. Pass +** the error message to callback function xOut. +*/ +static void idxDatabaseError( + sqlite3 *db, /* Database handle */ + char **pzErrmsg /* Write error here */ +){ + *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); +} + +/* +** Prepare an SQL statement. +*/ +static int idxPrepareStmt( + sqlite3 *db, /* Database handle to compile against */ + sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ + char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ + const char *zSql /* SQL statement to compile */ +){ + int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); + if( rc!=SQLITE_OK ){ + *ppStmt = 0; + idxDatabaseError(db, pzErrmsg); + } + return rc; +} + +/* +** Prepare an SQL statement using the results of a printf() formatting. +*/ +static int idxPrintfPrepareStmt( + sqlite3 *db, /* Database handle to compile against */ + sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ + char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ + const char *zFmt, /* printf() format of SQL statement */ + ... /* Trailing printf() arguments */ +){ + va_list ap; + int rc; + char *zSql; + va_start(ap, zFmt); + zSql = sqlite3_vmprintf(zFmt, ap); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql); + sqlite3_free(zSql); + } + va_end(ap); + return rc; +} + + +/************************************************************************* +** Beginning of virtual table implementation. +*/ +typedef struct ExpertVtab ExpertVtab; +struct ExpertVtab { + sqlite3_vtab base; + IdxTable *pTab; + sqlite3expert *pExpert; +}; + +typedef struct ExpertCsr ExpertCsr; +struct ExpertCsr { + sqlite3_vtab_cursor base; + sqlite3_stmt *pData; +}; + +static char *expertDequote(const char *zIn){ + int n = STRLEN(zIn); + char *zRet = sqlite3_malloc(n); + + assert( zIn[0]=='\'' ); + assert( zIn[n-1]=='\'' ); + + if( zRet ){ + int iOut = 0; + int iIn = 0; + for(iIn=1; iIn<(n-1); iIn++){ + if( zIn[iIn]=='\'' ){ + assert( zIn[iIn+1]=='\'' ); + iIn++; + } + zRet[iOut++] = zIn[iIn]; + } + zRet[iOut] = '\0'; + } + + return zRet; +} + +/* +** This function is the implementation of both the xConnect and xCreate +** methods of the r-tree virtual table. +** +** argv[0] -> module name +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> column names... +*/ +static int expertConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + sqlite3expert *pExpert = (sqlite3expert*)pAux; + ExpertVtab *p = 0; + int rc; + + if( argc!=4 ){ + *pzErr = sqlite3_mprintf("internal error!"); + rc = SQLITE_ERROR; + }else{ + char *zCreateTable = expertDequote(argv[3]); + if( zCreateTable ){ + rc = sqlite3_declare_vtab(db, zCreateTable); + if( rc==SQLITE_OK ){ + p = idxMalloc(&rc, sizeof(ExpertVtab)); + } + if( rc==SQLITE_OK ){ + p->pExpert = pExpert; + p->pTab = pExpert->pTable; + assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); + } + sqlite3_free(zCreateTable); + }else{ + rc = SQLITE_NOMEM; + } + } + + *ppVtab = (sqlite3_vtab*)p; + return rc; +} + +static int expertDisconnect(sqlite3_vtab *pVtab){ + ExpertVtab *p = (ExpertVtab*)pVtab; + sqlite3_free(p); + return SQLITE_OK; +} + +static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){ + ExpertVtab *p = (ExpertVtab*)pVtab; + int rc = SQLITE_OK; + int n = 0; + IdxScan *pScan; + const int opmask = + SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT | + SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE | + SQLITE_INDEX_CONSTRAINT_LE; + + pScan = idxMalloc(&rc, sizeof(IdxScan)); + if( pScan ){ + int i; + + /* Link the new scan object into the list */ + pScan->pTab = p->pTab; + pScan->pNextScan = p->pExpert->pScan; + p->pExpert->pScan = pScan; + + /* Add the constraints to the IdxScan object */ + for(i=0; inConstraint; i++){ + struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; + if( pCons->usable + && pCons->iColumn>=0 + && p->pTab->aCol[pCons->iColumn].iPk==0 + && (pCons->op & opmask) + ){ + IdxConstraint *pNew; + const char *zColl = sqlite3_vtab_collation(pIdxInfo, i); + pNew = idxNewConstraint(&rc, zColl); + if( pNew ){ + pNew->iCol = pCons->iColumn; + if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + pNew->pNext = pScan->pEq; + pScan->pEq = pNew; + }else{ + pNew->bRange = 1; + pNew->pNext = pScan->pRange; + pScan->pRange = pNew; + } + } + n++; + pIdxInfo->aConstraintUsage[i].argvIndex = n; + } + } + + /* Add the ORDER BY to the IdxScan object */ + for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ + int iCol = pIdxInfo->aOrderBy[i].iColumn; + if( iCol>=0 ){ + IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); + if( pNew ){ + pNew->iCol = iCol; + pNew->bDesc = pIdxInfo->aOrderBy[i].desc; + pNew->pNext = pScan->pOrder; + pNew->pLink = pScan->pOrder; + pScan->pOrder = pNew; + n++; + } + } + } + } + + pIdxInfo->estimatedCost = 1000000.0 / (n+1); + return rc; +} + +static int expertUpdate( + sqlite3_vtab *pVtab, + int nData, + sqlite3_value **azData, + sqlite_int64 *pRowid +){ + (void)pVtab; + (void)nData; + (void)azData; + (void)pRowid; + return SQLITE_OK; +} + +/* +** Virtual table module xOpen method. +*/ +static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_OK; + ExpertCsr *pCsr; + (void)pVTab; + pCsr = idxMalloc(&rc, sizeof(ExpertCsr)); + *ppCursor = (sqlite3_vtab_cursor*)pCsr; + return rc; +} + +/* +** Virtual table module xClose method. +*/ +static int expertClose(sqlite3_vtab_cursor *cur){ + ExpertCsr *pCsr = (ExpertCsr*)cur; + sqlite3_finalize(pCsr->pData); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Virtual table module xEof method. +** +** Return non-zero if the cursor does not currently point to a valid +** record (i.e if the scan has finished), or zero otherwise. +*/ +static int expertEof(sqlite3_vtab_cursor *cur){ + ExpertCsr *pCsr = (ExpertCsr*)cur; + return pCsr->pData==0; +} + +/* +** Virtual table module xNext method. +*/ +static int expertNext(sqlite3_vtab_cursor *cur){ + ExpertCsr *pCsr = (ExpertCsr*)cur; + int rc = SQLITE_OK; + + assert( pCsr->pData ); + rc = sqlite3_step(pCsr->pData); + if( rc!=SQLITE_ROW ){ + rc = sqlite3_finalize(pCsr->pData); + pCsr->pData = 0; + }else{ + rc = SQLITE_OK; + } + + return rc; +} + +/* +** Virtual table module xRowid method. +*/ +static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + (void)cur; + *pRowid = 0; + return SQLITE_OK; +} + +/* +** Virtual table module xColumn method. +*/ +static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + ExpertCsr *pCsr = (ExpertCsr*)cur; + sqlite3_value *pVal; + pVal = sqlite3_column_value(pCsr->pData, i); + if( pVal ){ + sqlite3_result_value(ctx, pVal); + } + return SQLITE_OK; +} + +/* +** Virtual table module xFilter method. +*/ +static int expertFilter( + sqlite3_vtab_cursor *cur, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + ExpertCsr *pCsr = (ExpertCsr*)cur; + ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); + sqlite3expert *pExpert = pVtab->pExpert; + int rc; + + (void)idxNum; + (void)idxStr; + (void)argc; + (void)argv; + rc = sqlite3_finalize(pCsr->pData); + pCsr->pData = 0; + if( rc==SQLITE_OK ){ + rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, + "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName + ); + } + + if( rc==SQLITE_OK ){ + rc = expertNext(cur); + } + return rc; +} + +static int idxRegisterVtab(sqlite3expert *p){ + static sqlite3_module expertModule = { + 2, /* iVersion */ + expertConnect, /* xCreate - create a table */ + expertConnect, /* xConnect - connect to an existing table */ + expertBestIndex, /* xBestIndex - Determine search strategy */ + expertDisconnect, /* xDisconnect - Disconnect from a table */ + expertDisconnect, /* xDestroy - Drop a table */ + expertOpen, /* xOpen - open a cursor */ + expertClose, /* xClose - close a cursor */ + expertFilter, /* xFilter - configure scan constraints */ + expertNext, /* xNext - advance a cursor */ + expertEof, /* xEof */ + expertColumn, /* xColumn - read data */ + expertRowid, /* xRowid - read data */ + expertUpdate, /* xUpdate - write data */ + 0, /* xBegin - begin transaction */ + 0, /* xSync - sync transaction */ + 0, /* xCommit - commit transaction */ + 0, /* xRollback - rollback transaction */ + 0, /* xFindFunction - function overloading */ + 0, /* xRename - rename the table */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadowName */ + 0, /* xIntegrity */ + }; + + return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); +} +/* +** End of virtual table implementation. +*************************************************************************/ +/* +** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function +** is called, set it to the return value of sqlite3_finalize() before +** returning. Otherwise, discard the sqlite3_finalize() return value. +*/ +static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){ + int rc = sqlite3_finalize(pStmt); + if( *pRc==SQLITE_OK ) *pRc = rc; +} + +/* +** Attempt to allocate an IdxTable structure corresponding to table zTab +** in the main database of connection db. If successful, set (*ppOut) to +** point to the new object and return SQLITE_OK. Otherwise, return an +** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be +** set to point to an error string. +** +** It is the responsibility of the caller to eventually free either the +** IdxTable object or error message using sqlite3_free(). +*/ +static int idxGetTableInfo( + sqlite3 *db, /* Database connection to read details from */ + const char *zTab, /* Table name */ + IdxTable **ppOut, /* OUT: New object (if successful) */ + char **pzErrmsg /* OUT: Error message (if not) */ +){ + sqlite3_stmt *p1 = 0; + int nCol = 0; + int nTab; + int nByte; + IdxTable *pNew = 0; + int rc, rc2; + char *pCsr = 0; + int nPk = 0; + + *ppOut = 0; + if( zTab==0 ) return SQLITE_ERROR; + nTab = STRLEN(zTab); + nByte = sizeof(IdxTable) + nTab + 1; + rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab); + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ + const char *zCol = (const char*)sqlite3_column_text(p1, 1); + const char *zColSeq = 0; + if( zCol==0 ){ + rc = SQLITE_ERROR; + break; + } + nByte += 1 + STRLEN(zCol); + rc = sqlite3_table_column_metadata( + db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0 + ); + if( zColSeq==0 ) zColSeq = "binary"; + nByte += 1 + STRLEN(zColSeq); + nCol++; + nPk += (sqlite3_column_int(p1, 5)>0); + } + rc2 = sqlite3_reset(p1); + if( rc==SQLITE_OK ) rc = rc2; + + nByte += sizeof(IdxColumn) * nCol; + if( rc==SQLITE_OK ){ + pNew = idxMalloc(&rc, nByte); + } + if( rc==SQLITE_OK ){ + pNew->aCol = (IdxColumn*)&pNew[1]; + pNew->nCol = nCol; + pCsr = (char*)&pNew->aCol[nCol]; + } + + nCol = 0; + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ + const char *zCol = (const char*)sqlite3_column_text(p1, 1); + const char *zColSeq = 0; + int nCopy; + if( zCol==0 ) continue; + nCopy = STRLEN(zCol) + 1; + pNew->aCol[nCol].zName = pCsr; + pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1); + memcpy(pCsr, zCol, nCopy); + pCsr += nCopy; + + rc = sqlite3_table_column_metadata( + db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0 + ); + if( rc==SQLITE_OK ){ + if( zColSeq==0 ) zColSeq = "binary"; + nCopy = STRLEN(zColSeq) + 1; + pNew->aCol[nCol].zColl = pCsr; + memcpy(pCsr, zColSeq, nCopy); + pCsr += nCopy; + } + + nCol++; + } + idxFinalize(&rc, p1); + + if( rc!=SQLITE_OK ){ + sqlite3_free(pNew); + pNew = 0; + }else if( ALWAYS(pNew!=0) ){ + pNew->zName = pCsr; + if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1); + } + + *ppOut = pNew; + return rc; +} + +/* +** This function is a no-op if *pRc is set to anything other than +** SQLITE_OK when it is called. +** +** If *pRc is initially set to SQLITE_OK, then the text specified by +** the printf() style arguments is appended to zIn and the result returned +** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on +** zIn before returning. +*/ +static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){ + va_list ap; + char *zAppend = 0; + char *zRet = 0; + int nIn = zIn ? STRLEN(zIn) : 0; + int nAppend = 0; + va_start(ap, zFmt); + if( *pRc==SQLITE_OK ){ + zAppend = sqlite3_vmprintf(zFmt, ap); + if( zAppend ){ + nAppend = STRLEN(zAppend); + zRet = (char*)sqlite3_malloc(nIn + nAppend + 1); + } + if( zAppend && zRet ){ + if( nIn ) memcpy(zRet, zIn, nIn); + memcpy(&zRet[nIn], zAppend, nAppend+1); + }else{ + sqlite3_free(zRet); + zRet = 0; + *pRc = SQLITE_NOMEM; + } + sqlite3_free(zAppend); + sqlite3_free(zIn); + } + va_end(ap); + return zRet; +} + +/* +** Return true if zId must be quoted in order to use it as an SQL +** identifier, or false otherwise. +*/ +static int idxIdentifierRequiresQuotes(const char *zId){ + int i; + int nId = STRLEN(zId); + + if( sqlite3_keyword_check(zId, nId) ) return 1; + + for(i=0; zId[i]; i++){ + if( !(zId[i]=='_') + && !(zId[i]>='0' && zId[i]<='9') + && !(zId[i]>='a' && zId[i]<='z') + && !(zId[i]>='A' && zId[i]<='Z') + ){ + return 1; + } + } + return 0; +} + +/* +** This function appends an index column definition suitable for constraint +** pCons to the string passed as zIn and returns the result. +*/ +static char *idxAppendColDefn( + int *pRc, /* IN/OUT: Error code */ + char *zIn, /* Column defn accumulated so far */ + IdxTable *pTab, /* Table index will be created on */ + IdxConstraint *pCons +){ + char *zRet = zIn; + IdxColumn *p = &pTab->aCol[pCons->iCol]; + if( zRet ) zRet = idxAppendText(pRc, zRet, ", "); + + if( idxIdentifierRequiresQuotes(p->zName) ){ + zRet = idxAppendText(pRc, zRet, "%Q", p->zName); + }else{ + zRet = idxAppendText(pRc, zRet, "%s", p->zName); + } + + if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ + if( idxIdentifierRequiresQuotes(pCons->zColl) ){ + zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); + }else{ + zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); + } + } + + if( pCons->bDesc ){ + zRet = idxAppendText(pRc, zRet, " DESC"); + } + return zRet; +} + +/* +** Search database dbm for an index compatible with the one idxCreateFromCons() +** would create from arguments pScan, pEq and pTail. If no error occurs and +** such an index is found, return non-zero. Or, if no such index is found, +** return zero. +** +** If an error occurs, set *pRc to an SQLite error code and return zero. +*/ +static int idxFindCompatible( + int *pRc, /* OUT: Error code */ + sqlite3* dbm, /* Database to search */ + IdxScan *pScan, /* Scan for table to search for index on */ + IdxConstraint *pEq, /* List of == constraints */ + IdxConstraint *pTail /* List of range constraints */ +){ + const char *zTbl = pScan->pTab->zName; + sqlite3_stmt *pIdxList = 0; + IdxConstraint *pIter; + int nEq = 0; /* Number of elements in pEq */ + int rc; + + /* Count the elements in list pEq */ + for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; + + rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl); + while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){ + int bMatch = 1; + IdxConstraint *pT = pTail; + sqlite3_stmt *pInfo = 0; + const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1); + if( zIdx==0 ) continue; + + /* Zero the IdxConstraint.bFlag values in the pEq list */ + for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; + + rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx); + while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){ + int iIdx = sqlite3_column_int(pInfo, 0); + int iCol = sqlite3_column_int(pInfo, 1); + const char *zColl = (const char*)sqlite3_column_text(pInfo, 4); + + if( iIdxpLink){ + if( pIter->bFlag ) continue; + if( pIter->iCol!=iCol ) continue; + if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; + pIter->bFlag = 1; + break; + } + if( pIter==0 ){ + bMatch = 0; + break; + } + }else{ + if( pT ){ + if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ + bMatch = 0; + break; + } + pT = pT->pLink; + } + } + } + idxFinalize(&rc, pInfo); + + if( rc==SQLITE_OK && bMatch ){ + sqlite3_finalize(pIdxList); + return 1; + } + } + idxFinalize(&rc, pIdxList); + + *pRc = rc; + return 0; +} + +/* Callback for sqlite3_exec() with query with leading count(*) column. + * The first argument is expected to be an int*, referent to be incremented + * if that leading column is not exactly '0'. + */ +static int countNonzeros(void* pCount, int nc, + char* azResults[], char* azColumns[]){ + (void)azColumns; /* Suppress unused parameter warning */ + if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){ + *((int *)pCount) += 1; + } + return 0; +} + +static int idxCreateFromCons( + sqlite3expert *p, + IdxScan *pScan, + IdxConstraint *pEq, + IdxConstraint *pTail +){ + sqlite3 *dbm = p->dbm; + int rc = SQLITE_OK; + if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){ + IdxTable *pTab = pScan->pTab; + char *zCols = 0; + char *zIdx = 0; + IdxConstraint *pCons; + unsigned int h = 0; + const char *zFmt; + + for(pCons=pEq; pCons; pCons=pCons->pLink){ + zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); + } + for(pCons=pTail; pCons; pCons=pCons->pLink){ + zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); + } + + if( rc==SQLITE_OK ){ + /* Hash the list of columns to come up with a name for the index */ + const char *zTable = pScan->pTab->zName; + int quoteTable = idxIdentifierRequiresQuotes(zTable); + char *zName = 0; /* Index name */ + int collisions = 0; + do{ + int i; + char *zFind; + for(i=0; zCols[i]; i++){ + h += ((h<<3) + zCols[i]); + } + sqlite3_free(zName); + zName = sqlite3_mprintf("%s_idx_%08x", zTable, h); + if( zName==0 ) break; + /* Is is unique among table, view and index names? */ + zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q" + " AND type in ('index','table','view')"; + zFind = sqlite3_mprintf(zFmt, zName); + i = 0; + rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0); + assert(rc==SQLITE_OK); + sqlite3_free(zFind); + if( i==0 ){ + collisions = 0; + break; + } + ++collisions; + }while( collisions<50 && zName!=0 ); + if( collisions ){ + /* This return means "Gave up trying to find a unique index name." */ + rc = SQLITE_BUSY_TIMEOUT; + }else if( zName==0 ){ + rc = SQLITE_NOMEM; + }else{ + if( quoteTable ){ + zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)"; + }else{ + zFmt = "CREATE INDEX %s ON %s(%s)"; + } + zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols); + if( !zIdx ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); + if( rc!=SQLITE_OK ){ + rc = SQLITE_BUSY_TIMEOUT; + }else{ + idxHashAdd(&rc, &p->hIdx, zName, zIdx); + } + } + sqlite3_free(zName); + sqlite3_free(zIdx); + } + } + + sqlite3_free(zCols); + } + return rc; +} + +/* +** Return true if list pList (linked by IdxConstraint.pLink) contains +** a constraint compatible with *p. Otherwise return false. +*/ +static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){ + IdxConstraint *pCmp; + for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ + if( p->iCol==pCmp->iCol ) return 1; + } + return 0; +} + +static int idxCreateFromWhere( + sqlite3expert *p, + IdxScan *pScan, /* Create indexes for this scan */ + IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */ +){ + IdxConstraint *p1 = 0; + IdxConstraint *pCon; + int rc; + + /* Gather up all the == constraints. */ + for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ + if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ + pCon->pLink = p1; + p1 = pCon; + } + } + + /* Create an index using the == constraints collected above. And the + ** range constraint/ORDER BY terms passed in by the caller, if any. */ + rc = idxCreateFromCons(p, pScan, p1, pTail); + + /* If no range/ORDER BY passed by the caller, create a version of the + ** index for each range constraint. */ + if( pTail==0 ){ + for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ + assert( pCon->pLink==0 ); + if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ + rc = idxCreateFromCons(p, pScan, p1, pCon); + } + } + } + + return rc; +} + +/* +** Create candidate indexes in database [dbm] based on the data in +** linked-list pScan. +*/ +static int idxCreateCandidates(sqlite3expert *p){ + int rc = SQLITE_OK; + IdxScan *pIter; + + for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ + rc = idxCreateFromWhere(p, pIter, 0); + if( rc==SQLITE_OK && pIter->pOrder ){ + rc = idxCreateFromWhere(p, pIter, pIter->pOrder); + } + } + + return rc; +} + +/* +** Free all elements of the linked list starting at pConstraint. +*/ +static void idxConstraintFree(IdxConstraint *pConstraint){ + IdxConstraint *pNext; + IdxConstraint *p; + + for(p=pConstraint; p; p=pNext){ + pNext = p->pNext; + sqlite3_free(p); + } +} + +/* +** Free all elements of the linked list starting from pScan up until pLast +** (pLast is not freed). +*/ +static void idxScanFree(IdxScan *pScan, IdxScan *pLast){ + IdxScan *p; + IdxScan *pNext; + for(p=pScan; p!=pLast; p=pNext){ + pNext = p->pNextScan; + idxConstraintFree(p->pOrder); + idxConstraintFree(p->pEq); + idxConstraintFree(p->pRange); + sqlite3_free(p); + } +} + +/* +** Free all elements of the linked list starting from pStatement up +** until pLast (pLast is not freed). +*/ +static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){ + IdxStatement *p; + IdxStatement *pNext; + for(p=pStatement; p!=pLast; p=pNext){ + pNext = p->pNext; + sqlite3_free(p->zEQP); + sqlite3_free(p->zIdx); + sqlite3_free(p); + } +} + +/* +** Free the linked list of IdxTable objects starting at pTab. +*/ +static void idxTableFree(IdxTable *pTab){ + IdxTable *pIter; + IdxTable *pNext; + for(pIter=pTab; pIter; pIter=pNext){ + pNext = pIter->pNext; + sqlite3_free(pIter); + } +} + +/* +** Free the linked list of IdxWrite objects starting at pTab. +*/ +static void idxWriteFree(IdxWrite *pTab){ + IdxWrite *pIter; + IdxWrite *pNext; + for(pIter=pTab; pIter; pIter=pNext){ + pNext = pIter->pNext; + sqlite3_free(pIter); + } +} + + + +/* +** This function is called after candidate indexes have been created. It +** runs all the queries to see which indexes they prefer, and populates +** IdxStatement.zIdx and IdxStatement.zEQP with the results. +*/ +static int idxFindIndexes( + sqlite3expert *p, + char **pzErr /* OUT: Error message (sqlite3_malloc) */ +){ + IdxStatement *pStmt; + sqlite3 *dbm = p->dbm; + int rc = SQLITE_OK; + + IdxHash hIdx; + idxHashInit(&hIdx); + + for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ + IdxHashEntry *pEntry; + sqlite3_stmt *pExplain = 0; + idxHashClear(&hIdx); + rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr, + "EXPLAIN QUERY PLAN %s", pStmt->zSql + ); + while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){ + /* int iId = sqlite3_column_int(pExplain, 0); */ + /* int iParent = sqlite3_column_int(pExplain, 1); */ + /* int iNotUsed = sqlite3_column_int(pExplain, 2); */ + const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3); + int nDetail; + int i; + + if( !zDetail ) continue; + nDetail = STRLEN(zDetail); + + for(i=0; ihIdx, zIdx, nIdx); + if( zSql ){ + idxHashAdd(&rc, &hIdx, zSql, 0); + if( rc ) goto find_indexes_out; + } + break; + } + } + + if( zDetail[0]!='-' ){ + pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail); + } + } + + for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ + pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); + } + + idxFinalize(&rc, pExplain); + } + + find_indexes_out: + idxHashClear(&hIdx); + return rc; +} + +static int idxAuthCallback( + void *pCtx, + int eOp, + const char *z3, + const char *z4, + const char *zDb, + const char *zTrigger +){ + int rc = SQLITE_OK; + (void)z4; + (void)zTrigger; + if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){ + if( sqlite3_stricmp(zDb, "main")==0 ){ + sqlite3expert *p = (sqlite3expert*)pCtx; + IdxTable *pTab; + for(pTab=p->pTable; pTab; pTab=pTab->pNext){ + if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; + } + if( pTab ){ + IdxWrite *pWrite; + for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ + if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; + } + if( pWrite==0 ){ + pWrite = idxMalloc(&rc, sizeof(IdxWrite)); + if( rc==SQLITE_OK ){ + pWrite->pTab = pTab; + pWrite->eOp = eOp; + pWrite->pNext = p->pWrite; + p->pWrite = pWrite; + } + } + } + } + } + return rc; +} + +static int idxProcessOneTrigger( + sqlite3expert *p, + IdxWrite *pWrite, + char **pzErr +){ + static const char *zInt = UNIQUE_TABLE_NAME; + static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME; + IdxTable *pTab = pWrite->pTab; + const char *zTab = pTab->zName; + const char *zSql = + "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema " + "WHERE tbl_name = %Q AND type IN ('table', 'trigger') " + "ORDER BY type;"; + sqlite3_stmt *pSelect = 0; + int rc = SQLITE_OK; + char *zWrite = 0; + + /* Create the table and its triggers in the temp schema */ + rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){ + const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0); + if( zCreate==0 ) continue; + rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); + } + idxFinalize(&rc, pSelect); + + /* Rename the table in the temp schema to zInt */ + if( rc==SQLITE_OK ){ + char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt); + if( z==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); + sqlite3_free(z); + } + } + + switch( pWrite->eOp ){ + case SQLITE_INSERT: { + int i; + zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt); + for(i=0; inCol; i++){ + zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", "); + } + zWrite = idxAppendText(&rc, zWrite, ")"); + break; + } + case SQLITE_UPDATE: { + int i; + zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt); + for(i=0; inCol; i++){ + zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", + pTab->aCol[i].zName + ); + } + break; + } + default: { + assert( pWrite->eOp==SQLITE_DELETE ); + if( rc==SQLITE_OK ){ + zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt); + if( zWrite==0 ) rc = SQLITE_NOMEM; + } + } + } + + if( rc==SQLITE_OK ){ + sqlite3_stmt *pX = 0; + rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); + idxFinalize(&rc, pX); + if( rc!=SQLITE_OK ){ + idxDatabaseError(p->dbv, pzErr); + } + } + sqlite3_free(zWrite); + + if( rc==SQLITE_OK ){ + rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); + } + + return rc; +} + +static int idxProcessTriggers(sqlite3expert *p, char **pzErr){ + int rc = SQLITE_OK; + IdxWrite *pEnd = 0; + IdxWrite *pFirst = p->pWrite; + + while( rc==SQLITE_OK && pFirst!=pEnd ){ + IdxWrite *pIter; + for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ + rc = idxProcessOneTrigger(p, pIter, pzErr); + } + pEnd = pFirst; + pFirst = p->pWrite; + } + + return rc; +} + +/* +** This function tests if the schema of the main database of database handle +** db contains an object named zTab. Assuming no error occurs, output parameter +** (*pbContains) is set to true if zTab exists, or false if it does not. +** +** Or, if an error occurs, an SQLite error code is returned. The final value +** of (*pbContains) is undefined in this case. +*/ +static int expertDbContainsObject( + sqlite3 *db, + const char *zTab, + int *pbContains /* OUT: True if object exists */ +){ + const char *zSql = "SELECT 1 FROM sqlite_schema WHERE name = ?"; + sqlite3_stmt *pSql = 0; + int rc = SQLITE_OK; + int ret = 0; + + rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pSql) ){ + ret = 1; + } + rc = sqlite3_finalize(pSql); + } + + *pbContains = ret; + return rc; +} + +/* +** Execute SQL command zSql using database handle db. If no error occurs, +** set (*pzErr) to NULL and return SQLITE_OK. +** +** If an error does occur, return an SQLite error code and set (*pzErr) to +** point to a buffer containing an English language error message. Except, +** if the error message begins with "no such module:", then ignore the +** error and return as if the SQL statement had succeeded. +** +** This is used to copy as much of the database schema as possible while +** ignoring any errors related to missing virtual table modules. +*/ +static int expertSchemaSql(sqlite3 *db, const char *zSql, char **pzErr){ + int rc = SQLITE_OK; + char *zErr = 0; + + rc = sqlite3_exec(db, zSql, 0, 0, &zErr); + if( rc!=SQLITE_OK && zErr ){ + int nErr = STRLEN(zErr); + if( nErr>=15 && memcmp(zErr, "no such module:", 15)==0 ){ + sqlite3_free(zErr); + rc = SQLITE_OK; + zErr = 0; + } + } + + *pzErr = zErr; + return rc; +} + +static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){ + int rc = idxRegisterVtab(p); + sqlite3_stmt *pSchema = 0; + + /* For each table in the main db schema: + ** + ** 1) Add an entry to the p->pTable list, and + ** 2) Create the equivalent virtual table in dbv. + */ + rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, + "SELECT type, name, sql, 1, " + " substr(sql,1,14)=='create virtual' COLLATE nocase " + "FROM sqlite_schema " + "WHERE type IN ('table','view') AND " + " substr(name,1,7)!='sqlite_' COLLATE nocase " + " UNION ALL " + "SELECT type, name, sql, 2, 0 FROM sqlite_schema " + "WHERE type = 'trigger'" + " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') " + "ORDER BY 4, 5 DESC, 1" + ); + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){ + const char *zType = (const char*)sqlite3_column_text(pSchema, 0); + const char *zName = (const char*)sqlite3_column_text(pSchema, 1); + const char *zSql = (const char*)sqlite3_column_text(pSchema, 2); + int bVirtual = sqlite3_column_int(pSchema, 4); + int bExists = 0; + + if( zType==0 || zName==0 ) continue; + rc = expertDbContainsObject(p->dbv, zName, &bExists); + if( rc || bExists ) continue; + + if( zType[0]=='v' || zType[1]=='r' || bVirtual ){ + /* A view. Or a trigger on a view. */ + if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg); + }else{ + IdxTable *pTab; + rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); + if( rc==SQLITE_OK && ALWAYS(pTab!=0) ){ + int i; + char *zInner = 0; + char *zOuter = 0; + pTab->pNext = p->pTable; + p->pTable = pTab; + + /* The statement the vtab will pass to sqlite3_declare_vtab() */ + zInner = idxAppendText(&rc, 0, "CREATE TABLE x("); + for(i=0; inCol; i++){ + zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", + (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl + ); + } + zInner = idxAppendText(&rc, zInner, ")"); + + /* The CVT statement to create the vtab */ + zOuter = idxAppendText(&rc, 0, + "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner + ); + if( rc==SQLITE_OK ){ + rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); + } + sqlite3_free(zInner); + sqlite3_free(zOuter); + } + } + } + idxFinalize(&rc, pSchema); + return rc; +} + +struct IdxSampleCtx { + int iTarget; + double target; /* Target nRet/nRow value */ + double nRow; /* Number of rows seen */ + double nRet; /* Number of rows returned */ +}; + +static void idxSampleFunc( + sqlite3_context *pCtx, + int argc, + sqlite3_value **argv +){ + struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx); + int bRet; + + (void)argv; + assert( argc==0 ); + if( p->nRow==0.0 ){ + bRet = 1; + }else{ + bRet = (p->nRet / p->nRow) <= p->target; + if( bRet==0 ){ + unsigned short rnd; + sqlite3_randomness(2, (void*)&rnd); + bRet = ((int)rnd % 100) <= p->iTarget; + } + } + + sqlite3_result_int(pCtx, bRet); + p->nRow += 1.0; + p->nRet += (double)bRet; +} + +struct IdxRemCtx { + int nSlot; + struct IdxRemSlot { + int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */ + i64 iVal; /* SQLITE_INTEGER value */ + double rVal; /* SQLITE_FLOAT value */ + int nByte; /* Bytes of space allocated at z */ + int n; /* Size of buffer z */ + char *z; /* SQLITE_TEXT/BLOB value */ + } aSlot[1]; +}; + +/* +** Implementation of scalar function sqlite_expert_rem(). +*/ +static void idxRemFunc( + sqlite3_context *pCtx, + int argc, + sqlite3_value **argv +){ + struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx); + struct IdxRemSlot *pSlot; + int iSlot; + assert( argc==2 ); + + iSlot = sqlite3_value_int(argv[0]); + assert( iSlotnSlot ); + pSlot = &p->aSlot[iSlot]; + + switch( pSlot->eType ){ + case SQLITE_NULL: + /* no-op */ + break; + + case SQLITE_INTEGER: + sqlite3_result_int64(pCtx, pSlot->iVal); + break; + + case SQLITE_FLOAT: + sqlite3_result_double(pCtx, pSlot->rVal); + break; + + case SQLITE_BLOB: + sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); + break; + + case SQLITE_TEXT: + sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); + break; + } + + pSlot->eType = sqlite3_value_type(argv[1]); + switch( pSlot->eType ){ + case SQLITE_NULL: + /* no-op */ + break; + + case SQLITE_INTEGER: + pSlot->iVal = sqlite3_value_int64(argv[1]); + break; + + case SQLITE_FLOAT: + pSlot->rVal = sqlite3_value_double(argv[1]); + break; + + case SQLITE_BLOB: + case SQLITE_TEXT: { + int nByte = sqlite3_value_bytes(argv[1]); + const void *pData = 0; + if( nByte>pSlot->nByte ){ + char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); + if( zNew==0 ){ + sqlite3_result_error_nomem(pCtx); + return; + } + pSlot->nByte = nByte*2; + pSlot->z = zNew; + } + pSlot->n = nByte; + if( pSlot->eType==SQLITE_BLOB ){ + pData = sqlite3_value_blob(argv[1]); + if( pData ) memcpy(pSlot->z, pData, nByte); + }else{ + pData = sqlite3_value_text(argv[1]); + memcpy(pSlot->z, pData, nByte); + } + break; + } + } +} + +static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){ + int rc = SQLITE_OK; + const char *zMax = + "SELECT max(i.seqno) FROM " + " sqlite_schema AS s, " + " pragma_index_list(s.name) AS l, " + " pragma_index_info(l.name) AS i " + "WHERE s.type = 'table'"; + sqlite3_stmt *pMax = 0; + + *pnMax = 0; + rc = idxPrepareStmt(db, &pMax, pzErr, zMax); + if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ + *pnMax = sqlite3_column_int(pMax, 0) + 1; + } + idxFinalize(&rc, pMax); + + return rc; +} + +static int idxPopulateOneStat1( + sqlite3expert *p, + sqlite3_stmt *pIndexXInfo, + sqlite3_stmt *pWriteStat, + const char *zTab, + const char *zIdx, + char **pzErr +){ + char *zCols = 0; + char *zOrder = 0; + char *zQuery = 0; + int nCol = 0; + int i; + sqlite3_stmt *pQuery = 0; + int *aStat = 0; + int rc = SQLITE_OK; + + assert( p->iSample>0 ); + + /* Formulate the query text */ + sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); + while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){ + const char *zComma = zCols==0 ? "" : ", "; + const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0); + const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1); + if( zName==0 ){ + /* This index contains an expression. Ignore it. */ + sqlite3_free(zCols); + sqlite3_free(zOrder); + return sqlite3_reset(pIndexXInfo); + } + zCols = idxAppendText(&rc, zCols, + "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s", + zComma, zName, nCol, zName, zColl + ); + zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol); + } + sqlite3_reset(pIndexXInfo); + if( rc==SQLITE_OK ){ + if( p->iSample==100 ){ + zQuery = sqlite3_mprintf( + "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder + ); + }else{ + zQuery = sqlite3_mprintf( + "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder + ); + } + } + sqlite3_free(zCols); + sqlite3_free(zOrder); + + /* Formulate the query text */ + if( rc==SQLITE_OK ){ + sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); + rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery); + } + sqlite3_free(zQuery); + + if( rc==SQLITE_OK ){ + aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1)); + } + if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ + IdxHashEntry *pEntry; + char *zStat = 0; + for(i=0; i<=nCol; i++) aStat[i] = 1; + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ + aStat[0]++; + for(i=0; ihIdx, zIdx, STRLEN(zIdx)); + if( pEntry ){ + assert( pEntry->zVal2==0 ); + pEntry->zVal2 = zStat; + }else{ + sqlite3_free(zStat); + } + } + sqlite3_free(aStat); + idxFinalize(&rc, pQuery); + + return rc; +} + +static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){ + int rc; + char *zSql; + + rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); + if( rc!=SQLITE_OK ) return rc; + + zSql = sqlite3_mprintf( + "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab + ); + if( zSql==0 ) return SQLITE_NOMEM; + rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); + sqlite3_free(zSql); + + return rc; +} + +/* +** This function is called as part of sqlite3_expert_analyze(). Candidate +** indexes have already been created in database sqlite3expert.dbm, this +** function populates sqlite_stat1 table in the same database. +** +** The stat1 data is generated by querying the +*/ +static int idxPopulateStat1(sqlite3expert *p, char **pzErr){ + int rc = SQLITE_OK; + int nMax =0; + struct IdxRemCtx *pCtx = 0; + struct IdxSampleCtx samplectx; + int i; + i64 iPrev = -100000; + sqlite3_stmt *pAllIndex = 0; + sqlite3_stmt *pIndexXInfo = 0; + sqlite3_stmt *pWrite = 0; + + const char *zAllIndex = + "SELECT s.rowid, s.name, l.name FROM " + " sqlite_schema AS s, " + " pragma_index_list(s.name) AS l " + "WHERE s.type = 'table'"; + const char *zIndexXInfo = + "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key"; + const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)"; + + /* If iSample==0, no sqlite_stat1 data is required. */ + if( p->iSample==0 ) return SQLITE_OK; + + rc = idxLargestIndex(p->dbm, &nMax, pzErr); + if( nMax<=0 || rc!=SQLITE_OK ) return rc; + + rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); + + if( rc==SQLITE_OK ){ + int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax); + pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte); + } + + if( rc==SQLITE_OK ){ + sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); + rc = sqlite3_create_function(dbrem, "sqlite_expert_rem", + 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0 + ); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(p->db, "sqlite_expert_sample", + 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0 + ); + } + + if( rc==SQLITE_OK ){ + pCtx->nSlot = nMax+1; + rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); + } + if( rc==SQLITE_OK ){ + rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); + } + if( rc==SQLITE_OK ){ + rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); + } + + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){ + i64 iRowid = sqlite3_column_int64(pAllIndex, 0); + const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1); + const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2); + if( zTab==0 || zIdx==0 ) continue; + if( p->iSample<100 && iPrev!=iRowid ){ + samplectx.target = (double)p->iSample / 100.0; + samplectx.iTarget = p->iSample; + samplectx.nRow = 0.0; + samplectx.nRet = 0.0; + rc = idxBuildSampleTable(p, zTab); + if( rc!=SQLITE_OK ) break; + } + rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr); + iPrev = iRowid; + } + if( rc==SQLITE_OK && p->iSample<100 ){ + rc = sqlite3_exec(p->dbv, + "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0 + ); + } + + idxFinalize(&rc, pAllIndex); + idxFinalize(&rc, pIndexXInfo); + idxFinalize(&rc, pWrite); + + if( pCtx ){ + for(i=0; inSlot; i++){ + sqlite3_free(pCtx->aSlot[i].z); + } + sqlite3_free(pCtx); + } + + if( rc==SQLITE_OK ){ + rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0); + } + + sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0); + sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0); + + sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); + return rc; +} + +/* +** Define and possibly pretend to use a useless collation sequence. +** This pretense allows expert to accept SQL using custom collations. +*/ +int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){ + (void)up1; + (void)up2; + (void)up3; + (void)up4; + (void)up5; + assert(0); /* VDBE should never be run. */ + return 0; +} +/* And a callback to register above upon actual need */ +void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){ + (void)up1; + sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0); +} + +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \ + && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) +/* +** dummy functions for no-op implementation of UDFs during expert's work +*/ +void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){ + (void)up1; + (void)up2; + (void)up3; + assert(0); /* VDBE should never be run. */ +} +void dummyUDFvalue(sqlite3_context *up1){ + (void)up1; + assert(0); /* VDBE should never be run. */ +} + +/* +** Register UDFs from user database with another. +*/ +int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){ + sqlite3_stmt *pStmt; + int rc = sqlite3_prepare_v2(dbSrc, + "SELECT name,type,enc,narg,flags " + "FROM pragma_function_list() " + "WHERE builtin==0", -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ + int nargs = sqlite3_column_int(pStmt,3); + int flags = sqlite3_column_int(pStmt,4); + const char *name = (char*)sqlite3_column_text(pStmt,0); + const char *type = (char*)sqlite3_column_text(pStmt,1); + const char *enc = (char*)sqlite3_column_text(pStmt,2); + if( name==0 || type==0 || enc==0 ){ + /* no-op. Only happens on OOM */ + }else{ + int ienc = SQLITE_UTF8; + int rcf = SQLITE_ERROR; + if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE; + else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE; + ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY)); + if( strcmp(type,"w")==0 ){ + rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0, + dummyUDF,dummyUDFvalue,0,0,0); + }else if( strcmp(type,"a")==0 ){ + rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0, + 0,dummyUDF,dummyUDFvalue); + }else if( strcmp(type,"s")==0 ){ + rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0, + dummyUDF,0,0); + } + if( rcf!=SQLITE_OK ){ + rc = rcf; + break; + } + } + } + sqlite3_finalize(pStmt); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + return rc; +} +#endif + +/* +** Allocate a new sqlite3expert object. +*/ +sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){ + int rc = SQLITE_OK; + sqlite3expert *pNew; + + pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert)); + + /* Open two in-memory databases to work with. The "vtab database" (dbv) + ** will contain a virtual table corresponding to each real table in + ** the user database schema, and a copy of each view. It is used to + ** collect information regarding the WHERE, ORDER BY and other clauses + ** of the user's query. + */ + if( rc==SQLITE_OK ){ + pNew->db = db; + pNew->iSample = 100; + rc = sqlite3_open(":memory:", &pNew->dbv); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_open(":memory:", &pNew->dbm); + if( rc==SQLITE_OK ){ + sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); + } + } + + /* Allow custom collations to be dealt with through prepare. */ + if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS); + if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS); + +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \ + && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) + /* Register UDFs from database [db] with [dbm] and [dbv]. */ + if( rc==SQLITE_OK ){ + rc = registerUDFs(pNew->db, pNew->dbm); + } + if( rc==SQLITE_OK ){ + rc = registerUDFs(pNew->db, pNew->dbv); + } +#endif + + /* Copy the entire schema of database [db] into [dbm]. */ + if( rc==SQLITE_OK ){ + sqlite3_stmt *pSql = 0; + rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, + "SELECT sql, name, substr(sql,1,14)=='create virtual' COLLATE nocase" + " FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' COLLATE nocase" + " ORDER BY 3 DESC, rowid" + ); + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ + const char *zSql = (const char*)sqlite3_column_text(pSql, 0); + const char *zName = (const char*)sqlite3_column_text(pSql, 1); + int bExists = 0; + rc = expertDbContainsObject(pNew->dbm, zName, &bExists); + if( rc==SQLITE_OK && zSql && bExists==0 ){ + rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg); + } + } + idxFinalize(&rc, pSql); + } + + /* Create the vtab schema */ + if( rc==SQLITE_OK ){ + rc = idxCreateVtabSchema(pNew, pzErrmsg); + } + + /* Register the auth callback with dbv */ + if( rc==SQLITE_OK ){ + sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); + } + + /* If an error has occurred, free the new object and reutrn NULL. Otherwise, + ** return the new sqlite3expert handle. */ + if( rc!=SQLITE_OK ){ + sqlite3_expert_destroy(pNew); + pNew = 0; + } + return pNew; +} + +/* +** Configure an sqlite3expert object. +*/ +int sqlite3_expert_config(sqlite3expert *p, int op, ...){ + int rc = SQLITE_OK; + va_list ap; + va_start(ap, op); + switch( op ){ + case EXPERT_CONFIG_SAMPLE: { + int iVal = va_arg(ap, int); + if( iVal<0 ) iVal = 0; + if( iVal>100 ) iVal = 100; + p->iSample = iVal; + break; + } + default: + rc = SQLITE_NOTFOUND; + break; + } + + va_end(ap); + return rc; +} + +/* +** Add an SQL statement to the analysis. +*/ +int sqlite3_expert_sql( + sqlite3expert *p, /* From sqlite3_expert_new() */ + const char *zSql, /* SQL statement to add */ + char **pzErr /* OUT: Error message (if any) */ +){ + IdxScan *pScanOrig = p->pScan; + IdxStatement *pStmtOrig = p->pStatement; + int rc = SQLITE_OK; + const char *zStmt = zSql; + + if( p->bRun ) return SQLITE_MISUSE; + + while( rc==SQLITE_OK && zStmt && zStmt[0] ){ + sqlite3_stmt *pStmt = 0; + /* Ensure that the provided statement compiles against user's DB. */ + rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt); + if( rc!=SQLITE_OK ) break; + sqlite3_finalize(pStmt); + rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); + if( rc==SQLITE_OK ){ + if( pStmt ){ + IdxStatement *pNew; + const char *z = sqlite3_sql(pStmt); + int n = STRLEN(z); + pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1); + if( rc==SQLITE_OK ){ + pNew->zSql = (char*)&pNew[1]; + memcpy(pNew->zSql, z, n+1); + pNew->pNext = p->pStatement; + if( p->pStatement ) pNew->iId = p->pStatement->iId+1; + p->pStatement = pNew; + } + sqlite3_finalize(pStmt); + } + }else{ + idxDatabaseError(p->dbv, pzErr); + } + } + + if( rc!=SQLITE_OK ){ + idxScanFree(p->pScan, pScanOrig); + idxStatementFree(p->pStatement, pStmtOrig); + p->pScan = pScanOrig; + p->pStatement = pStmtOrig; + } + + return rc; +} + +int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){ + int rc; + IdxHashEntry *pEntry; + + /* Do trigger processing to collect any extra IdxScan structures */ + rc = idxProcessTriggers(p, pzErr); + + /* Create candidate indexes within the in-memory database file */ + if( rc==SQLITE_OK ){ + rc = idxCreateCandidates(p); + }else if ( rc==SQLITE_BUSY_TIMEOUT ){ + if( pzErr ) + *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose."); + return rc; + } + + /* Generate the stat1 data */ + if( rc==SQLITE_OK ){ + rc = idxPopulateStat1(p, pzErr); + } + + /* Formulate the EXPERT_REPORT_CANDIDATES text */ + for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ + p->zCandidates = idxAppendText(&rc, p->zCandidates, + "%s;%s%s\n", pEntry->zVal, + pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 + ); + } + + /* Figure out which of the candidate indexes are preferred by the query + ** planner and report the results to the user. */ + if( rc==SQLITE_OK ){ + rc = idxFindIndexes(p, pzErr); + } + + if( rc==SQLITE_OK ){ + p->bRun = 1; + } + return rc; +} + +/* +** Return the total number of statements that have been added to this +** sqlite3expert using sqlite3_expert_sql(). +*/ +int sqlite3_expert_count(sqlite3expert *p){ + int nRet = 0; + if( p->pStatement ) nRet = p->pStatement->iId+1; + return nRet; +} + +/* +** Return a component of the report. +*/ +const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){ + const char *zRet = 0; + IdxStatement *pStmt; + + if( p->bRun==0 ) return 0; + for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); + switch( eReport ){ + case EXPERT_REPORT_SQL: + if( pStmt ) zRet = pStmt->zSql; + break; + case EXPERT_REPORT_INDEXES: + if( pStmt ) zRet = pStmt->zIdx; + break; + case EXPERT_REPORT_PLAN: + if( pStmt ) zRet = pStmt->zEQP; + break; + case EXPERT_REPORT_CANDIDATES: + zRet = p->zCandidates; + break; + } + return zRet; +} + +/* +** Free an sqlite3expert object. +*/ +void sqlite3_expert_destroy(sqlite3expert *p){ + if( p ){ + sqlite3_close(p->dbm); + sqlite3_close(p->dbv); + idxScanFree(p->pScan, 0); + idxStatementFree(p->pStatement, 0); + idxTableFree(p->pTable); + idxWriteFree(p->pWrite); + idxHashClear(&p->hIdx); + sqlite3_free(p->zCandidates); + sqlite3_free(p); + } +} + +#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ diff --git a/subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.h b/subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.h new file mode 100644 index 0000000000..6048137237 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/expert/sqlite3expert.h @@ -0,0 +1,168 @@ +/* +** 2017 April 07 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ +#if !defined(SQLITEEXPERT_H) +#define SQLITEEXPERT_H 1 +#include "sqlite3.h" + +typedef struct sqlite3expert sqlite3expert; + +/* +** Create a new sqlite3expert object. +** +** If successful, a pointer to the new object is returned and (*pzErr) set +** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to +** an English-language error message. In this case it is the responsibility +** of the caller to eventually free the error message buffer using +** sqlite3_free(). +*/ +sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr); + +/* +** Configure an sqlite3expert object. +** +** EXPERT_CONFIG_SAMPLE: +** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for +** each candidate index. This involves scanning and sorting the entire +** contents of each user database table once for each candidate index +** associated with the table. For large databases, this can be +** prohibitively slow. This option allows the sqlite3expert object to +** be configured so that sqlite_stat1 data is instead generated based on a +** subset of each table, or so that no sqlite_stat1 data is used at all. +** +** A single integer argument is passed to this option. If the value is less +** than or equal to zero, then no sqlite_stat1 data is generated or used by +** the analysis - indexes are recommended based on the database schema only. +** Or, if the value is 100 or greater, complete sqlite_stat1 data is +** generated for each candidate index (this is the default). Finally, if the +** value falls between 0 and 100, then it represents the percentage of user +** table rows that should be considered when generating sqlite_stat1 data. +** +** Examples: +** +** // Do not generate any sqlite_stat1 data +** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0); +** +** // Generate sqlite_stat1 data based on 10% of the rows in each table. +** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10); +*/ +int sqlite3_expert_config(sqlite3expert *p, int op, ...); + +#define EXPERT_CONFIG_SAMPLE 1 /* int */ + +/* +** Specify zero or more SQL statements to be included in the analysis. +** +** Buffer zSql must contain zero or more complete SQL statements. This +** function parses all statements contained in the buffer and adds them +** to the internal list of statements to analyze. If successful, SQLITE_OK +** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example +** due to a error in the SQL - an SQLite error code is returned and (*pzErr) +** may be set to point to an English language error message. In this case +** the caller is responsible for eventually freeing the error message buffer +** using sqlite3_free(). +** +** If an error does occur while processing one of the statements in the +** buffer passed as the second argument, none of the statements in the +** buffer are added to the analysis. +** +** This function must be called before sqlite3_expert_analyze(). If a call +** to this function is made on an sqlite3expert object that has already +** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned +** immediately and no statements are added to the analysis. +*/ +int sqlite3_expert_sql( + sqlite3expert *p, /* From a successful sqlite3_expert_new() */ + const char *zSql, /* SQL statement(s) to add */ + char **pzErr /* OUT: Error message (if any) */ +); + + +/* +** This function is called after the sqlite3expert object has been configured +** with all SQL statements using sqlite3_expert_sql() to actually perform +** the analysis. Once this function has been called, it is not possible to +** add further SQL statements to the analysis. +** +** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if +** an error occurs, an SQLite error code is returned and (*pzErr) set to +** point to a buffer containing an English language error message. In this +** case it is the responsibility of the caller to eventually free the buffer +** using sqlite3_free(). +** +** If an error does occur within this function, the sqlite3expert object +** is no longer useful for any purpose. At that point it is no longer +** possible to add further SQL statements to the object or to re-attempt +** the analysis. The sqlite3expert object must still be freed using a call +** sqlite3_expert_destroy(). +*/ +int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr); + +/* +** Return the total number of statements loaded using sqlite3_expert_sql(). +** The total number of SQL statements may be different from the total number +** to calls to sqlite3_expert_sql(). +*/ +int sqlite3_expert_count(sqlite3expert*); + +/* +** Return a component of the report. +** +** This function is called after sqlite3_expert_analyze() to extract the +** results of the analysis. Each call to this function returns either a +** NULL pointer or a pointer to a buffer containing a nul-terminated string. +** The value passed as the third argument must be one of the EXPERT_REPORT_* +** #define constants defined below. +** +** For some EXPERT_REPORT_* parameters, the buffer returned contains +** information relating to a specific SQL statement. In these cases that +** SQL statement is identified by the value passed as the second argument. +** SQL statements are numbered from 0 in the order in which they are parsed. +** If an out-of-range value (less than zero or equal to or greater than the +** value returned by sqlite3_expert_count()) is passed as the second argument +** along with such an EXPERT_REPORT_* parameter, NULL is always returned. +** +** EXPERT_REPORT_SQL: +** Return the text of SQL statement iStmt. +** +** EXPERT_REPORT_INDEXES: +** Return a buffer containing the CREATE INDEX statements for all recommended +** indexes for statement iStmt. If there are no new recommeded indexes, NULL +** is returned. +** +** EXPERT_REPORT_PLAN: +** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query +** iStmt after the proposed indexes have been added to the database schema. +** +** EXPERT_REPORT_CANDIDATES: +** Return a pointer to a buffer containing the CREATE INDEX statements +** for all indexes that were tested (for all SQL statements). The iStmt +** parameter is ignored for EXPERT_REPORT_CANDIDATES calls. +*/ +const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport); + +/* +** Values for the third argument passed to sqlite3_expert_report(). +*/ +#define EXPERT_REPORT_SQL 1 +#define EXPERT_REPORT_INDEXES 2 +#define EXPERT_REPORT_PLAN 3 +#define EXPERT_REPORT_CANDIDATES 4 + +/* +** Free an (sqlite3expert*) handle and all associated resources. There +** should be one call to this function for each successful call to +** sqlite3-expert_new(). +*/ +void sqlite3_expert_destroy(sqlite3expert*); + +#endif /* !defined(SQLITEEXPERT_H) */ diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index cf60e234d8..103d9d09a8 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -627,6 +627,8 @@ int sqlitedbg_end_transaction(sqlite3 *db) { return rc; } +void sqlitedbg_private_open(int on) { tls_opening_server = on; } + int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db) { *db = NULL; pthread_mutex_lock(&g_lock); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 71c2b23d0f..59c18070e2 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -233,6 +233,21 @@ int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db); // returned, and the transaction is still open. int sqlitedbg_end_transaction(sqlite3 *db); +// Index suggestions (sqlite3's .expert): runs SQLite's ext/expert (sqlitedbg_expert.c) over sql, one +// or more statements, on the server connection db. Expert copies db's schema into two in-memory +// connections of its own, which the extension neither lists nor traces, and only prepares sql on db, +// never runs it. Sampling is off, so no row of the app's data is read and nothing is added to db; the +// suggestions rest on SQLite's default estimates. progress (with arg) is set on expert's connections +// as on db, for the time limit; the caller sets db's own. On SQLITE_OK, *out holds the results, read +// with sqlite3_expert_count and sqlite3_expert_report and freed with sqlite3_expert_destroy. Otherwise +// *out is NULL and *errmsg may hold a message, freed with sqlite3_free. +typedef struct sqlite3expert sqlite3expert; +int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int (*progress)(void *), void *arg, sqlite3expert **out, + char **errmsg); + +// Set around a connection the extension opens for itself (expert's), so it is not taken for the app's. +void sqlitedbg_private_open(int on); + #ifdef __cplusplus } #endif diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c new file mode 100644 index 0000000000..82108702e9 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c @@ -0,0 +1,34 @@ +// SQLite's ext/expert (expert/, from SQLite 3.49.1, unchanged; public domain like the rest of SQLite), +// compiled into the extension for suggest_indexes. Like sqlitedbg.c it reaches SQLite through the api +// table (sqlite3ext.h), so it runs on requery's SQLite. Included rather than compiled on its own so +// that the progress handler can be set on expert's own connections (p->dbv, p->dbm). +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT3 + +#include "expert/sqlite3expert.c" +#include "sqlitedbg.h" + +int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int (*progress)(void *), void *arg, sqlite3expert **out, + char **errmsg) { + *out = NULL; + *errmsg = NULL; + // expert opens two in-memory connections; the extension must not list or trace them as the app's + sqlitedbg_private_open(1); + sqlite3expert *p = sqlite3_expert_new(db, errmsg); + sqlitedbg_private_open(0); + if (!p) return SQLITE_ERROR; + sqlite3_progress_handler(p->dbv, 1000, progress, arg); + sqlite3_progress_handler(p->dbm, 1000, progress, arg); + // No sqlite_stat1 from the app's data: sampling reads every row of every indexed table on db, and + // registers functions and a temp table on it. Suggestions then rest on SQLite's default estimates. + int rc = sqlite3_expert_config(p, EXPERT_CONFIG_SAMPLE, 0); + // The handler runs every 1000 VM steps, which a small schema may never reach: check between steps too. + if (rc == SQLITE_OK) rc = progress(arg) ? SQLITE_INTERRUPT : sqlite3_expert_sql(p, sql, errmsg); + if (rc == SQLITE_OK) rc = progress(arg) ? SQLITE_INTERRUPT : sqlite3_expert_analyze(p, errmsg); + if (rc != SQLITE_OK) { + sqlite3_expert_destroy(p); + return rc; + } + *out = p; + return SQLITE_OK; +} diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index bd7e613e07..226eed359e 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -14,6 +14,7 @@ #include #include "sqlite3ext.h" +#include "expert/sqlite3expert.h" #include "sqlitedbg.h" SQLITE_EXTENSION_INIT3 @@ -627,6 +628,62 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring return result; } +// Index suggestions: [candidates, then sql, indexes and plan for each statement] (sqlite3_expert_report). +static jobjectArray bridge_suggest_indexes(JNIEnv *env, jclass cls, jlong handle, jbyteArray sql_utf8, jlong deadline_ms) { + (void)cls; + sqlite3 *db = (sqlite3 *)(intptr_t)handle; + deadline dl = {(int64_t)deadline_ms, 0, 0}; + sqlite3expert *ex = NULL; + char *err = NULL; + jobjectArray result = NULL; + + if (now_ms() >= dl.at_ms) { + throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the analysis started"); + return NULL; + } + jsize len = (*env)->GetArrayLength(env, sql_utf8); + char *text = malloc((size_t)len + 1); + if (!text) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return NULL; + } + (*env)->GetByteArrayRegion(env, sql_utf8, 0, len, (jbyte *)text); + text[len] = 0; + if (memchr(text, 0, (size_t)len)) { + free(text); + throw_engine(env, SQLITE_ERROR, "the SQL holds a NUL character, and SQLite reads no further than it"); + return NULL; + } + sqlite3_progress_handler(db, 1000, progress_cb, &dl); + int rc = sqlitedbg_expert_run(db, text, progress_cb, &dl, &ex, &err); + sqlite3_progress_handler(db, 0, NULL, NULL); + free(text); + if (rc != SQLITE_OK) { + if (dl.hit) throw_engine(env, SQLITE_INTERRUPT, "the analysis ran past its time limit"); + else throw_engine(env, rc, err ? err : sqlite3_errstr(rc)); + sqlite3_free(err); + return NULL; + } + int n = sqlite3_expert_count(ex); + result = (*env)->NewObjectArray(env, 1 + 3 * n, g_string, NULL); + for (int i = -1; result && i < n; i++) { + static const int kinds[] = {EXPERT_REPORT_SQL, EXPERT_REPORT_INDEXES, EXPERT_REPORT_PLAN}; + for (int k = 0; k < (i < 0 ? 1 : 3); k++) { + const char *r = sqlite3_expert_report(ex, i < 0 ? 0 : i, i < 0 ? EXPERT_REPORT_CANDIDATES : kinds[k]); + if (!r) continue; + jstring js = utf8_string(env, r, (int)strlen(r)); + if (!js) { + result = NULL; + break; + } + (*env)->SetObjectArrayElement(env, result, i < 0 ? 0 : 1 + 3 * i + k, js); + (*env)->DeleteLocalRef(env, js); + } + } + sqlite3_expert_destroy(ex); + return result; +} + JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { (void)reserved; JNIEnv *env; @@ -667,6 +724,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"openServer", "([BZ)J", (void *)bridge_open_server}, {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"suggestIndexes", "(J[BJ)[Ljava/lang/String;", (void *)bridge_suggest_indexes}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 1c5cb10701..2d225e1bad 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -81,8 +81,34 @@ interface ServerConnection : Closeable { limits: QueryLimits, deadlineMillis: Long, ): QueryResult + + /** + * Index suggestions for [sql] (one or more statements) from SQLite's ext/expert (`sqlitedbg_expert_run`): + * the statements are prepared, never run, and no row of the app's data is read, so the suggestions + * rest on SQLite's default estimates. Stops at [deadlineMillis] like [query]. + * + * @throws DebugEngineException for SQLite errors (SQL that does not prepare, for one) or the deadline. + */ + fun suggestIndexes( + sql: String, + deadlineMillis: Long, + ): IndexSuggestions } +data class IndexSuggestions( + /** The candidate indexes expert weighed, one CREATE INDEX per line with its estimate; null when none. */ + val candidates: String?, + val statements: List, +) + +data class StatementSuggestion( + val sql: String, + /** The CREATE INDEX statements that would help, one per line; null when none would. */ + val indexes: String?, + /** EXPLAIN QUERY PLAN with those indexes, one line per step. */ + val plan: String?, +) + data class AppConnection( /** Unique within the process, never reused. */ val id: Long, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 6450b1c403..5db17cc916 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -62,6 +62,18 @@ internal object NativeBridge { deadlineMillis: Long, ): Array + /** + * Index suggestions from SQLite's ext/expert for [sqlUtf8] (one or more statements, UTF-8), which is + * prepared but never run: `[candidates, then sql, indexes and plan for each statement]`. Throws + * [DebugEngineException]. + */ + @JvmStatic + external fun suggestIndexes( + handle: Long, + sqlUtf8: ByteArray, + deadlineMillis: Long, + ): Array + @JvmStatic external fun close(handle: Long) } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index 9b4130b98d..0ca8247db6 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -132,6 +132,16 @@ class NativeDebugEngine : DebugEngine { ) } + override fun suggestIndexes( + sql: String, + deadlineMillis: Long, + ): IndexSuggestions { + check(handle != 0L) { "the connection is closed" } + val r = NativeBridge.suggestIndexes(handle, sql.toByteArray(Charsets.UTF_8), deadlineMillis) + val statements = (0 until (r.size - 1) / 3).map { i -> StatementSuggestion(r[1 + 3 * i] ?: "", r[2 + 3 * i], r[3 + 3 * i]) } + return IndexSuggestions(r[0], statements) + } + override fun close() { val h = handle handle = 0 diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 59551f962c..714d3247c1 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -72,6 +72,12 @@ class DatabaseTools internal constructor( /** Bound values stop being recorded this long after the last get_events call. */ const val EVENTS_IDLE_MS = 60_000L + /** export's limit on one TEXT or BLOB value: higher than query's, as a cut value is wrong data in an export. */ + const val EXPORT_VALUE_BYTES = 64 * 1024 + + /** dump's limit on one statement, a single TEXT cell; a longer one is cut and listed in truncated_statements. */ + const val DUMP_STATEMENT_BYTES = MAX_TOTAL_BYTES + /** get_events' row recording: rows per statement, bytes per TEXT or BLOB value, and bytes per row. */ const val EVENT_ROWS_PER_STATEMENT = 10 const val EVENT_VALUE_BYTES = 256 @@ -326,7 +332,11 @@ class DatabaseTools internal constructor( "get_stats", "Get statistics", "Returns page_count, page_size, freelist_count, and the row count of each table when the database has fewer than " + - "$MAX_TABLES_FOR_COUNTS tables. $NON_WAL_NOTE", + "$MAX_TABLES_FOR_COUNTS tables. Also what the sqlite3 shell's .dbinfo shows: schema_version, user_version, " + + "application_id, encoding, auto_vacuum, journal_mode, schema_objects (counts by type) and schema_size (bytes " + + "of CREATE statements), and header: the header fields no PRAGMA reads (write_format, read_format, " + + "reserved_bytes, file_change_counter, schema_format, default_cache_size, autovacuum_top_root, " + + "incremental_vacuum, software_version), when SQLite has sqlite_dbpage (else header_unavailable). $NON_WAL_NOTE", databaseSchema(), ) { call, args -> getStats(call, args) }, tool( @@ -343,6 +353,67 @@ class DatabaseTools internal constructor( "A full integrity_check of a big database that is not in WAL mode will stop early with that error.", databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), ) { call, args -> integrityCheck(call, args) }, + tool( + "suggest_indexes", + "Suggest indexes", + "Suggests indexes for one or more SQL statements, as the sqlite3 shell's .expert does (SQLite's ext/expert). " + + "The statements are prepared, never run, and no row of the app's data is read: the suggestions rest on " + + "SQLite's default estimates, not on the data, so check them with explain_query_plan. For each statement, " + + "indexes lists the CREATE INDEX statements that would help (empty when the existing ones suffice) and plan " + + "the query plan with them; candidates lists every index weighed. Nothing is created. $APP_FUNCTIONS_NOTE.", + databaseSchema("sql" to prop("string", "One or more SQL statements."), required = listOf("sql")), + ) { call, args -> suggestIndexes(call, args) }, + tool( + "lint_foreign_keys", + "Check foreign key indexes", + "Lists each foreign key and whether an index on the child table covers it, as the sqlite3 shell's " + + ".lint fkey-indexes does: without one, deleting or updating a parent row scans the child table. An " + + "uncovered key has create_index, a statement that would cover it (not run). Unlike sqlite3, a child column " + + "whose collation differs from its parent key's is not taken into account. truncated is true past the first " + + "$MAX_ROWS foreign key columns. $NON_WAL_NOTE", + databaseSchema(), + ) { call, args -> lintForeignKeys(call, args) }, + tool( + "dump", + "Dump as SQL", + "Returns a database, or one table with its indexes and triggers, as SQL text that rebuilds it, as the sqlite3 " + + "shell's .dump does: PRAGMA foreign_keys=OFF, BEGIN TRANSACTION, each table's CREATE and INSERTs, then the " + + "indexes, triggers and views, then COMMIT. A page holds at most $MAX_ROWS statements and about " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB; pass next_cursor as cursor for the next, until complete is true. " + + "A statement longer than ${DUMP_STATEMENT_BYTES / (1024 * 1024)} MiB is cut and listed in " + + "truncated_statements (indexes into sql), and the dump is then not whole. Paging re-reads the schema and " + + "the rows, so a dump of a database that changes between pages can miss or repeat rows. $NON_WAL_NOTE", + databaseSchema( + "table" to prop("string", "Only this table, with its indexes and triggers. Default: the whole database."), + "cursor" to prop("string", "The next_cursor of the previous page. Default: the start."), + ), + ) { call, args -> dump(call, args) }, + tool( + "export", + "Export a query", + "Runs one read-only SQL statement and returns its rows as CSV or SQL INSERT statements, as the sqlite3 shell's " + + ".mode csv and .mode insert do. CSV (RFC 4180, CRLF line ends): a header row on the first page unless " + + "header is false, NULL as an empty field, the empty string as \"\", a BLOB as hex. insert: one " + + "INSERT INTO table VALUES(...) per row, with literals that read back the same (X'..' for a BLOB). At most " + + "max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS) and about ${MAX_TOTAL_BYTES / (1024 * 1024)} " + + "MiB of values per page; use offset to page ($PAGING_NOTE) A TEXT or BLOB value longer than " + + "${EXPORT_VALUE_BYTES / 1024} KiB is cut, counted in truncated_cells, and the export is then not whole. " + + "$APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", + databaseSchema( + "sql" to prop("string", "The SQL statement."), + "args" to argsSchema(), + "format" to + JSONObject() + .put("type", "string") + .put("enum", JSONArray(listOf("csv", "insert"))) + .put("description", "csv or insert."), + "table" to prop("string", "insert: the table name in the statements. Default \"table\"."), + "header" to prop("boolean", "csv: a header row on the first page (offset 0). Default true."), + "offset" to prop("integer", "Rows to skip. Default 0."), + "max_rows" to prop("integer", "Rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), + required = listOf("sql", "format"), + ), + ) { call, args -> export(call, args) }, tool( "get_events", "Get SQL events", @@ -567,9 +638,59 @@ class DatabaseTools internal constructor( val count = if (tables.size >= MAX_ROWS) "at least ${tables.size}" else "${tables.size}" out.put("row_counts_skipped", "The database has $count tables; counts are given only under $MAX_TABLES_FOR_COUNTS.") } + addDbinfo(call, path, out, limits) return out } + /** + * What sqlite3's .dbinfo adds: PRAGMA values, schema object counts and size, and the header fields no PRAGMA + * reads, from page 1 through sqlite_dbpage when SQLite was built with it. Never from the file itself: closing + * any descriptor to it would drop the app's POSIX locks on it. + */ + private fun addDbinfo( + call: Call, + path: String, + out: JSONObject, + limits: QueryLimits, + ) { + fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", Bind.NONE, 0, limits).rows.firstOrNull()?.firstOrNull() + for (name in listOf("schema_version", "user_version", "application_id", "encoding", "auto_vacuum", "journal_mode")) { + out.put(name, encodeValue(pragma(name))) + } + val objects = JSONObject().put("table", 0).put("index", 0).put("trigger", 0).put("view", 0) + var schemaSize = 0L + for ( + row in runChecked( + call, + path, + "SELECT type, count(*), total(length(sql)) FROM sqlite_master GROUP BY type", + Bind.NONE, + 0, + limits, + ).rows + ) { + objects.put(row[0] as String, row[1] as Long) + schemaSize += (row[2] as Double).toLong() + } + out.put("schema_objects", objects).put("schema_size", schemaSize) + val page = + try { + runChecked(call, path, "SELECT data FROM sqlite_dbpage WHERE pgno = 1", Bind.NONE, 0, limits) + .rows + .firstOrNull() + ?.firstOrNull() + } catch (e: McpToolError) { + out.put("header_unavailable", "SQLite here has no sqlite_dbpage (${e.message}), so the header fields are left out.") + return + } + val fields = (page as? ByteArray)?.let { ShellFormat.headerFields(it) } + if (fields == null) { + out.put("header_unavailable", "Page 1 could not be read.") + return + } + out.put("header", JSONObject().also { h -> fields.forEach { (k, v) -> h.put(k, v) } }) + } + private fun integrityCheck( call: Call, args: JSONObject, @@ -591,6 +712,357 @@ class DatabaseTools internal constructor( .put("truncated_cell_indexes", truncatedCellIndexes(result)) } + private fun suggestIndexes( + call: Call, + args: JSONObject, + ): JSONObject { + val sql = stringArg(args, "sql") + val path = checkedPath(call, args) + val result = onConnection(call, path) { it.suggestIndexes(sql, call.deadline) } + + fun lines(text: String?) = JSONArray(text?.lines()?.map { it.trimEnd() }?.filter { it.isNotEmpty() } ?: emptyList()) + val statements = JSONArray() + for (st in result.statements) { + statements.put(JSONObject().put("sql", st.sql).put("indexes", lines(st.indexes)).put("plan", lines(st.plan))) + } + return JSONObject().put("statements", statements).put("candidates", lines(result.candidates)) + } + + private class ForeignKey( + val child: String, + val parent: String, + ) { + val from = mutableListOf() + val to = mutableListOf() + } + + private fun lintForeignKeys( + call: Call, + args: JSONObject, + ): JSONObject { + val path = checkedPath(call, args) + val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + val list = + runChecked( + call, + path, + "SELECT s.name, f.id, f.\"table\", f.\"from\", f.\"to\" FROM sqlite_master AS s, " + + "pragma_foreign_key_list(s.name) AS f WHERE s.type = 'table' ORDER BY s.name, f.id, f.seq", + Bind.NONE, + 0, + limits, + ) + val keys = LinkedHashMap, ForeignKey>() + for (row in list.rows) { + val key = keys.getOrPut((row[0] as String) to row[1]) { ForeignKey(row[0] as String, row[2] as String) } + key.from += row[3] as String + key.to += row[4] as String? + } + val out = JSONArray() + var uncovered = 0 + for (key in keys.values) { + // A key naming no parent columns refers to the parent's primary key, as in the shell's LEFT JOIN on pragma_table_info. + val parentColumns = + if (key.to.all { it != null }) { + key.to.map { it!! } + } else { + runChecked( + call, + path, + "SELECT name FROM pragma_table_info(?) WHERE pk > 0 ORDER BY pk", + Bind(listOf(key.parent), null), + 0, + limits, + ) + .rows + .map { it[0] as String } + } + val child = quoteIdentifier(key.child) + val plan = + runChecked( + call, + path, + "EXPLAIN QUERY PLAN SELECT 1 FROM $child WHERE " + key.from.joinToString(" AND ") { "$child.${quoteIdentifier(it)}=?" }, + Bind(List(key.from.size) { null }, null), + 0, + limits, + ).rows.firstOrNull()?.getOrNull(3) as? String ?: "" + // The shell's two patterns (lintFkeyIndexes in shell.c.in) + val covered = + ShellFormat.globMatches( + "SEARCH ${key.child} USING COVERING INDEX*(" + key.from.joinToString(" AND ") { "*=?" } + ")", + plan, + ) || + ShellFormat.globMatches("SEARCH * USING INTEGER PRIMARY KEY (rowid=?)", plan) + val item = + JSONObject() + .put("child_table", key.child) + .put("child_columns", JSONArray(key.from)) + .put("parent_table", key.parent) + .put("parent_columns", JSONArray(parentColumns)) + .put("covered", covered) + if (!covered) { + uncovered++ + item.put( + "create_index", + "CREATE INDEX ${quoteIdentifier(key.child + "_" + key.from.joinToString("_"))} ON $child(" + + key.from.joinToString(", ") { quoteIdentifier(it) } + ");", + ) + } + out.put(item) + } + return JSONObject().put("foreign_keys", out).put("uncovered", uncovered).put("truncated", list.hasMore) + } + + /** One step of a dump: statements known up front, or a table's rows as INSERTs (see [dump]). */ + private sealed class DumpUnit { + class Fixed( + val statements: List, + ) : DumpUnit() + + class Rows( + val table: String, + ) : DumpUnit() + } + + /** + * sqlite3's .dump: the plan is rebuilt from the schema on every page, and the cursor is "unit.offset", the + * statement or row to start from in that step. + */ + private fun dump( + call: Call, + args: JSONObject, + ): JSONObject { + val path = checkedPath(call, args) + val only = + when (val v = args.opt("table")) { + null, JSONObject.NULL -> null + is String -> v + else -> throw McpToolError("table must be a string.") + } + val cursor = + when (val v = args.opt("cursor")) { + null, JSONObject.NULL -> { + 0 to 0L + } + + is String -> { + val parts = v.split('.') + val unit = parts.getOrNull(0)?.toIntOrNull() + val offset = parts.getOrNull(1)?.toLongOrNull() + if (parts.size != 2 || unit == null || offset == null || unit < 0 || offset < 0) { + throw McpToolError("cursor must be a next_cursor from dump.") + } + unit to offset + } + + else -> { + throw McpToolError("cursor must be a string.") + } + } + val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + val tables = + runChecked( + call, + path, + "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND sql NOT NULL" + + (if (only != null) " AND name = ?" else "") + " ORDER BY name = 'sqlite_sequence', rowid", + if (only != null) Bind(listOf(only), null) else Bind.NONE, + 0, + QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), + ) + if (tables.hasMore) throw McpToolError("The database has more than $MAX_ROWS tables; dump them one at a time with table.") + if (only != null && tables.rows.isEmpty()) throw McpToolError("No table named \"$only\".") + val units = mutableListOf(DumpUnit.Fixed(listOf("PRAGMA foreign_keys=OFF;", "BEGIN TRANSACTION;"))) + var writableSchema = false + for (row in tables.rows) { + val name = row[0] as String + val sql = row[1] as String + when { + name == "sqlite_sequence" -> { + units += DumpUnit.Fixed(listOf("DELETE FROM sqlite_sequence;")) + units += DumpUnit.Rows(name) + } + + name == "sqlite_stat1" -> { + units += DumpUnit.Fixed(listOf("ANALYZE sqlite_schema;")) + units += DumpUnit.Rows(name) + } + + name.startsWith("sqlite_") -> {} + + sql.regionMatches(0, "CREATE VIRTUAL TABLE", 0, 20, ignoreCase = true) -> { + // As the shell does: its shadow tables are dumped as tables, so it must not be created again. + val statements = mutableListOf() + if (!writableSchema) statements += "PRAGMA writable_schema=ON;" + writableSchema = true + statements += + "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql) VALUES('table'," + + "${ShellFormat.sqlLiteral(name)},${ShellFormat.sqlLiteral(name)},0,${ShellFormat.sqlLiteral(sql)});" + units += DumpUnit.Fixed(statements) + } + + else -> { + units += DumpUnit.Fixed(listOf("$sql;")) + units += DumpUnit.Rows(name) + } + } + } + val others = + runChecked( + call, + path, + "SELECT sql FROM sqlite_master WHERE sql NOT NULL AND type IN ('index', 'trigger', 'view')" + + (if (only != null) " AND tbl_name = ?" else "") + " ORDER BY rowid", + if (only != null) Bind(listOf(only), null) else Bind.NONE, + 0, + QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), + ) + if (others.hasMore) { + throw McpToolError("The database has more than $MAX_ROWS indexes, triggers and views; dump one table at a time.") + } + val tail = others.rows.map { "${it[0]};" }.toMutableList() + if (writableSchema) tail += "PRAGMA writable_schema=OFF;" + tail += "COMMIT;" + units += DumpUnit.Fixed(tail) + + val out = JSONArray() + val cut = JSONArray() + var bytes = 0L + var unit = cursor.first + var offset = cursor.second + while (unit < units.size && out.length() < MAX_ROWS && bytes < MAX_TOTAL_BYTES) { + when (val u = units[unit]) { + is DumpUnit.Fixed -> { + while (offset < u.statements.size && out.length() < MAX_ROWS && bytes < MAX_TOTAL_BYTES) { + val st = u.statements[offset.toInt()] + out.put(st) + bytes += st.length + offset++ + } + if (offset < u.statements.size) break + } + + is DumpUnit.Rows -> { + val rows = + runChecked( + call, + path, + insertsFor(call, path, u.table, limits), + Bind.NONE, + offset, + QueryLimits(MAX_ROWS - out.length(), DUMP_STATEMENT_BYTES, MAX_BLOB_BYTES, (MAX_TOTAL_BYTES - bytes).toInt()), + ) + rows.rows.forEachIndexed { r, row -> + if (rows.isTruncated(r, 0)) cut.put(out.length()) + val st = row[0] as? String ?: "" + out.put(st) + bytes += st.length + } + offset += rows.rows.size + if (rows.hasMore) break + } + } + unit++ + offset = 0 + } + val complete = unit >= units.size + return JSONObject() + .put("sql", out) + .put("complete", complete) + .put("next_cursor", if (complete) JSONObject.NULL else "$unit.$offset") + .put("truncated_statements", cut) + } + + /** + * The SELECT that writes each row of [table] as an INSERT statement, in rowid order for a rowid table + * (so paging is stable). quote() writes literals that read back the same (a REAL that would not, with + * %!.15g, gets more digits). Generated columns are left out, with a column list, as the shell does. + */ + private fun insertsFor( + call: Call, + path: String, + table: String, + limits: QueryLimits, + ): String { + val all = runChecked(call, path, "SELECT name, hidden FROM pragma_table_xinfo(?)", Bind(listOf(table), null), 0, limits).rows + // hidden 2 and 3: a virtual and a stored generated column + val columns = all.filter { it[1] != 2L && it[1] != 3L }.map { it[0] as String } + val withoutRowid = + runChecked( + call, + path, + "SELECT wr FROM pragma_table_list WHERE schema = 'main' AND name = ?", + Bind(listOf(table), null), + 0, + limits, + ) + .rows + .firstOrNull() + ?.firstOrNull() == 1L + val target = + quoteIdentifier(table) + + if (columns.size < all.size) { + "(" + columns.joinToString(",") { quoteIdentifier(it) } + ")" + } else { + "" + } + val values = columns.joinToString(" || ',' || ") { "quote(${quoteIdentifier(it)})" } + return "SELECT ${ShellFormat.sqlLiteral("INSERT INTO $target VALUES(")} || $values || ');' FROM ${quoteIdentifier(table)}" + + if (withoutRowid) "" else " ORDER BY _rowid_" + } + + private fun export( + call: Call, + args: JSONObject, + ): JSONObject { + val sql = stringArg(args, "sql") + val format = stringArg(args, "format") + if (format != "csv" && format != "insert") throw McpToolError("format must be csv or insert.") + val table = + when (val v = args.opt("table")) { + null, JSONObject.NULL -> "table" + is String -> v + else -> throw McpToolError("table must be a string.") + } + val header = + when (val v = args.opt("header")) { + null, JSONObject.NULL -> true + is Boolean -> v + else -> throw McpToolError("header must be true or false.") + } + val offset = intArg(args, "offset", 0, 0, Long.MAX_VALUE) + val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() + val result = + run( + call, + args, + sql, + bindArgs(args), + offset, + QueryLimits(maxRows, EXPORT_VALUE_BYTES, EXPORT_VALUE_BYTES, MAX_TOTAL_BYTES), + ) + val text = StringBuilder() + if (format == "csv") { + if (header && offset == 0L) text.append(result.columns.joinToString(",") { ShellFormat.csvField(it) }).append("\r\n") + for (row in result.rows) text.append(row.joinToString(",") { ShellFormat.csvField(it) }).append("\r\n") + } else { + for (row in result.rows) { + text.append("INSERT INTO ").append(quoteIdentifier(table)).append(" VALUES(") + text.append(row.joinToString(",") { ShellFormat.sqlLiteral(it) }).append(");\n") + } + } + val out = + JSONObject() + .put("text", text.toString()) + .put("row_count", result.rows.size) + .put("offset", encodeLong(offset)) + .put("has_more", result.hasMore) + .put("truncated_cells", result.truncatedCells) + if (result.hasMore) out.put("next_offset", encodeLong(offset + result.rows.size)) + return out + } + private fun getEvents(args: JSONObject): JSONObject { val after = intArg(args, "after", 0, 0, Long.MAX_VALUE) val run = @@ -755,7 +1227,14 @@ class DatabaseTools internal constructor( bind: Bind, offset: Long, limits: QueryLimits, - ): QueryResult = + ): QueryResult = onConnection(call, path) { it.query(sql, bind.values, bind.names, offset, limits, call.deadline) } + + /** Runs [block] on the cached server connection to [path], opening it if needed, under [lock]. */ + private fun onConnection( + call: Call, + path: String, + block: (ServerConnection) -> T, + ): T = call.locked { try { val live = engine.connections() @@ -770,7 +1249,7 @@ class DatabaseTools internal constructor( if (ids.isEmpty()) throw unknownDatabase(path, knownPaths(live)) CachedConnection(engine.openServerConnection(path, writable = false), ids) }.connection - conn.query(sql, bind.values, bind.names, offset, limits, call.deadline) + block(conn) } catch (e: DebugEngineException) { val error = engineError(e) // The time limit counts the call's waits for the lock, so a quick query can run out of time diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt new file mode 100644 index 0000000000..ef94b7936c --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt @@ -0,0 +1,89 @@ +package org.appdevforall.sqlitedebugger.mcp + +/** + * Text formats of the sqlite3 shell tools (ADFA-7301): CSV and SQL INSERT for export, the glob that + * `.lint fkey-indexes` matches query plans with, and the database header `.dbinfo` reads. Pure, so + * they are tested without an engine. + */ +internal object ShellFormat { + /** + * One CSV field, RFC 4180: quoted when it holds a comma, a quote, CR or LF, with quotes doubled. + * NULL is an empty field and the empty string a quoted one ("") so the two stay apart; a BLOB is + * its hex; a REAL keeps every digit (Kotlin's shortest round-trip form). + */ + fun csvField(value: Any?): String = + when (value) { + null -> "" + is ByteArray -> DatabaseTools.hex(value) + is Double -> realText(value) + is String -> + if (value.isEmpty() || value.any { it == ',' || it == '"' || it == '\r' || it == '\n' }) { + "\"" + value.replace("\"", "\"\"") + "\"" + } else { + value + } + else -> value.toString() + } + + /** + * A value as an SQL literal that reads back the same: NULL, an integer, a REAL that round-trips + * (an infinity as 1e999, which SQLite reads as one; NaN as NULL, which is what SQLite stores for + * it), a quoted string with quotes doubled, or X'hex' for a BLOB. + */ + fun sqlLiteral(value: Any?): String = + when (value) { + null -> "NULL" + is ByteArray -> "X'" + DatabaseTools.hex(value) + "'" + is Double -> if (value.isNaN()) "NULL" else realText(value) + is String -> "'" + value.replace("'", "''") + "'" + else -> value.toString() + } + + /** A REAL that SQLite reads back as REAL with the same value: always with a point or an exponent. */ + private fun realText(value: Double): String = + when { + value == Double.POSITIVE_INFINITY -> "1e999" + value == Double.NEGATIVE_INFINITY -> "-1e999" + value.isNaN() -> "NaN" + else -> value.toString() + } + + /** sqlite3_strglob as the shell uses it: `*` any run of characters, `?` any one, everything else literal. */ + fun globMatches( + glob: String, + text: String, + ): Boolean { + val regex = StringBuilder() + for (c in glob) { + when (c) { + '*' -> regex.append(".*") + '?' -> regex.append('.') + else -> regex.append(Regex.escape(c.toString())) + } + } + return Regex(regex.toString(), RegexOption.DOT_MATCHES_ALL).matches(text) + } + + /** + * The fields of the 100-byte database header (page 1) that `.dbinfo` shows and no PRAGMA reads. + * Null when [page] is shorter than the header. + */ + fun headerFields(page: ByteArray): Map? { + if (page.size < 100) return null + + fun u8(at: Int) = (page[at].toLong() and 0xff) + + fun u32(at: Int) = (u8(at) shl 24) or (u8(at + 1) shl 16) or (u8(at + 2) shl 8) or u8(at + 3) + return linkedMapOf( + "write_format" to u8(18), + "read_format" to u8(19), + "reserved_bytes" to u8(20), + "file_change_counter" to u32(24), + "schema_format" to u32(44), + "default_cache_size" to u32(48), + "autovacuum_top_root" to u32(52), + "incremental_vacuum" to u32(64), + "software_version" to u32(96), + ) + } +} diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index a6300732b8..316cceaa89 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -16,6 +16,7 @@ #include #include "sqlite3.h" +#include "expert/sqlite3expert.h" #include "sqlitedbg.h" static int g_failures; @@ -1009,6 +1010,91 @@ static void test_server(void) { CHECK_EQ(sqlite3_close(app), SQLITE_OK); } +static int always_stop(void *unused) { + (void)unused; + return 1; +} + +static int never_stop(void *unused) { + (void)unused; + return 0; +} + +// Counts statements run on a connection whose SQL names one of expert's sampling functions. +static int sampling_trace(unsigned type, void *count, void *stmt, void *unused) { + (void)unused; + if (type == SQLITE_TRACE_STMT) { + const char *sql = sqlite3_sql((sqlite3_stmt *)stmt); + if (sql && strstr(sql, "sqlite_expert_")) ++*(int *)count; + } + return 0; +} + +// suggest_indexes: ext/expert on a read-only server connection (ADFA-7301). +static void test_expert(void) { + exec_ok(g_main, "CREATE TABLE IF NOT EXISTS orders(id INTEGER PRIMARY KEY, customer INTEGER, total REAL)"); + exec_ok(g_main, "CREATE TABLE IF NOT EXISTS lines(id INTEGER PRIMARY KEY, sku TEXT)"); + exec_ok(g_main, "CREATE INDEX IF NOT EXISTS lines_sku ON lines(sku)"); + listing l; + size_t before = list_conns(&l); + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_OK); + exec_ok(g_main, "INSERT INTO orders(customer, total) VALUES(1, 2.5), (2, 3.5)"); + uint64_t cur = cursor_now(); + // sampling would read the app's rows on srv with expert's sqlite_expert_rem and _sample functions + int sampling = 0; + CHECK_EQ(sqlite3_trace_v2(srv, SQLITE_TRACE_STMT, sampling_trace, &sampling), SQLITE_OK); + + sqlite3expert *ex = NULL; + char *err = NULL; + CHECK_EQ(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5; SELECT id FROM lines WHERE sku = 'a'", + never_stop, NULL, &ex, &err), + SQLITE_OK); + CHECK(err == NULL); + CHECK(ex != NULL); + if (ex) { + CHECK_EQ(sqlite3_expert_count(ex), 2); + const char *idx0 = sqlite3_expert_report(ex, 0, EXPERT_REPORT_INDEXES); + const char *idx1 = sqlite3_expert_report(ex, 1, EXPERT_REPORT_INDEXES); + const char *plan0 = sqlite3_expert_report(ex, 0, EXPERT_REPORT_PLAN); + CHECK(idx0 && strstr(idx0, "CREATE INDEX") && strstr(idx0, "orders(customer)")); + CHECK(idx1 == NULL); // lines_sku covers it: no suggestion (the shell prints "(no new indexes)") + CHECK(plan0 && strstr(plan0, "USING")); + CHECK(strstr(sqlite3_expert_report(ex, 0, EXPERT_REPORT_SQL), "customer = 5") != NULL); + // while it is open, its two in-memory connections are not the app's + CHECK_EQ(list_conns(&l), before); + sqlite3_expert_destroy(ex); + } + CHECK_EQ(sampling, 0); // no row of the app's data was read + sqlite3_trace_v2(srv, 0, NULL, NULL); + // nothing was traced: expert's statements ran on its own connections, never on the app's + batch b; + read_all(cur, &b); + CHECK_EQ(b.count, 0); + batch_free(&b); + // the server connection has no temp table, no new function, and is still read-only + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(srv, "SELECT count(*) FROM temp.sqlite_schema", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 0); + sqlite3_finalize(st); + CHECK(sqlite3_prepare_v2(srv, "SELECT sqlite_expert_rem(1, 1)", -1, &st, NULL) != SQLITE_OK); + CHECK_EQ(step_all(srv, "INSERT INTO orders(customer) VALUES(1)"), SQLITE_AUTH); + + // errors come back with SQLite's message; the time limit stops the analysis + CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM no_such_table", never_stop, NULL, &ex, &err) != SQLITE_OK); + CHECK(ex == NULL); + CHECK(err && strstr(err, "no_such_table")); + sqlite3_free(err); + err = NULL; + CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5", always_stop, NULL, &ex, &err) != SQLITE_OK); + CHECK(ex == NULL); + sqlite3_free(err); + + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + CHECK_EQ(list_conns(&l), before); +} + // Each of these would let a client keep a lock on the app's database (ADFA-7135 review, H3). static void test_server_holds_no_locks(void) { static const char *const denied[] = { @@ -1516,6 +1602,8 @@ int main(int argc, char **argv) { test_server_ends_transaction(); printf("# server waits for locks\n"); test_server_waits_for_locks(); + printf("# expert\n"); + test_expert(); printf("# threads\n"); test_threads(); if (argc == 4 && strcmp(argv[1], "--write-fixture") == 0) write_fixture(argv[2], argv[3]); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 727f47d991..9923936743 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -12,6 +12,9 @@ class FakeDebugEngine( ) : DebugEngine { val appConnections = mutableListOf() + /** Answers suggestIndexes: the path and the SQL. */ + var suggestAnswer: (path: String, sql: String) -> IndexSuggestions = { _, _ -> IndexSuggestions(null, emptyList()) } + override var runId = "run-1" private set @@ -160,6 +163,14 @@ class FakeDebugEngine( ) } + override fun suggestIndexes( + sql: String, + deadlineMillis: Long, + ): IndexSuggestions { + check(!closed) { "closed" } + return suggestAnswer(path, sql) + } + override fun close() { if (!closed) closedServerConnections++ closed = true diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 9a96068be4..657d9fb842 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -89,6 +89,10 @@ class DatabaseToolsTest { "explain_query_plan", "get_stats", "integrity_check", + "suggest_indexes", + "lint_foreign_keys", + "dump", + "export", "get_events", ), list.map { it.name }, @@ -98,7 +102,16 @@ class DatabaseToolsTest { @Test fun everyToolThatRunsAStatementSaysAStatementOnANonWalDatabaseStopsAfterOneAndAHalfSeconds() { val list = tools.tools().associateBy { it.name } - listOf("get_schema", "query", "explain_query_plan", "get_stats", "integrity_check").forEach { name -> + listOf( + "get_schema", + "query", + "explain_query_plan", + "get_stats", + "integrity_check", + "lint_foreign_keys", + "dump", + "export", + ).forEach { name -> val d = list.getValue(name).describe().getString("description") assertTrue("$name: $d", d.contains("not in WAL mode a statement is stopped after 1.5 s")) assertTrue("$name: $d", d.contains("WAL mode has no such limit")) @@ -423,6 +436,11 @@ class DatabaseToolsTest { deadline = deadlineMillis return c.query(sql, args, argNames, offset, limits, deadlineMillis) } + + override fun suggestIndexes( + sql: String, + deadlineMillis: Long, + ) = c.suggestIndexes(sql, deadlineMillis) } } } @@ -454,6 +472,11 @@ class DatabaseToolsTest { } return c.query(sql, args, argNames, offset, limits, deadlineMillis) } + + override fun suggestIndexes( + sql: String, + deadlineMillis: Long, + ) = c.suggestIndexes(sql, deadlineMillis) } } } @@ -538,6 +561,11 @@ class DatabaseToolsTest { now += runMs return c.query(sql, args, argNames, offset, limits, deadlineMillis) } + + override fun suggestIndexes( + sql: String, + deadlineMillis: Long, + ) = c.suggestIndexes(sql, deadlineMillis) } } } @@ -896,7 +924,7 @@ class DatabaseToolsTest { answerWith("SELECT name" to QueryResult(listOf("name"), listOf(listOf("sqlitecache")), 0, false)) val r = ok("get_stats", db()) // "_" is a wildcard in LIKE: without the escape, sqlitecache would be left out of the listing - val listing = seenSql.single { it.contains("FROM sqlite_master") } + val listing = seenSql.single { it.startsWith("SELECT name FROM sqlite_master") } assertTrue(listing, listing.contains("NOT LIKE 'sqlite\\_%' ESCAPE '\\'")) assertTrue(r.getJSONObject("row_counts").has("sqlitecache")) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt new file mode 100644 index 0000000000..3c9d9d66a9 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -0,0 +1,449 @@ +package org.appdevforall.sqlitedebugger.mcp + +import org.appdevforall.sqlitedebugger.engine.AppConnection +import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine +import org.appdevforall.sqlitedebugger.engine.IndexSuggestions +import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.appdevforall.sqlitedebugger.engine.StatementSuggestion +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The sqlite3 shell tools (ADFA-7301): suggest_indexes, lint_foreign_keys, dump, export, and get_stats' .dbinfo fields. */ +class ShellToolsTest { + private val engine = FakeDebugEngine().also { it.appConnections += AppConnection(1, "/data/a.db", false, false, 1, 5) } + private val tools = DatabaseTools(engine, null, { 1_000_000L }) + private val seen = mutableListOf>>() + + private fun call( + name: String, + args: JSONObject, + ): JSONObject { + val protocol = McpProtocol(tools.tools(), "test", { "s" }, 4) + val init = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 1) + .put("method", "initialize") + .put("params", JSONObject().put("protocolVersion", "2025-06-18")) + val session = protocol.post(init.toString(), null, null).headers[McpProtocol.SESSION_HEADER]!! + val request = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 2) + .put("method", "tools/call") + .put("params", JSONObject().put("name", name).put("arguments", args)) + return JSONObject(protocol.post(request.toString(), session, null).body!!).getJSONObject("result") + } + + private fun ok( + name: String, + args: JSONObject = JSONObject(), + ): JSONObject { + val r = call(name, args.put("database", "/data/a.db")) + assertFalse(r.toString(), r.getBoolean("isError")) + return r.getJSONObject("structuredContent") + } + + private fun error( + name: String, + args: JSONObject, + ): String { + val r = call(name, args.put("database", "/data/a.db")) + assertTrue(r.toString(), r.getBoolean("isError")) + return r.getJSONArray("content").getJSONObject(0).getString("text") + } + + private fun result( + columns: List, + vararg rows: List, + ) = QueryResult(columns, rows.toList(), 0, false) + + /** Answers by the first matching SQL prefix; anything else gets no rows. */ + private fun answer(vararg byPrefix: Pair) -> QueryResult>) { + engine.answer = { _, _, sql, args -> + seen += sql to args + byPrefix.firstOrNull { sql.startsWith(it.first) }?.second?.invoke(args) ?: QueryResult(emptyList(), emptyList(), 0, false) + } + } + + private fun JSONArray.strings() = (0 until length()).map { getString(it) } + + @Test fun suggestIndexesSplitsTheReportIntoLines() { + engine.suggestAnswer = { path, sql -> + assertEquals("/data/a.db", path) + assertEquals("SELECT * FROM t WHERE a = 1", sql) + IndexSuggestions( + "CREATE INDEX t_idx_1 ON t(a); -- stat1: 10 1\n", + listOf(StatementSuggestion(sql, "CREATE INDEX t_idx_1 ON t(a);\n", "SEARCH t USING INDEX t_idx_1 (a=?)\n")), + ) + } + val r = ok("suggest_indexes", JSONObject().put("sql", "SELECT * FROM t WHERE a = 1")) + val st = r.getJSONArray("statements").getJSONObject(0) + assertEquals("SELECT * FROM t WHERE a = 1", st.getString("sql")) + assertEquals(listOf("CREATE INDEX t_idx_1 ON t(a);"), st.getJSONArray("indexes").strings()) + assertEquals(listOf("SEARCH t USING INDEX t_idx_1 (a=?)"), st.getJSONArray("plan").strings()) + assertEquals(listOf("CREATE INDEX t_idx_1 ON t(a); -- stat1: 10 1"), r.getJSONArray("candidates").strings()) + } + + @Test fun suggestIndexesWithNothingToSuggestHasEmptyLists() { + engine.suggestAnswer = { _, sql -> IndexSuggestions(null, listOf(StatementSuggestion(sql, null, null))) } + val st = ok("suggest_indexes", JSONObject().put("sql", "SELECT 1")).getJSONArray("statements").getJSONObject(0) + assertEquals(0, st.getJSONArray("indexes").length()) + assertEquals(0, st.getJSONArray("plan").length()) + error("suggest_indexes", JSONObject()) + } + + @Test fun lintForeignKeysReportsWhichKeysAnIndexCovers() { + answer( + "SELECT s.name, f.id" to { + result( + listOf("name", "id", "table", "from", "to"), + listOf("lines", 0L, "orders", "order_id", "id"), + listOf("notes", 0L, "orders", "order_id", null), + listOf("pairs", 0L, "pk2", "a", "x"), + listOf("pairs", 0L, "pk2", "b", "y"), + listOf("pairs", 1L, "orders", "id", "id"), + ) + }, + "SELECT name FROM pragma_table_info" to { args -> + assertEquals(listOf("orders"), args) + result(listOf("name"), listOf("id")) + }, + "EXPLAIN QUERY PLAN SELECT 1 FROM \"lines\"" to { + result(listOf("id", "parent", "notused", "detail"), listOf(3L, 0L, 0L, "SCAN lines")) + }, + "EXPLAIN QUERY PLAN SELECT 1 FROM \"notes\"" to { + result( + listOf("id", "parent", "notused", "detail"), + listOf(3L, 0L, 0L, "SEARCH notes USING COVERING INDEX notes_order (order_id=?)"), + ) + }, + "EXPLAIN QUERY PLAN SELECT 1 FROM \"pairs\" WHERE \"pairs\".\"a\"=? AND" to { + result( + listOf("id", "parent", "notused", "detail"), + listOf(3L, 0L, 0L, "SEARCH pairs USING COVERING INDEX pairs_ab (a=? AND b=?)"), + ) + }, + "EXPLAIN QUERY PLAN SELECT 1 FROM \"pairs\" WHERE \"pairs\".\"id\"" to { + result(listOf("id", "parent", "notused", "detail"), listOf(3L, 0L, 0L, "SEARCH pairs USING INTEGER PRIMARY KEY (rowid=?)")) + }, + ) + val r = ok("lint_foreign_keys") + val keys = r.getJSONArray("foreign_keys") + assertEquals(4, keys.length()) + val lines = keys.getJSONObject(0) + assertFalse(lines.getBoolean("covered")) + assertEquals("CREATE INDEX \"lines_order_id\" ON \"lines\"(\"order_id\");", lines.getString("create_index")) + val notes = keys.getJSONObject(1) + assertTrue(notes.getBoolean("covered")) + assertFalse(notes.has("create_index")) + assertEquals( + "a key naming no parent column takes the parent's primary key", + listOf("id"), + notes.getJSONArray("parent_columns").strings(), + ) + val pairs = keys.getJSONObject(2) + assertEquals(listOf("a", "b"), pairs.getJSONArray("child_columns").strings()) + assertEquals(listOf("x", "y"), pairs.getJSONArray("parent_columns").strings()) + assertTrue("a two-column key is one key", pairs.getBoolean("covered")) + assertTrue("an INTEGER PRIMARY KEY covers it", keys.getJSONObject(3).getBoolean("covered")) + assertEquals(1, r.getInt("uncovered")) + val eqp = seen.single { it.first.startsWith("EXPLAIN QUERY PLAN SELECT 1 FROM \"pairs\" WHERE \"pairs\".\"a\"") } + assertEquals("EXPLAIN QUERY PLAN SELECT 1 FROM \"pairs\" WHERE \"pairs\".\"a\"=? AND \"pairs\".\"b\"=?", eqp.first) + assertEquals(listOf(null, null), eqp.second) + } + + @Test fun lintGlobFailsWhenTheIndexCoversOnlySomeColumns() { + assertTrue(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=? AND *=?)", "SEARCH t USING COVERING INDEX i (a=? AND b=?)")) + assertFalse(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=? AND *=?)", "SEARCH t USING COVERING INDEX i (a=?)")) + assertFalse(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=?)", "SCAN t")) + assertTrue("* also spans parentheses", ShellFormat.globMatches("a*b", "a(x)b")) + assertTrue("regex characters are literal", ShellFormat.globMatches("SEARCH t.x+ USING*", "SEARCH t.x+ USING y")) + assertFalse(ShellFormat.globMatches("SEARCH t.x+ USING*", "SEARCH tax USING y")) + } + + private fun dumpSchema( + tables: List>, + others: List> = emptyList(), + rows: (table: String, offset: Int) -> List = { _, _ -> emptyList() }, + xinfo: Map>> = emptyMap(), + withoutRowid: Set = emptySet(), + ) { + engine.answer = { _, _, sql, args -> + seen += sql to args + when { + sql.startsWith("SELECT name, sql FROM sqlite_master") -> { + val only = args.firstOrNull() + QueryResult(listOf("name", "sql"), tables.filter { only == null || it[0] == only }, 0, false) + } + + sql.startsWith("SELECT sql FROM sqlite_master") -> { + QueryResult(listOf("sql"), others, 0, false) + } + + sql.startsWith("SELECT name, hidden FROM pragma_table_xinfo") -> { + QueryResult(listOf("name", "hidden"), xinfo[args[0]] ?: listOf(listOf("a", 0L)), 0, false) + } + + sql.startsWith("SELECT wr FROM pragma_table_list") -> { + QueryResult(listOf("wr"), listOf(listOf(if (args[0] in withoutRowid) 1L else 0L)), 0, false) + } + + sql.startsWith("SELECT 'INSERT INTO ") -> { + val table = Regex("FROM \"([^\"]*)\"").findAll(sql).last().groupValues[1] + QueryResult(listOf("s"), rows(table, 0).map { listOf(it) }, 0, false) + } + + else -> { + QueryResult(emptyList(), emptyList(), 0, false) + } + } + } + } + + @Test fun dumpWritesTheShellsOrder() { + dumpSchema( + tables = + listOf( + listOf("t", "CREATE TABLE t(a)"), + listOf("sqlite_sequence", "CREATE TABLE sqlite_sequence(name,seq)"), + listOf("sqlite_stat4", "CREATE TABLE sqlite_stat4(tbl,idx,neq,nlt,ndlt,sample)"), + ), + others = listOf(listOf("CREATE INDEX ta ON t(a)"), listOf("CREATE VIEW v AS SELECT a FROM t")), + rows = { table, _ -> + if (table == "t") { + listOf("INSERT INTO \"t\" VALUES(1);", "INSERT INTO \"t\" VALUES('x');") + } else { + listOf("INSERT INTO \"sqlite_sequence\" VALUES('t',2);") + } + }, + ) + val r = ok("dump") + assertEquals( + listOf( + "PRAGMA foreign_keys=OFF;", + "BEGIN TRANSACTION;", + "CREATE TABLE t(a);", + "INSERT INTO \"t\" VALUES(1);", + "INSERT INTO \"t\" VALUES('x');", + "DELETE FROM sqlite_sequence;", + "INSERT INTO \"sqlite_sequence\" VALUES('t',2);", + "CREATE INDEX ta ON t(a);", + "CREATE VIEW v AS SELECT a FROM t;", + "COMMIT;", + ), + r.getJSONArray("sql").strings(), + ) + assertTrue(r.getBoolean("complete")) + assertTrue(r.isNull("next_cursor")) + assertEquals(0, r.getJSONArray("truncated_statements").length()) + val select = seen.first { it.first.startsWith("SELECT 'INSERT INTO ") }.first + assertEquals("SELECT 'INSERT INTO \"t\" VALUES(' || quote(\"a\") || ');' FROM \"t\" ORDER BY _rowid_", select) + } + + @Test fun dumpLeavesGeneratedColumnsOutAndKeepsAWithoutRowidTableUnordered() { + dumpSchema( + tables = listOf(listOf("g", "CREATE TABLE g(a, b AS (a + 1), c)")), + xinfo = mapOf("g" to listOf(listOf("a", 0L), listOf("b", 2L), listOf("c", 0L))), + withoutRowid = setOf("g"), + ) + ok("dump") + val select = seen.first { it.first.startsWith("SELECT 'INSERT INTO ") }.first + assertEquals("SELECT 'INSERT INTO \"g\"(\"a\",\"c\") VALUES(' || quote(\"a\") || ',' || quote(\"c\") || ');' FROM \"g\"", select) + } + + @Test fun dumpWritesAVirtualTableIntoTheSchemaAsTheShellDoes() { + dumpSchema( + tables = + listOf( + listOf("docs", "CREATE VIRTUAL TABLE docs USING fts5(body)"), + listOf("docs_data", "CREATE TABLE 'docs_data'(id INTEGER PRIMARY KEY, block BLOB)"), + ), + ) + val sql = ok("dump").getJSONArray("sql").strings() + assertEquals("PRAGMA writable_schema=ON;", sql[2]) + assertEquals( + "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql) " + + "VALUES('table','docs','docs',0,'CREATE VIRTUAL TABLE docs USING fts5(body)');", + sql[3], + ) + assertEquals("CREATE TABLE 'docs_data'(id INTEGER PRIMARY KEY, block BLOB);", sql[4]) + assertEquals(listOf("PRAGMA writable_schema=OFF;", "COMMIT;"), sql.takeLast(2)) + } + + @Test fun dumpOfOneTableAsksOnlyForItsObjects() { + dumpSchema(tables = listOf(listOf("t", "CREATE TABLE t(a)"), listOf("u", "CREATE TABLE u(b)"))) + val sql = ok("dump", JSONObject().put("table", "u")).getJSONArray("sql").strings() + assertEquals(listOf("PRAGMA foreign_keys=OFF;", "BEGIN TRANSACTION;", "CREATE TABLE u(b);", "COMMIT;"), sql) + assertTrue(seen.single { it.first.startsWith("SELECT sql FROM sqlite_master") }.first.contains("AND tbl_name = ?")) + assertEquals("No table named \"zz\".", error("dump", JSONObject().put("table", "zz"))) + } + + @Test fun dumpPagesAtTheStatementLimitAndResumesFromTheCursor() { + val all = (1..1500).map { "INSERT INTO \"t\" VALUES($it);" } + dumpSchema(tables = listOf(listOf("t", "CREATE TABLE t(a)"))) + engine.answer.let { base -> + engine.answer = { path, writable, sql, args -> + if (sql.startsWith("SELECT 'INSERT INTO ")) { + QueryResult(listOf("s"), all.map { listOf(it) }, 0, false) + } else { + base(path, writable, sql, args) + } + } + } + val first = ok("dump") + val firstSql = first.getJSONArray("sql").strings() + assertEquals(DatabaseTools.MAX_ROWS, firstSql.size) + assertFalse(first.getBoolean("complete")) + assertEquals("INSERT INTO \"t\" VALUES(997);", firstSql.last()) + val second = ok("dump", JSONObject().put("cursor", first.getString("next_cursor"))) + val secondSql = second.getJSONArray("sql").strings() + assertEquals("INSERT INTO \"t\" VALUES(998);", secondSql.first()) + assertEquals("COMMIT;", secondSql.last()) + assertTrue(second.getBoolean("complete")) + assertEquals(1500 + 4, firstSql.size + secondSql.size) + assertTrue(error("dump", JSONObject().put("cursor", "x")).contains("cursor")) + } + + @Test fun dumpListsACutStatement() { + dumpSchema(tables = listOf(listOf("t", "CREATE TABLE t(a)"))) + engine.answer.let { base -> + engine.answer = { path, writable, sql, args -> + if (sql.startsWith("SELECT 'INSERT INTO ")) { + QueryResult( + listOf("s"), + listOf(listOf("INSERT INTO \"t\" VALUES(1);"), listOf("INSERT INTO \"t\" VALUES('xx")), + 1, + false, + setOf(1L), + ) + } else { + base(path, writable, sql, args) + } + } + } + val r = ok("dump") + assertEquals( + listOf(4), + (0 until r.getJSONArray("truncated_statements").length()).map { r.getJSONArray("truncated_statements").getInt(it) }, + ) + } + + @Test fun exportWritesCsvAsTheShellDoes() { + answer( + "SELECT" to { + result( + listOf("id", "name,x", "b"), + listOf(1L, "a\"b", byteArrayOf(1, -1)), + listOf(2.5, "", null), + listOf(Double.POSITIVE_INFINITY, "l1\nl2", "plain"), + ) + }, + ) + val r = ok("export", JSONObject().put("sql", "SELECT").put("format", "csv")) + assertEquals("id,\"name,x\",b\r\n1,\"a\"\"b\",01ff\r\n2.5,\"\",\r\n1e999,\"l1\nl2\",plain\r\n", r.getString("text")) + assertEquals(3, r.getInt("row_count")) + val page2 = ok("export", JSONObject().put("sql", "SELECT").put("format", "csv").put("offset", 1)) + assertFalse("no header past the first page", page2.getString("text").startsWith("id,")) + val noHeader = ok("export", JSONObject().put("sql", "SELECT").put("format", "csv").put("header", false)) + assertTrue(noHeader.getString("text").startsWith("1,")) + } + + @Test fun exportWritesInsertStatementsThatReadBackTheSame() { + answer( + "SELECT" to { + result( + listOf("a", "b", "c", "d"), + listOf(1L, 2.0, "it's", byteArrayOf(0, 16)), + listOf(null, Double.NaN, "", byteArrayOf()), + ) + }, + ) + val r = ok("export", JSONObject().put("sql", "SELECT").put("format", "insert").put("table", "my \"t\"")) + assertEquals( + "INSERT INTO \"my \"\"t\"\"\" VALUES(1,2.0,'it''s',X'0010');\nINSERT INTO \"my \"\"t\"\"\" VALUES(NULL,NULL,'',X'');\n", + r.getString("text"), + ) + assertEquals( + "INSERT INTO \"table\" VALUES(1,2.0,'it''s',X'0010');", + ok("export", JSONObject().put("sql", "SELECT").put("format", "insert")).getString("text").lines().first(), + ) + assertTrue(error("export", JSONObject().put("sql", "SELECT").put("format", "json")).contains("csv or insert")) + } + + @Test fun exportUsesItsOwnValueLimitAndPassesArgs() { + var limits: Any? = null + engine.answer = { _, _, _, args -> + limits = args + result(listOf("a"), listOf(1L)) + } + ok("export", JSONObject().put("sql", "SELECT :x").put("format", "csv").put("args", JSONObject().put("x", 5))) + assertEquals(listOf(5L), limits) + assertEquals(listOf("x"), engine.lastArgNames) + } + + @Test fun sqlLiteralsAndCsvFieldsRoundTrip() { + assertEquals("0.1", ShellFormat.sqlLiteral(0.1)) + assertEquals("1.0E300", ShellFormat.sqlLiteral(1e300)) + assertEquals("-1e999", ShellFormat.sqlLiteral(Double.NEGATIVE_INFINITY)) + assertEquals("NULL", ShellFormat.sqlLiteral(Double.NaN)) + assertEquals("'a''b'", ShellFormat.sqlLiteral("a'b")) + assertEquals("X'7f'", ShellFormat.sqlLiteral(byteArrayOf(127))) + assertEquals("9223372036854775807", ShellFormat.sqlLiteral(Long.MAX_VALUE)) + assertEquals("", ShellFormat.csvField(null)) + assertEquals("\"\"", ShellFormat.csvField("")) + assertEquals("a\rb".let { "\"$it\"" }, ShellFormat.csvField("a\rb")) + } + + @Test fun getStatsAddsTheDbinfoFields() { + val page = ByteArray(4096) + page[18] = 2 + page[19] = 2 + page[20] = 12 + page[27] = 9 // file change counter 9 + page[47] = 4 // schema format 4 + page[50] = 1 // default cache size 256 + page[96] = 0 + page[97] = 0x2f.toByte() + page[98] = 0xc5.toByte() + page[99] = 0x2c // 3_130_668: 3.49.1 is 3049001, any value round-trips + answer( + "PRAGMA user_version" to { result(listOf("v"), listOf(7L)) }, + "PRAGMA encoding" to { result(listOf("e"), listOf("UTF-8")) }, + "SELECT type, count(*)" to { result(listOf("type", "n", "size"), listOf("table", 3L, 120.0), listOf("index", 1L, 30.0)) }, + "SELECT data FROM sqlite_dbpage" to { result(listOf("data"), listOf(page)) }, + ) + val r = ok("get_stats") + assertEquals(7, r.getInt("user_version")) + assertEquals("UTF-8", r.getString("encoding")) + assertEquals(3, r.getJSONObject("schema_objects").getInt("table")) + assertEquals(0, r.getJSONObject("schema_objects").getInt("view")) + assertEquals(150, r.getInt("schema_size")) + val header = r.getJSONObject("header") + assertEquals(2, header.getInt("write_format")) + assertEquals(12, header.getInt("reserved_bytes")) + assertEquals(9, header.getInt("file_change_counter")) + assertEquals(4, header.getInt("schema_format")) + assertEquals(256, header.getInt("default_cache_size")) + assertEquals(0x2fc52cL, header.getLong("software_version")) + assertFalse(r.has("header_unavailable")) + } + + @Test fun getStatsSaysWhyTheHeaderIsMissingWithoutSqliteDbpage() { + engine.answer = { _, _, sql, _ -> + if (sql.contains("sqlite_dbpage")) { + throw org.appdevforall.sqlitedebugger.engine.DebugEngineException(1, "no such table: sqlite_dbpage") + } + QueryResult(emptyList(), emptyList(), 0, false) + } + val r = ok("get_stats") + assertFalse(r.has("header")) + assertTrue(r.getString("header_unavailable"), r.getString("header_unavailable").contains("no such table: sqlite_dbpage")) + assertNull(ShellFormat.headerFields(ByteArray(99))) + } +} diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index f2cf88d016..3c0dc75b89 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -422,6 +422,59 @@ public static void main(String[] a) throws Exception { // the server connection is not listed eq(((String[]) NativeBridge.connections()[1]).length, 1, "server not listed"); + // The SQL the sqlite3 shell tools send (DatabaseTools, ADFA-7301), on this read-only server connection + eq(Helper.exec(app, "CREATE TABLE parent(id INTEGER PRIMARY KEY, code TEXT UNIQUE)"), 0, "fk parent"); + eq(Helper.exec(app, "CREATE TABLE lines(id INTEGER PRIMARY KEY, pid INTEGER REFERENCES parent, x REAL)"), 0, "fk child"); + eq(Helper.exec(app, "CREATE TABLE notes(id INTEGER PRIMARY KEY, pcode TEXT REFERENCES parent(code))"), 0, "fk child 2"); + eq(Helper.exec(app, "CREATE INDEX notes_pcode ON notes(pcode)"), 0, "fk index"); + eq(Helper.exec(app, "CREATE TABLE g(a INTEGER, b AS (a + 1), c TEXT) "), 0, "generated column"); + eq(Helper.exec(app, "CREATE TABLE w(k TEXT PRIMARY KEY, v) WITHOUT ROWID"), 0, "without rowid"); + eq(Helper.exec(app, "INSERT INTO lines VALUES(1, NULL, 0.1),(2, NULL, 1e300)"), 0, "fk rows"); + r = q(srv, "SELECT s.name, f.id, f.\"table\", f.\"from\", f.\"to\" FROM sqlite_master AS s, " + + "pragma_foreign_key_list(s.name) AS f WHERE s.type = 'table' ORDER BY s.name, f.id, f.seq"); + eq(r.rows.size(), 2, "lint: both foreign keys listed"); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("lines", 0L, "parent", "pid", null), "lint: a key naming no parent column"); + eq(Arrays.asList(r.rows.get(1)), Arrays.asList("notes", 0L, "parent", "pcode", "code"), "lint: a key naming one"); + r = query(srv, "SELECT name FROM pragma_table_info(?) WHERE pk > 0 ORDER BY pk", new Object[] {"parent"}, 0, 100, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], "id", "lint: the parent's primary key"); + r = query(srv, "EXPLAIN QUERY PLAN SELECT 1 FROM \"lines\" WHERE \"lines\".\"pid\"=?", new Object[] {null}, 0, 100, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[3], "SCAN lines", "lint: an uncovered key scans the child"); + r = query(srv, "EXPLAIN QUERY PLAN SELECT 1 FROM \"notes\" WHERE \"notes\".\"pcode\"=?", new Object[] {null}, 0, 100, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[3], "SEARCH notes USING COVERING INDEX notes_pcode (pcode=?)", "lint: a covered key, as the shell's glob expects"); + r = query(srv, "SELECT name, hidden FROM pragma_table_xinfo(?)", new Object[] {"g"}, 0, 100, 4096, 1024, MAX, FAR); + eq(r.rows.get(1)[1], 2L, "dump: a virtual generated column is hidden 2"); + r = query(srv, "SELECT wr FROM pragma_table_list WHERE schema = 'main' AND name = ?", new Object[] {"w"}, 0, 100, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 1L, "dump: pragma_table_list knows WITHOUT ROWID"); + r = q(srv, "SELECT 'INSERT INTO \"lines\" VALUES(' || quote(\"id\") || ',' || quote(\"pid\") || ',' || quote(\"x\") || ');' " + + "FROM \"lines\" ORDER BY _rowid_"); + eq(r.rows.get(0)[0], "INSERT INTO \"lines\" VALUES(1,NULL,0.1);", "dump: quote() keeps 0.1"); + eq(r.rows.get(1)[0], "INSERT INTO \"lines\" VALUES(2,NULL,1.0e+300);", "dump: and 1e300"); + r = q(srv, "SELECT 0, CAST(quote(x) AS REAL) = x FROM lines"); + eq(r.rows.get(0)[1], 1L, "dump: a quoted REAL reads back the same"); + r = q(srv, "SELECT type, count(*), total(length(sql)) FROM sqlite_master GROUP BY type"); + check(r.rows.size() >= 2, "get_stats: schema objects by type"); + eq(refusal(srv, "SELECT data FROM sqlite_dbpage WHERE pgno = 1"), "1 no such table: sqlite_dbpage", + "get_stats: this SQLite has no sqlite_dbpage, as requery's may not"); + String[] ex = NativeBridge.suggestIndexes(srv, "SELECT * FROM lines WHERE x = 1; SELECT id FROM notes WHERE pcode = 'a'" + .getBytes(StandardCharsets.UTF_8), FAR); + eq(ex.length, 7, "suggest_indexes: candidates, then sql, indexes and plan for two statements"); + check(ex[2] != null && ex[2].contains("CREATE INDEX") && ex[2].contains("lines(x)"), "suggest_indexes: an index on lines(x): " + ex[2]); + eq(ex[5], null, "suggest_indexes: notes_pcode already covers the second"); + check(ex[6] != null && ex[6].contains("notes_pcode"), "suggest_indexes: its plan uses it: " + ex[6]); + try { + NativeBridge.suggestIndexes(srv, "SELECT 1\0".getBytes(StandardCharsets.UTF_8), FAR); + check(false, "suggest_indexes: a NUL was accepted"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 1, "suggest_indexes: a NUL is refused"); + } + try { + NativeBridge.suggestIndexes(srv, "SELECT 1".getBytes(StandardCharsets.UTF_8), 1); + check(false, "suggest_indexes: ran past its deadline"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 9, "suggest_indexes: the deadline is SQLITE_INTERRUPT"); + } + eq(((String[]) NativeBridge.connections()[1]).length, 1, "suggest_indexes: expert's connections are not listed"); + NativeBridge.close(srv); // the backstop: a writable connection that opens a transaction does not keep it diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index 7e3e3dcd42..065af970cb 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -24,5 +24,7 @@ public static native Object[] query(long handle, String sql, Object[] args, byte int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; + public static native String[] suggestIndexes(long handle, byte[] sqlUtf8, long deadlineMillis) throws DebugEngineException; + public static native void close(long handle); } diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh index ce80e1702a..a3308cd206 100755 --- a/subprojects/sqlite-debugger/test.sh +++ b/subprojects/sqlite-debugger/test.sh @@ -53,7 +53,7 @@ run_with () { mkdir "$WORK/$name" build gcc -O1 -g -w -fsanitize="$sanitize" "${DEFS[@]}" -I"$AMAL" -c "$AMAL/sqlite3.c" -o "$WORK/$name/sqlite3.o" build gcc -O1 -g -Wall -Wextra -Werror -fsanitize="$sanitize" -fno-sanitize-recover=all "${DEFS[@]}" \ - -DSQLITEDBG_TEST -I"$AMAL" -I"$CPP" "$CPP/sqlitedbg.c" "$HERE/src/test/c/sqlitedbg_test.c" "$WORK/$name/sqlite3.o" \ + -DSQLITEDBG_TEST -I"$AMAL" -I"$CPP" "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_expert.c" "$HERE/src/test/c/sqlitedbg_test.c" "$WORK/$name/sqlite3.o" \ -o "$WORK/$name/test" -lpthread -ldl -lm TSAN_OPTIONS=halt_on_error=1 "$WORK/$name/test" ${3:+"${@:3}"} } @@ -87,7 +87,7 @@ run_jni () { build gcc -O1 -w -shared -fPIC -DSQLITE_THREADSAFE=2 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -I"$AMAL" \ "$AMAL/sqlite3.c" -o "$out/lib/libsqlite3x.so" -lpthread -ldl -lm build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -fvisibility=hidden -I"$AMAL" -I"$CPP" "${jinc[@]}" \ - "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_jni.c" -Wl,--version-script="$CPP/sqlitedbg.map" \ + "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_jni.c" "$CPP/sqlitedbg_expert.c" -Wl,--version-script="$CPP/sqlitedbg.map" \ -o "$out/lib/libsqlitedbg.so" -lpthread -ldl build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -I"$AMAL" "${jinc[@]}" "$jni/helper.c" \ -L"$out/lib" -lsqlite3x -Wl,-rpath,"$out/lib" -o "$out/lib/libhosthelper.so" From 2a1cf826b4d6787b89cbb074864cb9760fa82c92 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:10:57 +0000 Subject: [PATCH 02/16] ADFA-7301 suggest_indexes: opt-in sampling (sample 0 to 100) David asked for it after the default (no sampling) was explained. - sample (default 0) is expert's EXPERT_CONFIG_SAMPLE: that percentage of the rows of each table with a candidate index is read on the server connection, for estimates from the data. Expert registers two functions and a temp table there for the run and drops them after. - Sampling reads the app's rows, so on a database not in WAL mode it stops after 1.5 s like a query: the cap moved out of bridge_query into cap_non_wal, used by both; sampling's message says to lower sample. - Description, README and sqlitedbg.h updated. Tests: test.sh passes (JNI 333 checks): sampling 6,000,000 rows of a non-WAL database is stopped with the sampling message while the app commits, and sample 0 on it still suggests with no cap; sample 100 changes the suggestion on a two-row table; the C test sees the sampling queries and nothing left after. JVM tests pass (135). Revert proof: no cap on the sampling path fails "sampling was interrupted". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 3 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 10 +++-- .../src/main/cpp/sqlitedbg_expert.c | 11 ++--- .../src/main/cpp/sqlitedbg_jni.c | 39 +++++++++++------ .../sqlitedebugger/engine/DebugEngine.kt | 7 +++- .../sqlitedebugger/engine/NativeBridge.kt | 5 ++- .../engine/NativeDebugEngine.kt | 4 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 21 +++++++--- .../src/test/c/sqlitedbg_test.c | 20 +++++++-- .../sqlitedebugger/engine/FakeDebugEngine.kt | 6 +++ .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 9 ++-- .../sqlitedebugger/mcp/ShellToolsTest.kt | 11 +++++ .../src/test/jni/JniQueryTest.java | 42 +++++++++++++++++-- .../sqlitedebugger/engine/NativeBridge.java | 2 +- 14 files changed, 147 insertions(+), 43 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index f0a8b80a12..3c7e53a77e 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -52,7 +52,8 @@ What the server gives a client so it can format results as the sqlite3 shell wou Capabilities of the sqlite3 shell, in the server so every client has them. All are read-only. - **`suggest_indexes` (`.expert`).** SQLite's `ext/expert`, vendored unchanged from 3.49.1 in `src/main/cpp/expert/` (public domain, like SQLite), is compiled into `libsqlitedbg.so` through `sqlitedbg_expert.c`. That file includes it in a translation unit that reaches SQLite through the api table, like `sqlitedbg.c`. - Expert copies the schema of the server connection into two in-memory connections of its own. It opens them inside `sqlitedbg_private_open`, so the extension neither lists nor traces them, and it only prepares the client's SQL on the server connection. - - Sampling is off (`EXPERT_CONFIG_SAMPLE` 0). With sampling on, expert reads every row of every indexed table on the server connection, and adds functions and a temp table to it. So the suggestions rest on SQLite's default estimates, and the description says to check them with `explain_query_plan`. + - Sampling is off by default (`sample` 0). Then no row of the app's data is read and nothing is added to the server connection. The suggestions rest on SQLite's default estimates, which assume large tables, so on a small table they can name an index that would not help; the description says to check them with `explain_query_plan`. + - `sample` (1 to 100) is the opt-in: expert reads that percentage of the rows of each table with a candidate index, on the server connection, to build `sqlite_stat1`. For the run it registers two functions and a temp table there, and drops them after (C test). The rows are read in the app, so on a database not in WAL mode sampling stops after 1.5 s, the same limit as a query (`cap_non_wal`, JNI test), with a message to use a lower sample. - The time limit runs through a progress handler on expert's connections and a check between its steps. - Code size: about 22 KB on arm64 and 15 KB on armv7 (Thumb-2) at `-Os`, estimated with clang 18 and host headers, not the NDK. `sqlitedbg.c` is about 6 KB. - **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 59c18070e2..07791185b6 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -236,14 +236,16 @@ int sqlitedbg_end_transaction(sqlite3 *db); // Index suggestions (sqlite3's .expert): runs SQLite's ext/expert (sqlitedbg_expert.c) over sql, one // or more statements, on the server connection db. Expert copies db's schema into two in-memory // connections of its own, which the extension neither lists nor traces, and only prepares sql on db, -// never runs it. Sampling is off, so no row of the app's data is read and nothing is added to db; the -// suggestions rest on SQLite's default estimates. progress (with arg) is set on expert's connections +// never runs it. sample (0 to 100, clamped) is the percentage of rows expert reads, on db, to build +// sqlite_stat1 for its estimates; for that run it also registers two functions and a temp table on db, +// and drops them after. At 0 no row of the app's data is read and nothing is added to db; the +// suggestions then rest on SQLite's default estimates. progress (with arg) is set on expert's connections // as on db, for the time limit; the caller sets db's own. On SQLITE_OK, *out holds the results, read // with sqlite3_expert_count and sqlite3_expert_report and freed with sqlite3_expert_destroy. Otherwise // *out is NULL and *errmsg may hold a message, freed with sqlite3_free. typedef struct sqlite3expert sqlite3expert; -int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int (*progress)(void *), void *arg, sqlite3expert **out, - char **errmsg); +int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int sample, int (*progress)(void *), void *arg, + sqlite3expert **out, char **errmsg); // Set around a connection the extension opens for itself (expert's), so it is not taken for the app's. void sqlitedbg_private_open(int on); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c index 82108702e9..92d87082d6 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c @@ -8,8 +8,8 @@ SQLITE_EXTENSION_INIT3 #include "expert/sqlite3expert.c" #include "sqlitedbg.h" -int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int (*progress)(void *), void *arg, sqlite3expert **out, - char **errmsg) { +int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int sample, int (*progress)(void *), void *arg, + sqlite3expert **out, char **errmsg) { *out = NULL; *errmsg = NULL; // expert opens two in-memory connections; the extension must not list or trace them as the app's @@ -19,9 +19,10 @@ int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int (*progress)(void *), if (!p) return SQLITE_ERROR; sqlite3_progress_handler(p->dbv, 1000, progress, arg); sqlite3_progress_handler(p->dbm, 1000, progress, arg); - // No sqlite_stat1 from the app's data: sampling reads every row of every indexed table on db, and - // registers functions and a temp table on it. Suggestions then rest on SQLite's default estimates. - int rc = sqlite3_expert_config(p, EXPERT_CONFIG_SAMPLE, 0); + // Sampling reads that percentage of the rows of every table with a candidate index, on db, and registers + // two functions and a temp table on db for the run (expert drops them after). At 0 nothing of the app's + // data is read, and suggestions rest on SQLite's default estimates. + int rc = sqlite3_expert_config(p, EXPERT_CONFIG_SAMPLE, sample < 0 ? 0 : sample > 100 ? 100 : sample); // The handler runs every 1000 VM steps, which a small schema may never reach: check between steps too. if (rc == SQLITE_OK) rc = progress(arg) ? SQLITE_INTERRUPT : sqlite3_expert_sql(p, sql, errmsg); if (rc == SQLITE_OK) rc = progress(arg) ? SQLITE_INTERRUPT : sqlite3_expert_analyze(p, errmsg); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 49d9170b18..6aa26d284a 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -221,6 +221,18 @@ static int is_wal_mode(sqlite3 *db) { return wal; } +// Brings d forward to SQLITEDBG_SERVER_NON_WAL_MS from now on a database that is not in WAL mode, and +// marks it capped. Counted from after the mode check, which can wait on the app's lock. +static void cap_non_wal(sqlite3 *db, deadline *d) { + if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < d->at_ms && !is_wal_mode(db)) { + int64_t cap_at = now_ms() + SQLITEDBG_SERVER_NON_WAL_MS; + if (cap_at < d->at_ms) { + d->at_ms = cap_at; + d->capped = 1; + } + } +} + static int progress_cb(void *p) { deadline *d = (deadline *)p; if (now_ms() < d->at_ms) return 0; @@ -492,14 +504,7 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring // Every server tool runs its statements here, so this is the one place that bounds a read on a database // that is not in WAL mode: it holds a SHARED lock until the statement ends, and the app's commit gives // up after requery's 2500 ms busy timeout (see SQLITEDBG_SERVER_NON_WAL_MS). The mode is read per call. - if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < dl.at_ms && !is_wal_mode(db)) { - // counted from here, after the mode check, which can wait on the app's lock - int64_t cap_at = now_ms() + SQLITEDBG_SERVER_NON_WAL_MS; - if (cap_at < dl.at_ms) { - dl.at_ms = cap_at; - dl.capped = 1; - } - } + cap_non_wal(db, &dl); // SQLite checks the handler every 1000 virtual machine steps and stops the statement when it // returns non-zero; it is cleared before this returns, so it never outlives `dl`. @@ -628,7 +633,8 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring } // Index suggestions: [candidates, then sql, indexes and plan for each statement] (sqlite3_expert_report). -static jobjectArray bridge_suggest_indexes(JNIEnv *env, jclass cls, jlong handle, jbyteArray sql_utf8, jlong deadline_ms) { +static jobjectArray bridge_suggest_indexes(JNIEnv *env, jclass cls, jlong handle, jbyteArray sql_utf8, jint sample, + jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; deadline dl = {(int64_t)deadline_ms, 0, 0}; @@ -653,12 +659,21 @@ static jobjectArray bridge_suggest_indexes(JNIEnv *env, jclass cls, jlong handle throw_engine(env, SQLITE_ERROR, "the SQL holds a NUL character, and SQLite reads no further than it"); return NULL; } + // Sampling reads the app's rows on db, holding its SHARED lock on a database not in WAL mode: the same cap as a query. + if (sample > 0) cap_non_wal(db, &dl); sqlite3_progress_handler(db, 1000, progress_cb, &dl); - int rc = sqlitedbg_expert_run(db, text, progress_cb, &dl, &ex, &err); + int rc = sqlitedbg_expert_run(db, text, sample, progress_cb, &dl, &ex, &err); sqlite3_progress_handler(db, 0, NULL, NULL); free(text); if (rc != SQLITE_OK) { - if (dl.hit) throw_engine(env, SQLITE_INTERRUPT, "the analysis ran past its time limit"); + if (dl.hit && dl.capped) { + char msg[256]; + snprintf(msg, sizeof msg, + "sampling was stopped after %.1f s: this database is not in WAL mode, so a longer read would block " + "the app's own writes. Use a lower sample, or 0; a database in WAL mode has no such limit", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl.hit) throw_engine(env, SQLITE_INTERRUPT, "the analysis ran past its time limit"); else throw_engine(env, rc, err ? err : sqlite3_errstr(rc)); sqlite3_free(err); return NULL; @@ -723,7 +738,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"openServer", "([BZ)J", (void *)bridge_open_server}, {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, - {"suggestIndexes", "(J[BJ)[Ljava/lang/String;", (void *)bridge_suggest_indexes}, + {"suggestIndexes", "(J[BIJ)[Ljava/lang/String;", (void *)bridge_suggest_indexes}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 2d225e1bad..bb6d390cd8 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -84,13 +84,16 @@ interface ServerConnection : Closeable { /** * Index suggestions for [sql] (one or more statements) from SQLite's ext/expert (`sqlitedbg_expert_run`): - * the statements are prepared, never run, and no row of the app's data is read, so the suggestions - * rest on SQLite's default estimates. Stops at [deadlineMillis] like [query]. + * the statements are prepared, never run. [sample] (0 to 100) is the percentage of rows read for the + * estimates; at 0 no row of the app's data is read and the suggestions rest on SQLite's default + * estimates. Stops at [deadlineMillis] like [query], and, when sampling a database not in WAL mode, + * after `SQLITEDBG_SERVER_NON_WAL_MS`. * * @throws DebugEngineException for SQLite errors (SQL that does not prepare, for one) or the deadline. */ fun suggestIndexes( sql: String, + sample: Int, deadlineMillis: Long, ): IndexSuggestions } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 5db17cc916..974b77c09e 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -64,13 +64,14 @@ internal object NativeBridge { /** * Index suggestions from SQLite's ext/expert for [sqlUtf8] (one or more statements, UTF-8), which is - * prepared but never run: `[candidates, then sql, indexes and plan for each statement]`. Throws - * [DebugEngineException]. + * prepared but never run, reading [sample] percent of the rows for its estimates: + * `[candidates, then sql, indexes and plan for each statement]`. Throws [DebugEngineException]. */ @JvmStatic external fun suggestIndexes( handle: Long, sqlUtf8: ByteArray, + sample: Int, deadlineMillis: Long, ): Array diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index 0ca8247db6..308f7b7ef3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -134,10 +134,12 @@ class NativeDebugEngine : DebugEngine { override fun suggestIndexes( sql: String, + sample: Int, deadlineMillis: Long, ): IndexSuggestions { check(handle != 0L) { "the connection is closed" } - val r = NativeBridge.suggestIndexes(handle, sql.toByteArray(Charsets.UTF_8), deadlineMillis) + require(sample in 0..100) { "sample $sample outside 0..100" } + val r = NativeBridge.suggestIndexes(handle, sql.toByteArray(Charsets.UTF_8), sample, deadlineMillis) val statements = (0 until (r.size - 1) / 3).map { i -> StatementSuggestion(r[1 + 3 * i] ?: "", r[2 + 3 * i], r[3 + 3 * i]) } return IndexSuggestions(r[0], statements) } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 714d3247c1..11ec7ae458 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -357,11 +357,19 @@ class DatabaseTools internal constructor( "suggest_indexes", "Suggest indexes", "Suggests indexes for one or more SQL statements, as the sqlite3 shell's .expert does (SQLite's ext/expert). " + - "The statements are prepared, never run, and no row of the app's data is read: the suggestions rest on " + - "SQLite's default estimates, not on the data, so check them with explain_query_plan. For each statement, " + - "indexes lists the CREATE INDEX statements that would help (empty when the existing ones suffice) and plan " + - "the query plan with them; candidates lists every index weighed. Nothing is created. $APP_FUNCTIONS_NOTE.", - databaseSchema("sql" to prop("string", "One or more SQL statements."), required = listOf("sql")), + "The statements are prepared, never run. By default (sample 0) no row of the app's data is read: the " + + "suggestions rest on SQLite's default estimates, which assume large tables, so on a small table they can " + + "name an index that would not help; check them with explain_query_plan. sample (1 to 100) reads that " + + "percentage of the rows of each table with a candidate index first, for estimates from the data: it costs " + + "a scan of those tables in the app, and on a database that is not in WAL mode it stops after 1.5 s (use " + + "a lower sample, or 0). For each statement, indexes lists the CREATE INDEX statements that would help " + + "(empty when the existing ones suffice) and plan the query plan with them; candidates lists every index " + + "weighed. Nothing is created. $APP_FUNCTIONS_NOTE.", + databaseSchema( + "sql" to prop("string", "One or more SQL statements."), + "sample" to prop("integer", "Percentage of rows to read for the estimates, 0 to 100. Default 0: none."), + required = listOf("sql"), + ), ) { call, args -> suggestIndexes(call, args) }, tool( "lint_foreign_keys", @@ -717,8 +725,9 @@ class DatabaseTools internal constructor( args: JSONObject, ): JSONObject { val sql = stringArg(args, "sql") + val sample = intArg(args, "sample", 0, 0, 100).toInt() val path = checkedPath(call, args) - val result = onConnection(call, path) { it.suggestIndexes(sql, call.deadline) } + val result = onConnection(call, path) { it.suggestIndexes(sql, sample, call.deadline) } fun lines(text: String?) = JSONArray(text?.lines()?.map { it.trimEnd() }?.filter { it.isNotEmpty() } ?: emptyList()) val statements = JSONArray() diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 316cceaa89..e6de628793 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -1047,7 +1047,7 @@ static void test_expert(void) { sqlite3expert *ex = NULL; char *err = NULL; - CHECK_EQ(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5; SELECT id FROM lines WHERE sku = 'a'", + CHECK_EQ(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5; SELECT id FROM lines WHERE sku = 'a'", 0, never_stop, NULL, &ex, &err), SQLITE_OK); CHECK(err == NULL); @@ -1082,15 +1082,29 @@ static void test_expert(void) { CHECK_EQ(step_all(srv, "INSERT INTO orders(customer) VALUES(1)"), SQLITE_AUTH); // errors come back with SQLite's message; the time limit stops the analysis - CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM no_such_table", never_stop, NULL, &ex, &err) != SQLITE_OK); + CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM no_such_table", 0, never_stop, NULL, &ex, &err) != SQLITE_OK); CHECK(ex == NULL); CHECK(err && strstr(err, "no_such_table")); sqlite3_free(err); err = NULL; - CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5", always_stop, NULL, &ex, &err) != SQLITE_OK); + CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5", 0, always_stop, NULL, &ex, &err) != SQLITE_OK); CHECK(ex == NULL); sqlite3_free(err); + // sample > 0 reads the rows on srv (the opt-in), and still leaves nothing behind on it + sampling = 0; + CHECK_EQ(sqlite3_trace_v2(srv, SQLITE_TRACE_STMT, sampling_trace, &sampling), SQLITE_OK); + CHECK_EQ(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5", 100, never_stop, NULL, &ex, &err), SQLITE_OK); + CHECK(sampling > 0); + sqlite3_trace_v2(srv, 0, NULL, NULL); + sqlite3_expert_destroy(ex); + CHECK_EQ(sqlite3_prepare_v2(srv, "SELECT count(*) FROM temp.sqlite_schema", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 0); + sqlite3_finalize(st); + CHECK(sqlite3_prepare_v2(srv, "SELECT sqlite_expert_rem(1, 1)", -1, &st, NULL) != SQLITE_OK); + CHECK_EQ(list_conns(&l), before); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); CHECK_EQ(list_conns(&l), before); } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 9923936743..472198a2e8 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -15,6 +15,10 @@ class FakeDebugEngine( /** Answers suggestIndexes: the path and the SQL. */ var suggestAnswer: (path: String, sql: String) -> IndexSuggestions = { _, _ -> IndexSuggestions(null, emptyList()) } + /** The sample of the last suggestIndexes. */ + var lastSample: Int? = null + private set + override var runId = "run-1" private set @@ -165,9 +169,11 @@ class FakeDebugEngine( override fun suggestIndexes( sql: String, + sample: Int, deadlineMillis: Long, ): IndexSuggestions { check(!closed) { "closed" } + lastSample = sample return suggestAnswer(path, sql) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 657d9fb842..667fab30d3 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -439,8 +439,9 @@ class DatabaseToolsTest { override fun suggestIndexes( sql: String, + sample: Int, deadlineMillis: Long, - ) = c.suggestIndexes(sql, deadlineMillis) + ) = c.suggestIndexes(sql, sample, deadlineMillis) } } } @@ -475,8 +476,9 @@ class DatabaseToolsTest { override fun suggestIndexes( sql: String, + sample: Int, deadlineMillis: Long, - ) = c.suggestIndexes(sql, deadlineMillis) + ) = c.suggestIndexes(sql, sample, deadlineMillis) } } } @@ -564,8 +566,9 @@ class DatabaseToolsTest { override fun suggestIndexes( sql: String, + sample: Int, deadlineMillis: Long, - ) = c.suggestIndexes(sql, deadlineMillis) + ) = c.suggestIndexes(sql, sample, deadlineMillis) } } } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index 3c9d9d66a9..6c55bc2c2f 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -90,6 +90,17 @@ class ShellToolsTest { assertEquals(listOf("CREATE INDEX t_idx_1 ON t(a); -- stat1: 10 1"), r.getJSONArray("candidates").strings()) } + @Test fun suggestIndexesSamplesOnlyWhenAsked() { + ok("suggest_indexes", JSONObject().put("sql", "SELECT 1")) + assertEquals(0, engine.lastSample) + ok("suggest_indexes", JSONObject().put("sql", "SELECT 1").put("sample", 25)) + assertEquals(25, engine.lastSample) + assertTrue(error("suggest_indexes", JSONObject().put("sql", "SELECT 1").put("sample", 101)).contains("between 0 and 100")) + assertTrue(error("suggest_indexes", JSONObject().put("sql", "SELECT 1").put("sample", -1)).contains("between 0 and 100")) + val description = tools.tools().single { it.name == "suggest_indexes" }.description + for (text in listOf("sample 0", "1.5 s", "explain_query_plan")) assertTrue(text, description.contains(text)) + } + @Test fun suggestIndexesWithNothingToSuggestHasEmptyLists() { engine.suggestAnswer = { _, sql -> IndexSuggestions(null, listOf(StatementSuggestion(sql, null, null))) } val st = ok("suggest_indexes", JSONObject().put("sql", "SELECT 1")).getJSONArray("statements").getJSONObject(0) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 3c0dc75b89..d579b02bce 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -181,6 +181,39 @@ static void nonWalCap(Path dir, String delPath) throws Exception { eq(shorter.code, 9, "a 400 ms deadline: SQLITE_INTERRUPT"); check(shorter.message != null && shorter.message.contains("time limit") && !shorter.message.contains("WAL"), "the call's own deadline is reported as such: " + shorter.message); + // suggest_indexes with sampling reads the app's rows: the same cap, with a message about sampling. Without + // sampling it reads no rows and has no cap. + eq(Helper.exec(app, "CREATE TABLE big(a INTEGER, b INTEGER)"), 0, "a big table"); + eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 6000000) " + + "INSERT INTO big SELECT x % 1000, x % 977 FROM c"), 0, "6,000,000 rows: sampling 3,000,000 took 1.3 s on a computer"); + Ran sampled = new Ran(); + Thread sampler = new Thread(() -> { + long t = System.currentTimeMillis(); + try { + NativeBridge.suggestIndexes(srv, "SELECT * FROM big WHERE a = 1 AND b = 2".getBytes(StandardCharsets.UTF_8), 100, + System.currentTimeMillis() + 8000); + } catch (DebugEngineException e) { + sampled.code = e.sqliteCode; + sampled.message = e.getMessage(); + } + sampled.ms = System.currentTimeMillis() - t; + }); + sampler.start(); + Thread.sleep(300); + t0 = System.currentTimeMillis(); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(5002)"), 0, "the app commits while suggest_indexes samples"); + commitMs = System.currentTimeMillis() - t0; + sampler.join(); + check(commitMs < 2500, "the commit waited " + commitMs + " ms, under the busy timeout"); + eq(sampled.code, 9, "sampling was interrupted: SQLITE_INTERRUPT"); + check(sampled.message != null && sampled.message.contains("not in WAL mode") && sampled.message.contains("lower sample"), + "the message says why and what to do: " + sampled.message); + check(sampled.ms < 2500, "sampling stopped after " + sampled.ms + " ms"); + String[] unsampled = NativeBridge.suggestIndexes(srv, "SELECT * FROM big WHERE a = 1 AND b = 2".getBytes(StandardCharsets.UTF_8), 0, + System.currentTimeMillis() + 8000); + check(unsampled[2] != null && unsampled[2].contains("big("), "without sampling: a suggestion, no cap: " + unsampled[2]); + Helper.exec(app, "DELETE FROM t WHERE id = 5002"); + Helper.exec(app, "DROP TABLE big"); NativeBridge.close(srv); Helper.close(app); @@ -456,24 +489,27 @@ public static void main(String[] a) throws Exception { eq(refusal(srv, "SELECT data FROM sqlite_dbpage WHERE pgno = 1"), "1 no such table: sqlite_dbpage", "get_stats: this SQLite has no sqlite_dbpage, as requery's may not"); String[] ex = NativeBridge.suggestIndexes(srv, "SELECT * FROM lines WHERE x = 1; SELECT id FROM notes WHERE pcode = 'a'" - .getBytes(StandardCharsets.UTF_8), FAR); + .getBytes(StandardCharsets.UTF_8), 0, FAR); eq(ex.length, 7, "suggest_indexes: candidates, then sql, indexes and plan for two statements"); check(ex[2] != null && ex[2].contains("CREATE INDEX") && ex[2].contains("lines(x)"), "suggest_indexes: an index on lines(x): " + ex[2]); eq(ex[5], null, "suggest_indexes: notes_pcode already covers the second"); check(ex[6] != null && ex[6].contains("notes_pcode"), "suggest_indexes: its plan uses it: " + ex[6]); try { - NativeBridge.suggestIndexes(srv, "SELECT 1\0".getBytes(StandardCharsets.UTF_8), FAR); + NativeBridge.suggestIndexes(srv, "SELECT 1\0".getBytes(StandardCharsets.UTF_8), 0, FAR); check(false, "suggest_indexes: a NUL was accepted"); } catch (DebugEngineException e) { eq(e.sqliteCode, 1, "suggest_indexes: a NUL is refused"); } try { - NativeBridge.suggestIndexes(srv, "SELECT 1".getBytes(StandardCharsets.UTF_8), 1); + NativeBridge.suggestIndexes(srv, "SELECT 1".getBytes(StandardCharsets.UTF_8), 0, 1); check(false, "suggest_indexes: ran past its deadline"); } catch (DebugEngineException e) { eq(e.sqliteCode, 9, "suggest_indexes: the deadline is SQLITE_INTERRUPT"); } eq(((String[]) NativeBridge.connections()[1]).length, 1, "suggest_indexes: expert's connections are not listed"); + // sample 100: the statistics show a scan of two rows is cheap, so no index is suggested for lines(x) + ex = NativeBridge.suggestIndexes(srv, "SELECT * FROM lines WHERE x = 1".getBytes(StandardCharsets.UTF_8), 100, FAR); + eq(ex[2], null, "suggest_indexes: sampling changes the estimate"); NativeBridge.close(srv); diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index 065af970cb..6a777de798 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -24,7 +24,7 @@ public static native Object[] query(long handle, String sql, Object[] args, byte int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; - public static native String[] suggestIndexes(long handle, byte[] sqlUtf8, long deadlineMillis) throws DebugEngineException; + public static native String[] suggestIndexes(long handle, byte[] sqlUtf8, int sample, long deadlineMillis) throws DebugEngineException; public static native void close(long handle); } From 60df121424b5a7fb469ee98005f1e4c9da672e1f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 23:44:57 -0800 Subject: [PATCH 03/16] ADFA-7301 style: spotless reformat, no functional change spotlessKotlinCheck failed on DatabaseTools.kt, ShellFormat.kt and ShellToolsTest.kt; this is spotlessApply's output and nothing else. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 29 ++++++++++--------- .../sqlitedebugger/mcp/ShellFormat.kt | 23 +++++++++++---- .../sqlitedebugger/mcp/ShellToolsTest.kt | 3 +- 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 1e73da7159..eac2da1854 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -665,17 +665,22 @@ class DatabaseTools internal constructor( for (name in listOf("schema_version", "user_version", "application_id", "encoding", "auto_vacuum", "journal_mode")) { out.put(name, encodeValue(pragma(name))) } - val objects = JSONObject().put("table", 0).put("index", 0).put("trigger", 0).put("view", 0) + val objects = + JSONObject() + .put("table", 0) + .put("index", 0) + .put("trigger", 0) + .put("view", 0) var schemaSize = 0L for ( - row in runChecked( - call, - path, - "SELECT type, count(*), total(length(sql)) FROM sqlite_master GROUP BY type", - Bind.NONE, - 0, - limits, - ).rows + row in runChecked( + call, + path, + "SELECT type, count(*), total(length(sql)) FROM sqlite_master GROUP BY type", + Bind.NONE, + 0, + limits, + ).rows ) { objects.put(row[0] as String, row[1] as Long) schemaSize += (row[2] as Double).toLong() @@ -782,8 +787,7 @@ class DatabaseTools internal constructor( Bind(listOf(key.parent), null), 0, limits, - ) - .rows + ).rows .map { it[0] as String } } val child = quoteIdentifier(key.child) @@ -1005,8 +1009,7 @@ class DatabaseTools internal constructor( Bind(listOf(table), null), 0, limits, - ) - .rows + ).rows .firstOrNull() ?.firstOrNull() == 1L val target = diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt index ef94b7936c..970f5c6fb5 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/ShellFormat.kt @@ -13,16 +13,29 @@ internal object ShellFormat { */ fun csvField(value: Any?): String = when (value) { - null -> "" - is ByteArray -> DatabaseTools.hex(value) - is Double -> realText(value) - is String -> + null -> { + "" + } + + is ByteArray -> { + DatabaseTools.hex(value) + } + + is Double -> { + realText(value) + } + + is String -> { if (value.isEmpty() || value.any { it == ',' || it == '"' || it == '\r' || it == '\n' }) { "\"" + value.replace("\"", "\"\"") + "\"" } else { value } - else -> value.toString() + } + + else -> { + value.toString() + } } /** diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index 6c55bc2c2f..a4654856c3 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -448,7 +448,8 @@ class ShellToolsTest { @Test fun getStatsSaysWhyTheHeaderIsMissingWithoutSqliteDbpage() { engine.answer = { _, _, sql, _ -> if (sql.contains("sqlite_dbpage")) { - throw org.appdevforall.sqlitedebugger.engine.DebugEngineException(1, "no such table: sqlite_dbpage") + throw org.appdevforall.sqlitedebugger.engine + .DebugEngineException(1, "no such table: sqlite_dbpage") } QueryResult(emptyList(), emptyList(), 0, false) } From 1ee43e0801cd1956a712fef1ac3a96ea3ab43732 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 23:44:58 -0800 Subject: [PATCH 04/16] ADFA-7301 docs: say where expert's sampling functions and temp table live The texts said sampling registers two functions and a temp table on the server connection. In the vendored code the temp table is made on expert's own connection (idxBuildSampleTable on p->dbv); sqlite_expert_sample goes on db, and sqlite_expert_rem only at sample 100 (below that it is on p->dbv). Comments and docs only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h | 5 +++-- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c | 3 ++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 3c7e53a77e..ba9c1fc38f 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -53,7 +53,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - **`suggest_indexes` (`.expert`).** SQLite's `ext/expert`, vendored unchanged from 3.49.1 in `src/main/cpp/expert/` (public domain, like SQLite), is compiled into `libsqlitedbg.so` through `sqlitedbg_expert.c`. That file includes it in a translation unit that reaches SQLite through the api table, like `sqlitedbg.c`. - Expert copies the schema of the server connection into two in-memory connections of its own. It opens them inside `sqlitedbg_private_open`, so the extension neither lists nor traces them, and it only prepares the client's SQL on the server connection. - Sampling is off by default (`sample` 0). Then no row of the app's data is read and nothing is added to the server connection. The suggestions rest on SQLite's default estimates, which assume large tables, so on a small table they can name an index that would not help; the description says to check them with `explain_query_plan`. - - `sample` (1 to 100) is the opt-in: expert reads that percentage of the rows of each table with a candidate index, on the server connection, to build `sqlite_stat1`. For the run it registers two functions and a temp table there, and drops them after (C test). The rows are read in the app, so on a database not in WAL mode sampling stops after 1.5 s, the same limit as a query (`cap_non_wal`, JNI test), with a message to use a lower sample. + - `sample` (1 to 100) is the opt-in: expert reads that percentage of the rows of each table with a candidate index, on the server connection, to build `sqlite_stat1`. For the run it registers one function there (`sqlite_expert_sample`; at 100 also `sqlite_expert_rem`, which below 100 goes on expert's own in-memory connection with the temp table of sampled rows) and removes them after (C test, at 50 and 100). The rows are read in the app, so on a database not in WAL mode sampling stops after 1.5 s, the same limit as a query (`cap_non_wal`, JNI test), with a message to use a lower sample. - The time limit runs through a progress handler on expert's connections and a check between its steps. - Code size: about 22 KB on arm64 and 15 KB on armv7 (Thumb-2) at `-Os`, estimated with clang 18 and host headers, not the NDK. `sqlitedbg.c` is about 6 KB. - **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 07791185b6..77b7fc71b0 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -237,8 +237,9 @@ int sqlitedbg_end_transaction(sqlite3 *db); // or more statements, on the server connection db. Expert copies db's schema into two in-memory // connections of its own, which the extension neither lists nor traces, and only prepares sql on db, // never runs it. sample (0 to 100, clamped) is the percentage of rows expert reads, on db, to build -// sqlite_stat1 for its estimates; for that run it also registers two functions and a temp table on db, -// and drops them after. At 0 no row of the app's data is read and nothing is added to db; the +// sqlite_stat1 for its estimates; for that run it also registers sqlite_expert_sample on db, and at 100 also +// sqlite_expert_rem (below 100 that one, and the temp table of the sampled rows, are on expert's own +// connection), and removes them from db after. At 0 no row of the app's data is read and nothing is added to db; the // suggestions then rest on SQLite's default estimates. progress (with arg) is set on expert's connections // as on db, for the time limit; the caller sets db's own. On SQLITE_OK, *out holds the results, read // with sqlite3_expert_count and sqlite3_expert_report and freed with sqlite3_expert_destroy. Otherwise diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c index 92d87082d6..57a55bbac6 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_expert.c @@ -20,7 +20,8 @@ int sqlitedbg_expert_run(sqlite3 *db, const char *sql, int sample, int (*progres sqlite3_progress_handler(p->dbv, 1000, progress, arg); sqlite3_progress_handler(p->dbm, 1000, progress, arg); // Sampling reads that percentage of the rows of every table with a candidate index, on db, and registers - // two functions and a temp table on db for the run (expert drops them after). At 0 nothing of the app's + // sqlite_expert_sample on db for the run, and at 100 sqlite_expert_rem too (expert removes them after); the + // temp table is made on expert's own connection p->dbv. At 0 nothing of the app's // data is read, and suggestions rest on SQLite's default estimates. int rc = sqlite3_expert_config(p, EXPERT_CONFIG_SAMPLE, sample < 0 ? 0 : sample > 100 ? 100 : sample); // The handler runs every 1000 VM steps, which a small schema may never reach: check between steps too. From 15e406a3d620660f867ff95973709ff09a9f6386 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 23:44:58 -0800 Subject: [PATCH 05/16] ADFA-7301 test: expert sampling at 50 leaves nothing on the server connection Only 0 and 100 were tested. At 50 on a 5000-row table: suggestions come back, the sampling reads run on the server connection, and afterwards neither sqlite_expert_rem nor sqlite_expert_sample exists there, temp is empty, reads work and writes are still refused. The 1.5 s non-WAL cap is not exercised at 50: it sits in cap_non_wal, independent of the sample value, and the JNI test already reaches it at 100 with 6,000,000 rows; reaching it at 50 would cost the same seconds again for no new path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../src/test/c/sqlitedbg_test.c | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index e6de628793..5d278e33c1 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -1105,6 +1105,40 @@ static void test_expert(void) { CHECK(sqlite3_prepare_v2(srv, "SELECT sqlite_expert_rem(1, 1)", -1, &st, NULL) != SQLITE_OK); CHECK_EQ(list_conns(&l), before); + // sample 50 on a table big enough for the sample to matter: suggestions come back, the sampling reads run on srv, and + // afterwards srv has neither expert's two functions nor anything in temp, and still reads and refuses writes + exec_ok(g_main, "CREATE TABLE samp(id INTEGER PRIMARY KEY, a INTEGER, b INTEGER)"); + exec_ok(g_main, + "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000) " + "INSERT INTO samp SELECT x, x % 500, x % 7 FROM c"); + sampling = 0; + CHECK_EQ(sqlite3_trace_v2(srv, SQLITE_TRACE_STMT, sampling_trace, &sampling), SQLITE_OK); + CHECK_EQ(sqlitedbg_expert_run(srv, "SELECT * FROM samp WHERE a = 7 AND b = 3", 50, never_stop, NULL, &ex, &err), SQLITE_OK); + CHECK(sampling > 0); + sqlite3_trace_v2(srv, 0, NULL, NULL); + CHECK(ex != NULL); + if (ex) { + CHECK_EQ(sqlite3_expert_count(ex), 1); + const char *idx = sqlite3_expert_report(ex, 0, EXPERT_REPORT_INDEXES); + CHECK(idx && strstr(idx, "CREATE INDEX") && strstr(idx, "samp(")); + CHECK(sqlite3_expert_report(ex, 0, EXPERT_REPORT_PLAN) != NULL); + sqlite3_expert_destroy(ex); + } + CHECK_EQ(sqlite3_prepare_v2(srv, "SELECT count(*) FROM temp.sqlite_schema", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 0); + sqlite3_finalize(st); + CHECK_EQ(sqlite3_prepare_v2(srv, "SELECT count(*) FROM temp.sqlite_master", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 0); + sqlite3_finalize(st); + CHECK(sqlite3_prepare_v2(srv, "SELECT sqlite_expert_rem(1, 1)", -1, &st, NULL) != SQLITE_OK); + CHECK(sqlite3_prepare_v2(srv, "SELECT sqlite_expert_sample(1)", -1, &st, NULL) != SQLITE_OK); + CHECK_EQ(step_all(srv, "SELECT count(*) FROM samp"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "INSERT INTO samp(a) VALUES(1)"), SQLITE_AUTH); + CHECK_EQ(list_conns(&l), before); + exec_ok(g_main, "DROP TABLE samp"); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); CHECK_EQ(list_conns(&l), before); } From 31edf58b99ca425aa82083c517630038954de488 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:01:22 -0800 Subject: [PATCH 06/16] ADFA-7301 dump: read schema SQL at the statement limit, list a cut one dump read the CREATE statements (tables, and indexes/triggers/views) with get_schema's 64 KiB limit and never looked at isTruncated, so a longer CREATE was cut mid-statement, written with ";" and the dump still looked whole. They are now read with dump's own statement limit (4 MiB), and a statement still cut is listed in truncated_statements, as a cut row is. `complete` still means "no more pages": it drives paging, so a cut statement does not clear it; truncated_statements says the dump is not whole. The "more than 1000 tables" error also fired when the 4 MiB byte budget, not the row limit, ended the query; it now says which one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 61 +++++++++++---- .../sqlitedebugger/engine/FakeDebugEngine.kt | 4 + .../sqlitedebugger/mcp/ShellToolsTest.kt | 75 ++++++++++++++++++- 3 files changed, 121 insertions(+), 19 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index eac2da1854..89b9fff622 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -831,6 +831,8 @@ class DatabaseTools internal constructor( private sealed class DumpUnit { class Fixed( val statements: List, + /** Indexes into [statements] of those cut at the statement limit. */ + val cut: Set = emptySet(), ) : DumpUnit() class Rows( @@ -874,23 +876,39 @@ class DatabaseTools internal constructor( } } val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) - val tables = - runChecked( + val schemaLimits = QueryLimits(MAX_ROWS, DUMP_STATEMENT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + + fun tablesOf(names: List?): QueryResult { + val filter = if (names != null) " AND name IN (${names.joinToString(",") { "?" }})" else "" + return runChecked( call, path, - "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND sql NOT NULL" + - (if (only != null) " AND name = ?" else "") + " ORDER BY name = 'sqlite_sequence', rowid", - if (only != null) Bind(listOf(only), null) else Bind.NONE, + "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND sql NOT NULL$filter ORDER BY name = 'sqlite_sequence', rowid", + if (names != null) Bind(names, null) else Bind.NONE, 0, - QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), + schemaLimits, ) - if (tables.hasMore) throw McpToolError("The database has more than $MAX_ROWS tables; dump them one at a time with table.") + } + + val tables = tablesOf(only?.let { listOf(it) }) + if (tables.hasMore) { + throw McpToolError( + if (tables.rows.size < MAX_ROWS) { + "The CREATE statements of the tables come to more than ${MAX_TOTAL_BYTES / (1024 * 1024)} MiB; " + + "dump them one at a time with table." + } else { + "The database has more than $MAX_ROWS tables; dump them one at a time with table." + }, + ) + } if (only != null && tables.rows.isEmpty()) throw McpToolError("No table named \"$only\".") + val named = only?.let { listOf(it) } val units = mutableListOf(DumpUnit.Fixed(listOf("PRAGMA foreign_keys=OFF;", "BEGIN TRANSACTION;"))) var writableSchema = false - for (row in tables.rows) { + for ((r, row) in tables.rows.withIndex()) { val name = row[0] as String val sql = row[1] as String + val cutSql = tables.isTruncated(r, 1) when { name == "sqlite_sequence" -> { units += DumpUnit.Fixed(listOf("DELETE FROM sqlite_sequence;")) @@ -904,7 +922,7 @@ class DatabaseTools internal constructor( name.startsWith("sqlite_") -> {} - sql.regionMatches(0, "CREATE VIRTUAL TABLE", 0, 20, ignoreCase = true) -> { + isVirtualTable(sql) -> { // As the shell does: its shadow tables are dumped as tables, so it must not be created again. val statements = mutableListOf() if (!writableSchema) statements += "PRAGMA writable_schema=ON;" @@ -912,11 +930,11 @@ class DatabaseTools internal constructor( statements += "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql) VALUES('table'," + "${ShellFormat.sqlLiteral(name)},${ShellFormat.sqlLiteral(name)},0,${ShellFormat.sqlLiteral(sql)});" - units += DumpUnit.Fixed(statements) + units += DumpUnit.Fixed(statements, if (cutSql) setOf(statements.lastIndex) else emptySet()) } else -> { - units += DumpUnit.Fixed(listOf("$sql;")) + units += DumpUnit.Fixed(listOf("$sql;"), if (cutSql) setOf(0) else emptySet()) units += DumpUnit.Rows(name) } } @@ -926,18 +944,26 @@ class DatabaseTools internal constructor( call, path, "SELECT sql FROM sqlite_master WHERE sql NOT NULL AND type IN ('index', 'trigger', 'view')" + - (if (only != null) " AND tbl_name = ?" else "") + " ORDER BY rowid", - if (only != null) Bind(listOf(only), null) else Bind.NONE, + (if (named != null) " AND tbl_name IN (${named.joinToString(",") { "?" }})" else "") + " ORDER BY rowid", + if (named != null) Bind(named, null) else Bind.NONE, 0, - QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), + schemaLimits, ) if (others.hasMore) { - throw McpToolError("The database has more than $MAX_ROWS indexes, triggers and views; dump one table at a time.") + throw McpToolError( + if (others.rows.size < MAX_ROWS) { + "The CREATE statements of the indexes, triggers and views come to more than ${MAX_TOTAL_BYTES / (1024 * 1024)} MiB; " + + "dump one table at a time." + } else { + "The database has more than $MAX_ROWS indexes, triggers and views; dump one table at a time." + }, + ) } val tail = others.rows.map { "${it[0]};" }.toMutableList() + val tailCut = others.rows.indices.filter { others.isTruncated(it, 0) }.toMutableSet() if (writableSchema) tail += "PRAGMA writable_schema=OFF;" tail += "COMMIT;" - units += DumpUnit.Fixed(tail) + units += DumpUnit.Fixed(tail, tailCut) val out = JSONArray() val cut = JSONArray() @@ -949,6 +975,7 @@ class DatabaseTools internal constructor( is DumpUnit.Fixed -> { while (offset < u.statements.size && out.length() < MAX_ROWS && bytes < MAX_TOTAL_BYTES) { val st = u.statements[offset.toInt()] + if (offset.toInt() in u.cut) cut.put(out.length()) out.put(st) bytes += st.length offset++ @@ -987,6 +1014,8 @@ class DatabaseTools internal constructor( .put("truncated_statements", cut) } + private fun isVirtualTable(createSql: String) = createSql.regionMatches(0, "CREATE VIRTUAL TABLE", 0, 20, ignoreCase = true) + /** * The SELECT that writes each row of [table] as an INSERT statement, in rowid order for a rowid table * (so paging is stable). quote() writes literals that read back the same (a REAL that would not, with diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 472198a2e8..0717f5ad06 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -39,6 +39,9 @@ class FakeDebugEngine( /** Each setRowCapture call, in order: rows per statement, value bytes, row bytes. */ val rowCaptureCalls = mutableListOf>() + /** The SQL and limits of each query, in order. */ + val queries = mutableListOf>() + /** The argNames of the last query: null when its args were bound by position. */ var lastArgNames: List? = null private set @@ -140,6 +143,7 @@ class FakeDebugEngine( ): QueryResult { check(!closed) { "closed" } lastArgNames = argNames + queries += sql to limits val all = answer(path, writable, sql, args) val skip = offset.toInt().coerceAtMost(all.rows.size) val rest = all.rows.drop(skip) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index a4654856c3..fc265418fb 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -184,17 +184,25 @@ class ShellToolsTest { rows: (table: String, offset: Int) -> List = { _, _ -> emptyList() }, xinfo: Map>> = emptyMap(), withoutRowid: Set = emptySet(), + tablesCut: Set = emptySet(), + othersCut: Set = emptySet(), ) { engine.answer = { _, _, sql, args -> seen += sql to args when { sql.startsWith("SELECT name, sql FROM sqlite_master") -> { val only = args.firstOrNull() - QueryResult(listOf("name", "sql"), tables.filter { only == null || it[0] == only }, 0, false) + QueryResult( + listOf("name", "sql"), + tables.filter { only == null || it[0] == only }, + tablesCut.size, + false, + tablesCut, + ) } sql.startsWith("SELECT sql FROM sqlite_master") -> { - QueryResult(listOf("sql"), others, 0, false) + QueryResult(listOf("sql"), others, othersCut.size, false, othersCut) } sql.startsWith("SELECT name, hidden FROM pragma_table_xinfo") -> { @@ -291,7 +299,7 @@ class ShellToolsTest { dumpSchema(tables = listOf(listOf("t", "CREATE TABLE t(a)"), listOf("u", "CREATE TABLE u(b)"))) val sql = ok("dump", JSONObject().put("table", "u")).getJSONArray("sql").strings() assertEquals(listOf("PRAGMA foreign_keys=OFF;", "BEGIN TRANSACTION;", "CREATE TABLE u(b);", "COMMIT;"), sql) - assertTrue(seen.single { it.first.startsWith("SELECT sql FROM sqlite_master") }.first.contains("AND tbl_name = ?")) + assertTrue(seen.single { it.first.startsWith("SELECT sql FROM sqlite_master") }.first.contains("AND tbl_name IN (?)")) assertEquals("No table named \"zz\".", error("dump", JSONObject().put("table", "zz"))) } @@ -345,6 +353,67 @@ class ShellToolsTest { ) } + @Test fun dumpReadsSchemaSqlWithTheStatementLimitAndListsACutOne() { + // cut cells are row * columns + column: the table query has 2 columns, the others query 1 + dumpSchema( + tables = listOf(listOf("t", "CREATE TABLE t(a, b"), listOf("u", "CREATE TABLE u(b)")), + others = listOf(listOf("CREATE INDEX ok ON u(b)"), listOf("CREATE VIEW v AS SELECT 'x")), + tablesCut = setOf(1L), + othersCut = setOf(1L), + ) + val r = ok("dump") + val sql = r.getJSONArray("sql").strings() + assertEquals("CREATE TABLE t(a, b;", sql[2]) + assertEquals("CREATE VIEW v AS SELECT 'x;", sql[sql.size - 2]) + assertEquals(listOf(2, sql.size - 2), (0 until 2).map { r.getJSONArray("truncated_statements").getInt(it) }) + assertEquals(2, r.getJSONArray("truncated_statements").length()) + val schemaQueries = engine.queries.filter { it.first.contains("FROM sqlite_master") } + assertEquals(2, schemaQueries.size) + for ((sqlText, limits) in schemaQueries) { + assertEquals(sqlText, DatabaseTools.DUMP_STATEMENT_BYTES, limits.maxTextBytes) + } + } + + @Test fun dumpListsACutVirtualTableStatement() { + dumpSchema(tables = listOf(listOf("docs", "CREATE VIRTUAL TABLE docs USING fts5(bo")), tablesCut = setOf(1L)) + val r = ok("dump") + val cut = r.getJSONArray("truncated_statements") + assertEquals(listOf(3), (0 until cut.length()).map { cut.getInt(it) }) + } + + @Test fun dumpSaysWhenTheSchemaPassesTheByteBudgetNotTheTableLimit() { + val big = "x".repeat(3 * 1024 * 1024) + engine.answer = { _, _, sql, _ -> + if (sql.startsWith("SELECT name, sql")) { + QueryResult(listOf("name", "sql"), listOf(listOf("a", big), listOf("b", big)), 0, false) + } else { + QueryResult(listOf("sql"), listOf(listOf(big), listOf(big)), 0, false) + } + } + val message = error("dump", JSONObject()) + assertTrue(message, message.contains("MiB") && !message.contains("more than ${DatabaseTools.MAX_ROWS} tables")) + engine.answer = { _, _, sql, _ -> + if (sql.startsWith("SELECT name, sql")) { + QueryResult(listOf("name", "sql"), listOf(listOf("a", "CREATE TABLE a(x)")), 0, false) + } else { + QueryResult(listOf("sql"), listOf(listOf(big), listOf(big)), 0, false) + } + } + val others = error("dump", JSONObject()) + assertTrue(others, others.contains("MiB") && !others.contains("more than ${DatabaseTools.MAX_ROWS} indexes")) + } + + @Test fun dumpStillSaysMoreThanTheTableLimitWhenRowsRunOut() { + engine.answer = { _, _, sql, _ -> + if (sql.startsWith("SELECT name, sql")) { + QueryResult(listOf("name", "sql"), (1..1001).map { listOf("t$it", "CREATE TABLE t$it(a)") }, 0, false) + } else { + QueryResult(listOf("sql"), emptyList(), 0, false) + } + } + assertTrue(error("dump", JSONObject()).contains("more than ${DatabaseTools.MAX_ROWS} tables")) + } + @Test fun exportWritesCsvAsTheShellDoes() { answer( "SELECT" to { From 1e5ef3491c3760d6638c29cd83a3bb378367c77b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:38:42 -0800 Subject: [PATCH 07/16] ADFA-7301 style: spotless reformat of the dump change, no functional change ktlint splits the tailCut chain added in the previous commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 89b9fff622..0aea20abc3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -960,7 +960,10 @@ class DatabaseTools internal constructor( ) } val tail = others.rows.map { "${it[0]};" }.toMutableList() - val tailCut = others.rows.indices.filter { others.isTruncated(it, 0) }.toMutableSet() + val tailCut = + others.rows.indices + .filter { others.isTruncated(it, 0) } + .toMutableSet() if (writableSchema) tail += "PRAGMA writable_schema=OFF;" tail += "COMMIT;" units += DumpUnit.Fixed(tail, tailCut) From a98c7cce03944249d49252e395266b9e0bf92a15 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:03 -0800 Subject: [PATCH 08/16] ADFA-7301 dump: include a virtual table's shadow tables when table is one dump with table set to a virtual table filtered by name = ? and tbl_name = ?, so its shadow tables (docs_fts_data and the like) were not dumped, though the description and README say they are, and such a dump does not restore. The virtual table's shadow tables are now found with pragma_table_list (type 'shadow', SQLite 3.37+) by the virtual table's name and "_", and dumped with their indexes and triggers. A plain table does not run the extra query. Known gap: if another virtual table's name also starts with the same prefix (docs and docs_fts), its shadow tables come along; the README says so. The JNI test builds libsqlite3x with FTS5 (nothing else needs it) to check against real SQLite that the server's authorizer allows the query and that the shadow tables are the five FTS5 ones, not a table that merely shares the prefix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 25 +++++++-- .../sqlitedebugger/mcp/ShellToolsTest.kt | 51 ++++++++++++++++++- .../src/test/jni/JniQueryTest.java | 12 +++++ subprojects/sqlite-debugger/test.sh | 5 +- 5 files changed, 87 insertions(+), 8 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index ba9c1fc38f..7912e95ca3 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -67,7 +67,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a Details: - Other `sqlite_` tables are skipped, except that `sqlite_stat1` gets `ANALYZE sqlite_schema`. - - A virtual table goes into `sqlite_schema` under `PRAGMA writable_schema`, and its shadow tables are dumped as tables. + - A virtual table goes into `sqlite_schema` under `PRAGMA writable_schema`, and its shadow tables are dumped as tables. With `table` set to a virtual table, its shadow tables (`pragma_table_list` type `shadow`, SQLite 3.37 and later, whose names start with the virtual table's name and `_`) are dumped too, with their indexes and triggers; the whole-database dump already has them. Limitation: if another virtual table's name also starts that way (`docs` and `docs_fts`), its shadow tables are included. - Rows are written by `quote()` in SQL, which round-trips REALs (checked in the JNI test). They come in rowid order, so paging is stable. - Generated columns are left out, with a column list. - Paged by a cursor (`unit.offset`, rebuilt from the schema on each call): at most 1000 statements and about 4 MiB a page. A statement over 4 MiB is cut and listed. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 0aea20abc3..83ef3a5e9e 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -384,7 +384,8 @@ class DatabaseTools internal constructor( tool( "dump", "Dump as SQL", - "Returns a database, or one table with its indexes and triggers, as SQL text that rebuilds it, as the sqlite3 " + + "Returns a database, or one table with its indexes and triggers (for a virtual table, its shadow tables too), " + + "as SQL text that rebuilds it, as the sqlite3 " + "shell's .dump does: PRAGMA foreign_keys=OFF, BEGIN TRANSACTION, each table's CREATE and INSERTs, then the " + "indexes, triggers and views, then COMMIT. A page holds at most $MAX_ROWS statements and about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB; pass next_cursor as cursor for the next, until complete is true. " + @@ -890,7 +891,7 @@ class DatabaseTools internal constructor( ) } - val tables = tablesOf(only?.let { listOf(it) }) + var tables = tablesOf(only?.let { listOf(it) }) if (tables.hasMore) { throw McpToolError( if (tables.rows.size < MAX_ROWS) { @@ -902,7 +903,25 @@ class DatabaseTools internal constructor( ) } if (only != null && tables.rows.isEmpty()) throw McpToolError("No table named \"$only\".") - val named = only?.let { listOf(it) } + // The shell's .dump of a virtual table leaves its shadow tables out; they are needed to restore it, so they come too. + // SQLite names a shadow table after its virtual table and "_" (type 'shadow' in table_list, from 3.37). + var named = only?.let { listOf(it) } + if (only != null && isVirtualTable(tables.rows[0][1] as String)) { + val shadows = + runChecked( + call, + path, + "SELECT name FROM pragma_table_list WHERE schema = 'main' AND type = 'shadow' " + + "AND substr(name, 1, length(?) + 1) = ? || '_' ORDER BY name", + Bind(listOf(only, only), null), + 0, + limits, + ).rows.map { it[0] as String } + if (shadows.isNotEmpty()) { + named = listOf(only) + shadows + tables = tablesOf(named) + } + } val units = mutableListOf(DumpUnit.Fixed(listOf("PRAGMA foreign_keys=OFF;", "BEGIN TRANSACTION;"))) var writableSchema = false for ((r, row) in tables.rows.withIndex()) { diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index fc265418fb..75b3ca856f 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -186,15 +186,15 @@ class ShellToolsTest { withoutRowid: Set = emptySet(), tablesCut: Set = emptySet(), othersCut: Set = emptySet(), + shadows: List = emptyList(), ) { engine.answer = { _, _, sql, args -> seen += sql to args when { sql.startsWith("SELECT name, sql FROM sqlite_master") -> { - val only = args.firstOrNull() QueryResult( listOf("name", "sql"), - tables.filter { only == null || it[0] == only }, + tables.filter { args.isEmpty() || it[0] in args }, tablesCut.size, false, tablesCut, @@ -209,6 +209,11 @@ class ShellToolsTest { QueryResult(listOf("name", "hidden"), xinfo[args[0]] ?: listOf(listOf("a", 0L)), 0, false) } + sql.startsWith("SELECT name FROM pragma_table_list") -> { + // type 'shadow', named after the virtual table (args[0]) and "_" + QueryResult(listOf("name"), shadows.filter { it.startsWith("${args[0]}_") }.map { listOf(it) }, 0, false) + } + sql.startsWith("SELECT wr FROM pragma_table_list") -> { QueryResult(listOf("wr"), listOf(listOf(if (args[0] in withoutRowid) 1L else 0L)), 0, false) } @@ -303,6 +308,48 @@ class ShellToolsTest { assertEquals("No table named \"zz\".", error("dump", JSONObject().put("table", "zz"))) } + @Test fun dumpOfAVirtualTableIncludesItsShadowTables() { + dumpSchema( + tables = + listOf( + listOf("docs", "CREATE VIRTUAL TABLE docs USING fts5(body)"), + listOf("docs_data", "CREATE TABLE 'docs_data'(id INTEGER PRIMARY KEY, block BLOB)"), + listOf("docs_idx", "CREATE TABLE 'docs_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID"), + listOf("other_data", "CREATE TABLE other_data(a)"), + ), + others = listOf(listOf("CREATE INDEX docs_data_i ON docs_data(id)")), + shadows = listOf("docs_data", "docs_idx", "other_data"), + rows = { table, _ -> listOf("INSERT INTO \"$table\" VALUES(1);") }, + ) + val sql = ok("dump", JSONObject().put("table", "docs")).getJSONArray("sql").strings() + assertEquals( + listOf( + "PRAGMA foreign_keys=OFF;", + "BEGIN TRANSACTION;", + "PRAGMA writable_schema=ON;", + "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql) " + + "VALUES('table','docs','docs',0,'CREATE VIRTUAL TABLE docs USING fts5(body)');", + "CREATE TABLE 'docs_data'(id INTEGER PRIMARY KEY, block BLOB);", + "INSERT INTO \"docs_data\" VALUES(1);", + "CREATE TABLE 'docs_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID;", + "INSERT INTO \"docs_idx\" VALUES(1);", + "CREATE INDEX docs_data_i ON docs_data(id);", + "PRAGMA writable_schema=OFF;", + "COMMIT;", + ), + sql, + ) + val others = seen.single { it.first.startsWith("SELECT sql FROM sqlite_master") } + assertEquals(listOf("docs", "docs_data", "docs_idx"), others.second) + assertTrue(seen.any { it.first.startsWith("SELECT name FROM pragma_table_list") && it.first.contains("type = 'shadow'") }) + } + + @Test fun dumpOfAPlainTableDoesNotLookForShadowTables() { + dumpSchema(tables = listOf(listOf("t", "CREATE TABLE t(a)")), shadows = listOf("t_data")) + ok("dump", JSONObject().put("table", "t")) + assertTrue(seen.none { it.first.contains("'shadow'") }) + } + @Test fun dumpPagesAtTheStatementLimitAndResumesFromTheCursor() { val all = (1..1500).map { "INSERT INTO \"t\" VALUES($it);" } dumpSchema(tables = listOf(listOf("t", "CREATE TABLE t(a)"))) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index d579b02bce..4127c6f0c9 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -1,6 +1,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -476,6 +477,17 @@ public static void main(String[] a) throws Exception { eq(r.rows.get(0)[3], "SEARCH notes USING COVERING INDEX notes_pcode (pcode=?)", "lint: a covered key, as the shell's glob expects"); r = query(srv, "SELECT name, hidden FROM pragma_table_xinfo(?)", new Object[] {"g"}, 0, 100, 4096, 1024, MAX, FAR); eq(r.rows.get(1)[1], 2L, "dump: a virtual generated column is hidden 2"); + // dump of a virtual table: its shadow tables are found by name and type 'shadow', and the server's authorizer allows it + eq(Helper.exec(app, "CREATE VIRTUAL TABLE docs USING fts5(body)"), 0, "fts5 table"); + eq(Helper.exec(app, "CREATE TABLE docs_extra(a)"), 0, "a plain table that starts with the virtual table's name"); + r = query(srv, "SELECT name FROM pragma_table_list WHERE schema = 'main' AND type = 'shadow' " + + "AND substr(name, 1, length(?) + 1) = ? || '_' ORDER BY name", new Object[] {"docs", "docs"}, 0, 100, 4096, 1024, MAX, FAR); + List shadowNames = new ArrayList<>(); + for (Object[] shadow : r.rows) shadowNames.add(shadow[0]); + eq(shadowNames, Arrays.asList("docs_config", "docs_content", "docs_data", "docs_docsize", "docs_idx"), + "dump: the shadow tables of a virtual table, and not docs_extra"); + eq(Helper.exec(app, "DROP TABLE docs"), 0, "drop the fts5 table"); + eq(Helper.exec(app, "DROP TABLE docs_extra"), 0, "drop the plain table"); r = query(srv, "SELECT wr FROM pragma_table_list WHERE schema = 'main' AND name = ?", new Object[] {"w"}, 0, 100, 4096, 1024, MAX, FAR); eq(r.rows.get(0)[0], 1L, "dump: pragma_table_list knows WITHOUT ROWID"); r = q(srv, "SELECT 'INSERT INTO \"lines\" VALUES(' || quote(\"id\") || ',' || quote(\"pid\") || ',' || quote(\"x\") || ');' " diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh index a3308cd206..84f4775266 100755 --- a/subprojects/sqlite-debugger/test.sh +++ b/subprojects/sqlite-debugger/test.sh @@ -83,8 +83,9 @@ run_jni () { java_names=$(sed -n 's/.*static native .* \([A-Za-z]*\)(.*/\1/p' "$jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java" | sort | tr '\n' ' ') [ "$kotlin_names" = "$java_names" ] || { echo "NativeBridge.kt has ($kotlin_names) but the test stub has ($java_names)"; exit 1; } local jinc=(-I"$jdk/include" -I"$jdk/include/linux") - # as requery builds it: everything exported, so dlsym finds sqlite3_auto_extension - build gcc -O1 -w -shared -fPIC -DSQLITE_THREADSAFE=2 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -I"$AMAL" \ + # as requery builds it: everything exported, so dlsym finds sqlite3_auto_extension. FTS5 is on for the shadow + # tables of a virtual table (dump), which SQLite builds nothing else with. + build gcc -O1 -w -shared -fPIC -DSQLITE_ENABLE_FTS5 -DSQLITE_THREADSAFE=2 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -I"$AMAL" \ "$AMAL/sqlite3.c" -o "$out/lib/libsqlite3x.so" -lpthread -ldl -lm build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -fvisibility=hidden -I"$AMAL" -I"$CPP" "${jinc[@]}" \ "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_jni.c" "$CPP/sqlitedbg_expert.c" -Wl,--version-script="$CPP/sqlitedbg.map" \ From bd65e0a4e8d7c4a0c220d8cc2dfa0ed0a0bdda16 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:04 -0800 Subject: [PATCH 09/16] ADFA-7301 lint_foreign_keys: drop the last key when the list is cut The first query is cut at 1000 rows, which can end inside a foreign key, so that key had only some of its columns and its EXPLAIN QUERY PLAN check ran on a partial key and could report it covered. When the list is cut, the rows of the last (table, id) group are dropped; truncated stays true. A cut that falls exactly between two keys also drops a whole key that was complete; truncated says the list is partial either way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 12 ++++++++++-- .../sqlitedebugger/mcp/ShellToolsTest.kt | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 7912e95ca3..215794de69 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -56,7 +56,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - `sample` (1 to 100) is the opt-in: expert reads that percentage of the rows of each table with a candidate index, on the server connection, to build `sqlite_stat1`. For the run it registers one function there (`sqlite_expert_sample`; at 100 also `sqlite_expert_rem`, which below 100 goes on expert's own in-memory connection with the temp table of sampled rows) and removes them after (C test, at 50 and 100). The rows are read in the app, so on a database not in WAL mode sampling stops after 1.5 s, the same limit as a query (`cap_non_wal`, JNI test), with a message to use a lower sample. - The time limit runs through a progress handler on expert's connections and a check between its steps. - Code size: about 22 KB on arm64 and 15 KB on armv7 (Thumb-2) at `-Os`, estimated with clang 18 and host headers, not the NDK. `sqlitedbg.c` is about 6 KB. -- **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one. +- **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one. The key list is read up to 1000 columns; when it is cut, the last key is dropped whole (its columns may be only partly read, and a check on part of a key can call it covered) and `truncated` is true. - Limit: the shell adds a COLLATE clause when a child column's collation differs from its parent key's (`fkey_collate_clause`, through `sqlite3_table_column_metadata` and a function registered on the connection). This check doesn't. - **`dump` (`.dump`).** The shell's order: 1. `PRAGMA foreign_keys=OFF`, then `BEGIN TRANSACTION`; diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 83ef3a5e9e..ad2a86e166 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -378,7 +378,8 @@ class DatabaseTools internal constructor( ".lint fkey-indexes does: without one, deleting or updating a parent row scans the child table. An " + "uncovered key has create_index, a statement that would cover it (not run). Unlike sqlite3, a child column " + "whose collation differs from its parent key's is not taken into account. truncated is true past the first " + - "$MAX_ROWS foreign key columns. $NON_WAL_NOTE", + "$MAX_ROWS foreign key columns, and the last key, of which only some columns were read, is then left out. " + + NON_WAL_NOTE, databaseSchema(), ) { call, args -> lintForeignKeys(call, args) }, tool( @@ -767,8 +768,15 @@ class DatabaseTools internal constructor( 0, limits, ) + // A cut list ends inside a foreign key with some of its columns missing: checking that key would test a + // partial one and could call it covered. Drop its rows (the list is ordered by table, id, seq). + var rows = list.rows + if (list.hasMore && rows.isNotEmpty()) { + val last = rows.last() + rows = rows.dropLastWhile { it[0] == last[0] && it[1] == last[1] } + } val keys = LinkedHashMap, ForeignKey>() - for (row in list.rows) { + for (row in rows) { val key = keys.getOrPut((row[0] as String) to row[1]) { ForeignKey(row[0] as String, row[2] as String) } key.from += row[3] as String key.to += row[4] as String? diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index 75b3ca856f..fda001c97a 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -169,6 +169,25 @@ class ShellToolsTest { assertEquals(listOf(null, null), eqp.second) } + @Test fun lintLeavesOutTheLastKeyWhenTheListIsCut() { + // 1001 columns: key a has 997 of them, key b has 4, and the engine returns the first 1000, so b has only 3 + val columns = listOf("name", "id", "table", "from", "to") + val all = (1..997).map { listOf("a", 0L, "p", "c$it", "k$it") } + (1..4).map { listOf("b", 0L, "p", "d$it", "m$it") } + answer( + "SELECT s.name, f.id" to { QueryResult(columns, all, 0, false) }, + "EXPLAIN QUERY PLAN SELECT 1 FROM" to { + result(listOf("id", "parent", "notused", "detail"), listOf(3L, 0L, 0L, "SEARCH t USING INTEGER PRIMARY KEY (rowid=?)")) + }, + ) + val r = ok("lint_foreign_keys") + assertTrue(r.getBoolean("truncated")) + val keys = r.getJSONArray("foreign_keys") + assertEquals(1, keys.length()) + assertEquals("a", keys.getJSONObject(0).getString("child_table")) + assertEquals(997, keys.getJSONObject(0).getJSONArray("child_columns").length()) + assertTrue("no check ran on the partial key", seen.none { it.first.startsWith("EXPLAIN QUERY PLAN SELECT 1 FROM \"b\"") }) + } + @Test fun lintGlobFailsWhenTheIndexCoversOnlySomeColumns() { assertTrue(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=? AND *=?)", "SEARCH t USING COVERING INDEX i (a=? AND b=?)")) assertFalse(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=? AND *=?)", "SEARCH t USING COVERING INDEX i (a=?)")) From 3eae3945e898561c82aca482c128428588d1aa49 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:24 -0800 Subject: [PATCH 10/16] ADFA-7301 export: lower the per-value limit for a wide result The engine always returns the first row whole, and export allowed 64 KiB per cell, so one row of 2000 columns could hold about 125 MB in the app's heap. The limit is now MAX_TOTAL_BYTES / columns, never above 64 KiB and never below query's 4096 bytes (a 2000-column row is then bounded as in query, about 7.8 MiB, as the README documents). The column count comes from a first call that wraps the statement in SELECT * FROM (...) LIMIT 0: SQLite ends before stepping the inner query (JNI test: an endless recursive CTE returns at once), so the statement is not run twice. A statement that cannot be wrapped (PRAGMA, EXPLAIN) is asked for its first row instead; those are cheap, and the README says such a statement may run to its first row twice. The C engine is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 45 ++++++++++---- .../sqlitedebugger/mcp/ShellToolsTest.kt | 61 +++++++++++++++++++ .../src/test/jni/JniQueryTest.java | 8 +++ 4 files changed, 104 insertions(+), 12 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 215794de69..7fe51ac546 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -74,7 +74,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - **`export` (`.mode csv`, `.mode insert`).** - CSV is RFC 4180 with CRLF line ends. NULL is an empty field, the empty string is `""`, and a BLOB is hex. - `insert` writes literals that read back the same (`X'..'`, an infinity as `1e999`, NaN as NULL). - - A value is cut at 64 KiB, higher than `query`'s limit, since a cut value is wrong data in an export. + - A value is cut at 64 KiB, higher than `query`'s limit, since a cut value is wrong data in an export. The engine returns the first row of a page whole, so a wide row would pass the 4 MiB cap: with more than 64 columns the limit is lowered to 4 MiB divided by the column count, never below `query`'s 4096 bytes (a row of 2000 columns, SQLite's default maximum, is then bounded as in `query`, about 7.8 MiB). The column count comes from a first call that wraps the statement as `SELECT * FROM (...) LIMIT 0`, which SQLite ends before stepping the inner query; a statement that cannot be wrapped (PRAGMA, EXPLAIN) is asked for its first row instead, so such a statement can run up to its first row twice. - **`get_stats` (`.dbinfo`).** - It adds `schema_version`, `user_version`, `application_id`, `encoding`, `auto_vacuum`, `journal_mode`, the schema object counts and the schema size. - The header fields no PRAGMA reads come from page 1 through `sqlite_dbpage`, when SQLite has it; otherwise `header_unavailable` says why. The host SQLite in `test.sh` has no `sqlite_dbpage`; whether requery's has it is unchecked. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index ad2a86e166..cb0043820f 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -72,7 +72,11 @@ class DatabaseTools internal constructor( /** Bound values stop being recorded this long after the last get_events call. */ const val EVENTS_IDLE_MS = 60_000L - /** export's limit on one TEXT or BLOB value: higher than query's, as a cut value is wrong data in an export. */ + /** + * export's limit on one TEXT or BLOB value: higher than query's, as a cut value is wrong data in an export. A + * result of many columns gets less, so that one row (always returned whole) stays within [MAX_TOTAL_BYTES]: + * [MAX_TOTAL_BYTES] / columns, but never below [MAX_TEXT_BYTES]. + */ const val EXPORT_VALUE_BYTES = 64 * 1024 /** dump's limit on one statement, a single TEXT cell; a longer one is cut and listed in truncated_statements. */ @@ -407,7 +411,10 @@ class DatabaseTools internal constructor( "INSERT INTO table VALUES(...) per row, with literals that read back the same (X'..' for a BLOB). At most " + "max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS) and about ${MAX_TOTAL_BYTES / (1024 * 1024)} " + "MiB of values per page; use offset to page ($PAGING_NOTE) A TEXT or BLOB value longer than " + - "${EXPORT_VALUE_BYTES / 1024} KiB is cut, counted in truncated_cells, and the export is then not whole. " + + "${EXPORT_VALUE_BYTES / 1024} KiB is cut, counted in truncated_cells, and the export is then not whole; " + + "with more than ${MAX_TOTAL_BYTES / EXPORT_VALUE_BYTES} columns the limit is lower, $MAX_TOTAL_BYTES divided by the " + + "column count but at least $MAX_TEXT_BYTES bytes, so that one row stays within about " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB (2000 columns: $MAX_TEXT_BYTES bytes each, about 7.8 MiB). " + "$APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), @@ -1083,6 +1090,28 @@ class DatabaseTools internal constructor( if (withoutRowid) "" else " ORDER BY _rowid_" } + /** + * The per-value limit for [sql]: the engine always returns a first row whole, so it is lowered with the column + * count, which a LIMIT 0 wrapper gives without running the statement (SQLite stops before its first step). A + * statement that cannot be wrapped (PRAGMA, EXPLAIN) is asked for its first row instead. + */ + private fun exportCellBytes( + call: Call, + args: JSONObject, + sql: String, + bind: Bind, + ): Int { + val probe = QueryLimits(1, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + val wrapped = "SELECT * FROM (\n${sql.trimEnd { it == ';' || it.isWhitespace() }}\n) LIMIT 0" + val columns = + try { + run(call, args, wrapped, bind, 0, probe).columns.size + } catch (e: McpToolError) { + run(call, args, sql, bind, 0, probe.copy(maxRows = 0)).columns.size + } + return (MAX_TOTAL_BYTES / columns.coerceAtLeast(1)).coerceIn(MAX_TEXT_BYTES, EXPORT_VALUE_BYTES) + } + private fun export( call: Call, args: JSONObject, @@ -1104,15 +1133,9 @@ class DatabaseTools internal constructor( } val offset = intArg(args, "offset", 0, 0, Long.MAX_VALUE) val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() - val result = - run( - call, - args, - sql, - bindArgs(args), - offset, - QueryLimits(maxRows, EXPORT_VALUE_BYTES, EXPORT_VALUE_BYTES, MAX_TOTAL_BYTES), - ) + val bind = bindArgs(args) + val cellBytes = exportCellBytes(call, args, sql, bind) + val result = run(call, args, sql, bind, offset, QueryLimits(maxRows, cellBytes, cellBytes, MAX_TOTAL_BYTES)) val text = StringBuilder() if (format == "csv") { if (header && offset == 0L) text.append(result.columns.joinToString(",") { ShellFormat.csvField(it) }).append("\r\n") diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index fda001c97a..13cbd7c0fd 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -3,6 +3,7 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine import org.appdevforall.sqlitedebugger.engine.IndexSuggestions +import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult import org.appdevforall.sqlitedebugger.engine.StatementSuggestion import org.json.JSONArray @@ -522,6 +523,66 @@ class ShellToolsTest { assertTrue(error("export", JSONObject().put("sql", "SELECT").put("format", "json")).contains("csv or insert")) } + private fun exportWith(columns: Int): QueryLimits { + engine.answer = { _, _, _, _ -> QueryResult(List(columns) { "c$it" }, listOf(List(columns) { 1L }), 0, false) } + engine.queries.clear() + ok("export", JSONObject().put("sql", "SELECT a FROM t;\n").put("format", "csv")) + return engine.queries.last().second + } + + @Test fun exportLowersTheValueLimitForAWideResult() { + val narrow = exportWith(3) + assertEquals(DatabaseTools.EXPORT_VALUE_BYTES, narrow.maxTextBytes) + assertEquals(DatabaseTools.EXPORT_VALUE_BYTES, narrow.maxBlobBytes) + val sixtyFour = exportWith(64) + assertEquals("64 columns of 64 KiB are the 4 MiB budget", DatabaseTools.EXPORT_VALUE_BYTES, sixtyFour.maxTextBytes) + val wide = exportWith(100) + assertEquals(DatabaseTools.MAX_TOTAL_BYTES / 100, wide.maxTextBytes) + assertEquals(DatabaseTools.MAX_TOTAL_BYTES / 100, wide.maxBlobBytes) + assertEquals(DatabaseTools.MAX_TOTAL_BYTES, wide.maxTotalBytes) + val widest = exportWith(2000) + assertEquals("never below query's TEXT limit", DatabaseTools.MAX_TEXT_BYTES, widest.maxTextBytes) + assertEquals(DatabaseTools.MAX_TEXT_BYTES, widest.maxBlobBytes) + } + + @Test fun exportCountsColumnsWithoutRunningTheStatement() { + exportWith(3) + val (probe, limits) = engine.queries.first() + assertEquals("SELECT * FROM (\nSELECT a FROM t\n) LIMIT 0", probe) + assertEquals(2, engine.queries.size) + assertEquals("SELECT a FROM t;\n", engine.queries.last().first) + assertTrue(limits.maxRows >= 1) + } + + @Test fun exportAsksForTheFirstRowWhenTheStatementCannotBeWrapped() { + engine.answer = { _, _, sql, _ -> + if (sql.contains("LIMIT 0")) { + throw org.appdevforall.sqlitedebugger.engine + .DebugEngineException(1, "near \"(\": syntax error") + } + QueryResult(List(100) { "c$it" }, listOf(List(100) { 1L }), 0, false) + } + engine.queries.clear() + ok("export", JSONObject().put("sql", "PRAGMA table_info(t)").put("format", "csv")) + assertEquals(3, engine.queries.size) + assertEquals("PRAGMA table_info(t)", engine.queries[1].first) + assertEquals(0, engine.queries[1].second.maxRows) + assertEquals( + DatabaseTools.MAX_TOTAL_BYTES / 100, + engine.queries + .last() + .second.maxTextBytes, + ) + } + + @Test fun exportReportsTheStatementsOwnErrorWhenItDoesNotPrepare() { + engine.answer = { _, _, _, _ -> + throw org.appdevforall.sqlitedebugger.engine + .DebugEngineException(1, "no such table: zz") + } + assertTrue(error("export", JSONObject().put("sql", "SELECT * FROM zz").put("format", "csv")).contains("no such table: zz")) + } + @Test fun exportUsesItsOwnValueLimitAndPassesArgs() { var limits: Any? = null engine.answer = { _, _, _, args -> diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 4127c6f0c9..71d251a224 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -488,6 +488,14 @@ public static void main(String[] a) throws Exception { "dump: the shadow tables of a virtual table, and not docs_extra"); eq(Helper.exec(app, "DROP TABLE docs"), 0, "drop the fts5 table"); eq(Helper.exec(app, "DROP TABLE docs_extra"), 0, "drop the plain table"); + // export asks for the column count with a LIMIT 0 wrapper: SQLite must stop before stepping the inner query, so + // an endless one (here a recursive CTE with no end) returns at once, with its columns and no rows + long probeStart = System.currentTimeMillis(); + r = query(srv, "SELECT * FROM (\nWITH RECURSIVE c(x, y) AS (SELECT 1, 2 UNION ALL SELECT x + 1, y FROM c) SELECT x, y FROM c\n) LIMIT 0", + new Object[0], 0, 1, 4096, 1024, MAX, System.currentTimeMillis() + 3000); + eq(r.columns.length, 2, "export: the wrapper reports the column count"); + eq(r.rows.size(), 0, "export: and runs no row"); + check(System.currentTimeMillis() - probeStart < 2000, "export: the wrapper did not step the inner query"); r = query(srv, "SELECT wr FROM pragma_table_list WHERE schema = 'main' AND name = ?", new Object[] {"w"}, 0, 100, 4096, 1024, MAX, FAR); eq(r.rows.get(0)[0], 1L, "dump: pragma_table_list knows WITHOUT ROWID"); r = q(srv, "SELECT 'INSERT INTO \"lines\" VALUES(' || quote(\"id\") || ',' || quote(\"pid\") || ',' || quote(\"x\") || ');' " From 7464dbc47c422aa534a946e9f172f744b69373c3 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:24 -0800 Subject: [PATCH 11/16] ADFA-7301 docs: suggest_indexes analyses read statements only ext/expert prepares each statement on the server connection first, and its read-only authorizer refuses INSERT, UPDATE and DELETE, so they fail with "not authorized". Say so in the tool description and the README, with the workaround (a SELECT with the same WHERE). No behaviour change; the C test now checks the three statements fail with that message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 5 ++++- .../sqlite-debugger/src/test/c/sqlitedbg_test.c | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index cb0043820f..1c02f3f296 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -368,7 +368,10 @@ class DatabaseTools internal constructor( "a scan of those tables in the app, and on a database that is not in WAL mode it stops after 1.5 s (use " + "a lower sample, or 0). For each statement, indexes lists the CREATE INDEX statements that would help " + "(empty when the existing ones suffice) and plan the query plan with them; candidates lists every index " + - "weighed. Nothing is created. $APP_FUNCTIONS_NOTE.", + "weighed. Nothing is created. Only read statements can be analysed: an INSERT, UPDATE or DELETE fails with " + + "\"not authorized\", because each statement is first prepared on the read-only connection. For an UPDATE or " + + "DELETE send a SELECT with the same WHERE: SELECT * FROM t WHERE a = 1 for DELETE FROM t WHERE a = 1. " + + "$APP_FUNCTIONS_NOTE.", databaseSchema( "sql" to prop("string", "One or more SQL statements."), "sample" to prop("integer", "Percentage of rows to read for the estimates, 0 to 100. Default 0: none."), diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 5d278e33c1..3d47473484 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -1087,6 +1087,16 @@ static void test_expert(void) { CHECK(err && strstr(err, "no_such_table")); sqlite3_free(err); err = NULL; + // only read statements can be analysed: expert prepares each on srv, whose authorizer refuses a write + static const char *const writes[] = {"UPDATE orders SET total = 1 WHERE customer = 5", "DELETE FROM orders WHERE customer = 5", + "INSERT INTO orders(customer) VALUES(5)"}; + for (size_t i = 0; i < sizeof writes / sizeof writes[0]; i++) { + CHECK(sqlitedbg_expert_run(srv, writes[i], 0, never_stop, NULL, &ex, &err) != SQLITE_OK); + CHECK(ex == NULL); + CHECK(err && strstr(err, "not authorized")); + sqlite3_free(err); + err = NULL; + } CHECK(sqlitedbg_expert_run(srv, "SELECT * FROM orders WHERE customer = 5", 0, always_stop, NULL, &ex, &err) != SQLITE_OK); CHECK(ex == NULL); sqlite3_free(err); From 240f622ea24ed9fa1e9a98254e65b80dc209bb60 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:24 -0800 Subject: [PATCH 12/16] ADFA-7301 docs: correct dump's page size The page budget counts UTF-16 characters (bytes += st.length) while the engine counts UTF-8 bytes, and the first-row rule lets a statement of up to 4 MiB through when the budget is nearly used, so a page can reach about 8 MiB. The description and README said about 4 MiB. The counting is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 7fe51ac546..da8bb79287 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -70,7 +70,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - A virtual table goes into `sqlite_schema` under `PRAGMA writable_schema`, and its shadow tables are dumped as tables. With `table` set to a virtual table, its shadow tables (`pragma_table_list` type `shadow`, SQLite 3.37 and later, whose names start with the virtual table's name and `_`) are dumped too, with their indexes and triggers; the whole-database dump already has them. Limitation: if another virtual table's name also starts that way (`docs` and `docs_fts`), its shadow tables are included. - Rows are written by `quote()` in SQL, which round-trips REALs (checked in the JNI test). They come in rowid order, so paging is stable. - Generated columns are left out, with a column list. - - Paged by a cursor (`unit.offset`, rebuilt from the schema on each call): at most 1000 statements and about 4 MiB a page. A statement over 4 MiB is cut and listed. + - Paged by a cursor (`unit.offset`, rebuilt from the schema on each call): at most 1000 statements and about 4 MiB a page. The budget counts UTF-16 characters (`String.length`), while the engine counts UTF-8 bytes, and the engine returns the first row whole whatever is left of the budget, so a page can reach about 8 MiB of characters (more bytes if the text is not ASCII). A statement over 4 MiB is cut and listed. - **`export` (`.mode csv`, `.mode insert`).** - CSV is RFC 4180 with CRLF line ends. NULL is an empty field, the empty string is `""`, and a BLOB is hex. - `insert` writes literals that read back the same (`X'..'`, an infinity as `1e999`, NaN as NULL). diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 1c02f3f296..209f725f6a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -396,7 +396,9 @@ class DatabaseTools internal constructor( "as SQL text that rebuilds it, as the sqlite3 " + "shell's .dump does: PRAGMA foreign_keys=OFF, BEGIN TRANSACTION, each table's CREATE and INSERTs, then the " + "indexes, triggers and views, then COMMIT. A page holds at most $MAX_ROWS statements and about " + - "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB; pass next_cursor as cursor for the next, until complete is true. " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of characters (UTF-16 characters, not bytes: non-ASCII text takes up to 3 " + + "bytes each), and a statement still goes in whole when the budget is nearly used, so a page can reach about " + + "${2 * MAX_TOTAL_BYTES / (1024 * 1024)} MiB; pass next_cursor as cursor for the next, until complete is true. " + "A statement longer than ${DUMP_STATEMENT_BYTES / (1024 * 1024)} MiB is cut and listed in " + "truncated_statements (indexes into sql), and the dump is then not whole. Paging re-reads the schema and " + "the rows, so a dump of a database that changes between pages can miss or repeat rows. $NON_WAL_NOTE", From f64fc6e103ce00bb13a7d0fc0b36e057f00a9ec9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:35 -0800 Subject: [PATCH 13/16] ADFA-7301 docs: README says suggest_indexes analyses read statements only The README half of the previous commit (the tool description and the C test were committed there). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index da8bb79287..3ee2937a40 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -53,6 +53,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - **`suggest_indexes` (`.expert`).** SQLite's `ext/expert`, vendored unchanged from 3.49.1 in `src/main/cpp/expert/` (public domain, like SQLite), is compiled into `libsqlitedbg.so` through `sqlitedbg_expert.c`. That file includes it in a translation unit that reaches SQLite through the api table, like `sqlitedbg.c`. - Expert copies the schema of the server connection into two in-memory connections of its own. It opens them inside `sqlitedbg_private_open`, so the extension neither lists nor traces them, and it only prepares the client's SQL on the server connection. - Sampling is off by default (`sample` 0). Then no row of the app's data is read and nothing is added to the server connection. The suggestions rest on SQLite's default estimates, which assume large tables, so on a small table they can name an index that would not help; the description says to check them with `explain_query_plan`. + - Only read statements can be analysed. `sqlite3_expert_sql` first prepares each statement on the server connection, whose read-only authorizer refuses an INSERT, UPDATE or DELETE, so the call fails with "not authorized". For an UPDATE or DELETE the description tells the agent to send a SELECT with the same WHERE (`SELECT * FROM t WHERE a = 1` for `DELETE FROM t WHERE a = 1`). - `sample` (1 to 100) is the opt-in: expert reads that percentage of the rows of each table with a candidate index, on the server connection, to build `sqlite_stat1`. For the run it registers one function there (`sqlite_expert_sample`; at 100 also `sqlite_expert_rem`, which below 100 goes on expert's own in-memory connection with the temp table of sampled rows) and removes them after (C test, at 50 and 100). The rows are read in the app, so on a database not in WAL mode sampling stops after 1.5 s, the same limit as a query (`cap_non_wal`, JNI test), with a message to use a lower sample. - The time limit runs through a progress handler on expert's connections and a check between its steps. - Code size: about 22 KB on arm64 and 15 KB on armv7 (Thumb-2) at `-Os`, estimated with clang 18 and host headers, not the NDK. `sqlitedbg.c` is about 6 KB. From c1596a87f4ae51325c2e8034d3a1dee4f401e839 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 00:39:35 -0800 Subject: [PATCH 14/16] ADFA-7301 docs: dump's row order for _rowid_ columns and WITHOUT ROWID Rows are read ORDER BY _rowid_, which binds to a user column of that name, so such a table is ordered by the column; a WITHOUT ROWID table gets no ORDER BY and comes in the planner's order (normally primary key order, not guaranteed). Document both in the description and the README, which said paging was stable. No code change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 3ee2937a40..7aa3f839f6 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -69,7 +69,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a Details: - Other `sqlite_` tables are skipped, except that `sqlite_stat1` gets `ANALYZE sqlite_schema`. - A virtual table goes into `sqlite_schema` under `PRAGMA writable_schema`, and its shadow tables are dumped as tables. With `table` set to a virtual table, its shadow tables (`pragma_table_list` type `shadow`, SQLite 3.37 and later, whose names start with the virtual table's name and `_`) are dumped too, with their indexes and triggers; the whole-database dump already has them. Limitation: if another virtual table's name also starts that way (`docs` and `docs_fts`), its shadow tables are included. - - Rows are written by `quote()` in SQL, which round-trips REALs (checked in the JNI test). They come in rowid order, so paging is stable. + - Rows are written by `quote()` in SQL, which round-trips REALs (checked in the JNI test). They come `ORDER BY _rowid_`, so paging is stable, with two exceptions: a table with a user column named `_rowid_` is ordered by that column (the name binds to the column), and a WITHOUT ROWID table gets no ORDER BY, so its order is the planner's (normally primary key order) and not guaranteed. - Generated columns are left out, with a column list. - Paged by a cursor (`unit.offset`, rebuilt from the schema on each call): at most 1000 statements and about 4 MiB a page. The budget counts UTF-16 characters (`String.length`), while the engine counts UTF-8 bytes, and the engine returns the first row whole whatever is left of the budget, so a page can reach about 8 MiB of characters (more bytes if the text is not ASCII). A statement over 4 MiB is cut and listed. - **`export` (`.mode csv`, `.mode insert`).** diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 209f725f6a..87b4b91b8f 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -400,7 +400,9 @@ class DatabaseTools internal constructor( "bytes each), and a statement still goes in whole when the budget is nearly used, so a page can reach about " + "${2 * MAX_TOTAL_BYTES / (1024 * 1024)} MiB; pass next_cursor as cursor for the next, until complete is true. " + "A statement longer than ${DUMP_STATEMENT_BYTES / (1024 * 1024)} MiB is cut and listed in " + - "truncated_statements (indexes into sql), and the dump is then not whole. Paging re-reads the schema and " + + "truncated_statements (indexes into sql), and the dump is then not whole. Rows are read ORDER BY _rowid_, which a " + + "user column named _rowid_ takes over (the order is then by that column), and a WITHOUT ROWID table is read " + + "with no ORDER BY, in the order SQLite chooses (normally its primary key). Paging re-reads the schema and " + "the rows, so a dump of a database that changes between pages can miss or repeat rows. $NON_WAL_NOTE", databaseSchema( "table" to prop("string", "Only this table, with its indexes and triggers. Default: the whole database."), From 9e9e5c859bc2d6b5002197b47f8eb4f7e466d18c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 15:33:14 -0800 Subject: [PATCH 15/16] ADFA-7301 debugger: lint counts a WITHOUT ROWID primary key that covers the key A WITHOUT ROWID child whose primary key starts with the foreign key's columns plans as "SEARCH t USING PRIMARY KEY (x=? AND y=?)", which neither of the shell's two globs matches, so the key was reported uncovered with a create_index that duplicated the primary key (#2323 review, comment 4713256686; the shell's .lint has the same gap). A third glob matches that plan; its b-tree holds every column, so the search covers the key. The description and README say so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 13 +++++----- .../sqlitedebugger/mcp/ShellToolsTest.kt | 26 +++++++++++++++++++ 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 3357c9b8b9..c786527d7e 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -57,7 +57,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - `sample` (1 to 100) is the opt-in: expert reads that percentage of the rows of each table with a candidate index, on the server connection, to build `sqlite_stat1`. For the run it registers one function there (`sqlite_expert_sample`; at 100 also `sqlite_expert_rem`, which below 100 goes on expert's own in-memory connection with the temp table of sampled rows) and removes them after (C test, at 50 and 100). The rows are read in the app, so on a database not in WAL mode sampling stops after 1.5 s, the same limit as a query (`cap_non_wal`, JNI test), with a message to use a lower sample. - The time limit runs through a progress handler on expert's connections and a check between its steps. - Code size: about 22 KB on arm64 and 15 KB on armv7 (Thumb-2) at `-Os`, estimated with clang 18 and host headers, not the NDK. `sqlitedbg.c` is about 6 KB. -- **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one. The key list is read up to 1000 columns; when it is cut, the last key is dropped whole (its columns may be only partly read, and a check on part of a key can call it covered) and `truncated` is true. +- **`lint_foreign_keys` (`.lint fkey-indexes`).** The shell's check, done in Kotlin: for each foreign key, `EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE col=?` must match the shell's globs, `SEARCH child USING COVERING INDEX*(*=?...)` or the INTEGER PRIMARY KEY one, or a third the shell lacks, `SEARCH child USING PRIMARY KEY (*=?...)`: a WITHOUT ROWID table's primary key holds every column, so a search on it covers the key (the shell reports such a key uncovered). The key list is read up to 1000 columns; when it is cut, the last key is dropped whole (its columns may be only partly read, and a check on part of a key can call it covered) and `truncated` is true. - Limit: the shell adds a COLLATE clause when a child column's collation differs from its parent key's (`fkey_collate_clause`, through `sqlite3_table_column_metadata` and a function registered on the connection). This check doesn't. - **`dump` (`.dump`).** The shell's order: 1. `PRAGMA foreign_keys=OFF`, then `BEGIN TRANSACTION`; diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 87b4b91b8f..6a382be63b 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -384,7 +384,8 @@ class DatabaseTools internal constructor( "Lists each foreign key and whether an index on the child table covers it, as the sqlite3 shell's " + ".lint fkey-indexes does: without one, deleting or updating a parent row scans the child table. An " + "uncovered key has create_index, a statement that would cover it (not run). Unlike sqlite3, a child column " + - "whose collation differs from its parent key's is not taken into account. truncated is true past the first " + + "whose collation differs from its parent key's is not taken into account, and a WITHOUT ROWID child's " + + "primary key counts when it starts with the key's columns. truncated is true past the first " + "$MAX_ROWS foreign key columns, and the last key, of which only some columns were read, is then left out. " + NON_WAL_NOTE, databaseSchema(), @@ -823,12 +824,12 @@ class DatabaseTools internal constructor( 0, limits, ).rows.firstOrNull()?.getOrNull(3) as? String ?: "" - // The shell's two patterns (lintFkeyIndexes in shell.c.in) + // The shell's two patterns (lintFkeyIndexes in shell.c.in), and a third the shell lacks: a WITHOUT ROWID + // table's primary key, whose b-tree holds every column, so a search on it covers the key. + val terms = "(" + key.from.joinToString(" AND ") { "*=?" } + ")" val covered = - ShellFormat.globMatches( - "SEARCH ${key.child} USING COVERING INDEX*(" + key.from.joinToString(" AND ") { "*=?" } + ")", - plan, - ) || + ShellFormat.globMatches("SEARCH ${key.child} USING COVERING INDEX*$terms", plan) || + ShellFormat.globMatches("SEARCH ${key.child} USING PRIMARY KEY $terms", plan) || ShellFormat.globMatches("SEARCH * USING INTEGER PRIMARY KEY (rowid=?)", plan) val item = JSONObject() diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index 13cbd7c0fd..61845231ae 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -189,6 +189,32 @@ class ShellToolsTest { assertTrue("no check ran on the partial key", seen.none { it.first.startsWith("EXPLAIN QUERY PLAN SELECT 1 FROM \"b\"") }) } + @Test fun lintCountsAWithoutRowidPrimaryKeyThatStartsWithTheKey() { + // The plans are SQLite 3.49.1's for ch2(x, y, PRIMARY KEY(x, y)) and ch3(x, y, z, PRIMARY KEY(x, z)), both + // WITHOUT ROWID, each with FOREIGN KEY(x, y) REFERENCES p(a, b). + answer( + "SELECT s.name, f.id" to { + result( + listOf("name", "id", "table", "from", "to"), + listOf("ch2", 0L, "p", "x", "a"), + listOf("ch2", 0L, "p", "y", "b"), + listOf("ch3", 0L, "p", "x", "a"), + listOf("ch3", 0L, "p", "y", "b"), + ) + }, + "EXPLAIN QUERY PLAN SELECT 1 FROM \"ch2\"" to { + result(listOf("id", "parent", "notused", "detail"), listOf(3L, 0L, 0L, "SEARCH ch2 USING PRIMARY KEY (x=? AND y=?)")) + }, + "EXPLAIN QUERY PLAN SELECT 1 FROM \"ch3\"" to { + result(listOf("id", "parent", "notused", "detail"), listOf(3L, 0L, 0L, "SEARCH ch3 USING PRIMARY KEY (x=?)")) + }, + ) + val keys = ok("lint_foreign_keys").getJSONArray("foreign_keys") + assertTrue("a primary key on both columns covers the key", keys.getJSONObject(0).getBoolean("covered")) + assertFalse("one that covers only x does not", keys.getJSONObject(1).getBoolean("covered")) + assertTrue(keys.getJSONObject(1).has("create_index")) + } + @Test fun lintGlobFailsWhenTheIndexCoversOnlySomeColumns() { assertTrue(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=? AND *=?)", "SEARCH t USING COVERING INDEX i (a=? AND b=?)")) assertFalse(ShellFormat.globMatches("SEARCH t USING COVERING INDEX*(*=? AND *=?)", "SEARCH t USING COVERING INDEX i (a=?)")) From 1133a58b495ee51d86b4ba61be8ecf5e64dc3e19 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 26 Nov 2026 15:33:14 -0800 Subject: [PATCH 16/16] ADFA-7301 debugger: dump a table of more than 500 columns insertsFor joined one quote() per column into a single chain of ||, which SQLite refuses past a depth of 1000: from about 500 columns, prepare failed with "Expression tree is too large" and a whole-database dump stopped at that table (#2323 review, comment 4713256695). Past 100 columns the calls are now joined in parenthesised groups of 100, so 2000 columns, SQLite's most, prepare, with the same output (checked on SQLite 3.49.1). The test for 2000 columns found a second fault: the column list was read as one page of 1000 rows, so a table of more columns got INSERTs short of values. It is now read whole, up to 32767 columns, SQLite's highest limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 1 + .../sqlitedebugger/mcp/DatabaseTools.kt | 30 +++++++++++++++++-- .../sqlitedebugger/mcp/ShellToolsTest.kt | 24 +++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index c786527d7e..2b2d837bca 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -71,6 +71,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - A virtual table goes into `sqlite_schema` under `PRAGMA writable_schema`, and its shadow tables are dumped as tables. With `table` set to a virtual table, its shadow tables (`pragma_table_list` type `shadow`, SQLite 3.37 and later, whose names start with the virtual table's name and `_`) are dumped too, with their indexes and triggers; the whole-database dump already has them. Limitation: if another virtual table's name also starts that way (`docs` and `docs_fts`), its shadow tables are included. - Rows are written by `quote()` in SQL, which round-trips REALs (checked in the JNI test). They come `ORDER BY _rowid_`, so paging is stable, with two exceptions: a table with a user column named `_rowid_` is ordered by that column (the name binds to the column), and a WITHOUT ROWID table gets no ORDER BY, so its order is the planner's (normally primary key order) and not guaranteed. - Generated columns are left out, with a column list. + - Past 100 columns, the `quote()` calls are joined in parenthesised groups of 100. One chain of `||` over all of them is what the shell builds, and SQLite refuses it from about 500 columns ("Expression tree is too large (maximum depth 1000)"). In groups, a table of 2000 columns, SQLite's most, prepares, with the same output (checked on SQLite 3.49.1). The column list is read whole, not as a page of 1000 rows, which wrote INSERTs short of values for a table of more columns. - Paged by a cursor (`unit.offset`, rebuilt from the schema on each call): at most 1000 statements and about 4 MiB a page. The budget counts UTF-16 characters (`String.length`), while the engine counts UTF-8 bytes, and the engine returns the first row whole whatever is left of the budget, so a page can reach about 8 MiB of characters (more bytes if the text is not ASCII). A statement over 4 MiB is cut and listed. - **`export` (`.mode csv`, `.mode insert`).** - CSV is RFC 4180 with CRLF line ends. NULL is an empty field, the empty string is `""`, and a BLOB is hex. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 6a382be63b..2f1fea9839 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -82,6 +82,15 @@ class DatabaseTools internal constructor( /** dump's limit on one statement, a single TEXT cell; a longer one is cut and listed in truncated_statements. */ const val DUMP_STATEMENT_BYTES = MAX_TOTAL_BYTES + /** + * dump's quote() calls per parenthesised group. A group's chain of || nests about twice this deep, and + * SQLite's limit is 1000; 2000 columns, SQLite's most, make 20 groups. + */ + const val DUMP_COLUMN_GROUP = 100 + + /** SQLite's highest possible column limit (SQLITE_MAX_COLUMN can be raised to 32767, and no further). */ + const val MAX_TABLE_COLUMNS = 32767 + /** get_events' row recording: rows per statement, bytes per TEXT or BLOB value, and bytes per row. */ const val EVENT_ROWS_PER_STATEMENT = 10 const val EVENT_VALUE_BYTES = 256 @@ -1072,7 +1081,18 @@ class DatabaseTools internal constructor( table: String, limits: QueryLimits, ): String { - val all = runChecked(call, path, "SELECT name, hidden FROM pragma_table_xinfo(?)", Bind(listOf(table), null), 0, limits).rows + // every column, not a page of them: a cut list would write INSERTs short of values + val xinfo = + runChecked( + call, + path, + "SELECT name, hidden FROM pragma_table_xinfo(?)", + Bind(listOf(table), null), + 0, + limits.copy(maxRows = MAX_TABLE_COLUMNS), + ) + if (xinfo.hasMore) throw McpToolError("Table \"$table\" has more than $MAX_TABLE_COLUMNS columns.") + val all = xinfo.rows // hidden 2 and 3: a virtual and a stored generated column val columns = all.filter { it[1] != 2L && it[1] != 3L }.map { it[0] as String } val withoutRowid = @@ -1093,7 +1113,13 @@ class DatabaseTools internal constructor( } else { "" } - val values = columns.joinToString(" || ',' || ") { "quote(${quoteIdentifier(it)})" } + // SQLite refuses an expression nested deeper than 1000 (SQLITE_MAX_EXPR_DEPTH), which one chain of || reaches + // at about 500 columns: past DUMP_COLUMN_GROUP columns, each group is a chain of its own, in parentheses. + val values = + columns.chunked(DUMP_COLUMN_GROUP).joinToString(" || ',' || ") { group -> + val chain = group.joinToString(" || ',' || ") { "quote(${quoteIdentifier(it)})" } + if (columns.size > DUMP_COLUMN_GROUP) "($chain)" else chain + } return "SELECT ${ShellFormat.sqlLiteral("INSERT INTO $target VALUES(")} || $values || ');' FROM ${quoteIdentifier(table)}" + if (withoutRowid) "" else " ORDER BY _rowid_" } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt index 61845231ae..dffe3a98d9 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/ShellToolsTest.kt @@ -327,6 +327,30 @@ class ShellToolsTest { assertEquals("SELECT 'INSERT INTO \"g\"(\"a\",\"c\") VALUES(' || quote(\"a\") || ',' || quote(\"c\") || ');' FROM \"g\"", select) } + @Test fun dumpJoinsTheColumnsOfAWideTableInGroupsOfAHundred() { + fun select(columns: Int): String { + seen.clear() + dumpSchema( + tables = listOf(listOf("w", "CREATE TABLE w(...)")), + xinfo = mapOf("w" to (1..columns).map { listOf("c$it", 0L) }), + ) + ok("dump") + return seen.first { it.first.startsWith("SELECT 'INSERT INTO ") }.first + } + + fun chain(columns: IntRange) = columns.joinToString(" || ',' || ") { "quote(\"c$it\")" } + + fun expected(values: String) = "SELECT 'INSERT INTO \"w\" VALUES(' || $values || ');' FROM \"w\" ORDER BY _rowid_" + // One chain of || is refused past about 500 columns ("Expression tree is too large (maximum depth 1000)"), + // SQLite 3.49.1; up to 100 columns the SELECT is as before, then each group of 100 is a chain of its own. + assertEquals(expected(chain(1..100)), select(100)) + assertEquals(expected("(${chain(1..100)}) || ',' || (${chain(101..101)})"), select(101)) + assertEquals( + expected((0 until 20).joinToString(" || ',' || ") { "(${chain(it * 100 + 1..it * 100 + 100)})" }), + select(2000), + ) + } + @Test fun dumpWritesAVirtualTableIntoTheSchemaAsTheShellDoes() { dumpSchema( tables =