diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index f472daecf4..d3e2980074 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -17,7 +17,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug ``` - `src/main/cpp/sqlitedbg.h` is the contract between the extension, its JNI layer and its host tests, with the semantics of each call. `SQLITEDBG_INTERFACE_VERSION` is raised when anything in it changes shape. -- `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, close), and opens connections for the server (`sqlitedbg_open_server`). +- `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`. @@ -30,18 +30,42 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer hands the bytes to Kotlin unchanged, so `EventDecoder.kt` mirrors the layout, field offsets included: change both together. A committed fixture pins them (see Testing). +**Execution id (ADFA-7379, interface version 4).** The header grew from 72 to 80 bytes: `execution_id` is a `uint64_t` at offset 72, after `changes`; the earlier fields kept their offsets. A 72-byte producer read by the 80-byte `EventDecoder` throws `IllegalArgumentException`: both ship in one AAR, so that pairing does not occur. +- `execution_id` tells which run of a statement an event belongs to, so rows of statements stepped interleaved on one connection can be told apart. A STATEMENT's id is its own `seq`. The PROFILE and ROW events of that run carry the same id, not their own `seq`, so ids are not contiguous. 0 means none or unknown (Kotlin: `executionId` null; CLOSE never has one). Ids are unique within a process and restart with it, like `seq`. A run that is stepped, reset and stepped again gets a new STATEMENT and a new id each time, and so does a statement prepared again at the same address. +- Events with id 0: a trigger's STATEMENT (its text starts with `-- `, and a STATEMENT whose id equals its `seq` is always the start of a run), a statement an app function runs inside a callback (its STATEMENT and PROFILE; no rows are recorded), an EXPLAIN's PROFILE, and the PROFILE and ROW events of a statement the extension did not see start. A statement evicted from its slot (more than 16 stepped in turn) keeps its id on its STATEMENT and on the ROW events recorded before the eviction; its later rows are not recorded and its PROFILE says 0, so a STATEMENT can have no PROFILE with its id. +- A PROFILE is not a reliable "the run ended" event. An EXPLAIN fires a PROFILE with no STATEMENT. A step that returns `SQLITE_BUSY` fires a PROFILE (rows 0) before any row, and the run that resumes may fire no closing PROFILE; it does fire one if the resumed step hits `SQLITE_SCHEMA`. So one `execution_id` can have more than one PROFILE, and a client must not key on one PROFILE per id. +- A statement that SQLite re-prepares after `SQLITE_SCHEMA` (another connection ran DDL since it was prepared, or a CREATE TABLE ran on the same connection) fires one STATEMENT, and the rerun fires none. The rerun's ROW and PROFILE events keep the STATEMENT's id: a PROFILE with no rows that is not busy leaves its slot, marked ended, and later events count for it only if the statement's `SQLITE_STMTSTATUS_REPREPARE` count has grown since the STATEMENT; otherwise they have no id (0) and no rows. So a retried SELECT gives one STATEMENT, a PROFILE with rows 0, its ROW events, and a PROFILE with the row count, all with one id; a retried write gives two PROFILEs, the second with the change count. An ended slot is reused before a live statement's is evicted. An app that calls `sqlite3_stmt_status(..., SQLITE_STMTSTATUS_REPREPARE, 1)` while the statement runs resets that count, and the rerun's rows are then lost, never given a wrong id. A CREATE INDEX on the same connection expires the statement before it runs: one STATEMENT, one PROFILE. +- Size: records grew from 72 to 80 bytes, about 10% more for an event with little data. Each ROW trace now makes one extra `sqlite3_sql` call (before the slot lookup), with or without a client connected. That cost was not re-measured; the benchmark below predates ADFA-7379. + +**Rows and changes (ADFA-7296, interface version 3).** Each record carries `rows` and `changes` (the header grew from 56 to 72 bytes; the earlier fields kept their offsets). +- A PROFILE event's `rows` counts the rows the statement returned. Its `changes` is the statement's own change count, as `sqlite3_changes64` reports it (not rows changed by triggers). A read-only statement has `changes` -1, and so has a statement that had not finished when its PROFILE fired (reset or finalized part way, such as an `INSERT ... VALUES (1),(2) RETURNING a` stepped once, or a step that returned `SQLITE_BUSY`; `sqlite3_stmt_busy` is true then), because the count is partial or not yet set. A statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write's count). `changes` is -1 as well when the connection's total changed while the statement ran and the statement is not an INSERT, UPDATE, DELETE or REPLACE (a leading WITH counts; decided from its own SQL, after whitespace and comments): a PRAGMA stepped across another statement's INSERT would otherwise get that INSERT's count. +- `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default; `get_events` turns it on (see "Results and bound parameters"). +- Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. Accepted limit: in a UTF-16 database, recording rows converts each TEXT value to UTF-8 in full (`sqlite3_column_bytes`) before the 1 MiB guard applies, so a large value costs its full size in memory and time on the app's thread, for each row recorded while a client is connected (measured with a 25-million-character TEXT: a 100 MB allocation and about 230 ms for one row, against about 54 ms with recording off). Android's own databases and Room use UTF-8, which has no such copy. Decided not to change (David). +- The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one; those reads are traced as ROW only and are ignored). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. +- Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). + +### Results and bound parameters (ADFA-7297) + +What the server gives a client so it can format results as the sqlite3 shell would (`.mode`, `.nullvalue` and the rest stay client-side): +- **Values.** A NULL is JSON `null`. A BLOB is `{hex, bytes, truncated}`, lowercase hex (base64 before). An integer beyond 2^53 is a decimal string, and a NaN or infinite REAL is `"NaN"`, `"Infinity"` or `"-Infinity"`, as before. +- **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. +- **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. +- **Bound parameters (`.parameter`).** `query`, `explain_query_plan` and `execute` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. +- **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`. Every event has `execution_id` (ADFA-7379): a `statement` event's own `seq`, and on that run's `profile` and `row` events the same number, so rows of two statements stepped in turn are told apart; it is `null` for `close`, a trigger's statements, a statement an app function runs inside a callback, an EXPLAIN's `profile`, a statement whose start was not seen, and the later `profile` and `row` events of a statement pushed out of its slot. One run can have more than one `profile`, such as one with `rows` 0 from a step that met a busy lock, before the run's rows (the event format above lists every case). 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.** Row recording is one switch for the process: the last `get_events` call decides it. + ## 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. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too. A PRAGMA with an argument (`PRAGMA x = v`, `PRAGMA x(v)`) is refused as well, unless it is `table_info`, `table_xinfo`, `table_list`, `index_info`, `index_xinfo`, `index_list`, `foreign_key_list`, `foreign_key_check`, `integrity_check` or `quick_check`: SQLite applies a flag such as `foreign_keys`, `ignore_check_constraints`, `recursive_triggers` or `cache_size` while it prepares the statement, so refusing the write afterwards would come too late, and no setting can be changed. A PRAGMA without an argument only reads, and the table-valued `pragma_*` functions are checked as the PRAGMA they run. The JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode once it has held its lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`; a wait for the app's lock before that is not counted), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). -- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. The writable connection also enforces foreign keys (`sqlite3_db_config` with `SQLITE_DBCONFIG_ENABLE_FKEY`, set when it is opened), whatever the app's own connections do, so a write cannot leave orphan rows: `ON DELETE` and `ON UPDATE` actions run for its deletes and updates (their rows are not in `changes`), and a write the app itself could make with foreign keys off may be refused. SQLite's default is off (`SQLITE_DEFAULT_FOREIGN_KEYS` is 0, which the host tests confirm on their build); the read-only connection leaves it alone. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped once it has held the write lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. A wait for the app's lock before the statement holds its own is not counted. A wait to commit is: in rollback-journal mode the commit waits for other connections' reads to end, and `execute` replaces the connection's busy timeout with a busy handler that stops at the limit too, so the write lock is not held up to 3 s past it; that error says to try again. A deadline that passes while the statement is prepared (preparing can wait on the app's lock to read the schema) stops it before it starts. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again. +- **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too. A PRAGMA with an argument (`PRAGMA x = v`, `PRAGMA x(v)`) is refused as well, unless it is `table_info`, `table_xinfo`, `table_list`, `index_info`, `index_xinfo`, `index_list`, `foreign_key_list`, `foreign_key_check`, `integrity_check` or `quick_check`: SQLite applies a flag such as `foreign_keys`, `ignore_check_constraints`, `recursive_triggers` or `cache_size` while it prepares the statement, so refusing the write afterwards would come too late, and no setting can be changed. A PRAGMA without an argument only reads, and the table-valued `pragma_*` functions are checked as the PRAGMA they run. The JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. The rollback comes after the statement, so a query that starts inside a transaction left open by a refused rollback reads in that transaction's snapshot, which in WAL mode can be stale, for that one call. This is accepted: it needs a way past the authorizer and then a refused ROLLBACK, and queries run on the read-only connection, so the transaction holds no uncommitted writes. `execute` also rolls one back before its statement runs, so a write is never left inside a transaction that would roll it back after the call reported it. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode once it has held its lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`; a wait for the app's lock before that is not counted), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). +- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. The writable connection also enforces foreign keys (`sqlite3_db_config` with `SQLITE_DBCONFIG_ENABLE_FKEY`, set when it is opened), whatever the app's own connections do, so a write cannot leave orphan rows: `ON DELETE` and `ON UPDATE` actions run for its deletes and updates (their rows are not in `changes`), and a write the app itself could make with foreign keys off may be refused. SQLite's default is off (`SQLITE_DEFAULT_FOREIGN_KEYS` is 0, which the host tests confirm on their build); the read-only connection leaves it alone. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` come back as `query`'s do, within the same limits (ADFA-7304): at most `max_rows`, the 4 MiB budget with the first row whole, cut cells listed, and `has_more`. There is no `offset`, since paging would run the write again. SQLite makes every change, and buffers every returned row, in the first `sqlite3_step` (ADFA-7304 comment 41621). So a statement stopped at a limit is reset, which commits all of it, `changes` counts every row written, and a failed commit at the reset is the call's error (one that stalled to the cap waiting for another connection's read is reported as a stalled step is: SQLITE_INTERRUPT, "Try it again"). A statement that fails at any step, even while its rows come back, returns only the error and no rows. SQLite rolls it back whole, except that FAIL conflict resolution (`OR FAIL`, `ON CONFLICT FAIL`, `RAISE(FAIL)`) keeps, and in autocommit commits, the rows changed before the failing one; the error then says how many (`sqlite3_changes64`, counted when `sqlite3_total_changes64` moved). Limit: if an allocation fails during or after the read (the JVM's for a row or the result, or SQLite's for a cell), the statement is finalized unfinished, which commits it while the call reports the error; that commit waits for a lock only as long as the step's limit allows, as the busy handler stays set until the finalize. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped once it has held the write lock for 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. A wait for the app's lock before the statement holds its own is not counted. A wait to commit is: in rollback-journal mode the commit waits for other connections' reads to end, and `execute` replaces the connection's busy timeout with a busy handler that stops at the limit too, so the write lock is not held up to 3 s past it; that error says to try again. A deadline that passes while the statement is prepared (preparing can wait on the app's lock to read the schema) stops it before it starts. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again. - **The first write to a Room database waits for an acknowledgement (ADFA-7299, D6).** Room records changes with TEMP triggers on its own connection, which a write on the server's connection does not fire, so its observers (Flow, LiveData, Paging, `InvalidationTracker`) miss it and a screen can show stale data. The debugger does not make Room refresh, as it must not change how the app behaves. Instead, `execute` looks for `room_master_table` on the read-only connection, and on a Room database it runs nothing and returns an error that says so, until the call is repeated with `acknowledge_room: true`. The acknowledgement is kept per database path for the life of `DatabaseTools`, one per app process (`DebuggerStartup`), so later writes to that database run without asking until the app restarts, and the check is not run again. A database without `room_master_table` never asks. The app's own connections and writes are not touched. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` is 2 for the changed struct), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. +- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` became 2 for the changed struct, and was raised again by later layout changes: `sqlitedbg.h` has the current value), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. - **The time limits are best effort.** The 1.5 s limit on a database that is not in WAL mode and the 50 s limit per call are checked by the progress handler, every 1,000 SQLite VM instructions. They are not checked inside one long VM instruction, or while a `query` statement waits for a lock the app holds (the busy wait, up to 3 s, `SQLITEDBG_SERVER_BUSY_MS`), so a result can arrive up to about 3 s after the 50 s limit (the client waits 60 s). The 1.5 s limit counts only time the statement holds its lock, and `execute`'s busy handler ends its waits at either limit. The tool descriptions say "best effort" too. - **Column names can be stale after a schema change.** The column names are read after prepare and before the first step, so a schema change by the app between the two can return the old column set. - **Turning off bound-value recording can be late.** After the client goes idle (60 s after the last `get_events`), turning recording off takes the tools' lock, so it waits for a running query and can be up to 50 s late (more by the overrun above). @@ -51,7 +75,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **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, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, and the 1.5 s cap on a write in DELETE and WAL mode while the app writes. 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. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`), plus the `SQLITEDBG_TEST` seam, 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; and `execute`: change counts, `last_insert_rowid`, the refusals, the 1.5 s cap on a write in DELETE and WAL mode while the app writes, binding by name, and RETURNING rows within the limits, including a failed commit at the reset and the time limit striking while rows come back, and what it says of a write when building its result fails (a seam in the test build, `SQLITEDBG_TEST`, fails it as a JNI allocation would). 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. `.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/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 0c28ceafbe..d75366c3a8 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -8,9 +8,11 @@ #define _GNU_SOURCE #endif +#include #include #include #include +#include #include #include #include @@ -22,14 +24,41 @@ SQLITE_EXTENSION_INIT1 #define DEFAULT_BUFFER_BYTES ((size_t)4 << 20) #define DEFAULT_MAX_SQL_BYTES 4096u -#define RECORD_HEADER_BYTES 56u +#define DEFAULT_MAX_VALUE_BYTES 256u +#define DEFAULT_MAX_ROW_BYTES 4096u +#define RECORD_HEADER_BYTES 80u +// add_record: the record's own seq is its execution id. +#define EXEC_SELF UINT64_MAX +#define ROW_HEADER_BYTES 8u +#define ROW_VALUE_BYTES 12u +// A TEXT or BLOB value larger than this, and larger than what the row can keep, is not read at all: +// sqlite3_column_blob/text can materialize it (a zeroblob is virtual until read) on the app's own +// statement, with a copy of its size and an allocation that could fail there. +#define ROW_READ_MAX_BYTES ((size_t)1 << 20) _Static_assert(sizeof(sqlitedbg_event_record) == RECORD_HEADER_BYTES, "event record layout"); +_Static_assert(offsetof(sqlitedbg_event_record, execution_id) == 72, "execution_id offset"); +_Static_assert(sizeof(sqlitedbg_row_header) == ROW_HEADER_BYTES, "row header layout"); +_Static_assert(sizeof(sqlitedbg_row_value) == ROW_VALUE_BYTES, "row value layout"); // Padding record written where the next record would not fit before the end of the ring, so a // record is always contiguous. kind 0 is never a real event. #define KIND_PAD 0u +// A statement the extension saw start on a connection (a TRACE_STMT that is not a trigger's or a +// nested statement's), until its PROFILE event. +typedef struct stmt_slot { + sqlite3_stmt *stmt; // NULL: free + int64_t rows; // TRACE_ROW events so far + int64_t recorded; // of those, recorded as SQLITEDBG_EVENT_ROW + int rows_cut; // a row went unrecorded because of the per-statement limit + sqlite3_int64 total_changes; // sqlite3_total_changes64 when it started + uint64_t last_use; // for evicting the least recently used slot + uint64_t exec_id; // seq of the STATEMENT record that started this run + int ended; // a PROFILE with no rows and not busy: kept in case of a SQLITE_SCHEMA rerun + int reprepares; // SQLITE_STMTSTATUS_REPREPARE at claim +} stmt_slot; + typedef struct conn_state { struct conn_state *prev, *next; uint64_t id; @@ -38,6 +67,14 @@ typedef struct conn_state { int closing; // atomic: set by the close event, cleared by a later statement event int64_t opened_at_ns; int64_t open_thread_id; + // Used only from the trace callback, which runs on the thread using the connection: requery's + // SQLITE_THREADSAFE=2 means one thread at a time, so these need no lock. + stmt_slot slots[SQLITEDBG_STATEMENT_SLOTS]; + uint64_t use_clock; + // The statement whose trigger was traced last ("-- TRIGGER name", P the outer statement), until + // that statement's PROFILE: its trigger's steps are traced as "-- " + step text, the same shape as a + // statement an app runs in a callback, and must not be taken for one. + sqlite3_stmt *trigger_owner; } conn_state; // Taken only for the fields below; never while SQLite runs. @@ -49,6 +86,10 @@ static int g_installed; // g_install_lock static int g_api_ready; // g_lock: sqlite3_api has been saved static uint32_t g_max_sql; // set before g_installed, then read-only static int g_client_connected; // atomic +// Row recording (sqlitedbg_set_row_capture); each read on its own, so a change mid-row is harmless. +static uint32_t g_max_rows; // atomic; 0: off +static uint32_t g_max_value = DEFAULT_MAX_VALUE_BYTES; // atomic +static uint32_t g_max_row = DEFAULT_MAX_ROW_BYTES; // atomic static conn_state *g_first, *g_last; static uint64_t g_next_conn_id = 1; @@ -129,13 +170,12 @@ static size_t utf8_cut(const char *sql, size_t len, size_t max) { return max; } -static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, uint32_t flags, - const char *sql, size_t sql_len) { +// Adds one record with `len` bytes of data, already within the limits. +static uint64_t add_record(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, + uint32_t flags, const void *data, size_t len, uint64_t exec_id) { int64_t time = now_ns(); int64_t tid = this_thread_id(); - size_t kept = utf8_cut(sql, sql_len, g_max_sql); - if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; - size_t need = (RECORD_HEADER_BYTES + kept + 7) & ~(size_t)7; + size_t need = (RECORD_HEADER_BYTES + len + 7) & ~(size_t)7; pthread_mutex_lock(&g_lock); uint64_t seq = g_next_seq++; @@ -150,14 +190,143 @@ static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns r->time_ns = time; r->duration_ns = duration_ns; r->flags = flags; - r->sql_bytes = (uint32_t)kept; - memcpy((unsigned char *)r + RECORD_HEADER_BYTES, sql, kept); - memset((unsigned char *)r + RECORD_HEADER_BYTES + kept, 0, need - RECORD_HEADER_BYTES - kept); + r->data_bytes = (uint32_t)len; + r->rows = rows; + r->changes = changes; + r->execution_id = exec_id == EXEC_SELF ? seq : exec_id; + memcpy((unsigned char *)r + RECORD_HEADER_BYTES, data, len); + memset((unsigned char *)r + RECORD_HEADER_BYTES + len, 0, need - RECORD_HEADER_BYTES - len); g_head += need; g_used += need; if (g_head >= g_cap) g_head = 0; } pthread_mutex_unlock(&g_lock); + return seq; +} + +static uint64_t add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, int64_t rows, int64_t changes, + uint32_t flags, const char *sql, size_t sql_len, uint64_t exec_id) { + size_t kept = utf8_cut(sql, sql_len, g_max_sql); + if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; + return add_record(kind, connection_id, duration_ns, rows, changes, flags, sql, kept, exec_id); +} + +static stmt_slot *find_slot(conn_state *cs, sqlite3_stmt *stmt) { + for (int i = 0; i < SQLITEDBG_STATEMENT_SLOTS; i++) + if (cs->slots[i].stmt == stmt) return &cs->slots[i]; + return NULL; +} + +// The slot for a statement that starts: its old one if it is restarting, else a free one, else an +// ended one, else the least recently used. +static stmt_slot *claim_slot(conn_state *cs, sqlite3_stmt *stmt) { + stmt_slot *slot = find_slot(cs, stmt); + if (!slot) slot = find_slot(cs, NULL); + for (int i = 0; !slot && i < SQLITEDBG_STATEMENT_SLOTS; i++) + if (cs->slots[i].ended) slot = &cs->slots[i]; + if (!slot) { + slot = &cs->slots[0]; + for (int i = 1; i < SQLITEDBG_STATEMENT_SLOTS; i++) + if (cs->slots[i].last_use < slot->last_use) slot = &cs->slots[i]; + } + memset(slot, 0, sizeof *slot); + slot->stmt = stmt; + slot->last_use = ++cs->use_clock; + // Counted from here. An app that calls sqlite3_stmt_status(..., REPREPARE, 1) mid-run resets the + // count, and the rerun after SQLITE_SCHEMA then loses its rows (they never get a wrong id). + slot->reprepares = sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0); + return slot; +} + +static size_t put_value(unsigned char *out, uint8_t type, uint8_t cut, uint32_t stored, uint32_t full) { + sqlitedbg_row_value v = {type, cut, 0, stored, full}; + memcpy(out, &v, sizeof v); + return sizeof v; +} + +// Records the row the statement is on; returns 1 if a ROW event was added, 0 if not (the byte limit +// is below a row header, or an allocation failed). Each column is read with the accessor of its own +// type, so nothing is converted and the app's later sqlite3_column_type and values are unchanged. +static int record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number, uint64_t exec_id) { + uint32_t max_value = __atomic_load_n(&g_max_value, __ATOMIC_RELAXED); + size_t budget = __atomic_load_n(&g_max_row, __ATOMIC_RELAXED); + // A record must fit beside a pad in the ring (see sqlitedbg_install). + size_t ring_max = g_cap / 2 > RECORD_HEADER_BYTES ? g_cap / 2 - RECORD_HEADER_BYTES : 0; + if (budget > ring_max) budget = ring_max; + if (budget < ROW_HEADER_BYTES) return 0; + unsigned char *data = (unsigned char *)malloc(budget); + if (!data) return 0; + int columns = sqlite3_column_count(stmt); + size_t len = ROW_HEADER_BYTES; + uint32_t kept = 0; + uint32_t flags = 0; + for (int i = 0; i < columns; i++) { + if (budget - len < ROW_VALUE_BYTES) break; + size_t room = budget - len - ROW_VALUE_BYTES; + int type = sqlite3_column_type(stmt, i); + unsigned char *v = data + len; + if (type == SQLITE_INTEGER || type == SQLITE_FLOAT) { + if (room < 8) break; + if (type == SQLITE_INTEGER) { + sqlite3_int64 n = sqlite3_column_int64(stmt, i); + memcpy(v + ROW_VALUE_BYTES, &n, 8); + } else { + double d = sqlite3_column_double(stmt, i); + memcpy(v + ROW_VALUE_BYTES, &d, 8); + } + len += put_value(v, (uint8_t)type, 0, 8, 8) + 8; + } else if (type == SQLITE_TEXT || type == SQLITE_BLOB) { + // The size first: in a UTF-8 database sqlite3_column_bytes does not copy a stored value, and it + // is how a huge one is recognised before anything reads it (see ROW_READ_MAX_BYTES). In a + // UTF-16 database it converts a whole TEXT value to UTF-8 first (a transient copy and the time + // to make it, whatever the guard), which this does not avoid yet. The pointer accessor then + // asks for the type the value already has, so nothing more is converted. + size_t full = (size_t)sqlite3_column_bytes(stmt, i); + size_t limit = room < max_value ? room : max_value; + const void *p = NULL; + if (full <= limit || full <= ROW_READ_MAX_BYTES) + p = type == SQLITE_TEXT ? (const void *)sqlite3_column_text(stmt, i) : sqlite3_column_blob(stmt, i); + // p is NULL for a value left unread and when SQLite is out of memory; utf8_cut would read through it. + size_t stored = !p ? 0 : type == SQLITE_TEXT ? utf8_cut((const char *)p, full, limit) : (full < limit ? full : limit); + uint8_t cut = stored < full; + if (cut) flags |= SQLITEDBG_EVENT_TRUNCATED; + if (stored) memcpy(v + ROW_VALUE_BYTES, p, stored); + len += put_value(v, (uint8_t)type, cut, (uint32_t)stored, (uint32_t)full) + stored; + } else { + len += put_value(v, SQLITE_NULL, 0, 0, 0); + } + kept++; + } + if (kept < (uint32_t)columns) flags |= SQLITEDBG_EVENT_TRUNCATED; + sqlitedbg_row_header h = {(uint32_t)columns, kept}; + memcpy(data, &h, sizeof h); + add_record(SQLITEDBG_EVENT_ROW, cs->id, -1, number, -1, flags, data, len, exec_id); + free(data); + return 1; +} + +// Whether sql starts with INSERT, UPDATE, DELETE or REPLACE (a leading WITH counts), after whitespace and +// comments: the statements that set sqlite3_changes64. +static int is_dml_sql(const char *sql) { + if (!sql) return 0; + for (;;) { + while (*sql == ' ' || *sql == '\t' || *sql == '\n' || *sql == '\r' || *sql == '\f') sql++; + if (sql[0] == '-' && sql[1] == '-') { + while (*sql && *sql != '\n') sql++; + } else if (sql[0] == '/' && sql[1] == '*') { + sql += 2; + while (*sql && !(sql[0] == '*' && sql[1] == '/')) sql++; + if (*sql) sql += 2; + } else { + break; + } + } + static const char *const words[] = {"INSERT", "UPDATE", "DELETE", "REPLACE", "WITH"}; + for (size_t i = 0; i < sizeof words / sizeof words[0]; i++) { + size_t n = strlen(words[i]); + if (!strncasecmp(sql, words[i], n) && !isalnum((unsigned char)sql[n]) && sql[n] != '_') return 1; + } + return 0; } // sqlite3_trace_v2 callback. C is the connection's conn_state, which lives until SQLite frees the @@ -193,16 +362,113 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { flags |= SQLITEDBG_EVENT_EXPANDED; } } + if (is_stmt && is_trigger && !strncmp(sql, "-- TRIGGER ", 11)) cs->trigger_owner = stmt; int64_t duration = is_stmt ? -1 : *(sqlite3_int64 *)x; - add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, flags, sql, - strlen(sql)); + int64_t rows = -1, changes = -1; + uint64_t exec_id = 0; + stmt_slot *claimed = NULL; + if (is_stmt) { + // A trigger's statements are traced with "-- " text and P the outer statement, so they get no + // slot. A schema read sends no STATEMENT at all, and an app statement run inside a callback is + // handled below. + const char *own = sqlite3_sql(stmt); + // A statement the app runs inside a callback is traced as "-- " + its own text, with P the + // statement itself: it claims no slot, and one left at this address is not its. Not so for a + // step of the running statement's own trigger, whose text may equal the statement's: P is + // then the running statement, and its live slot stays. + if (own && stmt != cs->trigger_owner && !strncmp(sql, "-- ", 3) && !strcmp(sql + 3, own)) { + stmt_slot *old = find_slot(cs, stmt); + if (old) memset(old, 0, sizeof *old); + } + if (!is_trigger) { + if (cs->trigger_owner == stmt) cs->trigger_owner = NULL; + claimed = claim_slot(cs, stmt); + claimed->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); + } + } else { + if (cs->trigger_owner == stmt) cs->trigger_owner = NULL; + stmt_slot *slot = find_slot(cs, stmt); + // An EXPLAIN is traced with no STATEMENT: a slot at its address is another statement's. + if (slot && sqlite3_stmt_isexplain(stmt)) { + memset(slot, 0, sizeof *slot); + slot = NULL; + } + // A slot that ended is this run's again only if SQLite re-prepared the statement since. + if (slot && slot->ended) { + if (sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0) > slot->reprepares) { + slot->ended = 0; + } else { + memset(slot, 0, sizeof *slot); + slot = NULL; + } + } + // Still busy: the statement did not finish, because it was reset or finalized before its + // last step, or its step returned SQLITE_BUSY. + int unfinished = sqlite3_stmt_busy(stmt); + if (slot) { + rows = slot->rows; + exec_id = slot->exec_id; + if (slot->rows_cut) flags |= SQLITEDBG_EVENT_ROWS_CUT; + if (!sqlite3_stmt_readonly(stmt)) { + // sqlite3_changes64 is this statement's count once it has run, but only INSERT, UPDATE + // and DELETE set it: after a CREATE TABLE it still holds the last write's. A total that + // did not move means the statement changed nothing. If it moved and the statement is not + // one of those (a PRAGMA stepped across another statement's INSERT), the count is + // another statement's: unknown. + sqlite3 *db = sqlite3_db_handle(stmt); + // A statement stopped part way (an INSERT ... RETURNING stepped once) has made only part + // of its changes, or all of them without sqlite3_changes64 knowing: unknown. + if (unfinished) changes = -1; + else if (sqlite3_total_changes64(db) == slot->total_changes) changes = 0; + else changes = is_dml_sql(sqlite3_sql(stmt)) ? sqlite3_changes64(db) : -1; + } + // A step that returned SQLITE_BUSY before any row also ends in this event, and SQLite + // fires no other for the execution that resumes when the lock is free: keep the slot, so + // its rows are still counted and recorded. A statement that went on to finish leaves it + // until the statement starts again (claim_slot reuses it) or is evicted. + // With no rows and not busy it may still be rerun after SQLITE_SCHEMA, with no STATEMENT: + // the slot is kept, marked ended. + if (slot->rows > 0) memset(slot, 0, sizeof *slot); + else if (!unfinished) slot->ended = 1; + } + } + uint32_t kind = is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE; + uint64_t seq = add_event(kind, cs->id, duration, rows, changes, flags, sql, strlen(sql), + claimed ? EXEC_SELF : exec_id); + if (claimed) claimed->exec_id = seq; if (expanded) sqlite3_free(expanded); break; } + case SQLITE_TRACE_ROW: { + sqlite3_stmt *stmt = (sqlite3_stmt *)p; + // A schema read (sqlite3_sql NULL) sends only ROW traces: no slot is theirs. + if (!sqlite3_sql(stmt)) break; + stmt_slot *slot = find_slot(cs, stmt); + if (!slot) break; + if (slot->ended) { + if (sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0) <= slot->reprepares) { + memset(slot, 0, sizeof *slot); + break; + } + slot->ended = 0; + } + slot->rows++; + slot->last_use = ++cs->use_clock; + uint32_t max_rows = __atomic_load_n(&g_max_rows, __ATOMIC_RELAXED); + if (!max_rows || !__atomic_load_n(&g_client_connected, __ATOMIC_RELAXED)) break; + if (slot->recorded >= max_rows) { + slot->rows_cut = 1; + break; + } + // Counted only if a ROW event was added; otherwise the cut is flagged, as for the limit. + if (record_row(cs, stmt, slot->rows, slot->exec_id)) slot->recorded++; + else slot->rows_cut = 1; + break; + } case SQLITE_TRACE_CLOSE: // The close can still fail or leave a zombie, so only mark it: xDestroy frees. __atomic_store_n(&cs->closing, 1, __ATOMIC_RELAXED); - add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, 0, "", 0); + add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, -1, -1, 0, "", 0, 0); break; } return 0; @@ -230,6 +496,8 @@ static void connection_id_fn(sqlite3_context *ctx, int argc, sqlite3_value **arg #ifdef SQLITEDBG_TEST // Host tests: 1 fails the allocation, 2 makes registering the function fail. int sqlitedbg_test_fail_init; +// Host tests: the row limit in force, since the tests' 8 KiB buffer caps a row before it would. +uint32_t sqlitedbg_test_max_row_bytes(void) { return __atomic_load_n(&g_max_row, __ATOMIC_RELAXED); } #endif static int init_connection(sqlite3 *db, const sqlite3_api_routines *api); @@ -287,7 +555,8 @@ static int init_connection(sqlite3 *db, const sqlite3_api_routines *api) { int rc = sqlite3_create_function_v2(db, fn_name, 0, SQLITE_UTF8 | SQLITE_INNOCUOUS, cs, connection_id_fn, NULL, NULL, conn_destroy); if (rc != SQLITE_OK) return rc; - return sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_CLOSE, trace_cb, cs); + return sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_ROW | SQLITE_TRACE_CLOSE, + trace_cb, cs); } int sqlitedbg_install(sqlitedbg_auto_extension_fn auto_extension, const sqlitedbg_config *config) { @@ -391,6 +660,13 @@ void sqlitedbg_set_client_connected(int connected) { __atomic_store_n(&g_client_connected, connected ? 1 : 0, __ATOMIC_RELAXED); } +void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes, uint32_t max_row_bytes) { + __atomic_store_n(&g_max_value, max_value_bytes ? max_value_bytes : DEFAULT_MAX_VALUE_BYTES, __ATOMIC_RELAXED); + uint32_t row = max_row_bytes ? max_row_bytes : DEFAULT_MAX_ROW_BYTES; + __atomic_store_n(&g_max_row, row < SQLITEDBG_MAX_ROW_BYTES ? row : SQLITEDBG_MAX_ROW_BYTES, __ATOMIC_RELAXED); + __atomic_store_n(&g_max_rows, max_rows_per_statement, __ATOMIC_RELAXED); +} + // The user data of a writable server connection's authorizer; a read-only one gets NULL. static const int k_writable = 1; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index cba3407c72..faee6f1bd0 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -23,7 +23,8 @@ extern "C" { #endif // The interface version. Raise it when anything below changes shape. -#define SQLITEDBG_INTERFACE_VERSION 2 +// 4: the event record has execution_id (72 to 80 bytes). +#define SQLITEDBG_INTERFACE_VERSION 4 // sqlite3_auto_extension's type. On a device the JNI layer looks it up in libsqlite3x.so with // dlsym (requery exports every sqlite3_ function); host tests pass SQLite's own. @@ -85,31 +86,84 @@ enum { SQLITEDBG_EVENT_PROFILE = 2, // The app asked SQLite to close the connection (SQLITE_TRACE_CLOSE); sql is empty. SQLITEDBG_EVENT_CLOSE = 3, + // A statement returned a row (SQLITE_TRACE_ROW). Recorded only while a client is connected and + // row recording is on (sqlitedbg_set_row_capture); the data is the row's values, in the row + // layout below, not SQL. rows is the row's number in its statement, from 1. + SQLITEDBG_EVENT_ROW = 4, }; enum { - // sql was cut at max_sql_bytes. + // The data was cut: SQL at max_sql_bytes, or a row's values at the row limits. SQLITEDBG_EVENT_TRUNCATED = 1u << 0, // sql has its bound values written in (sqlite3_expanded_sql). Only while a client is // connected (sqlitedbg_set_client_connected): expanding a 1 MB value costs 2 MB on every run. SQLITEDBG_EVENT_EXPANDED = 1u << 1, + // SQLITEDBG_EVENT_PROFILE only: rows were left unrecorded while row recording was on, because the + // statement returned more than the per-statement limit, or because the producer could not record + // a row (the byte budget is below a row header, or an allocation failed). + SQLITEDBG_EVENT_ROWS_CUT = 1u << 2, }; -// One event as sqlitedbg_read_events copies it out: this header, then sql_bytes of UTF-8 (no -// terminating NUL), then zero padding to a multiple of 8 bytes. Fields are in the CPU's byte order +// One event as sqlitedbg_read_events copies it out: this header, then data_bytes of data, then zero +// padding to a multiple of 8 bytes. The data is UTF-8 SQL (no terminating NUL) for every kind but +// SQLITEDBG_EVENT_ROW, whose data is its values (below). Fields are in the CPU's byte order // (little-endian on every ABI we build). The JNI layer hands the bytes to Kotlin unchanged, so // EventDecoder.kt mirrors this layout; change both together. typedef struct sqlitedbg_event_record { uint32_t record_bytes; // the whole record, padding included - uint32_t kind; // SQLITEDBG_EVENT_STATEMENT, _PROFILE or _CLOSE + uint32_t kind; // SQLITEDBG_EVENT_STATEMENT, _PROFILE, _CLOSE or _ROW uint64_t seq; // 1, 2, 3...: every event made, dropped or not, gets the next one uint64_t connection_id; // sqlitedbg_connection.id int64_t thread_id; // gettid() of the thread running the statement int64_t time_ns; // CLOCK_REALTIME when the event happened int64_t duration_ns; // SQLITEDBG_EVENT_PROFILE only; -1 for the others - uint32_t flags; // SQLITEDBG_EVENT_TRUNCATED, SQLITEDBG_EVENT_EXPANDED - uint32_t sql_bytes; -} sqlitedbg_event_record; // 56 bytes; the SQL text follows + uint32_t flags; // SQLITEDBG_EVENT_TRUNCATED, _EXPANDED, _ROWS_CUT + uint32_t data_bytes; + // SQLITEDBG_EVENT_PROFILE: the rows the statement returned, whether or not they were recorded. + // SQLITEDBG_EVENT_ROW: this row's number, from 1. -1 otherwise, and -1 for a statement the + // extension did not see start (SQLite's own nested statements, or more than + // SQLITEDBG_STATEMENT_SLOTS statements stepped in turn on one connection). + int64_t rows; + // SQLITEDBG_EVENT_PROFILE of a statement that may write (sqlite3_stmt_readonly false): the rows + // it changed itself, as sqlite3_changes64 counts them (not those changed by triggers or foreign + // key actions); 0 when it changed none, as a CREATE TABLE. -1 (unknown) for a read-only + // statement, for the other kinds, when rows is -1, and when the statement had not finished when + // the event fired (reset or finalized part way, as an INSERT ... RETURNING stepped once, or a step + // that returned SQLITE_BUSY): its count is then partial or not yet set. Also -1 when the + // connection's total changed while the statement ran and it is not an INSERT, UPDATE, DELETE or + // REPLACE (a leading WITH counts), as a PRAGMA stepped across another statement's INSERT: the + // count sqlite3_changes64 holds is then that statement's. + int64_t changes; + // The run of a statement this event belongs to: the seq of its STATEMENT record, on that record + // and on the PROFILE and ROW records of the run. 0: none or unknown (a trigger's STATEMENT, a + // statement nested in a callback, an EXPLAIN, a CLOSE, or a statement the extension did not see + // start). A statement evicted from its slot keeps its id on its STATEMENT and on the ROW events + // recorded before the eviction; its later rows are not recorded, and its PROFILE has 0. Not contiguous, + // and restarting with the process like seq. + uint64_t execution_id; +} sqlitedbg_event_record; // 80 bytes; the data follows + +// How many statements per connection the extension follows at once, to number their rows and count +// their changes. A connection that steps more statements in turn than this loses the oldest: +// its rows are not recorded and its PROFILE event has rows and changes -1. +#define SQLITEDBG_STATEMENT_SLOTS 16 + +// The data of an SQLITEDBG_EVENT_ROW: this header, then `kept` values, each a sqlitedbg_row_value +// followed by stored_bytes of value. Nothing is aligned: read each field with memcpy. +typedef struct sqlitedbg_row_header { + uint32_t columns; // sqlite3_column_count of the statement + uint32_t kept; // values that follow; fewer than columns when the row limit was reached +} sqlitedbg_row_header; // 8 bytes + +typedef struct sqlitedbg_row_value { + uint8_t type; // SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB or SQLITE_NULL + uint8_t cut; // 1 if fewer than full_bytes were stored + uint16_t reserved; // 0 + uint32_t stored_bytes; // bytes that follow: 8 for INTEGER (int64) and FLOAT (IEEE double), + // 0 for NULL, UTF-8 for TEXT (cut at a character boundary), BLOB bytes + uint32_t full_bytes; // the value's whole size (sqlite3_column_bytes for TEXT and BLOB) + // A value over 1 MiB that does not fit the limits is not read: stored_bytes 0, cut 1. +} sqlitedbg_row_value; // 12 bytes typedef struct sqlitedbg_read_result { // The seq of the last event copied out, or if none was, `after` moved past any dropped events @@ -137,9 +191,27 @@ typedef struct sqlitedbg_read_result { void sqlitedbg_read_events(uint64_t after, void *out, size_t out_bytes, sqlitedbg_read_result *result); // Whether a client is connected. While it is, statements are recorded with their bound values -// written in. Off at install. +// written in, and rows if row recording is on. Off at install. void sqlitedbg_set_client_connected(int connected); +// Turns row recording on (max_rows_per_statement > 0) or off (0, as at install). While it is on and +// a client is connected, the first max_rows_per_statement rows of each statement become +// SQLITEDBG_EVENT_ROW events. TEXT and BLOB values longer than max_value_bytes are cut (0: 256), and +// a row's data stops at max_row_bytes (0: 4 KiB; at most SQLITEDBG_MAX_ROW_BYTES; never more than +// half the buffer less one header). +// Each value is read with the accessor of its own type (sqlite3_column_type first), so the app sees +// the same values and types afterwards: sqlite3_column_text converts a value in place, and on a BLOB +// it makes the app's own sqlite3_column_type return SQLITE_TEXT (SQLite 3.49.1, sqlitedbg_test.c). Rows of statements the extension did +// not see start are never recorded: that drops the rows of SQLite's own nested statements, such as +// the schema read a CREATE TABLE runs. PROFILE events count rows whether or not this is on. +void sqlitedbg_set_row_capture(uint32_t max_rows_per_statement, uint32_t max_value_bytes, + uint32_t max_row_bytes); + +// The largest max_row_bytes that sqlitedbg_set_row_capture keeps; a larger one is lowered to it. +// sqlitedbg_read_events stops at the first record that does not fit its buffer, so a row record must +// stay well below the 256 KiB the server reads at a time (DatabaseTools.EVENT_BATCH_BYTES). +#define SQLITEDBG_MAX_ROW_BYTES (64u * 1024u) + // Server connections #define SQLITEDBG_SERVER_BUSY_MS 3000 diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index f2f1b1e7c4..e5ab68d7bf 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -167,6 +167,13 @@ static void bridge_set_client_connected(JNIEnv *env, jclass cls, jboolean connec sqlitedbg_set_client_connected(connected ? 1 : 0); } +static void bridge_set_row_capture(JNIEnv *env, jclass cls, jint max_rows, jint max_value_bytes, jint max_row_bytes) { + (void)env; + (void)cls; + sqlitedbg_set_row_capture(max_rows > 0 ? (uint32_t)max_rows : 0, max_value_bytes > 0 ? (uint32_t)max_value_bytes : 0, + max_row_bytes > 0 ? (uint32_t)max_row_bytes : 0); +} + // server connections static jlong bridge_open_server(JNIEnv *env, jclass cls, jbyteArray path, jboolean writable) { @@ -266,49 +273,166 @@ static int busy_cb(void *p, int count) { return 1; } -// Binds args[i] to parameter i + 1. Returns SQLITE_OK or a code with *message set. -static int bind_args(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { +// Binds v (null, Long, Double, String or byte[]) to parameter idx (from 1). +static int bind_value(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, int idx, jobject v, const char **message) { + int rc; + if (!v) { + rc = sqlite3_bind_null(st, idx); + } else if ((*env)->IsInstanceOf(env, v, g_long)) { + jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); + rc = sqlite3_bind_int64(st, idx, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_double)) { + jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); + rc = sqlite3_bind_double(st, idx, (*env)->CallDoubleMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_string)) { + jsize len = (*env)->GetStringLength(env, (jstring)v); + const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); + if (!chars) return SQLITE_NOMEM; + rc = sqlite3_bind_text16(st, idx, chars, len * 2, SQLITE_TRANSIENT); + (*env)->ReleaseStringChars(env, (jstring)v, chars); + } else { + jclass bytes_class = (*env)->FindClass(env, "[B"); + int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); + if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); + if (!is_bytes) { + *message = "unsupported argument type"; + return SQLITE_MISUSE; + } + jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); + void *copy = malloc(len ? (size_t)len : 1); + if (!copy) return SQLITE_NOMEM; + (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); + rc = sqlite3_bind_blob64(st, idx, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); + free(copy); + } + if (rc != SQLITE_OK) { + *message = sqlite3_errmsg(db); + return rc; + } + return (*env)->ExceptionCheck(env) ? SQLITE_ERROR : SQLITE_OK; +} + +// Binds args by position, ? and ?NNN alike: args[i] to parameter i + 1. Their number must be the +// statement's parameter count: a missing one would be bound as NULL and the query would run, +// returning a plausible empty result. +static int bind_positional(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { + int wanted = sqlite3_bind_parameter_count(st); jsize count = (*env)->GetArrayLength(env, args); + if (count != wanted) { + char msg[96]; + snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)count); + throw_engine(env, SQLITE_RANGE, msg); + return SQLITE_RANGE; + } for (jsize i = 0; i < count; i++) { jobject v = (*env)->GetObjectArrayElement(env, args, i); - int rc; - if (!v) { - rc = sqlite3_bind_null(st, i + 1); - } else if ((*env)->IsInstanceOf(env, v, g_long)) { - jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); - rc = sqlite3_bind_int64(st, i + 1, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); - } else if ((*env)->IsInstanceOf(env, v, g_double)) { - jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); - rc = sqlite3_bind_double(st, i + 1, (*env)->CallDoubleMethod(env, v, m)); - } else if ((*env)->IsInstanceOf(env, v, g_string)) { - jsize len = (*env)->GetStringLength(env, (jstring)v); - const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); - if (!chars) return SQLITE_NOMEM; - rc = sqlite3_bind_text16(st, i + 1, chars, len * 2, SQLITE_TRANSIENT); - (*env)->ReleaseStringChars(env, (jstring)v, chars); - } else { - jclass bytes_class = (*env)->FindClass(env, "[B"); - int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); - if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); - if (!is_bytes) { - *message = "unsupported argument type"; - return SQLITE_MISUSE; + int rc = bind_value(env, db, st, i + 1, v, message); + if (v) (*env)->DeleteLocalRef(env, v); + if (rc != SQLITE_OK) return rc; + } + return SQLITE_OK; +} + +typedef struct { + char *name; // UTF-8, not terminated + size_t len; + int used; +} bind_key; + +// Whether SQLite's parameter name (":id", "@id", "$id" or "?3") is key: written the same, or key +// without the prefix (":", "@" or "$"). +static int key_matches(const char *param, const bind_key *key) { + size_t plen = strlen(param); + if (plen == key->len && memcmp(param, key->name, plen) == 0) return 1; + if (key->len == 0 || strchr(":@$?", key->name[0])) return 0; + return strchr(":@$", param[0]) && plen - 1 == key->len && memcmp(param + 1, key->name, key->len) == 0; +} + +// Binds args by name: names[i] (UTF-8) names the parameter args[i] goes to. Every parameter must +// get exactly one value and every name must be used, so a misspelt name fails instead of leaving a +// NULL. The error names a name that matches no parameter even when a parameter also has no value, +// since that name is most likely the parameter's, misspelt. +static int bind_named(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, jobjectArray names, + const char **message) { + jsize n = (*env)->GetArrayLength(env, names); + if ((*env)->GetArrayLength(env, args) != n) { + *message = "names and args differ in length"; + return SQLITE_MISUSE; + } + bind_key *keys = calloc(n ? (size_t)n : 1, sizeof *keys); + if (!keys) return SQLITE_NOMEM; + int rc = SQLITE_OK; + char msg[320]; + const char *missing = NULL; // the first parameter with no value; SQLite owns the string + for (jsize i = 0; i < n && rc == SQLITE_OK; i++) { + jbyteArray b = (jbyteArray)(*env)->GetObjectArrayElement(env, names, i); + if (!b) { + *message = "a parameter name is null"; + rc = SQLITE_MISUSE; + break; + } + jsize len = (*env)->GetArrayLength(env, b); + keys[i].name = malloc(len ? (size_t)len : 1); + if (!keys[i].name) rc = SQLITE_NOMEM; + else { + (*env)->GetByteArrayRegion(env, b, 0, len, (jbyte *)keys[i].name); + keys[i].len = (size_t)len; + } + (*env)->DeleteLocalRef(env, b); + } + int count = sqlite3_bind_parameter_count(st); + for (int p = 1; p <= count && rc == SQLITE_OK; p++) { + const char *param = sqlite3_bind_parameter_name(st, p); + if (!param) { + snprintf(msg, sizeof msg, + "parameter %d has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", p); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; + } + jsize found = -1; + for (jsize i = 0; i < n; i++) { + if (!key_matches(param, &keys[i])) continue; + if (found >= 0) { + snprintf(msg, sizeof msg, "parameter %.100s is given more than once", param); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; } - jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); - void *copy = malloc(len ? (size_t)len : 1); - if (!copy) return SQLITE_NOMEM; - (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); - rc = sqlite3_bind_blob64(st, i + 1, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); - free(copy); + found = i; + } + if (rc != SQLITE_OK) break; + if (found < 0) { + if (!missing) missing = param; + continue; } + keys[found].used = 1; + jobject v = (*env)->GetObjectArrayElement(env, args, found); + rc = bind_value(env, db, st, p, v, message); if (v) (*env)->DeleteLocalRef(env, v); - if (rc != SQLITE_OK) { - *message = sqlite3_errmsg(db); - return rc; + } + jsize unused = -1; + for (jsize i = 0; i < n && unused < 0; i++) { + if (!keys[i].used) unused = i; + } + if (rc == SQLITE_OK && unused >= 0) { + int shown = keys[unused].len > 100 ? 100 : (int)keys[unused].len; + if (missing) { + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s, and no value was given for parameter %.100s", + shown, keys[unused].name, missing); + } else { + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s", shown, keys[unused].name); } - if ((*env)->ExceptionCheck(env)) return SQLITE_ERROR; + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + } else if (rc == SQLITE_OK && missing) { + snprintf(msg, sizeof msg, "no value was given for parameter %.100s", missing); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; } - return SQLITE_OK; + for (jsize i = 0; i < n; i++) free(keys[i].name); + free(keys); + return rc; } // A UTF-8 prefix of at most max bytes ending on a character boundary. @@ -352,7 +476,8 @@ static int prepare_one(sqlite3 *db, const jchar *sql, jsize len, sqlite3_stmt ** // Prepares sql (one statement, see prepare_one) and binds args to it. Returns 1 with *st set, or 0 // with an exception pending and *st NULL. -static int prepare_bound(JNIEnv *env, sqlite3 *db, jstring sql, jobjectArray args, sqlite3_stmt **st) { +static int prepare_bound(JNIEnv *env, sqlite3 *db, jstring sql, jobjectArray args, jobjectArray names, + sqlite3_stmt **st) { *st = NULL; const char *message = NULL; jsize sql_len = (*env)->GetStringLength(env, sql); @@ -364,17 +489,10 @@ static int prepare_bound(JNIEnv *env, sqlite3 *db, jstring sql, jobjectArray arg throw_engine(env, rc, message ? message : sqlite3_errmsg(db)); return 0; } - // A missing argument would be bound as NULL and the statement would run, with a plausible result. - int wanted = sqlite3_bind_parameter_count(*st); - jsize given = (*env)->GetArrayLength(env, args); - if (given != wanted) { - char msg[96]; - snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)given); - throw_engine(env, SQLITE_RANGE, msg); - } else { - rc = bind_args(env, db, *st, args, &message); - if (rc != SQLITE_OK && !(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); - } + // Both check that every parameter gets a value: a missing one would be bound as NULL and the statement + // would run, with a plausible result. + rc = names ? bind_named(env, db, *st, args, names, &message) : bind_positional(env, db, *st, args, &message); + if (rc != SQLITE_OK && !(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); if ((*env)->ExceptionCheck(env)) { sqlite3_finalize(*st); *st = NULL; @@ -439,59 +557,83 @@ static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, } } -static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong offset, - jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { - (void)cls; - sqlite3 *db = (sqlite3 *)(intptr_t)handle; - sqlite3_stmt *st = NULL; +// Steps st, skipping offset rows, and collects at most max_rows rows within max_total bytes of cells (the +// first row always goes in, so a page makes progress), each TEXT and BLOB cut at max_text and max_blob. +// Returns [columns, rows, counts, decltypes] as NativeBridge.query describes, with *rc the last +// sqlite3_step result and *has_more set when rows were left unread. When *has_more is 0 and *rc is not +// SQLITE_DONE the statement failed: the caller reports it and drops the result. NULL with an exception +// pending when a JNI allocation failed. +#ifdef SQLITEDBG_TEST +enum { TEST_FAIL_NONE, TEST_FAIL_NAMES, TEST_FAIL_ROW, TEST_FAIL_RESULT }; +// Host tests: a column named sqlitedbg_test_oom_names, _row or _result makes read_rows fail as a JNI +// allocation would: before the first step, at the first row it keeps, or after the last step. +static int test_fail_point(sqlite3_stmt *st) { + static const char *const names[] = {"sqlitedbg_test_oom_names", "sqlitedbg_test_oom_row", + "sqlitedbg_test_oom_result"}; + for (int c = 0; c < sqlite3_column_count(st); c++) { + const char *name = sqlite3_column_name(st, c); + for (int i = 0; name && i < 3; i++) + if (strcmp(name, names[i]) == 0) return i + 1; + } + return TEST_FAIL_NONE; +} +#define TEST_FAILS_AT(point) (fail_at == (point)) +#else +#define TEST_FAILS_AT(point) 0 +#endif + +static jobjectArray read_rows(JNIEnv *env, sqlite3_stmt *st, jlong offset, jint max_rows, jint max_text, jint max_blob, + jint max_total, int *rc, int *has_more) { jobjectArray result = NULL; jlong *cut_cells = NULL; // row * columns + column of each cut cell size_t cut_n = 0, cut_cap = 0; - deadline dl = {.db = db, .at_ms = (int64_t)deadline_ms}; - int handler_set = 0; - int rc; - - if (now_ms() >= dl.at_ms) { - throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); - goto done; + *rc = SQLITE_OK; + *has_more = 0; +#ifdef SQLITEDBG_TEST + int fail_at = test_fail_point(st); + if (TEST_FAILS_AT(TEST_FAIL_NAMES)) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return NULL; } - if (!prepare_bound(env, db, sql, args, &st)) goto done; - - // 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. - // The cap starts once the read holds its lock (start_cap_once_locked). - if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < dl.at_ms && !is_wal_mode(db)) dl.cap_ms = SQLITEDBG_SERVER_NON_WAL_MS; - - // 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`. - sqlite3_progress_handler(db, 1000, progress_cb, &dl); - handler_set = 1; +#endif int ncols = sqlite3_column_count(st); - jobjectArray names = (*env)->NewObjectArray(env, ncols, g_string, NULL); - jobject rows = names ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; + jobjectArray columns = (*env)->NewObjectArray(env, ncols, g_string, NULL); + // The declared type of each column, null for an expression (sqlite3_column_decltype) + jobjectArray decltypes = columns ? (*env)->NewObjectArray(env, ncols, g_string, NULL) : NULL; + jobject rows = decltypes ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; if (!rows) goto done; for (int c = 0; c < ncols; c++) { const char *name = sqlite3_column_name(st, c); jstring s = utf8_string(env, name ? name : "", name ? (int)strlen(name) : 0); if (!s) goto done; - (*env)->SetObjectArrayElement(env, names, c, s); + (*env)->SetObjectArrayElement(env, columns, c, s); (*env)->DeleteLocalRef(env, s); + const char *decl = sqlite3_column_decltype(st, c); + if (decl) { + jstring d = utf8_string(env, decl, (int)strlen(decl)); + if (!d) goto done; + (*env)->SetObjectArrayElement(env, decltypes, c, d); + (*env)->DeleteLocalRef(env, d); + } } - int has_more = 0, row_count = 0; + int row_count = 0; int64_t total = 0; jlong skipped = 0; - while ((rc = sqlite3_step(st)) == SQLITE_ROW) { + while ((*rc = sqlite3_step(st)) == SQLITE_ROW) { if (skipped < offset) { skipped++; continue; } if (row_count >= max_rows) { - has_more = 1; + *has_more = 1; break; } + if (TEST_FAILS_AT(TEST_FAIL_ROW)) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + goto done; + } jobjectArray row = (*env)->NewObjectArray(env, ncols, g_object, NULL); if (!row) goto done; int64_t row_bytes = 0; @@ -518,12 +660,11 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring (*env)->DeleteLocalRef(env, cell); } } - // The total bounds the host app's heap. The first row always goes in, so a page makes - // progress; one row is bounded by the per-cell limits. + // The total bounds the host app's heap. One row is bounded by the per-cell limits. if (row_count > 0 && total + row_bytes > max_total) { (*env)->DeleteLocalRef(env, row); cut_n = cut_before; - has_more = 1; + *has_more = 1; break; } total += row_bytes; @@ -532,7 +673,59 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring if ((*env)->ExceptionCheck(env)) goto done; row_count++; } - if (!has_more && rc != SQLITE_DONE) { + + if (TEST_FAILS_AT(TEST_FAIL_RESULT)) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + goto done; + } + // {cut cell count, hasMore, then the index of each cut cell} + jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); + result = counts ? (*env)->NewObjectArray(env, 4, g_object, NULL) : NULL; + if (!result) goto done; + jlong head[2] = {(jlong)cut_n, *has_more}; + (*env)->SetLongArrayRegion(env, counts, 0, 2, head); + if (cut_n) (*env)->SetLongArrayRegion(env, counts, 2, (jsize)cut_n, cut_cells); + (*env)->SetObjectArrayElement(env, result, 0, columns); + (*env)->SetObjectArrayElement(env, result, 1, rows); + (*env)->SetObjectArrayElement(env, result, 2, counts); + (*env)->SetObjectArrayElement(env, result, 3, decltypes); + +done: + free(cut_cells); + return result; +} + +static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jlong offset, + jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { + (void)cls; + sqlite3 *db = (sqlite3 *)(intptr_t)handle; + sqlite3_stmt *st = NULL; + jobjectArray result = NULL; + deadline dl = {.db = db, .at_ms = (int64_t)deadline_ms}; + int handler_set = 0; + int rc, has_more; + + if (now_ms() >= dl.at_ms) { + throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); + goto done; + } + if (!prepare_bound(env, db, sql, args, names, &st)) goto done; + + // 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. + // The cap starts once the read holds its lock (start_cap_once_locked). + if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < dl.at_ms && !is_wal_mode(db)) dl.cap_ms = SQLITEDBG_SERVER_NON_WAL_MS; + + // 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`. + sqlite3_progress_handler(db, 1000, progress_cb, &dl); + handler_set = 1; + + result = read_rows(env, st, offset, max_rows, max_text, max_blob, max_total, &rc, &has_more); + if (result && !has_more && rc != SQLITE_DONE) { + result = NULL; if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { char msg[256]; snprintf(msg, sizeof msg, @@ -542,50 +735,108 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring throw_engine(env, SQLITE_INTERRUPT, msg); } else if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); else throw_engine(env, rc, sqlite3_errmsg(db)); - goto done; } - // {cut cell count, hasMore, then the index of each cut cell} - jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); - result = counts ? (*env)->NewObjectArray(env, 3, g_object, NULL) : NULL; - if (!result) goto done; - jlong head[2] = {(jlong)cut_n, has_more}; - (*env)->SetLongArrayRegion(env, counts, 0, 2, head); - if (cut_n) (*env)->SetLongArrayRegion(env, counts, 2, (jsize)cut_n, cut_cells); - (*env)->SetObjectArrayElement(env, result, 0, names); - (*env)->SetObjectArrayElement(env, result, 1, rows); - (*env)->SetObjectArrayElement(env, result, 2, counts); - done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); sqlite3_finalize(st); - free(cut_cells); if (!end_transaction_backstop(env, db)) result = NULL; return result; } -// Runs one statement that writes, to its end, on a writable server connection (ADFA-7298). Rows it -// returns (RETURNING) are read and dropped. Returns {changes, last_insert_rowid}: changes is the rows the -// statement itself inserted, updated or deleted (sqlite3_changes64), or 0 when it changed none, such as -// CREATE TABLE, which leaves sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). -// last_insert_rowid is the rowid of the last row the statement inserted into a rowid table, and INT64_MIN -// when it inserted none: SQLite never assigns that rowid itself, so only a row inserted explicitly with -// it reads as none (accepted), while 0 and other negative rowids are reported as they are. Inserts made -// by a trigger do not count: SQLite restores the value when the trigger ends. -static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong deadline_ms) { +// Reports a statement that the time limit or the cap stopped, as execute's error, and returns 1; returns 0 +// when rc is not that, for the caller to report. Used for a failed step and for a failed commit at reset. +static int throw_if_stopped(JNIEnv *env, const deadline *dl, int rc) { + // busy_cb giving up makes the step or the commit fail with SQLITE_BUSY; SQLite then rolls back + if (dl->busy_hit && rc == SQLITE_BUSY && dl->capped) { + char msg[320]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s and rolled back: it was waiting for another connection to finish " + "reading the database, and a write holds the database's write lock, so waiting longer would make the " + "app's own writes fail. Try it again", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl->hit && rc == SQLITE_INTERRUPT && dl->capped) { + char msg[256]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s and rolled back: a write holds the database's write lock, so a " + "longer one would make the app's own writes fail. Change fewer rows per call", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl->hit && (rc == SQLITE_INTERRUPT || rc == SQLITE_BUSY)) { + throw_engine(env, SQLITE_INTERRUPT, "the statement ran past its time limit"); + } else return 0; + return 1; +} + +// Whether SQLite rolled back a writing statement whose commit failed with rc: it does for a lock, a +// constraint, a full disk or an interrupt; after an I/O error or corruption it cannot say what reached the file. +static int commit_failure_rolled_back(int rc) { + int primary = rc & 0xff; + return primary == SQLITE_BUSY || primary == SQLITE_LOCKED || primary == SQLITE_CONSTRAINT || primary == SQLITE_FULL || + primary == SQLITE_INTERRUPT; +} + +// Replaces the exception pending from a failed allocation while execute built its result, for one that also +// says what became of the write, so a caller can tell whether a retry repeats it. The statement had run, and +// finalize (finalize_rc) commits what an unfinished one changed: execute runs only in autocommit, so a +// finalize that succeeds has committed it. The code stays SQLITE_NOMEM, so no caller takes finalize_rc (an +// interrupt, say) for the cause. The pending exception is kept when the replacement cannot be built. +static void report_unfinished_write(JNIEnv *env, int finalize_rc) { + char msg[256]; + if (finalize_rc == SQLITE_OK) + snprintf(msg, sizeof msg, + "out of memory while reading the rows the statement returned; the write was committed, so do not repeat it"); + else if (commit_failure_rolled_back(finalize_rc)) + snprintf(msg, sizeof msg, + "out of memory while reading the rows the statement returned; committing the write failed (%.100s), " + "and nothing it changed was kept", + sqlite3_errstr(finalize_rc)); + else + snprintf(msg, sizeof msg, + "out of memory while reading the rows the statement returned; finishing the write failed (%.100s), " + "so it may not have been committed", + sqlite3_errstr(finalize_rc)); + jthrowable pending = (*env)->ExceptionOccurred(env); + (*env)->ExceptionClear(env); + throw_engine(env, SQLITE_NOMEM, msg); + if (pending && !(*env)->ExceptionCheck(env)) (*env)->Throw(env, pending); +} + +// Runs one statement that writes on a writable server connection (ADFA-7298), and returns the rows it +// returns (RETURNING) as read_rows does, within the same limits (ADFA-7304): [columns, rows, counts, +// decltypes, {changes, last_insert_rowid}]. changes is the rows the statement itself inserted, updated or +// deleted (sqlite3_changes64), or 0 when it changed none, such as CREATE TABLE, which leaves +// sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). last_insert_rowid is the rowid +// of the last row the statement inserted into a rowid table, and INT64_MIN when it inserted none: SQLite +// never assigns that rowid itself, so only a row inserted explicitly with it reads as none (accepted), while +// 0 and other negative rowids are reported as they are. Inserts made by a trigger do not count: SQLite +// restores the value when the trigger ends. +// SQLite makes every change, and buffers every RETURNING row, in the first sqlite3_step (ADFA-7304 comment +// 41621). So a statement stopped at the row limit is reset, which commits all its changes and leaves +// changes counting every row written. A statement that fails at any step, even after rows came back, returns +// only the error. SQLite rolls it back whole, except that FAIL conflict resolution keeps the rows changed +// before the failing one, which the error then counts. +static jobjectArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jint max_rows, jint max_text, jint max_blob, jint max_total, + jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; sqlite3_stmt *st = NULL; - jlongArray result = NULL; + jobjectArray result = NULL; deadline dl = {.db = db, .at_ms = (int64_t)deadline_ms}; int handler_set = 0; - int rc; + int report_write_outcome = 0; // building the result failed with an exception pending: say what became of the write + int rc, has_more; if (now_ms() >= dl.at_ms) { throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the statement started"); goto done; } - if (!prepare_bound(env, db, sql, args, &st)) goto done; + // A transaction left open (a way past the authorizer, then a refused rollback) would hold this write + // uncommitted until the backstop below rolled it back, after the call reported it as written. + if (!end_transaction_backstop(env, db)) goto done; + if (!prepare_bound(env, db, sql, args, names, &st)) goto done; // Preparing can wait on the app's lock to read the schema. A short write would then run to its // commit before the progress handler's first callback, so check again before it starts. if (now_ms() >= dl.at_ms) { @@ -610,41 +861,71 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring // the connection is cached and keeps its value across statements: without this an UPDATE would // report the rowid of an earlier execute's INSERT. Not 0, SQLite's own "none": 0 is a valid rowid. sqlite3_set_last_insert_rowid(db, INT64_MIN); - while ((rc = sqlite3_step(st)) == SQLITE_ROW) {} - if (rc != SQLITE_DONE) { - // busy_cb giving up makes the step fail with SQLITE_BUSY; at the commit SQLite then rolls back - if (dl.busy_hit && rc == SQLITE_BUSY && dl.capped) { - char msg[320]; - snprintf(msg, sizeof msg, - "the statement was stopped after %.1f s and rolled back: it was waiting for another connection to finish " - "reading the database, and a write holds the database's write lock, so waiting longer would make the " - "app's own writes fail. Try it again", - SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); - throw_engine(env, SQLITE_INTERRUPT, msg); - } else if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { + jobjectArray rows = read_rows(env, st, 0, max_rows, max_text, max_blob, max_total, &rc, &has_more); + if (!rows) { + if (rc == SQLITE_OK || rc == SQLITE_ROW || rc == SQLITE_DONE) { + report_write_outcome = 1; + goto done; + } + // The statement failed before its result was built: that failure, and what SQLite kept of the + // write, are the outcome, not the allocation. + (*env)->ExceptionClear(env); + } + if (rows && has_more) { + // Commits every change, not only those of the rows read; the commit itself can fail. + rc = sqlite3_reset(st); + if (rc != SQLITE_OK) { + if (throw_if_stopped(env, &dl, rc)) goto done; + int rolled_back = commit_failure_rolled_back(rc); char msg[256]; - snprintf(msg, sizeof msg, - "the statement was stopped after %.1f s and rolled back: a write holds the database's write lock, so a " - "longer one would make the app's own writes fail. Change fewer rows per call", - SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); - throw_engine(env, SQLITE_INTERRUPT, msg); - } else if (dl.hit && (rc == SQLITE_INTERRUPT || rc == SQLITE_BUSY)) { - throw_engine(env, SQLITE_INTERRUPT, "the statement ran past its time limit"); + snprintf(msg, sizeof msg, "the statement could not be committed, and %s: %s", + rolled_back ? "nothing it changed was kept" : "what it changed may not have been kept", + sqlite3_errmsg(db)); + throw_engine(env, rc, msg); + goto done; + } + } else if (rc != SQLITE_DONE) { + if (throw_if_stopped(env, &dl, rc)) { + // reported + } else if (sqlite3_total_changes64(db) != total_before) { + // FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps, and in autocommit + // commits, the rows changed before the failing one; ABORT and ROLLBACK keep none, and leave the + // total where it was. + sqlite3_int64 kept = sqlite3_changes64(db); + char msg[512]; + snprintf(msg, sizeof msg, "%.300s. The %lld %s it changed before the failure %s kept: FAIL conflict resolution keeps them", + sqlite3_errmsg(db), (long long)kept, kept == 1 ? "row" : "rows", kept == 1 ? "was" : "were"); + throw_engine(env, rc, msg); } else throw_engine(env, rc, sqlite3_errmsg(db)); goto done; } jlong out[2]; out[0] = sqlite3_total_changes64(db) == total_before ? 0 : (jlong)sqlite3_changes64(db); out[1] = (jlong)sqlite3_last_insert_rowid(db); - result = (*env)->NewLongArray(env, 2); - if (result) (*env)->SetLongArrayRegion(env, result, 0, 2, out); + jlongArray counts = (*env)->NewLongArray(env, 2); + result = counts ? (*env)->NewObjectArray(env, 5, g_object, NULL) : NULL; + if (!result) { + report_write_outcome = 1; + goto done; + } + (*env)->SetLongArrayRegion(env, counts, 0, 2, out); + for (int i = 0; i < 4; i++) { + jobject part = (*env)->GetObjectArrayElement(env, rows, i); + (*env)->SetObjectArrayElement(env, result, i, part); + (*env)->DeleteLocalRef(env, part); + } + (*env)->SetObjectArrayElement(env, result, 4, counts); done: - if (handler_set) { - sqlite3_progress_handler(db, 0, NULL, NULL); - sqlite3_busy_timeout(db, SQLITEDBG_SERVER_BUSY_MS); // as sqlitedbg_open_server set it; dl is gone - } - sqlite3_finalize(st); + // The progress handler goes first, as it can no longer matter. Finalizing commits a statement that is + // unfinished (a JNI or SQLite allocation failed while rows were read), and busy_cb, still set, bounds + // that commit's wait; only then is the connection's busy timeout restored, as sqlitedbg_open_server set it. + if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); + // A statement that ran and was left unfinished is committed by finalize, whose result says whether it was. + int ran = st && sqlite3_stmt_status(st, SQLITE_STMTSTATUS_RUN, 0) > 0; + int finalize_rc = sqlite3_finalize(st); + if (handler_set) sqlite3_busy_timeout(db, SQLITEDBG_SERVER_BUSY_MS); + if (report_write_outcome && ran) report_unfinished_write(env, finalize_rc); if (!end_transaction_backstop(env, db)) result = NULL; return result; } @@ -687,8 +968,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"readEvents", "(J[B[J)V", (void *)bridge_read_events}, {"setClientConnected", "(Z)V", (void *)bridge_set_client_connected}, {"openServer", "([BZ)J", (void *)bridge_open_server}, - {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, - {"execute", "(JLjava/lang/String;[Ljava/lang/Object;J)[J", (void *)bridge_execute}, + {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, + {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"execute", "(JLjava/lang/String;[Ljava/lang/Object;[[BIIIIJ)[Ljava/lang/Object;", (void *)bridge_execute}, {"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 12de62e1e5..9b00f4456f 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 @@ -29,9 +29,20 @@ interface DebugEngine { maxBytes: Int, ): EventBatch - /** While true, statements are recorded with their bound values written in. */ + /** While true, statements are recorded with their bound values written in, and rows if [setRowCapture] is on. */ fun setClientConnected(connected: Boolean) + /** + * Records the first [maxRowsPerStatement] rows of each statement as [EventKind.ROW] events while a + * client is connected; 0 turns it off, as at install. TEXT and BLOB values are cut at [maxValueBytes] + * and a row's data at [maxRowBytes] (`sqlitedbg_set_row_capture`). + */ + fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) + /** * Opens [path] for the server: read-only (an authorizer refuses writes) unless [writable]. Either * way the authorizer refuses transactions, the PRAGMAs that would reach the app's own @@ -57,30 +68,45 @@ interface ServerConnection : Closeable { * progress handler on this server connection) once [deadlineMillis] (System.currentTimeMillis * clock) has passed. * + * [argNames] null binds [args] by position, `?NNN` by its number; otherwise `argNames[i]` names the + * parameter `args[i]` goes to, written as in the SQL (`:id`, `@id`, `$id`, `?3`) or bare (`id`, for + * any of `:`, `@` and `$`). Every parameter must get exactly one value and every name must be used. + * * @throws DebugEngineException for SQLite errors, SQL with no statement or more than one, a - * refused write, or the deadline. + * refused write, the deadline, or arguments that do not match the parameters (SQLITE_RANGE). */ fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult /** - * Runs [sql], one statement that writes, to its end in autocommit, with [args] bound as in [query]; rows it - * returns (RETURNING) are dropped. Needs a connection opened with `writable = true`. The statement is - * stopped and rolled back once [deadlineMillis] has passed, or once it has held the write lock for - * SQLITEDBG_SERVER_NON_WAL_MS (1.5 s), waiting to commit included, whichever is first: the app's own writes - * wait for that lock. A deadline that passes while the statement is prepared stops it before it starts. + * Runs [sql], one statement that writes, in autocommit, with [args] bound as in [query] (by name when + * [argNames] is not null), and returns the rows it returns (RETURNING) within [limits] as [query] does, + * from the first row, with no offset: paging would run the write again. Every change is committed + * however many rows are returned ([ExecuteResult.rows] has hasMore). Needs a connection opened with + * `writable = true`. The statement is stopped, and SQLite rolls it back, once [deadlineMillis] has passed, + * or once it has held the write lock for SQLITEDBG_SERVER_NON_WAL_MS (1.5 s), waiting to commit included, + * whichever is first: the app's own writes wait for that lock. The limits are best effort, though: a write + * cut at the row or size limit is committed in full. A deadline that passes while the statement is prepared + * stops it before it starts. A statement that fails, even after rows came back, returns no rows and SQLite + * rolls it back, except that FAIL conflict resolution keeps the rows changed before the failing one; the + * error counts them. A failure building the result after the write finished (an allocation failure) can leave + * the write committed, so a failed call is not always safe to retry; that error says whether the write was + * committed or may not have been. A transaction left open on the connection is rolled back before the statement runs. * * @throws DebugEngineException as [query] does, and for a statement that does not write - * (`sqlite3_stmt_readonly`), a transaction statement, or a refused PRAGMA. + * (`sqlite3_stmt_readonly`), a transaction statement, a refused PRAGMA, or a failed commit. */ fun execute( sql: String, args: List, + argNames: List?, + limits: QueryLimits, deadlineMillis: Long, ): ExecuteResult } @@ -98,6 +124,8 @@ data class ExecuteResult( * assigns itself, reads as null; 0 and other negative rowids are reported. */ val lastInsertRowid: Long?, + /** The rows from RETURNING, as [ServerConnection.query] returns rows; no columns without RETURNING. */ + val rows: QueryResult = QueryResult(emptyList(), emptyList(), 0, false), ) data class AppConnection( @@ -124,6 +152,12 @@ enum class EventKind( /** The app asked SQLite to close the connection; [Event.sql] is empty. */ CLOSE(3), + + /** + * A statement returned a row, recorded only while a client is connected and row recording is on. + * [Event.row] holds its values, [Event.rows] its number in the statement; [Event.sql] is empty. + */ + ROW(4), } data class Event( @@ -136,10 +170,48 @@ data class Event( /** Set for [EventKind.PROFILE] only. */ val durationNanos: Long?, val sql: String, - /** [sql] was cut at the extension's limit. */ + /** [sql] was cut at the extension's limit, or for [EventKind.ROW], [row] was (see [RowValues]). */ val truncated: Boolean, /** [sql] has its bound values written in. */ val expanded: Boolean, + /** + * [EventKind.PROFILE]: the rows the statement returned, recorded or not. [EventKind.ROW]: the row's + * number in its statement, from 1. Null otherwise, and for a statement the extension did not see start. + */ + val rows: Long? = null, + /** + * [EventKind.PROFILE] of a statement that may write: the rows it changed itself, as + * `sqlite3_changes64` counts them (not those changed by triggers); 0 when it changed none. Null for a + * read-only statement, for the other kinds, and when the statement had not finished (reset or finalized + * part way, or its step returned `SQLITE_BUSY`), as the count is then unknown. + */ + val changes: Long? = null, + /** + * [EventKind.PROFILE]: rows went unrecorded while row recording was on, because the statement returned + * more than the per-statement limit, or because the producer could not record a row (the byte budget + * was below a row header, or an allocation failed). + */ + val rowsCut: Boolean = false, + /** [EventKind.ROW] only: the row's values. */ + val row: RowValues? = null, + /** + * The run of a statement this event belongs to: the [seq] of its [EventKind.STATEMENT] event, on that + * event and on the [EventKind.PROFILE] and [EventKind.ROW] events of the run. Null when there is none or + * it is unknown, and for [EventKind.CLOSE]. + */ + val executionId: Long? = null, +) + +data class RowValues( + /** The statement's column count. */ + val columnCount: Int, + /** + * The values kept, in column order: null, [Long], [Double], [String] or [ByteArray]. Fewer than + * [columnCount] when the row's data reached its limit. + */ + val values: List, + /** Indexes into [values] of TEXT and BLOB values that were cut at the value limit. */ + val cutIndexes: Set, ) data class EventBatch( @@ -178,6 +250,8 @@ data class QueryResult( * is whole and not listed, one byte more is. [truncatedCells] is its size. */ val truncatedCellIndexes: Set = emptySet(), + /** Each column's declared type, as `sqlite3_column_decltype` gives it; null for an expression. */ + val declaredTypes: List = List(columns.size) { null }, ) { fun isTruncated( row: Int, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt index 73af648598..468a467c20 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -4,12 +4,13 @@ import java.nio.ByteBuffer import java.nio.ByteOrder /** - * Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` in - * `sqlitedbg.h`: change both together. Little-endian, because the CPU is on every ABI we build. + * Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` and the + * row layout (`sqlitedbg_row_header`, `sqlitedbg_row_value`) in `sqlitedbg.h`: change both together. + * Little-endian, because the CPU is on every ABI we build. */ internal object EventDecoder { /** `sizeof(sqlitedbg_event_record)`. */ - const val HEADER_BYTES = 56 + const val HEADER_BYTES = 80 private const val OFFSET_RECORD_BYTES = 0 private const val OFFSET_KIND = 4 @@ -19,10 +20,24 @@ internal object EventDecoder { private const val OFFSET_TIME_NS = 32 private const val OFFSET_DURATION_NS = 40 private const val OFFSET_FLAGS = 48 - private const val OFFSET_SQL_BYTES = 52 + private const val OFFSET_DATA_BYTES = 52 + private const val OFFSET_ROWS = 56 + private const val OFFSET_CHANGES = 64 + private const val OFFSET_EXECUTION_ID = 72 private const val FLAG_TRUNCATED = 1 private const val FLAG_EXPANDED = 2 + private const val FLAG_ROWS_CUT = 4 + + internal const val ROW_HEADER_BYTES = 8 + internal const val ROW_VALUE_BYTES = 12 + + // SQLite's fundamental types, as sqlite3_column_type returns them. + private const val SQLITE_INTEGER = 1 + private const val SQLITE_FLOAT = 2 + private const val SQLITE_TEXT = 3 + private const val SQLITE_BLOB = 4 + private const val SQLITE_NULL = 5 /** * The records in the first [length] bytes of [bytes]. @@ -40,9 +55,9 @@ internal object EventDecoder { while (offset < length) { require(length - offset >= HEADER_BYTES) { "record at $offset is cut off by the end of the data" } val recordBytes = buffer.getInt(offset + OFFSET_RECORD_BYTES) - val sqlBytes = buffer.getInt(offset + OFFSET_SQL_BYTES) - require(sqlBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && sqlBytes <= recordBytes - HEADER_BYTES) { - "record at $offset has record_bytes=$recordBytes sql_bytes=$sqlBytes" + val dataBytes = buffer.getInt(offset + OFFSET_DATA_BYTES) + require(dataBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && dataBytes <= recordBytes - HEADER_BYTES) { + "record at $offset has record_bytes=$recordBytes data_bytes=$dataBytes" } require(recordBytes <= length - offset) { "record at $offset runs past the end of the data" } val kindValue = buffer.getInt(offset + OFFSET_KIND) @@ -50,6 +65,12 @@ internal object EventDecoder { EventKind.values().firstOrNull { it.nativeValue == kindValue } ?: throw IllegalArgumentException("record at $offset has unknown kind $kindValue") val flags = buffer.getInt(offset + OFFSET_FLAGS) + val dataStart = offset + HEADER_BYTES + // -1 in the record: does not apply, or the extension did not see the statement start + val rows = buffer.getLong(offset + OFFSET_ROWS).takeIf { it >= 0 && (kind == EventKind.PROFILE || kind == EventKind.ROW) } + val changes = buffer.getLong(offset + OFFSET_CHANGES).takeIf { it >= 0 && kind == EventKind.PROFILE } + // 0 in the record: none or unknown; CLOSE never has one + val executionId = buffer.getLong(offset + OFFSET_EXECUTION_ID).takeIf { it != 0L && kind != EventKind.CLOSE } events += Event( seq = buffer.getLong(offset + OFFSET_SEQ), @@ -58,12 +79,80 @@ internal object EventDecoder { threadId = buffer.getLong(offset + OFFSET_THREAD_ID), timeEpochNanos = buffer.getLong(offset + OFFSET_TIME_NS), durationNanos = if (kind == EventKind.PROFILE) buffer.getLong(offset + OFFSET_DURATION_NS) else null, - sql = String(bytes, offset + HEADER_BYTES, sqlBytes, Charsets.UTF_8), + sql = if (kind == EventKind.ROW) "" else String(bytes, dataStart, dataBytes, Charsets.UTF_8), truncated = flags and FLAG_TRUNCATED != 0, expanded = flags and FLAG_EXPANDED != 0, + rows = rows, + changes = changes, + rowsCut = kind == EventKind.PROFILE && flags and FLAG_ROWS_CUT != 0, + row = if (kind == EventKind.ROW) decodeRow(bytes, buffer, dataStart, dataBytes) else null, + executionId = executionId, ) offset += recordBytes } return events } + + private fun decodeRow( + bytes: ByteArray, + buffer: ByteBuffer, + start: Int, + length: Int, + ): RowValues { + require(length >= ROW_HEADER_BYTES) { "row at $start is shorter than its header" } + val end = start + length + val columns = buffer.getInt(start) + val kept = buffer.getInt(start + 4) + require(columns >= 0 && kept in 0..columns) { "row at $start has columns=$columns kept=$kept" } + // Each value takes at least ROW_VALUE_BYTES. Checked before ArrayList(kept) allocates: a count near + // Int.MAX_VALUE throws OutOfMemoryError there, before any value's own check runs. + require(kept <= (length - ROW_HEADER_BYTES) / ROW_VALUE_BYTES) { + "row at $start has kept=$kept, more values than its $length bytes hold" + } + val values = ArrayList(kept) + val cut = HashSet() + var pos = start + ROW_HEADER_BYTES + repeat(kept) { i -> + require(end - pos >= ROW_VALUE_BYTES) { "row at $start: value $i is cut off" } + val type = buffer.get(pos).toInt() and 0xff + val isCut = buffer.get(pos + 1).toInt() != 0 + val stored = buffer.getInt(pos + 4) + val full = buffer.getInt(pos + 8) + pos += ROW_VALUE_BYTES + require(stored in 0..(end - pos) && full >= stored && isCut == (stored < full)) { + "row at $start: value $i has stored_bytes=$stored full_bytes=$full cut=$isCut" + } + values += + when (type) { + SQLITE_INTEGER, SQLITE_FLOAT -> { + require(stored == 8) { "row at $start: number $i is $stored bytes" } + // The producer never cuts a number: full_bytes is the stored 8. + require(full == stored) { "row at $start: number $i has stored_bytes=$stored full_bytes=$full" } + if (type == SQLITE_INTEGER) buffer.getLong(pos) else buffer.getDouble(pos) + } + + SQLITE_TEXT -> { + String(bytes, pos, stored, Charsets.UTF_8) + } + + SQLITE_BLOB -> { + bytes.copyOfRange(pos, pos + stored) + } + + SQLITE_NULL -> { + require(stored == 0) { "row at $start: null $i has $stored bytes" } + require(full == 0) { "row at $start: null $i has full_bytes=$full" } + null + } + + else -> { + throw IllegalArgumentException("row at $start: value $i has unknown type $type") + } + } + if (isCut) cut += i + pos += stored + } + require(pos == end) { "row at $start has ${end - pos} bytes after its last value" } + return RowValues(columns, values, cut) + } } 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 2887e68fd3..1ea538bb4b 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 @@ -24,6 +24,17 @@ internal object NativeBridge { @JvmStatic external fun setClientConnected(connected: Boolean) + /** + * Turns row recording on (`maxRowsPerStatement` > 0) or off (0): `sqlitedbg_set_row_capture`. A value + * or row limit of 0 takes the extension's default. + */ + @JvmStatic + external fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) + /** A handle for [query] and [close]. Throws [DebugEngineException]. */ @JvmStatic external fun openServer( @@ -32,15 +43,17 @@ internal object NativeBridge { ): Long /** - * `[Array, ArrayList>, LongArray]`: the column names, the rows, and - * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column). - * Throws [DebugEngineException]. + * `[Array, ArrayList>, LongArray, Array]`: the column names, the rows, + * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column), and each + * column's declared type. [names] null binds [args] by position; otherwise `names[i]` (UTF-8) names + * the parameter `args[i]` goes to. Throws [DebugEngineException]. */ @JvmStatic external fun query( handle: Long, sql: String, args: Array, + names: Array?, offset: Long, maxRows: Int, maxTextBytes: Int, @@ -50,17 +63,22 @@ internal object NativeBridge { ): Array /** - * `{changes, last_insert_rowid}` of one statement that writes (see [ServerConnection.execute]); the - * rowid is [Long.MIN_VALUE] when the statement inserted no row into a rowid table. Throws - * [DebugEngineException]. + * One statement that writes (see [ServerConnection.execute]): its RETURNING rows as [query] returns + * them, then `{changes, last_insert_rowid}`; the rowid is [Long.MIN_VALUE] when the statement inserted + * no row into a rowid table. [names] binds [args] as in [query]. Throws [DebugEngineException]. */ @JvmStatic external fun execute( handle: Long, sql: String, args: Array, + names: Array?, + maxRows: Int, + maxTextBytes: Int, + maxBlobBytes: Int, + maxTotalBytes: Int, deadlineMillis: Long, - ): LongArray + ): 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 b4467b8ca9..df346eb2a4 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 @@ -70,6 +70,12 @@ class NativeDebugEngine : DebugEngine { override fun setClientConnected(connected: Boolean) = NativeBridge.setClientConnected(connected) + override fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) = NativeBridge.setRowCapture(maxRowsPerStatement, maxValueBytes, maxRowBytes) + override fun openServerConnection( path: String, writable: Boolean, @@ -81,12 +87,14 @@ class NativeDebugEngine : DebugEngine { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult { check(handle != 0L) { "the connection is closed" } require(offset >= 0) { "offset $offset is negative" } + require(argNames == null || argNames.size == args.size) { "${argNames?.size} names for ${args.size} args" } require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0 && limits.maxTotalBytes > 0) { "bad limits $limits" } @@ -95,6 +103,7 @@ class NativeDebugEngine : DebugEngine { handle, sql, Array(args.size) { bindable(args[it]) }, + argNames?.map { it.toByteArray(Charsets.UTF_8) }?.toTypedArray(), offset, limits.maxRows, limits.maxTextBytes, @@ -103,25 +112,61 @@ class NativeDebugEngine : DebugEngine { deadlineMillis, ) - @Suppress("UNCHECKED_CAST") - val columns = (result[0] as Array).asList() - - @Suppress("UNCHECKED_CAST") - val rows = (result[1] as List>).map { it.asList() } - val counts = result[2] as LongArray - val cut = HashSet() - for (i in 2 until counts.size) cut += counts[i] - return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L, truncatedCellIndexes = cut) + return rowsOf(result) } override fun execute( sql: String, args: List, + argNames: List?, + limits: QueryLimits, deadlineMillis: Long, ): ExecuteResult { check(handle != 0L) { "the connection is closed" } - val result = NativeBridge.execute(handle, sql, Array(args.size) { bindable(args[it]) }, deadlineMillis) - return ExecuteResult(changes = result[0], lastInsertRowid = result[1].takeIf { it != Long.MIN_VALUE }) + require(argNames == null || argNames.size == args.size) { "${argNames?.size} names for ${args.size} args" } + require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0 && limits.maxTotalBytes > 0) { + "bad limits $limits" + } + val result = + NativeBridge.execute( + handle, + sql, + Array(args.size) { bindable(args[it]) }, + argNames?.map { it.toByteArray(Charsets.UTF_8) }?.toTypedArray(), + limits.maxRows, + limits.maxTextBytes, + limits.maxBlobBytes, + limits.maxTotalBytes, + deadlineMillis, + ) + val counts = result[4] as LongArray + return ExecuteResult( + changes = counts[0], + lastInsertRowid = counts[1].takeIf { it != Long.MIN_VALUE }, + rows = rowsOf(result), + ) + } + + /** The first four elements of what [NativeBridge.query] and [NativeBridge.execute] return. */ + private fun rowsOf(result: Array): QueryResult { + @Suppress("UNCHECKED_CAST") + val columns = (result[0] as Array).asList() + + @Suppress("UNCHECKED_CAST") + val rows = (result[1] as List>).map { it.asList() } + val counts = result[2] as LongArray + val cut = HashSet() + for (i in 2 until counts.size) cut += counts[i] + @Suppress("UNCHECKED_CAST") + val declaredTypes = (result[3] as Array).asList() + return QueryResult( + columns, + rows, + truncatedCells = counts[0].toInt(), + hasMore = counts[1] != 0L, + truncatedCellIndexes = cut, + declaredTypes = declaredTypes, + ) } override fun close() { 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 266dcbdc2d..555a5e7b59 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 @@ -3,6 +3,8 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.Event +import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult import org.appdevforall.sqlitedebugger.engine.ServerConnection @@ -75,11 +77,23 @@ class DatabaseTools internal constructor( /** Bound values stop being recorded this long after the last get_events call. */ const val EVENTS_IDLE_MS = 60_000L + /** 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 + const val EVENT_ROW_BYTES = 4096 + private const val MAX_SAFE_INTEGER = 9007199254740992L // 2^53 private val SIDE_FILE_SUFFIXES = listOf("-wal", "-shm", "-journal") const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + /** How a cell is written, said by every tool that returns cells. */ + const val VALUES_NOTE = + "A NULL is JSON null; a BLOB is {hex, bytes, truncated}; an integer beyond 2^53 is a decimal string, and a " + + "NaN or infinite REAL is the string \"NaN\", \"Infinity\" or \"-Infinity\". storage_classes gives each row's " + + "SQLite storage classes, one letter per column: i INTEGER, r REAL, t TEXT, b BLOB, n NULL (JSON writes a REAL " + + "such as 2.0 as 2)." + /** Said by the tools that return cells whose TEXT and BLOB values the server can cut. */ private const val CUT_CELLS_NOTE = "truncated_cells counts the cut cells and truncated_cell_indexes lists each as [row, column], both from 0 and " + @@ -105,6 +119,15 @@ class DatabaseTools internal constructor( "included (best effort; a wait of up to 3 s for the app's lock before that is not counted), in every journal " + "mode, so a long write does not make the app's own writes fail; change fewer rows per call." + /** + * Said by execute: the rollbacks above are SQLite's and the limits are best effort, so an error is not always a + * proof that nothing changed. + */ + const val COMMIT_UNCERTAIN_NOTE = + "Limits are best effort: a write cut at the row or size limit is committed in full, and an out-of-memory " + + "failure while building the result after the write finished can leave it committed, in which case the error " + + "says whether it was; if an error does not say the write was rolled back, check the data before repeating it." + /** Said by execute's description: the first write to a Room database is refused until acknowledged (ADFA-7299). */ const val ROOM_DESCRIPTION = "The first write to a Room database (one with room_master_table) is refused with a warning until it is sent again " + @@ -164,7 +187,7 @@ class DatabaseTools internal constructor( is ByteArray -> { JSONObject() - .put("base64", McpHttp.base64(value, urlSafe = false, pad = true)) + .put("hex", hex(value)) .put("bytes", value.size) .put("truncated", truncated) } @@ -174,6 +197,29 @@ class DatabaseTools internal constructor( } } + private val HEX_DIGITS = "0123456789abcdef".toCharArray() + + fun hex(bytes: ByteArray): String { + val out = CharArray(bytes.size * 2) + bytes.forEachIndexed { i, b -> + out[i * 2] = HEX_DIGITS[(b.toInt() shr 4) and 0xf] + out[i * 2 + 1] = HEX_DIGITS[b.toInt() and 0xf] + } + return String(out) + } + + /** One letter per value: i INTEGER, r REAL, t TEXT, b BLOB, n NULL (see [VALUES_NOTE]). */ + fun storageClasses(values: List): String = + values.joinToString("") { + when (it) { + null -> "n" + is Long, is Int -> "i" + is Double -> "r" + is ByteArray -> "b" + else -> "t" + } + } + fun encodeLong(value: Long): Any = if (value > MAX_SAFE_INTEGER || value < -MAX_SAFE_INTEGER) value.toString() else value fun quoteIdentifier(name: String) = "\"" + name.replace("\"", "\"\"") + "\"" @@ -191,6 +237,7 @@ class DatabaseTools internal constructor( */ private val roomAcknowledged = HashSet() private var clientConnected = false + private var rowCapture = false private var lastEventsCallMs = 0L private var cancelIdleCheck: (() -> Unit)? = null private var idleCheckGeneration = 0 @@ -229,9 +276,17 @@ class DatabaseTools internal constructor( clientConnected = false engine.setClientConnected(false) } + setRowCaptureLocked(false) } } + /** Row recording costs the app time on every row it reads, so it is on only while a get_events client asks for rows. [lock] held. */ + private fun setRowCaptureLocked(on: Boolean) { + if (on == rowCapture) return + rowCapture = on + if (on) engine.setRowCapture(EVENT_ROWS_PER_STATEMENT, EVENT_VALUE_BYTES, EVENT_ROW_BYTES) else engine.setRowCapture(0, 0, 0) + } + /** * Stops recording bound values once [EVENTS_IDLE_MS] have passed since the last get_events call: * expanding every statement costs memory, and nobody is reading. Checked on every tool call and @@ -243,6 +298,7 @@ class DatabaseTools internal constructor( if (clientConnected && clock() - lastEventsCallMs >= EVENTS_IDLE_MS) { clientConnected = false engine.setClientConnected(false) + setRowCaptureLocked(false) } } @@ -296,7 +352,8 @@ class DatabaseTools internal constructor( tool( "query", "Run a query", - "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + + "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS), " + + "with each column's declared_type in column_types (null for an expression). $VALUES_NOTE " + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES: $CUT_CELLS_NOTE " + "A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + @@ -305,7 +362,7 @@ class DatabaseTools internal constructor( "$READ_PRAGMAS_NOTE. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), + "args" to argsSchema(), "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"), @@ -321,7 +378,16 @@ class DatabaseTools internal constructor( "the rowid of the last row it inserted into a rowid table, or null when it inserted none (an UPDATE, " + "a WITHOUT ROWID table, an ignored row; rows inserted by triggers do not count). One statement per call; " + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused, so several statements cannot be made atomic. " + - "A statement that does not write is refused: use query. Rows from RETURNING are not returned. " + + "A statement that does not write is refused: use query. Rows from RETURNING come back as query returns " + + "them (columns, column_types, rows, storage_classes, has_more, truncated_cells, truncated_cell_indexes), at " + + "most max_rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS) and about " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cells; $CUT_CELLS_NOTE Every change is committed whatever is returned: " + + "has_more true means RETURNING produced more rows than came back, and the omitted rows cannot be " + + "recovered from this result or paged (that would write again); a follow-up query returns them only if the " + + "data still exists, which it does not after a DELETE. SQLite makes every change before the first row comes back, " + + "so the time limit covers the whole write. A statement that fails returns no rows, and SQLite rolls back " + + "its changes, except that FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows " + + "changed before the failing one; the error then says how many were kept. $COMMIT_UNCERTAIN_NOTE " + "Foreign keys are enforced here whatever the app's own connections do: ON DELETE and ON UPDATE actions " + "run, and a write the app could make with foreign keys off may be refused. " + "Also refused: ATTACH, every PRAGMA that takes a value except user_version (no setting can be " + @@ -331,7 +397,8 @@ class DatabaseTools internal constructor( "stale until it reads it again. $ROOM_DESCRIPTION $APP_FUNCTIONS_NOTE.", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), + "args" to argsSchema(), + "max_rows" to prop("integer", "RETURNING rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), "acknowledge_room" to prop( "boolean", @@ -348,7 +415,7 @@ class DatabaseTools internal constructor( "A cell cut at $MAX_TEXT_BYTES bytes is listed as in query: $CUT_CELLS_NOTE $APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), + "args" to argsSchema(), required = listOf("sql"), ), ) { call, args -> explain(call, args) }, @@ -380,7 +447,25 @@ class DatabaseTools internal constructor( "as run to continue; dropped counts events that left the buffer unread. reset true means the app restarted " + "(run differs, or after is past the newest event), and events are read from the start. " + "The first call starts recording bound values into the SQL; " + - "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while watching.", + "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while " + + "watching. " + + "kind is statement (one starts; a trigger's SQL starts with --), profile (one finished: duration_nanos; rows, the " + + "rows it returned; changes, the rows it changed itself, not through triggers, null for a read; null when the " + + "statement's start was not seen), close, or row. execution_id names one run of a statement: a statement event's " + + "own seq, and on that run's profile and row events the same number, so rows of statements stepped in turn " + + "are told apart by it. It is null for close, a trigger's statements, a statement an app function runs inside a " + + "callback (its SQL also starts with --), an EXPLAIN's profile, and a statement whose start was not seen; a " + + "statement pushed out after more than 16 were stepped in turn keeps its id on its statement event, but its " + + "later profile and row events have null. A run can have more than one profile (a retry after a schema " + + "change, or a profile with rows 0 from a step that met a busy lock, before the run's rows), or none at its " + + "end. " + + "With include_rows true (the default), the app's statements " + + "after the call also record their first $EVENT_ROWS_PER_STATEMENT rows as row events: row_number (from 1), " + + "column_count, values, storage_classes and cut_values (indexes of TEXT and BLOB values cut at " + + "$EVENT_VALUE_BYTES bytes); a row's data stops at ${EVENT_ROW_BYTES / 1024} KiB, and then values holds fewer " + + "than column_count and truncated is true. A profile's rows_cut says rows went unrecorded past the limit. " + + "$VALUES_NOTE Recording rows costs the app a few microseconds a row, so pass include_rows false when you need " + + "only the SQL; it then stops, and row events are left out.", JSONObject() .put("type", "object") .put("additionalProperties", false) @@ -391,7 +476,7 @@ class DatabaseTools internal constructor( .put( "run", prop("string", "The run from the last call. If it differs from the current, the read starts from 0."), - ), + ).put("include_rows", prop("boolean", "Record and return rows the app's statements return. Default true.")), ).put("required", JSONArray()), ) { _, args -> getEvents(args) }, ) @@ -414,6 +499,16 @@ class DatabaseTools internal constructor( description: String, ) = JSONObject().put("type", type).put("description", description) + private fun argsSchema() = + JSONObject() + .put("type", JSONArray(listOf("array", "object"))) + .put( + "description", + "Values to bind: null, numbers or strings. An array binds by position (? and ?NNN, by number); an object binds " + + "by name (:name, @name, \$name, ?NNN), with keys written as in the SQL. A key without a prefix, such as id, " + + "matches :id, @id and \$id; a ?NNN key keeps its ?. Every parameter needs a value, and every key a parameter.", + ) + private fun databaseSchema( vararg extra: Pair, required: List = emptyList(), @@ -473,7 +568,7 @@ class DatabaseTools internal constructor( call, args, "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", - emptyList(), + Bind.NONE, 0, QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) @@ -515,6 +610,7 @@ class DatabaseTools internal constructor( ): JSONObject { val sql = stringArg(args, "sql") val bind = bindArgs(args) + val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() val acknowledge = when (val v = args.opt("acknowledge_room")) { null, JSONObject.NULL -> false @@ -528,8 +624,19 @@ class DatabaseTools internal constructor( } call.locked { roomAcknowledged += path } } - val result = withConnection(call, path, writable = true) { it.execute(sql, bind, call.deadline) } - return JSONObject() + val limits = QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + val result = withConnection(call, path, writable = true) { it.execute(sql, bind.values, bind.names, limits, call.deadline) } + // Rows only for a statement with RETURNING; there is no offset to page with. + val out = + if (result.rows.columns.isEmpty()) { + JSONObject() + } else { + encodeResult(result.rows, 0).also { + it.remove("offset") + it.remove("next_offset") + } + } + return out .put("changes", encodeLong(result.changes)) .put("last_insert_rowid", result.lastInsertRowid?.let { encodeLong(it) } ?: JSONObject.NULL) } @@ -543,7 +650,7 @@ class DatabaseTools internal constructor( call, path, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'room_master_table'", - emptyList(), + Bind.NONE, 0, QueryLimits(1, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ).rows.isNotEmpty() @@ -574,7 +681,7 @@ class DatabaseTools internal constructor( val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) val path = checkedPath(call, args) - fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", emptyList(), 0, limits).rows.firstOrNull()?.firstOrNull() + fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", Bind.NONE, 0, limits).rows.firstOrNull()?.firstOrNull() val pageCount = pragma("page_count") as? Long val pageSize = pragma("page_size") as? Long val out = @@ -588,7 +695,7 @@ class DatabaseTools internal constructor( call, path, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", - emptyList(), + Bind.NONE, 0, limits, ).rows @@ -602,7 +709,7 @@ class DatabaseTools internal constructor( call, path, "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", - emptyList(), + Bind.NONE, 0, limits, ).rows.firstOrNull()?.firstOrNull() @@ -631,7 +738,7 @@ class DatabaseTools internal constructor( else -> throw McpToolError("full must be true or false.") } val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" - val result = run(call, args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) + val result = run(call, args, pragma, Bind.NONE, 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } return JSONObject() .put("check", if (full) "integrity_check" else "quick_check") @@ -649,9 +756,16 @@ class DatabaseTools internal constructor( is String -> v else -> throw McpToolError("run must be a string.") } + val includeRows = + when (val v = args.opt("include_rows")) { + null, JSONObject.NULL -> true + is Boolean -> v + else -> throw McpToolError("include_rows must be true or false.") + } val otherRun = run != null && run != engine.runId synchronized(lock) { lastEventsCallMs = clock() + setRowCaptureLocked(includeRows) if (!clientConnected) { engine.setClientConnected(true) clientConnected = true @@ -666,18 +780,8 @@ class DatabaseTools internal constructor( } val events = JSONArray() for (e in batch.events) { - events.put( - JSONObject() - .put("seq", encodeLong(e.seq)) - .put("kind", e.kind.name.lowercase()) - .put("connection_id", encodeLong(e.connectionId)) - .put("thread_id", encodeLong(e.threadId)) - .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) - .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) - .put("sql", e.sql) - .put("truncated", e.truncated) - .put("expanded", e.expanded), - ) + if (e.kind == EventKind.ROW && !includeRows) continue + events.put(encodeEvent(e)) } return JSONObject() .put("run", engine.runId) @@ -687,6 +791,44 @@ class DatabaseTools internal constructor( .put("events", events) } + private fun encodeEvent(e: Event): JSONObject { + val out = + JSONObject() + .put("seq", encodeLong(e.seq)) + .put("kind", e.kind.name.lowercase()) + .put("connection_id", encodeLong(e.connectionId)) + .put("execution_id", e.executionId?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("thread_id", encodeLong(e.threadId)) + .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) + .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("sql", e.sql) + .put("truncated", e.truncated) + .put("expanded", e.expanded) + when (e.kind) { + EventKind.PROFILE -> { + out + .put("rows", e.rows?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("changes", e.changes?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("rows_cut", e.rowsCut) + } + + EventKind.ROW -> { + val row = e.row + out.put("row_number", e.rows?.let { encodeLong(it) } ?: JSONObject.NULL) + if (row != null) { + out + .put("column_count", row.columnCount) + .put("values", JSONArray(row.values.mapIndexed { i, v -> encodeValue(v, i in row.cutIndexes) })) + .put("storage_classes", storageClasses(row.values)) + .put("cut_values", JSONArray(row.cutIndexes.sorted())) + } + } + + else -> {} + } + return out + } + private fun encodeResult( result: QueryResult, offset: Long, @@ -698,7 +840,9 @@ class DatabaseTools internal constructor( val out = JSONObject() .put("columns", JSONArray(result.columns)) + .put("column_types", JSONArray().also { a -> result.declaredTypes.forEach { a.put(it ?: JSONObject.NULL) } }) .put("rows", rows) + .put("storage_classes", JSONArray(result.rows.map { storageClasses(it) })) .put("row_count", result.rows.size) .put("offset", encodeLong(offset)) .put("has_more", result.hasMore) @@ -757,7 +901,7 @@ class DatabaseTools internal constructor( call: Call, args: JSONObject, sql: String, - bind: List, + bind: Bind, offset: Long, limits: QueryLimits, ): QueryResult = runChecked(call, checkedPath(call, args), sql, bind, offset, limits) @@ -766,10 +910,10 @@ class DatabaseTools internal constructor( call: Call, path: String, sql: String, - bind: List, + bind: Bind, offset: Long, limits: QueryLimits, - ): QueryResult = withConnection(call, path, writable = false) { it.query(sql, bind, offset, limits, call.deadline) } + ): QueryResult = withConnection(call, path, writable = false) { it.query(sql, bind.values, bind.names, offset, limits, call.deadline) } /** Runs [block] on the cached server connection to [path], opened if need be, under [lock]. */ private fun withConnection( @@ -862,18 +1006,51 @@ class DatabaseTools internal constructor( return l } - private fun bindArgs(args: JSONObject): List { - val raw = args.opt("args") - if (raw == null || raw == JSONObject.NULL) return emptyList() - val arr = raw as? JSONArray ?: throw McpToolError("args must be an array.") - return (0 until arr.length()).map { i -> - when (val v = arr.opt(i)) { + /** Values to bind: by position when [names] is null, else `names[i]` names the parameter of `values[i]`. */ + private class Bind( + val values: List, + val names: List?, + ) { + companion object { + val NONE = Bind(emptyList(), null) + } + } + + private fun bindArgs(args: JSONObject): Bind { + fun value( + v: Any?, + what: String, + ): Any? = + when (v) { null, JSONObject.NULL -> null is Int, is Long, is Short -> (v as Number).toLong() is Number -> v.toDouble() is String -> v is Boolean -> if (v) 1L else 0L - else -> throw McpToolError("args[$i] must be null, a number or a string.") + else -> throw McpToolError("$what must be null, a number or a string.") + } + return when (val raw = args.opt("args")) { + null, JSONObject.NULL -> { + Bind.NONE + } + + is JSONArray -> { + Bind((0 until raw.length()).map { i -> value(raw.opt(i), "args[$i]") }, null) + } + + is JSONObject -> { + val names = + raw + .keys() + .asSequence() + .sorted() + .toList() + names.forEach { if (it.isEmpty()) throw McpToolError("args has an empty name.") } + Bind(names.map { value(raw.opt(it), "args.$it") }, names) + } + + else -> { + throw McpToolError("args must be an array or an object.") } } } diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 5af550f109..a20e0053fa 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -12,12 +12,16 @@ #include #include #include +#include #include #include #include "sqlite3.h" #include "sqlitedbg.h" +_Static_assert(offsetof(sqlitedbg_event_record, execution_id) == 72, "execution_id offset"); +_Static_assert(sizeof(sqlitedbg_event_record) == 80, "event record size"); + static int g_failures; static int g_checks; @@ -66,12 +70,16 @@ static sqlite3 *open_app(const char *path) { // Events +// The largest row data a test records (sqlitedbg_set_row_capture's max_row_bytes in the row tests). +#define MAX_ROW_DATA 1024 + typedef struct ev { uint32_t kind, flags; uint64_t seq, conn; - int64_t tid, time_ns, duration_ns; - char sql[MAX_SQL * 4 + 8]; - uint32_t sql_bytes; + int64_t tid, time_ns, duration_ns, rows, changes; + uint64_t exec_id; + char sql[MAX_ROW_DATA + 8]; // SQL text, or a row's data for SQLITEDBG_EVENT_ROW + uint32_t data_bytes; } ev; typedef struct batch { @@ -101,9 +109,12 @@ static void read_all(uint64_t after, batch *b) { const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); CHECK(rec->record_bytes >= sizeof *rec); CHECK_EQ(rec->record_bytes % 8, 0); - CHECK(rec->sql_bytes <= MAX_SQL); - CHECK(rec->record_bytes >= sizeof *rec + rec->sql_bytes); + CHECK(rec->data_bytes <= (rec->kind == SQLITEDBG_EVENT_ROW ? MAX_ROW_DATA : MAX_SQL)); + CHECK(rec->record_bytes >= sizeof *rec + rec->data_bytes); CHECK(rec->seq > prev); + // rows and changes are -1 where they do not apply + if (rec->kind != SQLITEDBG_EVENT_PROFILE && rec->kind != SQLITEDBG_EVENT_ROW) CHECK_EQ(rec->rows, -1); + if (rec->kind != SQLITEDBG_EVENT_PROFILE) CHECK_EQ(rec->changes, -1); prev = rec->seq; ev *e = &b->events[i]; e->kind = rec->kind; @@ -113,9 +124,12 @@ static void read_all(uint64_t after, batch *b) { e->tid = rec->thread_id; e->time_ns = rec->time_ns; e->duration_ns = rec->duration_ns; - e->sql_bytes = rec->sql_bytes; - memcpy(e->sql, (const char *)buf + off + sizeof *rec, rec->sql_bytes); - e->sql[rec->sql_bytes] = 0; + e->rows = rec->rows; + e->changes = rec->changes; + e->exec_id = rec->execution_id; + e->data_bytes = rec->data_bytes; + memcpy(e->sql, (const char *)buf + off + sizeof *rec, rec->data_bytes); + e->sql[rec->data_bytes] = 0; off += rec->record_bytes; } CHECK_EQ(off, r.bytes); @@ -184,6 +198,7 @@ static uint64_t conn_id_of(sqlite3 *db) { // Tests extern int sqlitedbg_test_fail_init; // sqlitedbg.c, built with SQLITEDBG_TEST +extern uint32_t sqlitedbg_test_max_row_bytes(void); // likewise static sqlitedbg_config g_config = {BUFFER_BYTES, MAX_SQL}; static sqlite3 *g_main; @@ -220,7 +235,7 @@ static void test_install(void) { read_all(cur, &b); CHECK_EQ(b.count, 2); CHECK(b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED); - CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ(b.events[0].data_bytes, MAX_SQL); batch_free(&b); } @@ -251,6 +266,9 @@ static void test_events(void) { CHECK_EQ(b.events[3].kind, SQLITEDBG_EVENT_PROFILE); CHECK(strcmp(b.events[3].sql, "INSERT INTO t VALUES(?)") == 0); CHECK(b.events[3].duration_ns >= 0); + // no rows; one row changed by the insert itself, not counting the trigger's + CHECK_EQ(b.events[3].rows, 0); + CHECK_EQ(b.events[3].changes, 1); for (size_t i = 0; i < b.count; i++) { CHECK_EQ(b.events[i].conn, 1); CHECK_EQ(b.events[i].tid, tid()); @@ -338,7 +356,7 @@ static void test_expanded(void) { read_all(cur, &b); CHECK(b.events[0].flags & SQLITEDBG_EVENT_EXPANDED); CHECK(b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED); - CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ(b.events[0].data_bytes, MAX_SQL); batch_free(&b); } @@ -357,9 +375,9 @@ static void test_truncation(void) { read_all(cur, &b); CHECK_EQ(b.count, 2); for (int i = 0; i < 2; i++) { - CHECK_EQ(b.events[i].sql_bytes, 62); + CHECK_EQ(b.events[i].data_bytes, 62); CHECK(b.events[i].flags & SQLITEDBG_EVENT_TRUNCATED); - CHECK(utf8_valid(b.events[i].sql, b.events[i].sql_bytes)); + CHECK(utf8_valid(b.events[i].sql, b.events[i].data_bytes)); } batch_free(&b); @@ -372,8 +390,8 @@ static void test_truncation(void) { exec_ok(g_main, sql); read_all(cur, &b); CHECK_EQ(b.count, 2); - CHECK_EQ(b.events[0].sql_bytes, 63); - CHECK(utf8_valid(b.events[0].sql, b.events[0].sql_bytes)); + CHECK_EQ(b.events[0].data_bytes, 63); + CHECK(utf8_valid(b.events[0].sql, b.events[0].data_bytes)); batch_free(&b); // exactly at the limit is whole, one byte over is cut @@ -388,12 +406,1068 @@ static void test_truncation(void) { cur = cursor_now(); exec_ok(g_main, sql); read_all(cur, &b); - CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ(b.events[0].data_bytes, MAX_SQL); CHECK_EQ((b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED) != 0, over); batch_free(&b); } } +// Rows and changes (ADFA-7296) + +typedef struct rv { + int type, cut; + uint32_t stored, full; + const unsigned char *p; +} rv; + +// Parses a ROW event's data into at most max values; checks it is exactly as long as data_bytes. +// Returns the values kept, or -1 if the data is malformed. +static int parse_row(const ev *e, uint32_t *columns, rv *vals, int max) { + const unsigned char *d = (const unsigned char *)e->sql; + size_t n = e->data_bytes, off = sizeof(sqlitedbg_row_header); + if (n < off) return -1; + sqlitedbg_row_header h; + memcpy(&h, d, sizeof h); + *columns = h.columns; + if (h.kept > h.columns || (int)h.kept > max) return -1; + for (uint32_t i = 0; i < h.kept; i++) { + sqlitedbg_row_value v; + if (n - off < sizeof v) return -1; + memcpy(&v, d + off, sizeof v); + off += sizeof v; + if (v.stored_bytes > n - off || v.stored_bytes > v.full_bytes || v.reserved != 0 || v.cut != (v.stored_bytes < v.full_bytes)) return -1; + vals[i] = (rv){v.type, v.cut, v.stored_bytes, v.full_bytes, d + off}; + off += v.stored_bytes; + } + return off == n ? (int)h.kept : -1; +} + +static int64_t rv_int(const rv *v) { + int64_t x = 0; + if (v->stored == 8) memcpy(&x, v->p, 8); + return x; +} + +static double rv_double(const rv *v) { + double x = 0; + if (v->stored == 8) memcpy(&x, v->p, 8); + return x; +} + +// The last event of `kind` whose SQL is `sql`, or NULL. +static const ev *find_event(const batch *b, uint32_t kind, const char *sql) { + for (size_t i = b->count; i-- > 0;) + if (b->events[i].kind == kind && strcmp(b->events[i].sql, sql) == 0) return &b->events[i]; + return NULL; +} + +static size_t count_kind(const batch *b, uint32_t kind) { + size_t n = 0; + for (size_t i = 0; i < b->count; i++) n += b->events[i].kind == kind; + return n; +} + +// The n-th (from 0) event of `kind` whose SQL is `sql`, or NULL. +static const ev *nth_event(const batch *b, uint32_t kind, const char *sql, size_t n) { + for (size_t i = 0; i < b->count; i++) + if (b->events[i].kind == kind && strcmp(b->events[i].sql, sql) == 0 && n-- == 0) return &b->events[i]; + return NULL; +} + +// For statements that ran one after another (no nesting, no trigger): each STATEMENT's execution id +// is its own seq, and each PROFILE and ROW carries that of the STATEMENT before it. Returns the +// number of STATEMENTs. +static size_t check_runs(const batch *b) { + uint64_t run = 0; + size_t n = 0; + for (size_t i = 0; i < b->count; i++) { + const ev *e = &b->events[i]; + if (e->kind == SQLITEDBG_EVENT_STATEMENT) { + CHECK_EQ(e->exec_id, e->seq); + run = e->seq; + n++; + } else if (e->kind == SQLITEDBG_EVENT_PROFILE || e->kind == SQLITEDBG_EVENT_ROW) { + CHECK_EQ(e->exec_id, run); + } + } + return n; +} + +static void test_rows(void) { + exec_ok(g_main, "CREATE TABLE r(i INTEGER, f REAL, s TEXT, b BLOB, n)"); + // row 2's text is 20 two-byte characters (40 bytes) and its blob 40 bytes, both over the 15-byte + // value limit below; 15 falls inside a character, so the text is cut to 14 + char long_text[64] = ""; + for (int k = 0; k < 20; k++) strcat(long_text, "\xC3\xA9"); + char sql[256]; + exec_ok(g_main, "INSERT INTO r VALUES(1, 1.5, 'one', x'0102', NULL)"); + snprintf(sql, sizeof sql, "INSERT INTO r VALUES(2, 2.5, '%s', zeroblob(40), NULL)", long_text); + exec_ok(g_main, sql); + exec_ok(g_main, "INSERT INTO r VALUES(3, 3.5, 'three', x'03', NULL)"); + exec_ok(g_main, "INSERT INTO r VALUES(4, 4.5, 'four', x'04', NULL)"); + exec_ok(g_main, "INSERT INTO r VALUES(5, 5.5, 'five', x'05', NULL)"); + + sqlitedbg_set_row_capture(3, 15, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT i, f, s, b, n FROM r ORDER BY i", -1, &st, NULL), SQLITE_OK); + int steps = 0; + while (sqlite3_step(st) == SQLITE_ROW) { + steps++; + // the app sees its own types and values: the extension read each column with its own accessor + CHECK_EQ(sqlite3_column_type(st, 0), SQLITE_INTEGER); + CHECK_EQ(sqlite3_column_type(st, 1), SQLITE_FLOAT); + CHECK_EQ(sqlite3_column_type(st, 2), SQLITE_TEXT); + CHECK_EQ(sqlite3_column_type(st, 3), SQLITE_BLOB); + CHECK_EQ(sqlite3_column_type(st, 4), SQLITE_NULL); + CHECK_EQ(sqlite3_column_int64(st, 0), steps); + CHECK(sqlite3_column_double(st, 1) == steps + 0.5); + } + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + CHECK_EQ(steps, 5); + + batch b; + read_all(cur, &b); + // the statement, its first three rows, its profile + CHECK_EQ(b.count, 5); + CHECK_EQ(b.events[0].kind, SQLITEDBG_EVENT_STATEMENT); + for (int k = 1; k <= 3; k++) { + const ev *e = &b.events[k]; + CHECK_EQ(e->kind, SQLITEDBG_EVENT_ROW); + CHECK_EQ(e->rows, k); + CHECK_EQ(e->changes, -1); + CHECK_EQ(e->duration_ns, -1); + CHECK_EQ(e->conn, 1); + CHECK_EQ(e->tid, tid()); + uint32_t columns = 0; + rv v[5]; + CHECK_EQ(parse_row(e, &columns, v, 5), 5); + CHECK_EQ(columns, 5); + CHECK_EQ(v[0].type, SQLITE_INTEGER); + CHECK_EQ(rv_int(&v[0]), k); + CHECK_EQ(v[1].type, SQLITE_FLOAT); + CHECK(rv_double(&v[1]) == k + 0.5); + CHECK_EQ(v[2].type, SQLITE_TEXT); + CHECK_EQ(v[3].type, SQLITE_BLOB); + CHECK_EQ(v[4].type, SQLITE_NULL); + CHECK_EQ(v[4].stored, 0); + if (k == 2) { + CHECK(e->flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK_EQ(v[2].full, 40); + CHECK_EQ(v[2].stored, 14); + CHECK_EQ(v[2].cut, 1); + CHECK(utf8_valid((const char *)v[2].p, v[2].stored)); + CHECK(memcmp(v[2].p, long_text, 14) == 0); + CHECK_EQ(v[3].full, 40); + CHECK_EQ(v[3].stored, 15); + CHECK_EQ(v[3].cut, 1); + } else { + CHECK_EQ(e->flags, 0); + const char *want = k == 1 ? "one" : "three"; + CHECK_EQ(v[2].stored, strlen(want)); + CHECK(memcmp(v[2].p, want, strlen(want)) == 0); + CHECK_EQ(v[3].cut, 0); + } + } + CHECK(memcmp(b.events[1].sql + 8 + 12 + 8 + 12 + 8 + 12 + 3 + 12, "\x01\x02", 2) == 0); + const ev *prof = &b.events[4]; + CHECK_EQ(prof->kind, SQLITEDBG_EVENT_PROFILE); + // all five rows counted, two left unrecorded by the limit; a read changes nothing + CHECK_EQ(prof->rows, 5); + CHECK(prof->flags & SQLITEDBG_EVENT_ROWS_CUT); + CHECK_EQ(prof->changes, -1); + batch_free(&b); + + // with no client, or with recording off, rows are counted but not recorded + cur = cursor_now(); + exec_ok(g_main, "SELECT i FROM r"); + sqlitedbg_set_row_capture(0, 0, 0); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "SELECT i FROM r WHERE i < 3"); + sqlitedbg_set_client_connected(0); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + const ev *all = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r"); + const ev *some = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r WHERE i < 3"); + CHECK(all != NULL); + CHECK(some != NULL); + if (all) { + CHECK_EQ(all->rows, 5); + CHECK_EQ(all->flags, 0); + } + if (some) CHECK_EQ(some->rows, 2); + batch_free(&b); +} + +static void test_internal_rows(void) { + // a CREATE TABLE runs SQLite's own nested statement that returns a row (the schema read); with + // recording on, it is not recorded + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + exec_ok(g_main, "CREATE TABLE ri(a)"); + exec_ok(g_main, "CREATE INDEX rii ON ri(a)"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + batch b; + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "CREATE TABLE ri(a)"); + CHECK(e != NULL); + if (e) CHECK_EQ(e->rows, 0); + batch_free(&b); +} + +static void test_changes(void) { + exec_ok(g_main, "CREATE TABLE c(a)"); + uint64_t cur = cursor_now(); + exec_ok(g_main, "INSERT INTO c SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3"); + exec_ok(g_main, "UPDATE c SET a = a + 1 WHERE a > 1"); + exec_ok(g_main, "DELETE FROM c WHERE a = 1"); + exec_ok(g_main, "SELECT a FROM c"); + // after the DELETE, sqlite3_changes64 still says 1: a CREATE TABLE does not set it + exec_ok(g_main, "CREATE TABLE c2(a)"); + exec_ok(g_main, "UPDATE c SET a = a WHERE 0"); + // t's trigger inserts into log too: only the insert's own row counts + exec_ok(g_main, "INSERT INTO t VALUES(5)"); + // a WITH ... INSERT is DML and keeps its count after a comment + exec_ok(g_main, "/*c*/ WITH w(x) AS (VALUES(1),(2)) INSERT INTO c SELECT x FROM w"); + // a PRAGMA stepped once, a 3-row INSERT, then the PRAGMA finished: sqlite3_changes64 holds the + // INSERT's 3 at the PRAGMA's PROFILE, which is not the PRAGMA's + exec_ok(g_main, "BEGIN"); + sqlite3_stmt *pragma; + CHECK_EQ(sqlite3_prepare_v2(g_main, "PRAGMA main.journal_mode", -1, &pragma, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(pragma), SQLITE_ROW); + exec_ok(g_main, "INSERT INTO c VALUES(1),(2),(3)"); + while (sqlite3_step(pragma) == SQLITE_ROW) { + } + sqlite3_finalize(pragma); + exec_ok(g_main, "COMMIT"); + batch b; + read_all(cur, &b); + const ev *pe = find_event(&b, SQLITEDBG_EVENT_PROFILE, "PRAGMA main.journal_mode"); + CHECK(pe != NULL); + if (pe) CHECK_EQ(pe->changes, -1); + struct { + const char *sql; + int64_t changes, rows; + } want[] = { + {"INSERT INTO c SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3", 3, 0}, + {"UPDATE c SET a = a + 1 WHERE a > 1", 2, 0}, + {"DELETE FROM c WHERE a = 1", 1, 0}, + {"SELECT a FROM c", -1, 2}, + {"CREATE TABLE c2(a)", 0, 0}, + {"UPDATE c SET a = a WHERE 0", 0, 0}, + {"INSERT INTO t VALUES(5)", 1, 0}, + {"/*c*/ WITH w(x) AS (VALUES(1),(2)) INSERT INTO c SELECT x FROM w", 2, 0}, + {"INSERT INTO c VALUES(1),(2),(3)", 3, 0}, + }; + for (size_t i = 0; i < sizeof want / sizeof want[0]; i++) { + const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, want[i].sql); + CHECK(e != NULL); + if (!e) continue; + if (e->changes != want[i].changes) fprintf(stderr, " changes of %s\n", want[i].sql); + CHECK_EQ(e->changes, want[i].changes); + CHECK_EQ(e->rows, want[i].rows); + } + batch_free(&b); +} + +// The first value of a ROW event, as an int (INTEGER) or its first byte (TEXT). +static int64_t first_value(const ev *e, int *type) { + uint32_t columns; + rv v[2]; + *type = 0; + if (parse_row(e, &columns, v, 2) < 1) return -1; + *type = v[0].type; + return v[0].type == SQLITE_INTEGER ? rv_int(&v[0]) : v[0].stored ? v[0].p[0] : -1; +} + +static void test_interleaved_rows(void) { + // two statements stepped in turn on one connection keep their own row numbers + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + sqlite3_stmt *a, *s; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 10 UNION ALL SELECT 20", -1, &a, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'", -1, &s, NULL), + SQLITE_OK); + CHECK_EQ(sqlite3_step(a), SQLITE_ROW); + CHECK_EQ(sqlite3_step(s), SQLITE_ROW); + CHECK_EQ(sqlite3_step(a), SQLITE_ROW); + CHECK_EQ(sqlite3_step(s), SQLITE_ROW); + CHECK_EQ(sqlite3_step(s), SQLITE_ROW); + sqlite3_finalize(a); + sqlite3_finalize(s); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + batch b; + read_all(cur, &b); + int64_t want_rows[] = {1, 1, 2, 2, 3}; + int64_t want_first[] = {10, 'x', 20, 'y', 'z'}; + // the execution id tells which statement a row belongs to: a, s, a, s, s + const ev *sa = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 10 UNION ALL SELECT 20"); + const ev *ss = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'"); + CHECK(sa != NULL && ss != NULL); + CHECK_EQ(b.dropped, 0); + if (sa && ss) CHECK(sa->seq != ss->seq); + size_t k = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + int type; + int64_t first = first_value(&b.events[i], &type); + if (k < 5) { + CHECK_EQ(b.events[i].rows, want_rows[k]); + CHECK_EQ(first, want_first[k]); + CHECK_EQ(type, k == 0 || k == 2 ? SQLITE_INTEGER : SQLITE_TEXT); + if (sa && ss) CHECK_EQ(b.events[i].exec_id, (k == 0 || k == 2 ? sa : ss)->seq); + } + k++; + } + CHECK_EQ(k, 5); + const ev *pa = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 10 UNION ALL SELECT 20"); + const ev *ps = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'"); + CHECK(pa != NULL); + CHECK(ps != NULL); + if (pa) CHECK_EQ(pa->rows, 2); + if (ps) CHECK_EQ(ps->rows, 3); + if (pa && sa) CHECK_EQ(pa->exec_id, sa->seq); + if (ps && ss) CHECK_EQ(ps->exec_id, ss->seq); + batch_free(&b); + + // one statement more than there are slots, each started in turn: the oldest loses its slot, so its + // later rows go unrecorded and its profile has no counts + enum { N = SQLITEDBG_STATEMENT_SLOTS + 1 }; + sqlite3_stmt *st[N]; + char sql[64]; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + for (int i = 0; i < N; i++) { + snprintf(sql, sizeof sql, "SELECT %d UNION ALL SELECT %d", i, i); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st[i], NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st[i]), SQLITE_ROW); + } + CHECK_EQ(sqlite3_step(st[0]), SQLITE_ROW); + CHECK_EQ(sqlite3_step(st[1]), SQLITE_ROW); + for (int i = 0; i < N; i++) sqlite3_finalize(st[i]); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + // one row each, plus statement 1's second row; statement 0's first row was recorded before its slot + // was evicted, and its second row found no slot and was not recorded + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), N + 1); + const ev *p0 = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 0 UNION ALL SELECT 0"); + const ev *p1 = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 1 UNION ALL SELECT 1"); + CHECK(p0 && p1); + if (p0) CHECK_EQ(p0->rows, -1); + if (p0) CHECK_EQ(p0->changes, -1); + if (p1) CHECK_EQ(p1->rows, 2); + // the evicted statement keeps its id on its STATEMENT and on the ROW recorded before the eviction; its + // later rows are not recorded, and its PROFILE says none + const ev *s0 = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 0 UNION ALL SELECT 0"); + const ev *s1 = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 1 UNION ALL SELECT 1"); + CHECK(s0 && s1); + CHECK_EQ(b.dropped, 0); + if (s0) CHECK_EQ(s0->exec_id, s0->seq); + size_t s0_rows = 0; + for (size_t i = 0; s0 && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW && b.events[i].exec_id == s0->seq) s0_rows++; + CHECK_EQ(s0_rows, 1); + if (p0) CHECK_EQ(p0->exec_id, 0); + if (s1 && p1) CHECK_EQ(p1->exec_id, s1->seq); + batch_free(&b); +} + +static void test_row_limits(void) { + // the row's data stops at max_row_bytes: the header (8) and one INTEGER (12 + 8) fit in 40, a + // second INTEGER does not + sqlitedbg_set_row_capture(10, 0, 40); + sqlitedbg_set_client_connected(1); + uint64_t cur = cursor_now(); + exec_ok(g_main, "SELECT 1, 2"); + // a value limit of 1 cuts a two-byte character to nothing, which is still a whole value + sqlitedbg_set_row_capture(10, 1, MAX_ROW_DATA); + exec_ok(g_main, "SELECT '\xC3\xA9', x'0a0b'"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + batch b; + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 2); + const ev *wide = NULL, *cut = NULL; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + if (!wide) wide = &b.events[i]; + else cut = &b.events[i]; + } + uint32_t columns; + rv v[2]; + if (wide) { + CHECK_EQ(parse_row(wide, &columns, v, 2), 1); + CHECK_EQ(columns, 2); + CHECK_EQ(rv_int(&v[0]), 1); + CHECK(wide->flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK(wide->data_bytes <= 40); + } + if (cut) { + CHECK_EQ(parse_row(cut, &columns, v, 2), 2); + CHECK_EQ(v[0].type, SQLITE_TEXT); + CHECK_EQ(v[0].stored, 0); + CHECK_EQ(v[0].full, 2); + CHECK_EQ(v[1].type, SQLITE_BLOB); + CHECK_EQ(v[1].stored, 1); + CHECK_EQ(v[1].p[0], 0x0a); + CHECK(cut->flags & SQLITEDBG_EVENT_TRUNCATED); + } + CHECK(wide && cut); + batch_free(&b); + // a row limit above SQLITEDBG_MAX_ROW_BYTES is lowered to it, so no row record outgrows a reader's batch + sqlitedbg_set_row_capture(1, 0, UINT32_MAX); + CHECK_EQ(sqlitedbg_test_max_row_bytes(), SQLITEDBG_MAX_ROW_BYTES); + sqlitedbg_set_row_capture(1, 0, 1000); + CHECK_EQ(sqlitedbg_test_max_row_bytes(), 1000); + sqlitedbg_set_row_capture(0, 0, 0); + CHECK_EQ(sqlitedbg_test_max_row_bytes(), 4096); +} + +// Peak resident set size in KiB. +static long peak_rss_kb(void) { + struct rusage u; + getrusage(RUSAGE_SELF, &u); + return u.ru_maxrss; +} + +// The CodeRabbit findings on #2332 (ADFA-7296) +static void test_review_fixes(void) { + batch b; + uint64_t cur; + const ev *e; + uint32_t columns; + rv v[2]; + + // F02: a BLOB too big to keep is not read, so the app's statement does not materialize it. A bound + // zeroblob is virtual until sqlite3_column_blob; the app only asks for the size. + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT ?1 /* big blob */", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_bind_zeroblob64(st, 1, 200u << 20), SQLITE_OK); + long before = peak_rss_kb(); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_type(st, 0), SQLITE_BLOB); + CHECK_EQ(sqlite3_column_bytes(st, 0), 200 << 20); + long grew = peak_rss_kb() - before; + if (grew > 50 * 1024) fprintf(stderr, " peak RSS grew %ld KiB\n", grew); + CHECK(grew < 50 * 1024); + sqlite3_finalize(st); + // the same size as TEXT + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT CAST(zeroblob(2000000) AS TEXT) /* big text */", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + sqlite3_finalize(st); + // and a value of exactly 1 MiB is still read, for its prefix up to the 256-byte default limit + exec_ok(g_main, "SELECT zeroblob(1048576) /* 1 MiB blob */"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 3); + size_t k = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + CHECK_EQ(parse_row(&b.events[i], &columns, v, 2), 1); + CHECK(b.events[i].flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK_EQ(v[0].type, k == 1 ? SQLITE_TEXT : SQLITE_BLOB); + CHECK_EQ(v[0].cut, 1); + CHECK_EQ(v[0].full, k == 0 ? 200u << 20 : k == 1 ? 2000000u : 1048576u); + CHECK_EQ(v[0].stored, k == 2 ? 256 : 0); + k++; + } + batch_free(&b); + + // F04: an INSERT ... RETURNING stepped once and reset has inserted both rows, but its count is + // not known yet; run to the end it is exact + exec_ok(g_main, "CREATE TABLE rt(a)"); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO rt VALUES(1),(2) RETURNING a", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_reset(st), SQLITE_OK); + CHECK_EQ(sqlite3_finalize(st), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO rt VALUES(3),(4) RETURNING a", -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + exec_ok(g_main, "SELECT count(*) FROM rt /* four */"); + read_all(cur, &b); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "INSERT INTO rt VALUES(1),(2) RETURNING a"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->changes, -1); + CHECK_EQ(e->rows, 1); + } + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "INSERT INTO rt VALUES(3),(4) RETURNING a"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->changes, 2); + CHECK_EQ(e->rows, 2); + } + batch_free(&b); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT count(*) FROM rt", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 4); + sqlite3_finalize(st); + + // F05: a first step that returns SQLITE_BUSY ends in a PROFILE event; when the lock is gone the + // same execution goes on, and its rows are still numbered and recorded + exec_ok(g_main, "CREATE TABLE bq(a); INSERT INTO bq VALUES(1),(2),(3)"); + sqlite3 *other = open_app(g_db_path); + exec_ok(other, "BEGIN EXCLUSIVE"); + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM bq", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_BUSY); + exec_ok(other, "COMMIT"); + int n = 0; + while (sqlite3_step(st) == SQLITE_ROW) n++; + CHECK_EQ(n, 3); + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + sqlite3_close(other); + read_all(cur, &b); + size_t rows_seen = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW) continue; + rows_seen++; + CHECK_EQ(b.events[i].rows, (int64_t)rows_seen); + CHECK_EQ(parse_row(&b.events[i], &columns, v, 2), 1); + CHECK_EQ(rv_int(&v[0]), (int64_t)rows_seen); + } + CHECK_EQ(rows_seen, 3); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT a FROM bq"); + CHECK(e != NULL); + if (e) CHECK_EQ(e->rows, 0); + // the rows after the BUSY profile keep the execution id + const ev *bs = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT a FROM bq"); + CHECK(bs != NULL); + if (e && bs) CHECK_EQ(e->exec_id, bs->seq); + for (size_t i = 0; bs && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW) CHECK_EQ(b.events[i].exec_id, bs->seq); + batch_free(&b); + + // F06: a row limit below a row header records nothing, and the profile says rows were left out + sqlitedbg_set_row_capture(1, 0, 7); + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + exec_ok(g_main, "SELECT 1 /* no room */"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 1 /* no room */"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->rows, 1); + CHECK(e->flags & SQLITEDBG_EVENT_ROWS_CUT); + } + batch_free(&b); +} + +// A statement run by an app function, on the connection that called it. +static sqlite3_stmt *g_inner; + +static void nested_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv) { + (void)argc; + (void)argv; + int n = 0; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 100 UNION ALL SELECT 200 /* nested */", -1, &g_inner, NULL), SQLITE_OK); + while (sqlite3_step(g_inner) == SQLITE_ROW) n++; + sqlite3_finalize(g_inner); + sqlite3_result_int(ctx, n); +} + +// Leaves a slot behind at the address of a finalized statement: a first step that returns SQLITE_BUSY +// (rows 0, so the slot is kept) and a resumed run to the end, which fires no PROFILE. The address is +// returned so a test can make another statement land on it. +static sqlite3_stmt *leave_stale_slot(sqlite3 *other, const char *sql) { + sqlite3_stmt *st; + exec_ok(other, "BEGIN EXCLUSIVE"); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_BUSY); + exec_ok(other, "COMMIT"); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + return st; +} + +static void test_execution_id(void) { + batch b; + uint64_t cur; + sqlite3_stmt *st; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "CREATE TABLE xe(a); INSERT INTO xe VALUES(1),(2)"); + + // the STATEMENT's execution id is its own seq, and its PROFILE carries it + cur = cursor_now(); + exec_ok(g_main, "SELECT 1 /* own id */"); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(b.count, 3); + CHECK_EQ(check_runs(&b), 1); + const ev *e = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT 1 /* own id */"); + if (e) CHECK(e->exec_id != 0); + batch_free(&b); + + // runs of one statement get their own ids: after reset, after stepping past DONE, and after a + // finalize and a prepare of the same text (often at the same address) + cur = cursor_now(); + const char *again = "SELECT a FROM xe /* again */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, again, -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); // a new run, started by stepping past DONE + CHECK_EQ(sqlite3_reset(st), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + CHECK_EQ(sqlite3_prepare_v2(g_main, again, -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(check_runs(&b), 4); + for (size_t i = 0; i < 4; i++) + for (size_t j = i + 1; j < 4; j++) { + const ev *x = nth_event(&b, SQLITEDBG_EVENT_STATEMENT, again, i); + const ev *y = nth_event(&b, SQLITEDBG_EVENT_STATEMENT, again, j); + CHECK(x && y && x->exec_id != y->exec_id); + } + batch_free(&b); + + // a trigger's statements carry no id; a statement an app function runs carries none either, and its + // rows are not recorded (a slot left at its address is not its) + exec_ok(g_main, "CREATE TABLE xt(a); CREATE TABLE xlog(a)"); + exec_ok(g_main, "CREATE TRIGGER xtrg AFTER INSERT ON xt BEGIN INSERT INTO xlog VALUES(new.a); END"); + cur = cursor_now(); + exec_ok(g_main, "INSERT INTO xt VALUES(1)"); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + size_t outer = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_STATEMENT) continue; + if (!strncmp(b.events[i].sql, "-- ", 3)) CHECK_EQ(b.events[i].exec_id, 0); + else { + CHECK_EQ(b.events[i].exec_id, b.events[i].seq); + outer++; + } + } + CHECK_EQ(outer, 1); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "INSERT INTO xt VALUES(1)"); + const ev *os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "INSERT INTO xt VALUES(1)"); + CHECK(e && os); + if (e && os) CHECK_EQ(e->exec_id, os->seq); + batch_free(&b); + + // RETURNING from a statement that fires a trigger: the row keeps the outer id + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO xt VALUES(2) RETURNING a", -1, &st, NULL), SQLITE_OK); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "INSERT INTO xt VALUES(2) RETURNING a"); + CHECK(os != NULL); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 1); + for (size_t i = 0; os && i < b.count; i++) { + if (b.events[i].kind == SQLITEDBG_EVENT_ROW) CHECK_EQ(b.events[i].exec_id, os->seq); + if (b.events[i].kind == SQLITEDBG_EVENT_STATEMENT && !strncmp(b.events[i].sql, "-- ", 3)) + CHECK_EQ(b.events[i].exec_id, 0); + } + batch_free(&b); + + // a trigger whose step has the same text as the statement that fires it: the step is traced as + // "-- UPDATE tr SET b=1" with P the running statement, which is not a nested statement. The live slot + // stays, so the PROFILE keeps the id and the counts. + exec_ok(g_main, "CREATE TABLE tr(a, b); INSERT INTO tr VALUES(1, 0)"); + exec_ok(g_main, "CREATE TRIGGER trs AFTER UPDATE ON tr BEGIN UPDATE tr SET b=1; END"); + cur = cursor_now(); + exec_ok(g_main, "UPDATE tr SET b=1"); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "UPDATE tr SET b=1"); + CHECK(os != NULL); + CHECK(find_event(&b, SQLITEDBG_EVENT_STATEMENT, "-- UPDATE tr SET b=1") != NULL); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "UPDATE tr SET b=1"); + CHECK(e != NULL); + if (e && os) { + CHECK_EQ(e->exec_id, os->seq); + CHECK_EQ(e->rows, 0); + CHECK_EQ(e->changes, 1); + } + batch_free(&b); + + exec_ok(g_main, "CREATE TABLE xb(a); INSERT INTO xb VALUES(1),(2),(3)"); + sqlite3 *other = open_app(g_db_path); + sqlite3_create_function(g_main, "nested_fn", 0, SQLITE_UTF8, NULL, nested_fn, NULL, NULL); + + // a statement run inside an app function, at the address of a stale slot + cur = cursor_now(); + sqlite3_stmt *stale = leave_stale_slot(other, "SELECT a FROM xb /* stale 1 */"); + sqlite3_stmt *filler, *outerst; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 0 /* filler */", -1, &filler, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT nested_fn()", -1, &outerst, NULL), SQLITE_OK); + sqlite3_finalize(filler); // the stale address is free again, for the statement the function prepares + while (sqlite3_step(outerst) == SQLITE_ROW) { + } + sqlite3_finalize(outerst); + CHECK(g_inner == stale); // else this checks nothing + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT nested_fn()"); + CHECK(os != NULL); + e = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "-- SELECT 100 UNION ALL SELECT 200 /* nested */"); + CHECK(e != NULL); + if (e) CHECK_EQ(e->exec_id, 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 100 UNION ALL SELECT 200 /* nested */"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT nested_fn()"); + CHECK(e != NULL); + if (e && os) CHECK_EQ(e->exec_id, os->seq); + // the three rows of the stale statement, one of the outer statement, none of the nested one + size_t outer_rows = 0; + for (size_t i = 0; os && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW && b.events[i].exec_id == os->seq) outer_rows++; + CHECK_EQ(outer_rows, 1); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 4); + batch_free(&b); + + // an EXPLAIN is traced with no STATEMENT: at the address of a stale slot it is not that statement + cur = cursor_now(); + stale = leave_stale_slot(other, "SELECT a FROM xb /* stale 2 */"); + CHECK_EQ(sqlite3_prepare_v2(g_main, "EXPLAIN SELECT 1", -1, &st, NULL), SQLITE_OK); + CHECK(st == stale); // else this checks nothing + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "EXPLAIN SELECT 1"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + batch_free(&b); + + // a schema read (traced as ROW only, sqlite3_sql NULL) after another connection's DDL, with a + // stale slot about: the stale statement keeps just its own three rows. Not known to fail without + // the guard; kept as a regression test. + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM xb WHERE a = 2 /* kept */", -1, &st, NULL), SQLITE_OK); + stale = leave_stale_slot(other, "SELECT a FROM xb /* stale 3 */"); + exec_ok(other, "CREATE TABLE xother(y)"); + while (sqlite3_step(st) == SQLITE_ROW) { + } + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT a FROM xb /* stale 3 */"); + CHECK(os != NULL); + size_t stale_rows = 0; + for (size_t i = 0; os && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW && b.events[i].exec_id == os->seq) stale_rows++; + CHECK_EQ(stale_rows, 3); + batch_free(&b); + sqlite3_close(other); + + // a client that connects mid-run: the row recorded after it keeps the STATEMENT's id, though the + // STATEMENT was recorded with no client + sqlitedbg_set_client_connected(0); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM xe /* late client */", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + sqlitedbg_set_client_connected(1); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 1); + os = find_event(&b, SQLITEDBG_EVENT_STATEMENT, "SELECT a FROM xe /* late client */"); + CHECK(os != NULL); + for (size_t i = 0; os && i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_ROW) { + CHECK_EQ(b.events[i].rows, 2); + CHECK_EQ(b.events[i].exec_id, os->seq); + } + batch_free(&b); + + // CLOSE has no id + cur = cursor_now(); + sqlite3 *c = open_app(":memory:"); + exec_ok(c, "SELECT 1"); + CHECK_EQ(sqlite3_close(c), SQLITE_OK); + read_all(cur, &b); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_CLOSE), 1); + for (size_t i = 0; i < b.count; i++) + if (b.events[i].kind == SQLITEDBG_EVENT_CLOSE) CHECK_EQ(b.events[i].exec_id, 0); + batch_free(&b); + + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); +} + +static void step_to_done(sqlite3_stmt *st) { + while (sqlite3_step(st) == SQLITE_ROW) { + } +} + +// The events of one statement text, after the run: how many STATEMENTs, PROFILEs and ROWs there are, +// and that each carries the STATEMENT's id. Rows are the only ROW events in the batch. +typedef struct retry_events { + const ev *stmt; + const ev *first_profile, *last_profile; + size_t statements, profiles, rows; +} retry_events; + +static retry_events check_retry(const batch *b, const char *sql) { + retry_events r = {0}; + for (size_t i = 0; i < b->count; i++) { + const ev *e = &b->events[i]; + if (e->kind == SQLITEDBG_EVENT_ROW) r.rows++; + if (strcmp(e->sql, sql) != 0) continue; + if (e->kind == SQLITEDBG_EVENT_STATEMENT) { + r.statements++; + r.stmt = e; + } + if (e->kind == SQLITEDBG_EVENT_PROFILE) { + r.profiles++; + if (!r.first_profile) r.first_profile = e; + r.last_profile = e; + } + } + CHECK(r.stmt != NULL); + for (size_t i = 0; r.stmt && i < b->count; i++) { + const ev *e = &b->events[i]; + if (e->kind == SQLITEDBG_EVENT_ROW || (e->kind == SQLITEDBG_EVENT_PROFILE && strcmp(e->sql, sql) == 0)) + CHECK_EQ(e->exec_id, r.stmt->seq); + } + return r; +} + +// A statement that is run again by SQLite after SQLITE_SCHEMA fires no second STATEMENT: the rerun's +// rows and PROFILE keep the id of the one that started it (option b of ADFA-7379). +static void test_schema_retry(void) { + batch b; + uint64_t cur; + sqlite3_stmt *st; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "CREATE TABLE sr(a); INSERT INTO sr VALUES(1),(2)"); + sqlite3 *other = open_app(g_db_path); + + // a SELECT, after another connection's DDL and after a CREATE TABLE on its own connection + for (int same = 0; same < 2; same++) { + const char *sql = same ? "SELECT a FROM sr /* retry same */" : "SELECT a FROM sr /* retry other */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(same ? g_main : other, same ? "CREATE TABLE sr_same(y)" : "CREATE TABLE sr_other(y)"); + step_to_done(st); + CHECK_EQ(sqlite3_stmt_status(st, SQLITE_STMTSTATUS_REPREPARE, 0), 1); // else this checks nothing + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + retry_events r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 2); + CHECK_EQ(r.rows, 2); + if (r.first_profile) CHECK_EQ(r.first_profile->rows, 0); + if (r.last_profile) CHECK_EQ(r.last_profile->rows, 2); + batch_free(&b); + } + + // control: CREATE INDEX on the same connection expires the statement before it runs: one STATEMENT + // and one PROFILE + const char *sql = "SELECT a FROM sr /* control */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(g_main, "CREATE INDEX sr_i ON sr(a)"); + step_to_done(st); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + retry_events r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 1); + CHECK_EQ(r.rows, 2); + if (r.last_profile) CHECK_EQ(r.last_profile->rows, 2); + batch_free(&b); + + // a write with no rows: both PROFILEs carry the id, and the second has the change + sql = "INSERT INTO sr VALUES(7) /* retry write */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(other, "CREATE TABLE sr_w(y)"); + step_to_done(st); + CHECK_EQ(sqlite3_stmt_status(st, SQLITE_STMTSTATUS_REPREPARE, 0), 1); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 2); + if (r.last_profile) CHECK_EQ(r.last_profile->changes, 1); + batch_free(&b); + + // BUSY on the first step, and the lock holder's DDL makes the resumed step hit SQLITE_SCHEMA + sql = "SELECT a FROM sr /* busy then schema */"; + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &st, NULL), SQLITE_OK); + cur = cursor_now(); + exec_ok(other, "BEGIN EXCLUSIVE; CREATE TABLE sr_b(y)"); + CHECK_EQ(sqlite3_step(st), SQLITE_BUSY); + exec_ok(other, "COMMIT"); + step_to_done(st); + CHECK_EQ(sqlite3_stmt_status(st, SQLITE_STMTSTATUS_REPREPARE, 0), 1); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + r = check_retry(&b, sql); + CHECK_EQ(r.statements, 1); + CHECK_EQ(r.profiles, 2); + CHECK_EQ(r.rows, 3); + if (r.last_profile) CHECK_EQ(r.last_profile->rows, 3); + batch_free(&b); + + sqlite3_close(other); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); +} + +// A slot that ended (a finalized statement that returned no rows) stays until its address is used +// again, so an event with no STATEMENT at that address must not be taken for that statement's. The +// REPREPARE check that guards this is defence in depth: the EXPLAIN and nested-statement guards catch +// every such event first, and no event is known to reach it, so a mutation of the check does not fail +// this test; it covers those two guards against ended slots. +static void test_ended_slot(void) { + batch b; + uint64_t cur; + sqlite3_stmt *st, *zero; + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "CREATE TABLE ez(a)"); + + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM ez /* ended 1 */", -1, &zero, NULL), SQLITE_OK); + step_to_done(zero); + sqlite3_finalize(zero); + CHECK_EQ(sqlite3_prepare_v2(g_main, "EXPLAIN SELECT 1", -1, &st, NULL), SQLITE_OK); + CHECK(st == zero); // else this checks nothing + step_to_done(st); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + const ev *e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "EXPLAIN SELECT 1"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 0); + batch_free(&b); + + // a statement an app function runs, at that address + sqlite3_create_function(g_main, "nested_fn", 0, SQLITE_UTF8, NULL, nested_fn, NULL, NULL); + exec_ok(g_main, "INSERT INTO ez VALUES(1)"); + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT a FROM ez WHERE a < 0 /* ended 2 */", -1, &zero, NULL), SQLITE_OK); + step_to_done(zero); + sqlite3_finalize(zero); + sqlite3_stmt *filler, *outerst; + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT 0 /* filler */", -1, &filler, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT nested_fn()", -1, &outerst, NULL), SQLITE_OK); + sqlite3_finalize(filler); + step_to_done(outerst); + sqlite3_finalize(outerst); + CHECK(g_inner == zero); // else this checks nothing + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + e = find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 100 UNION ALL SELECT 200 /* nested */"); + CHECK(e != NULL); + if (e) { + CHECK_EQ(e->exec_id, 0); + CHECK_EQ(e->rows, -1); + } + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), 1); // the outer statement's only + batch_free(&b); + + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); +} + +// Finished 0-row statements leave ended slots; they are reused before a live cursor's slot is evicted. +static void test_slot_pressure(void) { + enum { CURSORS = SQLITEDBG_STATEMENT_SLOTS - 1, INSERTS = 40 }; + batch b; + sqlite3_stmt *cur_st[CURSORS], *ins[INSERTS]; + char sql[64]; + exec_ok(g_main, "CREATE TABLE sp(a)"); + sqlitedbg_set_row_capture(10, 0, MAX_ROW_DATA); + sqlitedbg_set_client_connected(0); + uint64_t cur = cursor_now(); + for (int i = 0; i < CURSORS; i++) { + snprintf(sql, sizeof sql, "SELECT %d UNION ALL SELECT %d", i, i + 100); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &cur_st[i], NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(cur_st[i]), SQLITE_ROW); + } + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_STATEMENT), CURSORS); + uint64_t stmt_id[CURSORS] = {0}; + for (int i = 0; i < CURSORS; i++) { + snprintf(sql, sizeof sql, "SELECT %d UNION ALL SELECT %d", i, i + 100); + const ev *s = find_event(&b, SQLITEDBG_EVENT_STATEMENT, sql); + CHECK(s != NULL); + if (s) stmt_id[i] = s->seq; + } + batch_free(&b); + + // all 40 are prepared before any is finalized, so they are 40 different statements + for (int i = 0; i < INSERTS; i++) { + snprintf(sql, sizeof sql, "INSERT INTO sp VALUES(%d)", i); + CHECK_EQ(sqlite3_prepare_v2(g_main, sql, -1, &ins[i], NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(ins[i]), SQLITE_DONE); + } + for (int i = 0; i < INSERTS; i++) sqlite3_finalize(ins[i]); + + sqlitedbg_set_client_connected(1); + cur = cursor_now(); + for (int i = 0; i < CURSORS; i++) CHECK_EQ(sqlite3_step(cur_st[i]), SQLITE_ROW); + for (int i = 0; i < CURSORS; i++) sqlite3_finalize(cur_st[i]); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + read_all(cur, &b); + CHECK_EQ(b.dropped, 0); + // every cursor's second row is recorded, with its own statement's id + CHECK_EQ(count_kind(&b, SQLITEDBG_EVENT_ROW), CURSORS); + int k = 0; + for (size_t i = 0; i < b.count; i++) { + if (b.events[i].kind != SQLITEDBG_EVENT_ROW || k >= CURSORS) continue; + CHECK_EQ(b.events[i].rows, 2); + CHECK_EQ(b.events[i].exec_id, stmt_id[k]); + k++; + } + batch_free(&b); +} + static void test_burst(void) { uint64_t cur = cursor_now(); const int stmts = 2000; @@ -513,7 +1587,7 @@ static void test_close_and_list(void) { CHECK_EQ(b.count, 1); CHECK_EQ(b.events[0].kind, SQLITEDBG_EVENT_CLOSE); CHECK_EQ(b.events[0].conn, id); - CHECK_EQ(b.events[0].sql_bytes, 0); + CHECK_EQ(b.events[0].data_bytes, 0); batch_free(&b); // the failed close left the connection open: a statement on it clears closing, a second failed close sets it @@ -971,6 +2045,7 @@ typedef struct worker { int index; atomic_int *stop; long long stmts, closes; + long long row_stmts; // statements that return one row: each adds at most one row event int failed; } worker; @@ -998,6 +2073,7 @@ static void *worker_main(void *arg) { if (n % 7 == 0) { if (sqlite3_exec(db, "SELECT count(*) FROM w", NULL, NULL, NULL) != SQLITE_OK) w->failed = 1; w->stmts++; + w->row_stmts++; } if (n % 50 == 0) { // connection churn beside the other threads' statements @@ -1008,6 +2084,7 @@ static void *worker_main(void *arg) { } if (sqlite3_exec(extra, "SELECT 1", NULL, NULL, NULL) != SQLITE_OK) w->failed = 1; w->stmts++; + w->row_stmts++; if (sqlite3_close(extra) != SQLITE_OK) w->failed = 1; w->closes++; } @@ -1020,6 +2097,7 @@ static void *worker_main(void *arg) { typedef struct reader { atomic_int *stop; + uint64_t first; // read from here: the earlier tests' events have triggers and nested statements int failed; long long reads; } reader; @@ -1029,20 +2107,44 @@ static void list_noop(void *context, const sqlitedbg_connection *c) { if (c->id == 0 || !c->path) *(int *)context = 1; } +// The last STATEMENT's execution id seen on each connection (by id modulo the table size), to check +// that every ROW and PROFILE carries its connection's current one. +#define RUNS 256 +typedef struct run_table { + uint64_t conn[RUNS], run[RUNS]; +} run_table; + static void *reader_main(void *arg) { reader *r = arg; static unsigned char buf[2048]; - uint64_t after = 0; + uint64_t after = r->first; + run_table runs; + memset(&runs, 0, sizeof runs); while (!atomic_load(r->stop)) { sqlitedbg_read_result res; sqlitedbg_read_events(after, buf, sizeof buf, &res); + if (res.dropped) memset(&runs, 0, sizeof runs); size_t off = 0; uint64_t prev = after; for (size_t i = 0; i < res.count; i++) { const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); - if (rec->seq <= prev || rec->record_bytes % 8 || rec->kind < 1 || rec->kind > 3 || - rec->record_bytes < sizeof *rec + rec->sql_bytes) + if (rec->seq <= prev || rec->record_bytes % 8 || rec->kind < 1 || rec->kind > 4 || + rec->record_bytes < sizeof *rec + rec->data_bytes) + r->failed = 1; + // The workers run statements one at a time on each connection, so a STATEMENT's id is its + // seq, later than the connection's last, and its ROWs and PROFILE carry it. Events dropped + // before this read can have taken the STATEMENT, so the table is only trusted after it. + uint64_t slot = rec->connection_id % RUNS; + if (rec->kind == SQLITEDBG_EVENT_STATEMENT) { + if (rec->execution_id != rec->seq) r->failed = 1; + if (runs.conn[slot] == rec->connection_id && runs.run[slot] >= rec->execution_id) r->failed = 1; + runs.conn[slot] = rec->connection_id; + runs.run[slot] = rec->execution_id; + } else if (rec->kind == SQLITEDBG_EVENT_CLOSE) { + if (rec->execution_id != 0) r->failed = 1; + } else if (runs.conn[slot] == rec->connection_id && rec->execution_id != runs.run[slot]) { r->failed = 1; + } prev = rec->seq; off += rec->record_bytes; } @@ -1051,9 +2153,12 @@ static void *reader_main(void *arg) { int bad = 0; sqlitedbg_each_connection(list_noop, &bad); if (bad) r->failed = 1; + // row recording switched on and off while the workers' statements return rows + sqlitedbg_set_row_capture(r->reads % 2 ? 4 : 0, 0, 0); sqlitedbg_set_client_connected(r->reads++ % 3 == 0); } sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); return NULL; } @@ -1069,6 +2174,7 @@ static void test_threads(void) { memset(w, 0, sizeof w); memset(&rd, 0, sizeof rd); rd.stop = &stop; + rd.first = cur; pthread_create(&rt, NULL, reader_main, &rd); for (int i = 0; i < N; i++) { w[i].index = i; @@ -1081,11 +2187,12 @@ static void test_threads(void) { for (int i = 0; i < N; i++) pthread_join(th[i], NULL); pthread_join(rt, NULL); - long long stmts = 0, closes = 0; + long long stmts = 0, closes = 0, row_stmts = 0; for (int i = 0; i < N; i++) { CHECK_EQ(w[i].failed, 0); stmts += w[i].stmts; closes += w[i].closes; + row_stmts += w[i].row_stmts; } CHECK_EQ(rd.failed, 0); CHECK(stmts > 1000); @@ -1093,17 +2200,64 @@ static void test_threads(void) { CHECK_EQ(list_conns(&l), before); batch b; read_all(0, &b); - CHECK_EQ(b.next - cur, 2 * (uint64_t)stmts + (uint64_t)closes); + // two events per statement, one per close, and one per recorded row: at most one per row statement + uint64_t made = b.next - cur, base = 2 * (uint64_t)stmts + (uint64_t)closes; + CHECK(made >= base); + CHECK(made <= base + (uint64_t)row_stmts); batch_free(&b); printf(" threads: %lld statements, %lld closes, %lld reads\n", stmts, closes, rd.reads); } // Fixture for EventDecoder's JVM test: a known run, as bytes plus a table of what they hold. -static void write_tsv_row(FILE *f, const sqlitedbg_event_record *r, const char *sql) { - fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%.*s\n", (unsigned long long)r->seq, r->kind, +// A ROW event's data as text: "/|" and then each value, comma-separated, as a type +// letter (i, f, t, b, n), "*" if it was cut, ":" and the value: an integer in decimal, a float with +// %.17g, text as is, a blob in lowercase hex, nothing for NULL. Returns 0 if the data is malformed. +static int write_row_data(FILE *f, const unsigned char *d, size_t n) { + sqlitedbg_row_header h; + if (n < sizeof h) return 0; + memcpy(&h, d, sizeof h); + fprintf(f, "%u/%u|", h.columns, h.kept); + size_t off = sizeof h; + for (uint32_t i = 0; i < h.kept; i++) { + sqlitedbg_row_value v; + if (n - off < sizeof v) return 0; + memcpy(&v, d + off, sizeof v); + off += sizeof v; + if (v.stored_bytes > n - off) return 0; + const unsigned char *p = d + off; + const char *letter = v.type == SQLITE_INTEGER ? "i" : v.type == SQLITE_FLOAT ? "f" : v.type == SQLITE_TEXT ? "t" + : v.type == SQLITE_BLOB ? "b" : "n"; + fprintf(f, "%s%s%s:", i ? "," : "", letter, v.cut ? "*" : ""); + if (v.type == SQLITE_INTEGER || v.type == SQLITE_FLOAT) { + if (v.stored_bytes != 8) return 0; + long long x; + double y; + memcpy(&x, p, 8); + memcpy(&y, p, 8); + if (v.type == SQLITE_INTEGER) fprintf(f, "%lld", x); + else fprintf(f, "%.17g", y); + } else if (v.type == SQLITE_TEXT) { + fprintf(f, "%.*s", (int)v.stored_bytes, (const char *)p); + } else if (v.type == SQLITE_BLOB) { + for (uint32_t k = 0; k < v.stored_bytes; k++) fprintf(f, "%02x", p[k]); + } + off += v.stored_bytes; + } + return off == n; +} + +// seq, kind, connection, thread, time, duration, flags, rows, changes, execution id, then the SQL or the row data. +static int write_tsv_row(FILE *f, const sqlitedbg_event_record *r, const char *data) { + fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%lld\t%lld\t%llu\t", (unsigned long long)r->seq, r->kind, (unsigned long long)r->connection_id, (long long)r->thread_id, (long long)r->time_ns, - (long long)r->duration_ns, r->flags, (int)r->sql_bytes, sql); + (long long)r->duration_ns, r->flags, (long long)r->rows, (long long)r->changes, + (unsigned long long)r->execution_id); + int ok = 1; + if (r->kind == SQLITEDBG_EVENT_ROW) ok = write_row_data(f, (const unsigned char *)data, r->data_bytes); + else fprintf(f, "%.*s", (int)r->data_bytes, data); + fputc('\n', f); + return ok; } static void run_fixture_scenario(void) { @@ -1130,6 +2284,14 @@ static void run_fixture_scenario(void) { sqlite3 *c = open_app(":memory:"); exec_ok(c, "SELECT 1"); CHECK_EQ(sqlite3_close(c), SQLITE_OK); + // recorded rows (ADFA-7296): every type, a text and a blob cut at 4 bytes, and a profile with its + // counts and ROWS_CUT; then a write's change count + sqlitedbg_set_row_capture(1, 4, 1024); + sqlitedbg_set_client_connected(1); + exec_ok(g_main, "SELECT 7, 2.5, 'h\xC3\xA9llo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9, -0.125, 'ab', x'', NULL"); + sqlitedbg_set_client_connected(0); + sqlitedbg_set_row_capture(0, 0, 0); + exec_ok(g_main, "DELETE FROM fxlog"); } static unsigned char *slurp(const char *path, size_t *n) { @@ -1159,11 +2321,14 @@ static int bin_to_tsv(const unsigned char *bin, size_t n, char **out) { while (off < n) { const sqlitedbg_event_record *r = (const sqlitedbg_event_record *)(const void *)(bin + off); if (off + sizeof *r > n || r->record_bytes % 8 || off + r->record_bytes > n || - r->record_bytes < sizeof *r + r->sql_bytes) { + r->record_bytes < sizeof *r + r->data_bytes) { + ok = 0; + break; + } + if (!write_tsv_row(f, r, (const char *)bin + off + sizeof *r)) { ok = 0; break; } - write_tsv_row(f, r, (const char *)bin + off + sizeof *r); off += r->record_bytes; } fclose(f); @@ -1231,6 +2396,17 @@ int main(int argc, char **argv) { test_expanded(); printf("# truncation\n"); test_truncation(); + printf("# rows and changes\n"); + test_rows(); + test_internal_rows(); + test_changes(); + test_interleaved_rows(); + test_row_limits(); + test_review_fixes(); + test_execution_id(); + test_schema_retry(); + test_ended_slot(); + test_slot_pressure(); printf("# burst\n"); test_burst(); printf("# cursor reset\n"); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt index 555e566544..b2bc5aed91 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -9,13 +9,13 @@ import java.nio.ByteOrder class EventDecoderTest { // events.bin is what sqlitedbg_read_events copied out in sqlitedbg_test.c (test.sh --update-fixture); // events.tsv is the same records as the C struct reads them: seq, kind, connection, thread, time, - // duration, flags, sql. + // duration, flags, rows, changes, execution id, then the SQL or, for a row, its values (see write_row_data there). private val bytes = resource("events.bin") private val table = String(resource("events.tsv"), Charsets.UTF_8) .trimEnd('\n') .split('\n') - .map { it.split('\t', limit = 8) } + .map { it.split('\t', limit = 11) } private fun resource(name: String): ByteArray = checkNotNull(javaClass.getResourceAsStream(name)) { "missing fixture $name" }.use { it.readBytes() } @@ -34,7 +34,43 @@ class EventDecoderTest { assertThat(event.durationNanos).isEqualTo(if (event.kind == EventKind.PROFILE) row[5].toLong() else null) assertThat(event.truncated).isEqualTo(row[6].toInt() and 1 != 0) assertThat(event.expanded).isEqualTo(row[6].toInt() and 2 != 0) - assertThat(event.sql).isEqualTo(row[7]) + assertThat(event.rowsCut).isEqualTo(row[6].toInt() and 4 != 0) + assertThat(event.rows).isEqualTo(row[7].toLong().takeIf { it >= 0 }) + assertThat(event.changes).isEqualTo(row[8].toLong().takeIf { it >= 0 }) + assertThat(event.executionId).isEqualTo(row[9].toLong().takeIf { it != 0L && event.kind != EventKind.CLOSE }) + if (event.kind == EventKind.ROW) { + assertThat(event.sql).isEmpty() + assertRow(event.row, row[10]) + } else { + assertThat(event.row).isNull() + assertThat(event.sql).isEqualTo(row[10]) + } + } + } + + // row is "/|" and then each value: a type letter (i, f, t, b, n), "*" if cut, ":" and + // the value (decimal, %.17g, text, lowercase hex, nothing for NULL). + private fun assertRow( + actual: RowValues?, + row: String, + ) { + checkNotNull(actual) + val (counts, values) = row.split('|', limit = 2) + val (columns, kept) = counts.split('/').map { it.toInt() } + assertThat(actual.columnCount).isEqualTo(columns) + assertThat(actual.values).hasSize(kept) + values.split(',').forEachIndexed { i, token -> + val (type, text) = token.split(':', limit = 2) + assertThat(i in actual.cutIndexes).isEqualTo(type.endsWith("*")) + val value = actual.values[i] + when (type.trimEnd('*')) { + "i" -> assertThat(value).isEqualTo(text.toLong()) + "f" -> assertThat(value).isEqualTo(text.toDouble()) + "t" -> assertThat(value).isEqualTo(text) + "b" -> assertThat((value as ByteArray).joinToString("") { "%02x".format(it) }).isEqualTo(text) + "n" -> assertThat(value).isNull() + else -> error("unknown type $type") + } } } @@ -45,12 +81,93 @@ class EventDecoderTest { assertThat(events.map { it.kind }.toSet()).containsExactlyElementsIn(EventKind.values().toList()) assertThat(events.any { it.truncated }).isTrue() assertThat(events.any { it.expanded }).isTrue() + assertThat(events.any { it.rowsCut }).isTrue() + assertThat(events.any { (it.changes ?: 0) > 0 }).isTrue() + // a row with every type, and a cut TEXT and BLOB + val row = checkNotNull(events.single { it.kind == EventKind.ROW }.row) + assertThat(row.values.map { it?.javaClass }) + .containsExactly( + Long::class.javaObjectType, + Double::class.javaObjectType, + String::class.java, + ByteArray::class.java, + null, + ).inOrder() + assertThat(row.cutIndexes).containsExactly(2, 3) assertThat(events.any { it.sql.startsWith("--") }).isTrue() // multi-byte text survives, including a character outside the BMP assertThat(events.any { it.sql.contains("héllo € 😀") }).isTrue() assertThat(events.map { it.seq }).isInOrder() } + @Test + fun `the header is 80 bytes and the execution id sits at offset 72`() { + assertThat(EventDecoder.HEADER_BYTES).isEqualTo(80) + val copy = bytes.copyOf() + ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN).putLong(72, 77) + assertThat(EventDecoder.decode(copy, copy.size).first().executionId).isEqualTo(77) + } + + @Test + fun `the fixture's ROW and PROFILE events carry their STATEMENT's id`() { + val events = EventDecoder.decode(bytes, bytes.size) + + var run: Long? = null + for (event in events) { + when { + event.kind == EventKind.STATEMENT && event.sql.startsWith("-- ") -> { + assertThat(event.executionId).isNull() + } + + event.kind == EventKind.STATEMENT -> { + assertThat(event.executionId).isEqualTo(event.seq) + run = event.seq + } + + event.kind == EventKind.CLOSE -> { + assertThat(event.executionId).isNull() + } + + else -> { + assertThat(event.executionId).isEqualTo(run) + } + } + } + assertThat(events.single { it.kind == EventKind.ROW }.executionId).isNotNull() + } + + @Test + fun `ROW records decode their own execution ids`() { + fun rowRecord( + seq: Long, + executionId: Long, + ): ByteArray { + // the header, then an empty row: columns 0, kept 0 + val record = ByteBuffer.allocate(EventDecoder.HEADER_BYTES + EventDecoder.ROW_HEADER_BYTES).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(0, record.capacity()) + record.putInt(4, EventKind.ROW.nativeValue) + record.putLong(8, seq) + record.putInt(52, EventDecoder.ROW_HEADER_BYTES) + record.putLong(56, 1) + record.putLong(64, -1) + record.putLong(72, executionId) + return record.array() + } + val both = rowRecord(5, 77) + rowRecord(6, 91) + rowRecord(7, 0) + + assertThat(EventDecoder.decode(both, both.size).map { it.executionId }).containsExactly(77L, 91L, null).inOrder() + } + + @Test + fun `a record with a 72-byte header is refused`() { + // a producer built before interface version 4: header 72 bytes, no data + val old = ByteBuffer.allocate(72).order(ByteOrder.LITTLE_ENDIAN) + old.putInt(0, 72) + old.putInt(4, EventKind.CLOSE.nativeValue) + + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(old.array(), 72) } + } + @Test fun `a prefix ending on a record boundary decodes to those records`() { val firstRecordBytes = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(0) @@ -89,4 +206,105 @@ class EventDecoderTest { val negative = patched(52, -1) assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(negative, negative.size) } } + + @Test + fun `a malformed row is refused`() { + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + var offset = 0 + while (buffer.getInt(offset + 4) != EventKind.ROW.nativeValue) offset += buffer.getInt(offset) + val data = offset + EventDecoder.HEADER_BYTES + + fun patched( + at: Int, + value: Int, + ): ByteArray { + val copy = bytes.copyOf() + ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN).putInt(at, value) + return copy + } + + // kept above columns; its stored bytes past the row; + // an unknown type in the first value's type byte (and its neighbours left alone) + val first = data + 8 + for (broken in listOf( + patched(data + 4, 99), + patched(first + 4, 100000), + patched(first, 9), + )) { + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(broken, broken.size) } + } + // stored and full both 4: the value is not cut, so it is the width check that refuses it + val narrow = patched(first + 4, 4).also { ByteBuffer.wrap(it).order(ByteOrder.LITTLE_ENDIAN).putInt(first + 8, 4) } + val e = assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(narrow, narrow.size) } + assertThat(e.message).contains("number 0 is 4 bytes") + } + + @Test + fun `a number or null that claims to be cut is refused`() { + // One ROW record: the 80-byte header, the row header (1 column, 1 value kept), one value header, + // then 8 bytes of value data (none for NULL), padded to a multiple of 8. + fun rowWithValue( + type: Int, + stored: Int, + full: Int, + ): ByteArray { + val data = EventDecoder.ROW_HEADER_BYTES + EventDecoder.ROW_VALUE_BYTES + stored + val record = ByteBuffer.allocate((EventDecoder.HEADER_BYTES + data + 7) and 7.inv()).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(0, record.capacity()) + record.putInt(4, EventKind.ROW.nativeValue) + record.putLong(8, 1) + record.putInt(52, data) + record.putLong(56, 1) + record.putLong(64, -1) + val row = EventDecoder.HEADER_BYTES + record.putInt(row, 1) + record.putInt(row + 4, 1) + val value = row + EventDecoder.ROW_HEADER_BYTES + record.put(value, type.toByte()) + record.put(value + 1, if (full > stored) 1 else 0) + record.putInt(value + 4, stored) + record.putInt(value + 8, full) + return record.array() + } + // whole values decode, so the refusals below are down to full_bytes + val integer = rowWithValue(1, 8, 8) + assertThat( + EventDecoder + .decode(integer, integer.size) + .single() + .row!! + .values, + ).containsExactly(0L) + val nothing = rowWithValue(5, 0, 0) + assertThat( + EventDecoder + .decode(nothing, nothing.size) + .single() + .row!! + .values, + ).containsExactly(null) + // INTEGER and FLOAT with 8 stored of 9, and NULL with 0 stored of 1, each flagged cut + for (broken in listOf(rowWithValue(1, 8, 9), rowWithValue(2, 8, 9), rowWithValue(5, 0, 1))) { + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(broken, broken.size) } + } + } + + @Test + fun `a row with more values than its bytes hold is refused before they are read`() { + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + var offset = 0 + while (buffer.getInt(offset + 4) != EventKind.ROW.nativeValue) offset += buffer.getInt(offset) + val data = offset + EventDecoder.HEADER_BYTES + val huge = bytes.copyOf() + ByteBuffer + .wrap(huge) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(data, Int.MAX_VALUE) + .putInt(data + 4, Int.MAX_VALUE) + + // columns = kept = Int.MAX_VALUE passes the kept <= columns check; sizing the value list from it threw + // OutOfMemoryError before the first value's check could refuse the row + val e = assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(huge, huge.size) } + assertThat(e.message).contains("kept=${Int.MAX_VALUE}") + } } 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 0a7117d66f..8b5e24c813 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 @@ -31,6 +31,17 @@ class FakeDebugEngine( var clientConnected = false private set + /** Each setRowCapture call, in order: rows per statement, value bytes, row bytes. */ + val rowCaptureCalls = mutableListOf>() + + /** The limits of the last execute. */ + var lastExecuteLimits: QueryLimits? = null + private set + + /** The argNames of the last query: null when its args were bound by position. */ + var lastArgNames: List? = null + private set + val openedServerConnections = mutableListOf>() /** How many times the server asked to open one, counted before any refusal: [openedServerConnections] holds only successes. */ @@ -46,14 +57,38 @@ class FakeDebugEngine( sql: String, connectionId: Long = 1, durationNanos: Long? = null, + executionId: Long? = null, ) { lastSeq++ - buffered.addLast(Event(lastSeq, kind, connectionId, 1, lastSeq, durationNanos, sql, false, clientConnected)) + buffered.addLast( + Event(lastSeq, kind, connectionId, 1, lastSeq, durationNanos, sql, false, clientConnected, executionId = executionId), + ) + } + + /** Adds the event [make] builds for the next number, for the kinds and fields [addEvent] does not set. */ + fun addEvent(make: (seq: Long) -> Event) { + lastSeq++ + buffered.addLast(make(lastSeq)) + } + + /** Adds [event] as the next one, numbered after the events before it whatever its own [Event.seq]. */ + fun addEvent(event: Event) { + lastSeq++ + // A native STATEMENT's execution id is its own seq: keep it so when the seq changes. Null ids, and the + // parent ids of ROW and PROFILE events, stay as given. + val own = event.kind == EventKind.STATEMENT && event.executionId == event.seq + buffered.addLast(event.copy(seq = lastSeq, executionId = if (own) lastSeq else event.executionId)) } /** Drops the [count] oldest buffered events, as a full native buffer would. */ fun dropOldest(count: Int) = repeat(count) { buffered.removeFirstOrNull() } + /** A record's data as [EventDecoder] reads it: the SQL, or a ROW event's values, each with its header. */ + private fun dataBytes(event: Event): Int { + val row = event.row ?: return event.sql.toByteArray().size + return EventDecoder.ROW_HEADER_BYTES + row.values.sumOf { EventDecoder.ROW_VALUE_BYTES + cellBytes(it).toInt() } + } + private fun cellBytes(value: Any?): Long = when (value) { is String -> value.toByteArray().size.toLong() @@ -76,8 +111,8 @@ class FakeDebugEngine( var bytes = 0 for (event in buffered) { if (event.seq <= after) continue - // the native record: a 56-byte header, then the SQL padded to 8 bytes - val size = 56 + (event.sql.toByteArray().size + 7) / 8 * 8 + // the native record: the header, then its data padded to 8 bytes + val size = EventDecoder.HEADER_BYTES + (dataBytes(event) + 7) / 8 * 8 if (bytes + size > maxBytes) break bytes += size events += event @@ -89,6 +124,14 @@ class FakeDebugEngine( clientConnected = connected } + override fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) { + rowCaptureCalls += Triple(maxRowsPerStatement, maxValueBytes, maxRowBytes) + } + override fun openServerConnection( path: String, writable: Boolean, @@ -107,11 +150,13 @@ class FakeDebugEngine( override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult { check(!closed) { "closed" } + lastArgNames = argNames val all = answer(path, writable, sql, args) val skip = offset.toInt().coerceAtMost(all.rows.size) val rest = all.rows.drop(skip) @@ -142,9 +187,13 @@ class FakeDebugEngine( override fun execute( sql: String, args: List, + argNames: List?, + limits: QueryLimits, deadlineMillis: Long, ): ExecuteResult { check(!closed) { "closed" } + lastArgNames = argNames + lastExecuteLimits = limits if (!writable) throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") return executeAnswer(path, sql, args) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt new file mode 100644 index 0000000000..094072fdbb --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngineTest.kt @@ -0,0 +1,59 @@ +package org.appdevforall.sqlitedebugger.engine + +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class FakeDebugEngineTest { + /** + * The fake fills a batch up to maxBytes as the native buffer does, so a test that sizes a batch to the + * byte gets the real cut. events.bin holds records the C layer wrote, a ROW event among them. + */ + @Test + fun `a batch ends where the native records would`() { + val bytes = checkNotNull(javaClass.getResourceAsStream("events.bin")).use { it.readBytes() } + val events = EventDecoder.decode(bytes, bytes.size) + assertThat(events.map { it.kind }).contains(EventKind.ROW) + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val recordBytes = mutableListOf() + var offset = 0 + while (offset < bytes.size) { + recordBytes += buffer.getInt(offset) + offset += recordBytes.last() + } + assertThat(recordBytes).hasSize(events.size) + + val engine = FakeDebugEngine() + events.forEach { engine.addEvent(it) } + var upTo = 0 + recordBytes.forEachIndexed { i, size -> + upTo += size + assertThat(engine.readEvents(0, upTo).events).hasSize(i + 1) + assertThat(engine.readEvents(0, upTo - 1).events).hasSize(i) + } + } + + /** + * The native STATEMENT's execution id is its own seq, so the fake's renumbering moves it along. Null ids + * and the parent ids of other kinds are left as given. + */ + @Test + fun `renumbering a STATEMENT keeps its execution id equal to its seq`() { + val engine = FakeDebugEngine() + + fun event( + kind: EventKind, + seq: Long, + executionId: Long?, + ) = Event(seq, kind, 1, 1, seq, null, "SELECT 1", false, false, executionId = executionId) + engine.addEvent(event(EventKind.STATEMENT, 77, 77)) + engine.addEvent(event(EventKind.ROW, 78, 77)) + engine.addEvent(event(EventKind.STATEMENT, 79, null)) + engine.addEvent(event(EventKind.STATEMENT, 80, 77)) + + val events = engine.readEvents(0, Int.MAX_VALUE).events + assertThat(events.map { it.seq }).containsExactly(1L, 2L, 3L, 4L).inOrder() + assertThat(events.map { it.executionId }).containsExactly(1L, 77L, null, 77L).inOrder() + } +} 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 5a3e7ad757..f30ea34665 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 @@ -3,11 +3,14 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.Event +import org.appdevforall.sqlitedebugger.engine.EventDecoder import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.ExecuteResult import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.appdevforall.sqlitedebugger.engine.RowValues import org.appdevforall.sqlitedebugger.engine.ServerConnection import org.json.JSONArray import org.json.JSONObject @@ -366,6 +369,8 @@ class DatabaseToolsTest { bad("sql" to "x", "max_rows" to 1.5) bad("sql" to "x", "args" to "nope") bad("sql" to "x", "args" to JSONArray().put(JSONObject())) + bad("sql" to "x", "args" to JSONObject().put("a", JSONArray())) + bad("sql" to "x", "args" to JSONObject().put("", 1)) assertTrue(engine.openedServerConnections.isEmpty()) assertEquals(0, engine.openAttempts) } @@ -390,6 +395,7 @@ class DatabaseToolsTest { ), ) assertEquals(listOf(null, 3L, 2.5, "s", 1L), got) + assertEquals("an array binds by position", null, engine.lastArgNames) } @Test fun queryErrorsCarryTheSqliteCode() { @@ -416,12 +422,13 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: org.appdevforall.sqlitedebugger.engine.QueryLimits, deadlineMillis: Long, ): QueryResult { deadline = deadlineMillis - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -441,6 +448,7 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -451,7 +459,7 @@ class DatabaseToolsTest { "the time limit passed before the query started", ) } - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -521,6 +529,7 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -534,7 +543,7 @@ class DatabaseToolsTest { throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the query ran past its time limit") } now += runMs - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -679,7 +688,7 @@ class DatabaseToolsTest { assertEquals("-9007199254740993", row.get(4)) assertEquals(9_007_199_254_740_992L, row.getLong(5)) val blob = row.getJSONObject(6) - assertEquals("AQID", blob.getString("base64")) + assertEquals("010203", blob.getString("hex")) assertEquals(3, blob.getInt("bytes")) assertFalse(blob.getBoolean("truncated")) assertTrue(row.isNull(7)) @@ -1093,6 +1102,233 @@ class DatabaseToolsTest { t.onServerStopped() } + @Test fun queryBindsAnObjectByName() { + engine.appConnections += conn(1, "/data/a.db") + var got: List = emptyList() + engine.answer = { _, _, _, a -> + got = a + QueryResult(emptyList(), emptyList(), 0, false) + } + ok( + "query", + db().put("sql", "x").put( + "args", + JSONObject() + .put(":b", "s") + .put("a", 1) + .put("\$c", JSONObject.NULL) + .put("?2", 2.5), + ), + ) + val byName = engine.lastArgNames!!.zip(got).toMap() + assertEquals(mapOf("a" to 1L, ":b" to "s", "\$c" to null, "?2" to 2.5), byName) + ok("explain_query_plan", db().put("sql", "x").put("args", JSONObject().put("id", 7))) + assertEquals(listOf("id"), engine.lastArgNames) + assertEquals(listOf(7L), got) + ok("query", db().put("sql", "x").put("args", JSONObject())) + assertEquals("an empty object still binds by name: a parameter left out is an error", emptyList(), engine.lastArgNames) + ok("query", db().put("sql", "x")) + assertEquals("no args", null, engine.lastArgNames) + } + + @Test fun queryDescribesBothArgForms() { + val query = tools.tools().single { it.name == "query" } + val args = query.inputSchema.getJSONObject("properties").getJSONObject("args") + assertEquals(listOf("array", "object"), args.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) + for (form in listOf(":name", "@name", "\$name", "?NNN")) assertTrue(form, args.getString("description").contains(form)) + } + + @Test fun queryReturnsDeclaredTypesAndStorageClasses() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> + QueryResult( + listOf("id", "r", "s", "b", "e"), + listOf(listOf(1L, 2.0, "x", byteArrayOf(0x0f, -1), null), listOf("t", null, 3L, 1.5, byteArrayOf())), + 0, + false, + declaredTypes = listOf("INTEGER", "REAL", "TEXT", "BLOB", null), + ) + } + val r = ok("query", db().put("sql", "x")) + val types = r.getJSONArray("column_types") + val declared = (0 until types.length()).map { if (types.isNull(it)) null else types.get(it) } + assertEquals(listOf("INTEGER", "REAL", "TEXT", "BLOB", null), declared) + val classes = r.getJSONArray("storage_classes").let { a -> (0 until a.length()).map { a.getString(it) } } + assertEquals(listOf("irtbn", "tnirb"), classes) + assertTrue( + "a REAL 2.0 reads as 2 in JSON, so only the storage class tells it from an INTEGER", + r.toString().contains("[1,2,\"x\""), + ) + assertEquals( + "0fff", + r + .getJSONArray("rows") + .getJSONArray(0) + .getJSONObject(3) + .getString("hex"), + ) + assertTrue(r.getJSONArray("rows").getJSONArray(0).isNull(4)) + val description = tools.tools().single { it.name == "query" }.description + assertTrue(description.contains("storage_classes") && description.contains("column_types") && description.contains("hex")) + } + + @Test fun queryResultWithoutDeclaredTypesGivesNullForEachColumn() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> QueryResult(listOf("a", "b"), listOf(listOf(1L, 2L)), 0, false) } + val types = ok("query", db().put("sql", "x")).getJSONArray("column_types") + assertEquals(2, types.length()) + assertTrue(types.isNull(0) && types.isNull(1)) + } + + private fun rowEvent( + seq: Long, + number: Long, + values: List, + cut: Set = emptySet(), + columns: Int = values.size, + ) = Event(seq, EventKind.ROW, 1, 1, seq, null, "", values.size < columns, true, rows = number, row = RowValues(columns, values, cut)) + + @Test fun getEventsReturnsRowsAndChangeCounts() { + engine.addEvent(EventKind.STATEMENT, "SELECT id, b FROM t") + engine.addEvent { rowEvent(it, 1, listOf(1L, byteArrayOf(1, 2)), cut = setOf(1)) } + engine.addEvent { rowEvent(it, 2, listOf("x"), columns = 2) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "SELECT id, b FROM t", false, true, rows = 12, rowsCut = true) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "DELETE FROM t", false, true, rows = 0, changes = 3) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "SELECT 1", false, true) } + val events = ok("get_events").getJSONArray("events") + assertEquals(6, events.length()) + val row1 = events.getJSONObject(1) + assertEquals("row", row1.getString("kind")) + assertEquals(1, row1.getInt("row_number")) + assertEquals(2, row1.getInt("column_count")) + assertEquals(1L, row1.getJSONArray("values").getLong(0)) + assertEquals("0102", row1.getJSONArray("values").getJSONObject(1).getString("hex")) + assertTrue(row1.getJSONArray("values").getJSONObject(1).getBoolean("truncated")) + assertEquals("ib", row1.getString("storage_classes")) + assertEquals(1, row1.getJSONArray("cut_values").getInt(0)) + assertFalse(row1.getBoolean("truncated")) + val row2 = events.getJSONObject(2) + assertEquals("a row whose data reached its limit keeps fewer values", 1, row2.getJSONArray("values").length()) + assertEquals(2, row2.getInt("column_count")) + assertTrue(row2.getBoolean("truncated")) + val select = events.getJSONObject(3) + assertEquals(12, select.getInt("rows")) + assertTrue("a read has no change count", select.isNull("changes")) + assertTrue(select.getBoolean("rows_cut")) + val delete = events.getJSONObject(4) + assertEquals(3, delete.getInt("changes")) + assertEquals(0, delete.getInt("rows")) + assertFalse(delete.getBoolean("rows_cut")) + val unseen = events.getJSONObject(5) + assertTrue("a statement whose start was not seen", unseen.isNull("rows") && unseen.isNull("changes")) + val statement = events.getJSONObject(0) + assertFalse("only a profile carries counts", statement.has("rows") || statement.has("changes") || statement.has("values")) + } + + @Test fun getEventsTurnsRowRecordingOnUnlessToldNotTo() { + val t = tools + ok("get_events", t = t) + assertEquals( + listOf(Triple(DatabaseTools.EVENT_ROWS_PER_STATEMENT, DatabaseTools.EVENT_VALUE_BYTES, DatabaseTools.EVENT_ROW_BYTES)), + engine.rowCaptureCalls, + ) + ok("get_events", t = t) + assertEquals("already on: no second call", 1, engine.rowCaptureCalls.size) + engine.addEvent(EventKind.STATEMENT, "SELECT 1") + engine.addEvent { rowEvent(it, 1, listOf(1L)) } + val r = ok("get_events", JSONObject().put("include_rows", false), t) + assertEquals(Triple(0, 0, 0), engine.rowCaptureCalls.last()) + assertEquals("row events are left out", listOf("statement"), kinds(r)) + assertEquals("the cursor still passes them", 2, r.getInt("next")) + ok("get_events", JSONObject().put("include_rows", true), t) + assertEquals(DatabaseTools.EVENT_ROWS_PER_STATEMENT, engine.rowCaptureCalls.last().first) + t.onServerStopped() + assertEquals("the server stopping turns it off", Triple(0, 0, 0), engine.rowCaptureCalls.last()) + assertTrue(runTool(tools, "get_events", JSONObject().put("include_rows", "yes")).getBoolean("isError")) + } + + @Test fun rowRecordingStopsWithTheIdleClient() { + val t = tools + ok("get_events", t = t) + now += DatabaseTools.EVENTS_IDLE_MS + t.expireIdleClient() + assertFalse(engine.clientConnected) + assertEquals(Triple(0, 0, 0), engine.rowCaptureCalls.last()) + ok("get_events", t = t) + assertEquals("the next get_events turns it on again", DatabaseTools.EVENT_ROWS_PER_STATEMENT, engine.rowCaptureCalls.last().first) + t.onServerStopped() + } + + @Test fun getEventsDescribesWhatIsCapped() { + val description = tools.tools().single { it.name == "get_events" }.description + for (text in listOf( + "first ${DatabaseTools.EVENT_ROWS_PER_STATEMENT} rows", + "${DatabaseTools.EVENT_VALUE_BYTES} bytes", + "${DatabaseTools.EVENT_ROW_BYTES / 1024} KiB", + "include_rows false", + "changes", + )) { + assertTrue(text, description.contains(text)) + } + } + + @Test fun getEventsEncodesTheEventsDecodedFromTheFixture() { + val bytes = checkNotNull(EventDecoder::class.java.getResourceAsStream("events.bin")).use { it.readBytes() } + val decoded = EventDecoder.decode(bytes, bytes.size) + assertTrue("the fixture has row events", decoded.any { it.kind == EventKind.ROW }) + assertTrue("and execution ids", decoded.any { it.kind == EventKind.ROW && it.executionId != null }) + assertTrue("and a change count", decoded.any { it.changes != null }) + decoded.forEach { e -> engine.addEvent { e.copy(seq = it) } } + val events = ok("get_events").getJSONArray("events") + assertEquals(decoded.size, events.length()) + decoded.forEachIndexed { i, e -> + val json = events.getJSONObject(i) + assertEquals(e.kind.name.lowercase(), json.getString("kind")) + assertTrue("execution_id is always present", json.has("execution_id")) + assertEquals(e.executionId, if (json.isNull("execution_id")) null else json.getLong("execution_id")) + when (e.kind) { + EventKind.ROW -> { + val row = e.row!! + assertEquals(row.columnCount, json.getInt("column_count")) + assertEquals(DatabaseTools.storageClasses(row.values), json.getString("storage_classes")) + val values = json.getJSONArray("values") + assertEquals(row.values.size, values.length()) + row.values.forEachIndexed { c, v -> + val got = values.get(c) + when (v) { + null -> assertTrue(values.isNull(c)) + is ByteArray -> assertEquals(DatabaseTools.hex(v), values.getJSONObject(c).getString("hex")) + is Double -> assertEquals(DatabaseTools.encodeValue(v), (got as? Number)?.toDouble() ?: got) + else -> assertEquals(DatabaseTools.encodeValue(v), if (got is Int) got.toLong() else got) + } + } + val cut = json.getJSONArray("cut_values") + assertEquals(row.cutIndexes.sorted(), (0 until cut.length()).map { cut.getInt(it) }) + } + + EventKind.PROFILE -> { + assertEquals(e.rows, if (json.isNull("rows")) null else json.getLong("rows")) + assertEquals(e.changes, if (json.isNull("changes")) null else json.getLong("changes")) + assertEquals(e.rowsCut, json.getBoolean("rows_cut")) + } + + else -> { + assertEquals(e.sql, json.getString("sql")) + } + } + } + } + + @Test fun hexIsLowercaseAndCoversEveryByte() { + assertEquals("00017f80ff", DatabaseTools.hex(byteArrayOf(0, 1, 127, -128, -1))) + assertEquals("", DatabaseTools.hex(ByteArray(0))) + } + + private fun kinds(r: JSONObject): List { + val events = r.getJSONArray("events") + return (0 until events.length()).map { events.getJSONObject(it).getString("kind") } + } + private class FakeIdleScheduler : IdleScheduler { class Check( val task: Runnable, @@ -1176,6 +1412,74 @@ class DatabaseToolsTest { assertEquals(listOf("/data/a.db" to false, "/data/a.db" to true), engine.openedServerConnections) } + @Test fun executeBindsAnObjectByName() { + engine.appConnections += conn(1, "/data/a.db") + var got: List = emptyList() + engine.executeAnswer = { _, _, args -> + got = args + ExecuteResult(changes = 1, lastInsertRowid = null) + } + ok("execute", db().put("sql", "update t set a = :a where b = @b").put("args", JSONObject().put("a", "x").put("@b", 2))) + assertEquals(mapOf("a" to "x", "@b" to 2L), engine.lastArgNames!!.zip(got).toMap()) + ok("execute", db().put("sql", "update t set a = ?").put("args", JSONArray().put(1))) + assertEquals("an array binds by position", null, engine.lastArgNames) + val schema = + tools + .tools() + .single { it.name == "execute" } + .inputSchema + .getJSONObject("properties") + .getJSONObject("args") + assertEquals(listOf("array", "object"), schema.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) + } + + @Test fun executeReturnsReturningRowsAsQueryDoes() { + engine.appConnections += conn(1, "/data/a.db") + engine.executeAnswer = { _, _, _ -> + ExecuteResult( + changes = 50, + lastInsertRowid = null, + rows = + QueryResult( + listOf("id", "b"), + listOf(listOf(1L, byteArrayOf(1)), listOf(2L, null)), + 1, + true, + setOf(1L), + listOf("INTEGER", "BLOB"), + ), + ) + } + val r = ok("execute", db().put("sql", "update t set v = 1 returning id, b").put("max_rows", 2)) + assertEquals(50, r.getInt("changes")) + assertEquals(listOf("id", "b"), r.getJSONArray("columns").let { a -> (0 until a.length()).map { a.getString(it) } }) + assertEquals("INTEGER", r.getJSONArray("column_types").getString(0)) + assertEquals(2, r.getInt("row_count")) + assertEquals( + "01", + r + .getJSONArray("rows") + .getJSONArray(0) + .getJSONObject(1) + .getString("hex"), + ) + assertEquals("ib", r.getJSONArray("storage_classes").getString(0)) + assertTrue(r.getBoolean("has_more")) + assertEquals(1, r.getInt("truncated_cells")) + assertEquals(0, r.getJSONArray("truncated_cell_indexes").getJSONArray(0).getInt(0)) + assertEquals(1, r.getJSONArray("truncated_cell_indexes").getJSONArray(0).getInt(1)) + assertFalse("no paging: running the write again would write again", r.has("offset") || r.has("next_offset")) + assertEquals(2, engine.lastExecuteLimits!!.maxRows) + assertEquals(DatabaseTools.MAX_TOTAL_BYTES, engine.lastExecuteLimits!!.maxTotalBytes) + + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1, lastInsertRowid = 9) } + val plain = ok("execute", db().put("sql", "insert into t values (1)")) + assertFalse("no RETURNING: no rows", plain.has("rows") || plain.has("columns")) + assertEquals(DatabaseTools.DEFAULT_MAX_ROWS, engine.lastExecuteLimits!!.maxRows) + assertTrue(runTool(tools, "execute", db().put("sql", "x").put("max_rows", 0)).getBoolean("isError")) + assertTrue(runTool(tools, "execute", db().put("sql", "x").put("max_rows", DatabaseTools.MAX_ROWS + 1)).getBoolean("isError")) + } + @Test fun executeReportsChangesPastTwoToTheFiftyThirdAsAString() { engine.appConnections += conn(1, "/data/a.db") engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1L shl 60, lastInsertRowid = null) } @@ -1231,14 +1535,23 @@ class DatabaseToolsTest { "committed at once and cannot be undone", "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused", "does not write is refused: use query", - "RETURNING are not returned", + "Rows from RETURNING come back as query returns them", + "truncated_cell_indexes lists each as [row, column]", + "or paged (that would write again)", + "A statement that fails returns no rows", + "FAIL conflict resolution (OR FAIL, ON CONFLICT FAIL, RAISE(FAIL)) keeps the rows", "stopped and rolled back after 1.5 s", + "the omitted rows cannot be recovered from this result", + "which it does not after a DELETE", + "Limits are best effort: a write cut at the row or size limit is committed in full", + "can leave it committed", "in every journal mode", "may stay stale", "Functions the app adds to its own connections", )) { assertTrue("$text: $d", d.contains(text)) } + assertFalse("omitted rows are not recoverable with query: $d", d.contains("read them with query")) assertTrue( tools .tools() diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java index 5c89abc374..994729c024 100644 --- a/subprojects/sqlite-debugger/src/test/jni/Helper.java +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -16,5 +16,9 @@ static long open(String path) { static native int busyTimeout(long db, int ms); + static native int traceRows(long db, boolean on); + + static native long tracedRows(); + static native int denyTransactions(long db, boolean deny); } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 44c20bd416..e2d7873c42 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -44,12 +44,25 @@ static class Result { long truncated; boolean hasMore; Set cut = new HashSet<>(); + String[] declaredTypes; } @SuppressWarnings("unchecked") static Result query(long h, String sql, Object[] args, long offset, int maxRows, int maxText, int maxBlob, int maxTotal, long deadline) throws DebugEngineException { - Object[] r = NativeBridge.query(h, sql, args, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + return named(h, sql, args, null, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + } + + /** As query, with args bound by name when names is not null. */ + @SuppressWarnings("unchecked") + static Result named(long h, String sql, Object[] args, String[] names, long offset, int maxRows, int maxText, int maxBlob, + int maxTotal, long deadline) throws DebugEngineException { + byte[][] nameBytes = null; + if (names != null) { + nameBytes = new byte[names.length][]; + for (int i = 0; i < names.length; i++) nameBytes[i] = names[i].getBytes(StandardCharsets.UTF_8); + } + Object[] r = NativeBridge.query(h, sql, args, nameBytes, offset, maxRows, maxText, maxBlob, maxTotal, deadline); Result out = new Result(); out.columns = (String[]) r[0]; out.rows = (List) r[1]; @@ -58,6 +71,8 @@ static Result query(long h, String sql, Object[] args, long offset, int maxRows, out.hasMore = counts[1] != 0; eq(counts.length, 2 + (int) counts[0], "one index per cut cell"); for (int i = 2; i < counts.length; i++) out.cut.add(counts[i]); + out.declaredTypes = (String[]) r[3]; + eq(out.declaredTypes.length, out.columns.length, "one declared type per column"); return out; } @@ -74,6 +89,59 @@ static int codeOf(long h, String sql, Object[] args, long deadline) { } } + /** The row events (kind 4) in the buffer, read from the start; the records' layout is in sqlitedbg.h. */ + static long rowEvents() { + byte[] buf = new byte[1 << 20]; + long[] out = new long[4]; + NativeBridge.readEvents(0, buf, out); + java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + long rows = 0; + for (int at = 0; at < out[2]; at += b.getInt(at)) { + if (b.getInt(at + 4) == 4) rows++; + } + return rows; + } + + /** + * ADFA-7379: whether the newest row event names a statement event in the buffer by its execution_id (offset 72), + * which is that statement event's seq (offset 8). + */ + /** + * The SQL of the STATEMENT event the newest ROW event names by execution_id, or null. The named event must be the + * newest STATEMENT before that row, and its seq must equal the id. + */ + static String newestRowStatementSql() { + byte[] buf = new byte[1 << 20]; + long[] out = new long[4]; + NativeBridge.readEvents(0, buf, out); + java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + long lastSeq = 0, rowExec = 0, rowStatementSeq = 0; + String lastSql = null, rowStatementSql = null; + for (int at = 0; at < out[2]; at += b.getInt(at)) { + int kind = b.getInt(at + 4); + if (kind == 1) { + lastSeq = b.getLong(at + 8); + lastSql = new String(buf, at + 80, b.getInt(at + 52), StandardCharsets.UTF_8); + } + if (kind == 4) { + rowExec = b.getLong(at + 72); + rowStatementSeq = lastSeq; + rowStatementSql = lastSql; + } + } + return rowExec != 0 && rowExec == rowStatementSeq ? rowStatementSql : null; + } + + /** "code message" of a refused query with args bound by name, or null when it ran. */ + static String namedRefusal(long h, String sql, Object[] args, String[] names) { + try { + named(h, sql, args, names, 0, 100, 4096, 1024, MAX, FAR); + return null; + } catch (DebugEngineException e) { + return e.sqliteCode + " " + e.getMessage(); + } + } + /** "code message" of the refusal, or null when the query ran. */ static String refusal(long h, String sql) { try { @@ -88,21 +156,45 @@ static Set set(Long... v) { return new HashSet<>(Arrays.asList(v)); } + /** execute with query's limits and no names: [columns, rows, counts, decltypes, {changes, last_insert_rowid}]. */ + static Object[] run(long h, String sql, byte[][] names, int maxRows, int maxText, int maxBlob, int maxTotal, long deadline, + Object... args) throws DebugEngineException { + Object[] r = NativeBridge.execute(h, sql, args, names, maxRows, maxText, maxBlob, maxTotal, deadline); + eq(r.length, 5, "execute returns the rows, then {changes, last_insert_rowid}"); + return r; + } + + static long[] counts(Object[] r) { + return (long[]) r[4]; + } + + /** What execute returned as rows, unpacked as query's are. */ + @SuppressWarnings("unchecked") + static Result rowsOf(Object[] r) { + Result out = new Result(); + out.columns = (String[]) r[0]; + out.rows = (List) r[1]; + long[] c = (long[]) r[2]; + out.truncated = c[0]; + out.hasMore = c[1] != 0; + for (int i = 2; i < c.length; i++) out.cut.add(c[i]); + out.declaredTypes = (String[]) r[3]; + return out; + } + static long exec(long h, String sql, Object... args) throws DebugEngineException { - long[] r = NativeBridge.execute(h, sql, args, FAR); - eq(r.length, 2, "execute returns {changes, last_insert_rowid}"); - return r[0]; + return counts(run(h, sql, null, 1000, 4096, 1024, MAX, FAR, args))[0]; } /** The rowid execute reports, or null (Long.MIN_VALUE on the wire) when the statement inserted no row. */ static Long rowid(long h, String sql, Object... args) throws DebugEngineException { - long r = NativeBridge.execute(h, sql, args, FAR)[1]; + long r = counts(run(h, sql, null, 1000, 4096, 1024, MAX, FAR, args))[1]; return r == Long.MIN_VALUE ? null : r; } static int execCode(long h, String sql, Object[] args, long deadline) { try { - NativeBridge.execute(h, sql, args, deadline); + NativeBridge.execute(h, sql, args, null, 1000, 4096, 1024, MAX, deadline); return 0; } catch (DebugEngineException e) { return e.sqliteCode; @@ -112,13 +204,207 @@ static int execCode(long h, String sql, Object[] args, long deadline) { /** "code message" of the refusal, or null when the statement ran. */ static String execRefusal(long h, String sql) { try { - NativeBridge.execute(h, sql, new Object[0], FAR); + NativeBridge.execute(h, sql, new Object[0], null, 1000, 4096, 1024, MAX, FAR); return null; } catch (DebugEngineException e) { return e.sqliteCode + " " + e.getMessage(); } } + /** + * ADFA-7304: RETURNING rows within query's limits. SQLite makes every change in the first step, so a + * statement stopped at a limit is reset, which commits all of it (comment 41621). + */ + static void returningCaps(long w, long r, long app) throws Exception { + eq(exec(w, "CREATE TABLE rt(id INTEGER PRIMARY KEY, v INTEGER, s TEXT, b BLOB)"), 0L, "create rt"); + eq(exec(w, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 50) " + + "INSERT INTO rt SELECT x, 0, printf('%.20c', 'x'), x'0102030405' FROM c"), 50L, "50 rows"); + + // past the row cap: the capped rows, has_more, every change made and counted + Object[] ret = run(w, "UPDATE rt SET v = v + 1 RETURNING *", null, 3, 4096, 1024, MAX, FAR); + Result rows = rowsOf(ret); + eq(rows.rows.size(), 3, "3 rows, the cap"); + check(rows.hasMore, "has_more past the cap"); + eq(counts(ret)[0], 50L, "changes counts every row written, not only those returned"); + eq(q(r, "SELECT count(*) FROM rt WHERE v = 1").rows.get(0)[0], 50L, "and every row was updated, and committed"); + eq(Arrays.asList(rows.columns), Arrays.asList("id", "v", "s", "b"), "RETURNING * columns"); + eq(Arrays.asList(rows.declaredTypes), Arrays.asList("INTEGER", "INTEGER", "TEXT", "BLOB"), "declared types, as query's"); + + // the byte budget: the first row always comes back, the rest is has_more + ret = run(w, "UPDATE rt SET v = v + 1 RETURNING s", null, 1000, 4096, 1024, 10, FAR); + eq(rowsOf(ret).rows.size(), 1, "the budget keeps the first row only"); + check(rowsOf(ret).hasMore, "and says there is more"); + eq(counts(ret)[0], 50L, "every row still counted"); + eq(q(r, "SELECT count(*) FROM rt WHERE v = 2").rows.get(0)[0], 50L, "and updated"); + + // a wide row is cut as in query + ret = run(w, "UPDATE rt SET v = v + 1 WHERE id = 1 RETURNING s, b", null, 1000, 4, 2, MAX, FAR); + rows = rowsOf(ret); + eq(rows.rows.get(0)[0], "xxxx", "TEXT cut at its limit"); + eq(((byte[]) rows.rows.get(0)[1]).length, 2, "BLOB cut at its limit"); + eq(rows.cut, set(0L, 1L), "both listed as cut"); + + // DELETE ... RETURNING cut short deletes every row + ret = run(w, "DELETE FROM rt WHERE id > 40 RETURNING id", null, 2, 4096, 1024, MAX, FAR); + eq(rowsOf(ret).rows.size(), 2, "2 rows back"); + eq(counts(ret)[0], 10L, "10 deleted"); + eq(q(r, "SELECT count(*) FROM rt WHERE id > 40").rows.get(0)[0], 0L, "all 10 gone"); + + // The commit at the reset can fail: the app holds a read transaction (SHARED, rollback journal), so the + // write waits to commit until busy_cb gives up at the 1.5 s cap. That is classified as a stalled step is + // (SQLITE_INTERRUPT, "Try it again"), and still says that nothing was kept. + eq(Helper.exec(app, "BEGIN; SELECT count(*) FROM rt"), 0, "the app opens a read transaction"); + long stalled = System.currentTimeMillis(); + try { + NativeBridge.execute(w, "UPDATE rt SET v = 100 RETURNING id", new Object[0], null, 1, 4096, 1024, MAX, FAR); + check(false, "a write whose commit failed returned rows"); + } catch (DebugEngineException e) { + long ms = System.currentTimeMillis() - stalled; + eq(e.sqliteCode, 9, "the failed commit stopped at the cap: SQLITE_INTERRUPT, as a stalled step is"); + check(e.getMessage().contains("rolled back") && e.getMessage().contains("Try it again"), + "and gives the advice: " + e.getMessage()); + check(ms >= 1400 && ms < 2400, "after " + ms + " ms, near the 1500 ms cap"); + } + eq(Helper.exec(app, "COMMIT"), 0, "the app ends its transaction"); + eq(Helper.autocommit(app), 1, "the app's connection is in autocommit"); + eq(q(r, "SELECT count(*) FROM rt WHERE v = 100").rows.get(0)[0], 0L, "and nothing of the failed write was kept"); + eq(exec(w, "UPDATE rt SET v = 7 WHERE id = 1"), 1L, "the writable connection still writes"); + eq(exec(w, "DROP TABLE rt"), 0L, "drop rt"); + + // FAIL conflict resolution keeps the rows changed before the failing one, and the error counts them; + // ABORT, the default, keeps none. + exec(w, "CREATE TABLE fr(id INTEGER PRIMARY KEY, u UNIQUE)"); + exec(w, "INSERT INTO fr VALUES(1, 10)"); + try { + run(w, "INSERT OR FAIL INTO fr(id, u) VALUES(2, 20), (3, 30), (4, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + check(false, "an OR FAIL write that failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 19, "OR FAIL on a duplicate: SQLITE_CONSTRAINT"); + check(e.getMessage().contains("The 2 rows it changed before the failure were kept"), "the error counts what was kept: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and those 2 rows are committed"); + try { + run(w, "INSERT INTO fr(id, u) VALUES(5, 50), (6, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + check(false, "an ABORT write that failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 19, "ABORT on a duplicate: SQLITE_CONSTRAINT"); + check(!e.getMessage().contains("kept"), "ABORT keeps nothing, and the error claims nothing was kept: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and nothing of the ABORT write was kept"); + + // ROLLBACK resolution fails the statement and keeps nothing (no claim of kept rows, unlike FAIL) + try { + run(w, "INSERT OR ROLLBACK INTO fr(id, u) VALUES(7, 70), (8, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + check(false, "an OR ROLLBACK write that failed returned rows"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 19, "OR ROLLBACK on a duplicate: SQLITE_CONSTRAINT"); + check(!e.getMessage().contains("kept"), "OR ROLLBACK keeps nothing, and the error claims nothing was kept: " + e.getMessage()); + } + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 3L, "and nothing of the OR ROLLBACK write was kept"); + eq(Helper.autocommit(app), 1, "the app's connection is in autocommit"); + eq(exec(w, "UPDATE fr SET u = u WHERE id = 1"), 1L, "the writable connection still writes"); + + // IGNORE skips the duplicate: the other rows come back and are counted + Object[] ign = run(w, "INSERT OR IGNORE INTO fr(id, u) VALUES(9, 90), (10, 10), (11, 110) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + eq(rowsOf(ign).rows.size(), 2, "OR IGNORE returns the 2 rows it inserted"); + eq(rowsOf(ign).rows.get(0)[0], 9L, "the first"); + eq(rowsOf(ign).rows.get(1)[0], 11L, "and the last, the duplicate skipped"); + eq(counts(ign)[0], 2L, "changes counts the 2 inserted"); + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 5L, "and the table has them"); + + // REPLACE deletes the conflicting row and inserts the new one + Object[] rep = run(w, "INSERT OR REPLACE INTO fr(id, u) VALUES(12, 10) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + eq(rowsOf(rep).rows.size(), 1, "OR REPLACE returns its row"); + eq(rowsOf(rep).rows.get(0)[0], 12L, "the new row"); + eq(counts(rep)[0], 1L, "changes counts the insert, not the replaced row"); + eq(q(r, "SELECT count(*) FROM fr WHERE id = 1").rows.get(0)[0], 0L, "the conflicting row is gone"); + eq(q(r, "SELECT count(*) FROM fr").rows.get(0)[0], 5L, "one in, one out"); + eq(exec(w, "DROP TABLE fr"), 0L, "drop fr"); + + // The time limit after rows came back: the first step (every change) must finish within 1.5 s, and + // copying every row out must run past it, and SQLite rolls back the whole statement (41621). The table + // is filled on the app's connection, which has no time limit, and sized to this machine by bisection + // between lo, the largest size whose copy finished within the limit, and hi, the smallest size whose + // first step was too slow: halved while the first step (timed with a statement that stops after one row) + // takes over 1 s, doubled while copying every row out finishes within the limit, and the middle once both + // bounds are known. Each try that finishes commits, so every try writes a value of its own and the final + // check counts only that value. The limit must strike while rows are being copied: a trace on the server connection + // (Helper.traceRows) counts the rows SQLite handed out, and 0 means the first step was cut instead (too + // slow: that size is a new hi). If no size fits, the test fails rather than pass without reaching the path. + eq(Helper.exec(app, "CREATE TABLE big(id INTEGER PRIMARY KEY, v, a, b, c, d, e, f, g, h)"), 0, "the app creates big"); + long bigRows = 0; + long target = 400000; + long value = 0; + long firstStep = -1; + long fastCopy = -1; + long lo = 0; + long hi = Long.MAX_VALUE; + boolean reached = false; + StringBuilder sizes = new StringBuilder(); + for (int tries = 0; tries < 12 && !reached; tries++) { + if (target > bigRows) { + eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT " + (bigRows + 1) + " UNION ALL SELECT x + 1 FROM c WHERE x < " + target + ") " + + "INSERT INTO big SELECT x, 0, 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh' FROM c"), 0, + "the app fills big to " + target + " rows"); + } else if (target < bigRows) { + eq(Helper.exec(app, "DELETE FROM big WHERE id > " + target), 0, "the app shrinks big to " + target + " rows"); + } + bigRows = target; + long t = System.currentTimeMillis(); + try { + eq(counts(run(w, "UPDATE big SET v = " + (++value) + " RETURNING *", null, 1, 4096, 1024, MAX, FAR))[0], bigRows, "one row back: every row changed"); + firstStep = System.currentTimeMillis() - t; + } catch (DebugEngineException e) { + // the first step alone passed the limit (a busy machine): too slow, so halve the table + eq(e.sqliteCode, 9, "only the time limit stops the first step: SQLITE_INTERRUPT"); + firstStep = Long.MAX_VALUE; + } + sizes.append(bigRows).append(" rows: first step ").append(firstStep == Long.MAX_VALUE ? "cut" : firstStep + " ms"); + if (firstStep > 1000) { + hi = bigRows; + if (bigRows < 25000) break; + target = lo > 0 ? (lo + hi) / 2 : bigRows / 2; + if (target <= lo) break; // lo and hi are next to each other: no size between them + sizes.append("; "); + continue; + } + long copyValue = ++value; + t = System.currentTimeMillis(); + Helper.traceRows(w, true); + try { + run(w, "UPDATE big SET v = " + copyValue + " RETURNING *", null, 1 << 30, 4096, 1024, 1 << 30, FAR); + // copying finished within the limit (a fast machine): grow the table, up to a size that was + // already too slow for the first step + fastCopy = System.currentTimeMillis() - t; + sizes.append(", copy ").append(fastCopy).append(" ms; "); + lo = bigRows; + if (bigRows >= 3200000) break; + target = hi == Long.MAX_VALUE ? bigRows * 2 : (lo + hi) / 2; + if (target <= lo) break; + } catch (DebugEngineException e) { + eq(e.sqliteCode, 9, "stopped while its rows came back: SQLITE_INTERRUPT"); + check(e.getMessage().contains("rolled back"), "the message says it was rolled back: " + e.getMessage()); + eq(q(r, "SELECT count(*) FROM big WHERE v = " + copyValue).rows.get(0)[0], 0L, "and nothing was kept, though rows had come back"); + long copied = Helper.tracedRows(); + if (copied > 0) { + check(copied < bigRows, "the limit struck before every row came back: " + copied + " of " + bigRows); + reached = true; + } else { + // no row came back: the first step was cut, so this size is too slow for it + sizes.append(", cut in its first step; "); + hi = bigRows; + if (bigRows < 25000) break; + target = lo > 0 ? (lo + hi) / 2 : bigRows / 2; + if (target <= lo) break; + } + } + } + check(reached, "the time limit struck while rows came back: tried " + sizes + " (lo " + lo + ", hi " + (hi == Long.MAX_VALUE ? "none" : hi) + + "); copying every row out last finished in " + fastCopy + " ms"); + System.out.println("RETURNING time limit: " + bigRows + " rows, first step " + firstStep + " ms"); + eq(Helper.exec(app, "DROP TABLE big"), 0, "the app drops big"); + } + /** ADFA-7298: execute on a writable server connection. */ static void execute(Path dir, String path, long app) throws Exception { long w = NativeBridge.openServer(path.getBytes(StandardCharsets.UTF_8), true); @@ -129,6 +415,20 @@ static void execute(Path dir, String path, long app) throws Exception { eq(exec(w, "UPDATE t SET s = ? WHERE id >= ?", "z", 6001L), 2L, "update 2: changes 2"); eq(exec(w, "DELETE FROM t WHERE id = :id", 6001L), 1L, "delete 1, named parameter: changes 1"); eq(exec(w, "DELETE FROM t WHERE id = -1"), 0L, "delete none: changes 0"); + // by name, as query binds (ADFA-7304: P2-2 and P2-3 met) + byte[][] names = {"s".getBytes(StandardCharsets.UTF_8), ":id".getBytes(StandardCharsets.UTF_8)}; + eq(counts(run(w, "INSERT INTO t(id, s) VALUES(:id, @s)", names, 1000, 4096, 1024, MAX, FAR, "n", 6004L))[0], 1L, + "execute binds by name: changes 1"); + eq(q(r, "SELECT count(*) FROM t WHERE id = 6004 AND s = 'n'").rows.get(0)[0], 1L, "each value went to its own parameter"); + try { + NativeBridge.execute(w, "DELETE FROM t WHERE id = :id", new Object[] {6004L}, new byte[][] {"idd".getBytes(StandardCharsets.UTF_8)}, + 1000, 4096, 1024, MAX, FAR); + check(false, "execute ran with a misspelt name"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 25, "execute: a misspelt name is SQLITE_RANGE, nothing run"); + } + eq(q(r, "SELECT count(*) FROM t WHERE id = 6004").rows.get(0)[0], 1L, "and the row is still there"); + Helper.exec(app, "DELETE FROM t WHERE id = 6004 OR s = '6004'"); // a statement that changes no row reports 0, not the previous write's count (sqlite3_changes64 keeps it) eq(exec(w, "UPDATE t SET s = 'y' WHERE id = 6002"), 1L, "update 1"); eq(exec(w, "CREATE TABLE ex(a)"), 0L, "CREATE TABLE: changes 0, not the update's 1"); @@ -136,7 +436,17 @@ static void execute(Path dir, String path, long app) throws Exception { eq(q(r, "PRAGMA user_version").rows.get(0)[0], 7L, "and is stored"); eq(exec(w, "PRAGMA user_version = 0"), 0L, "user_version back"); eq(exec(w, "DROP TABLE ex"), 0L, "DROP TABLE: changes 0"); - eq(exec(w, "INSERT INTO t(id) VALUES(6003) RETURNING id"), 1L, "RETURNING rows are read and dropped: changes 1"); + // RETURNING rows come back as query's do (ADFA-7304) + Object[] ret = run(w, "INSERT INTO t(id) VALUES(6003) RETURNING id", null, 1000, 4096, 1024, MAX, FAR); + eq(counts(ret)[0], 1L, "INSERT ... RETURNING: changes 1"); + eq(Arrays.asList(rowsOf(ret).columns), Arrays.asList("id"), "its RETURNING column"); + eq(rowsOf(ret).rows.size(), 1, "one row"); + eq(rowsOf(ret).rows.get(0)[0], 6003L, "the id it inserted"); + eq(counts(ret)[1], q(r, "SELECT rowid FROM t WHERE id = 6003").rows.get(0)[0], "and last_insert_rowid, its rowid"); + ret = run(w, "UPDATE t SET s = 'q' WHERE id = 6003", null, 1000, 4096, 1024, MAX, FAR); + eq(rowsOf(ret).columns.length, 0, "without RETURNING: no columns"); + eq(rowsOf(ret).rows.size(), 0, "and no rows"); + returningCaps(w, r, app); eq(q(r, "SELECT count(*) FROM t WHERE id IN (6002, 6003)").rows.get(0)[0], 2L, "the writes are visible to a reader"); eq(Helper.exec(app, "DELETE FROM t WHERE id IN (6002, 6003)"), 0, "the app's own connection writes after them"); eq(Helper.autocommit(app), 1, "and the app's connection is in autocommit"); @@ -240,8 +550,8 @@ static void execute(Path dir, String path, long app) throws Exception { // comes, as sentinel has no trigger and the SELECT does not read it. Then far more work than 1.5 s, // a cross join of t four times over, matching nothing. So the stopped write has a row to roll back. NativeBridge.execute(sw, "INSERT INTO sentinel SELECT -1 UNION ALL " - + "SELECT a.id FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0", new Object[0], - System.currentTimeMillis() + 8000); + + "SELECT a.id FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0", new Object[0], null, + 1000, 4096, 1024, MAX, System.currentTimeMillis() + 8000); } catch (DebugEngineException e) { ran.code = e.sqliteCode; ran.message = e.getMessage(); @@ -273,7 +583,7 @@ static Thread executeAsync(long h, String sql, long deadline, Ran out) { Thread th = new Thread(() -> { long t = System.currentTimeMillis(); try { - out.changes = NativeBridge.execute(h, sql, new Object[0], deadline)[0]; + out.changes = counts(run(h, sql, null, 1000, 4096, 1024, MAX, deadline))[0]; } catch (DebugEngineException e) { out.code = e.sqliteCode; out.message = e.getMessage(); @@ -401,6 +711,53 @@ static void lockWaits(Path dir) throws Exception { eq(Helper.close(a), 0, "waits: close the app connection"); } + static final String COMMITTED = "7 out of memory while reading the rows the statement returned; the write was committed, so do " + + "not repeat it"; + + /** + * #2332 review: what execute says of a write when building its result fails as a JNI allocation would. + * The test build's seam (SQLITEDBG_TEST) fails it on a column named sqlitedbg_test_oom_names, _row or _result. + */ + static void unfinishedWrites(Path dir) throws Exception { + String p = dir.resolve("unfinished.db").toString(); + byte[] bytes = p.getBytes(StandardCharsets.UTF_8); + long a = Helper.open(p); + eq(Helper.exec(a, "CREATE TABLE u(id INTEGER PRIMARY KEY)"), 0, "unfinished: create"); + long w = NativeBridge.openServer(bytes, true); + long r = NativeBridge.openServer(bytes, false); + + // at a row: finalize commits the write, and the error says so + eq(execRefusal(w, "INSERT INTO u(id) VALUES(1), (2) RETURNING id, 0 AS sqlitedbg_test_oom_row"), COMMITTED, + "unfinished: failing at a row, the write was committed"); + eq(q(r, "SELECT count(*) FROM u").rows.get(0)[0], 2L, "unfinished: and both rows are there"); + // after the last step + eq(execRefusal(w, "INSERT INTO u(id) VALUES(3) RETURNING 0 AS sqlitedbg_test_oom_result"), COMMITTED, + "unfinished: failing after the last step, the write was committed"); + eq(q(r, "SELECT count(*) FROM u").rows.get(0)[0], 3L, "unfinished: and its row is there"); + // before the first step the statement had not run: no claim about a write + eq(execRefusal(w, "INSERT INTO u(id) VALUES(4) RETURNING 0 AS sqlitedbg_test_oom_names"), "7 out of memory", + "unfinished: failing before the first step, nothing is claimed"); + eq(q(r, "SELECT count(*) FROM u WHERE id = 4").rows.get(0)[0], 0L, "unfinished: and nothing was written"); + // the statement failed, then its result could not be built: the statement's error is the outcome + String failed = execRefusal(w, "INSERT INTO u(id) VALUES(3) RETURNING 0 AS sqlitedbg_test_oom_result"); + check(failed != null && failed.startsWith("19 ") && failed.contains("UNIQUE constraint failed") && !failed.contains("memory"), + "unfinished: a failed statement reports its own error: " + failed); + + // the commit at finalize fails: an app reader holds SHARED past the 1.5 s cap + eq(Helper.exec(a, "BEGIN"), 0, "unfinished: the app opens a read"); + eq(Helper.exec(a, "SELECT count(*) FROM u"), 0, "unfinished: and holds SHARED"); + String locked = execRefusal(w, "INSERT INTO u(id) VALUES(5) RETURNING id, 0 AS sqlitedbg_test_oom_row"); + eq(Helper.exec(a, "COMMIT"), 0, "unfinished: the app ends its read"); + check(locked != null && locked.startsWith("7 ") && locked.contains("nothing it changed was kept") + && locked.contains("database is locked"), "unfinished: a commit failed for a lock says nothing was kept: " + locked); + eq(Helper.autocommit(w), 1, "unfinished: no transaction is left open"); + eq(q(r, "SELECT count(*) FROM u WHERE id = 5").rows.get(0)[0], 0L, "unfinished: SQLite rolled that write back"); + eq(exec(w, "INSERT INTO u(id) VALUES(6)"), 1L, "unfinished: the next execute writes"); + NativeBridge.close(r); + NativeBridge.close(w); + eq(Helper.close(a), 0, "unfinished: close the app connection"); + } + /** Reads t four times over: far longer than the cap, and it holds the lock from its first step. */ static final String LONG_READ = "SELECT count(*) FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0"; @@ -509,6 +866,20 @@ public static void main(String[] a) throws Exception { eq(((String[]) conns[1]).length, 1, "one app connection"); eq(((String[]) conns[1])[0], path, "its path"); + // setRowCapture reaches the extension: rows are recorded only while it is on (and a client is connected) + NativeBridge.setClientConnected(true); + long rowsBefore = rowEvents(); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off"); + eq(rowEvents(), rowsBefore, "no row events while row recording is off"); + NativeBridge.setRowCapture(1, 0, 0); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording on"); + eq(rowEvents(), rowsBefore + 1, "one row event: one row per statement"); + eq(newestRowStatementSql(), "SELECT id FROM t WHERE id < 3", "the row event names its own statement event (ADFA-7379)"); + NativeBridge.setRowCapture(0, 0, 0); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off again"); + eq(rowEvents(), rowsBefore + 1, "off again"); + NativeBridge.setClientConnected(false); + byte[] bytes = path.getBytes(StandardCharsets.UTF_8); long srv = NativeBridge.openServer(bytes, false); check(srv != 0, "server handle"); @@ -611,6 +982,39 @@ public static void main(String[] a) throws Exception { } eq(codeOf(srv, "SELECT ?", new Object[] {1L, 2L}, FAR), 25, "too many args: SQLITE_RANGE"); eq(codeOf(srv, "SELECT ?", new Object[] {new Object()}, FAR), 21, "unsupported arg type: SQLITE_MISUSE"); + r = query(srv, "SELECT ?2, ?1", new Object[] {"one", "two"}, 0, 10, 4096, 1024, MAX, FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("two", "one"), "?NNN in an array binds by number"); + + // by name: each prefix, written with it or bare + r = named(srv, "SELECT :a, @b, $c, :a", new Object[] {1L, "x", null}, new String[] {":a", "b", "$c"}, 0, 10, 4096, 1024, MAX, + FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList(1L, "x", null, 1L), "named: :a, @b, $c, and :a again"); + r = named(srv, "SELECT ?2, ?1", new Object[] {"one", "two"}, new String[] {"?1", "?2"}, 0, 10, 4096, 1024, MAX, FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("two", "one"), "named: ?NNN by its own name"); + r = named(srv, "SELECT :€", new Object[] {9L}, new String[] {"€"}, 0, 10, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 9L, "named: a non-ASCII name"); + r = named(srv, "SELECT 1", new Object[0], new String[0], 0, 10, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 1L, "named: no parameters, no names"); + eq(namedRefusal(srv, "SELECT :a, :b", new Object[] {1L}, new String[] {"a"}), "25 no value was given for parameter :b", + "named: a parameter left out"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L, 2L}, new String[] {"a", "zz"}), + "25 the statement has no parameter named zz", "named: a misspelt name"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L, 2L}, new String[] {"a", ":a"}), "25 parameter :a is given more than once", + "named: bare and prefixed"); + eq(namedRefusal(srv, "SELECT :a, ?", new Object[] {1L}, new String[] {"a"}), + "25 parameter 2 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: an anonymous ?"); + eq(namedRefusal(srv, "SELECT ?2", new Object[] {1L}, new String[] {"?2"}), + "25 parameter 1 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: a gap in ?NNN"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L}, new String[] {":b"}), + "25 the statement has no parameter named :b, and no value was given for parameter :a", + "named: a prefixed key matches only that prefix"); + eq(namedRefusal(srv, "SELECT id FROM t WHERE id = :id", new Object[] {1L}, new String[] {"idx"}), + "25 the statement has no parameter named idx, and no value was given for parameter :id", + "named: a misspelt key is named although a parameter also has no value"); + + // declared types: the column's, or null for an expression + r = q(srv, "SELECT id, r, s, b, id + 1, NULL FROM t LIMIT 1"); + eq(Arrays.asList(r.declaredTypes), Arrays.asList("INTEGER", "REAL", "TEXT", "BLOB", null, null), "declared types"); eq(codeOf(srv, "SELEKT 1", new Object[0], FAR), 1, "syntax error: SQLITE_ERROR"); // one statement per call: SQLite compiles only the first, so a second is refused, not dropped @@ -705,6 +1109,15 @@ public static void main(String[] a) throws Exception { eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path"); eq(execCode(w, "UPDATE t SET id = id WHERE id = -1; SELECT 1", new Object[0], FAR), 1, "execute's own error is kept"); eq(Helper.autocommit(w), 1, "rolled back after a failed execute"); + // #2332 review: a write is not run inside a transaction left open, which the backstop after it would + // roll back once the call had reported the write; that transaction is rolled back first + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path, before a write"); + eq(execRefusal(w, "INSERT INTO t(id) VALUES(4247)"), null, "execute writes"); + eq(Helper.autocommit(w), 1, "closed after the write"); + long seen = NativeBridge.openServer(bytes, false); + eq(q(seen, "SELECT count(*) FROM t WHERE id = 4247").rows.get(0)[0], 1L, "and the write was committed, as reported"); + NativeBridge.close(seen); + Helper.exec(app, "DELETE FROM t WHERE id = 4247"); eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path, rollback to be refused"); eq(Helper.denyTransactions(w, true), 0, "an authorizer that refuses ROLLBACK, for execute"); eq(execRefusal(w, "DELETE FROM t WHERE id = -1"), "23 a transaction was left open and rolling it back failed: not authorized", @@ -718,6 +1131,7 @@ public static void main(String[] a) throws Exception { execute(dir, path, app); lockWaits(dir); + unfinishedWrites(dir); nonWalCap(dir, path); diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c index d42983c3cd..acd5419d82 100644 --- a/subprojects/sqlite-debugger/src/test/jni/helper.c +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -67,3 +67,31 @@ JNIEXPORT jint JNICALL Java_Helper_autocommit(JNIEnv *e, jclass c, jlong db) { (void)c; return sqlite3_get_autocommit((sqlite3 *)(intptr_t)db); } + +static volatile long traced_rows; + +static int count_rows(unsigned type, void *c, void *p, void *x) { + (void)c; + (void)p; + (void)x; + if (type == SQLITE_TRACE_ROW) traced_rows++; + return 0; +} + +// Counts the rows sqlite3_step hands out on db from now on (SQLITE_TRACE_ROW), starting at 0, or stops counting (on +// false). Only for a server connection, which the extension does not trace; an app connection's own trace would be +// replaced. +JNIEXPORT jint JNICALL Java_Helper_traceRows(JNIEnv *e, jclass c, jlong db, jboolean on) { + (void)e; + (void)c; + traced_rows = 0; + return sqlite3_trace_v2((sqlite3 *)(intptr_t)db, on ? SQLITE_TRACE_ROW : 0, on ? count_rows : 0, 0); +} + +// The rows counted since traceRows(db, true): rows SQLite returned, so 0 means the statement never got past its +// first step. +JNIEXPORT jlong JNICALL Java_Helper_tracedRows(JNIEnv *e, jclass c) { + (void)e; + (void)c; + return traced_rows; +} 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 b78c60d0dc..e8c1bdc18a 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 @@ -16,13 +16,16 @@ private NativeBridge() {} public static native void setClientConnected(boolean connected); + public static native void setRowCapture(int maxRowsPerStatement, int maxValueBytes, int maxRowBytes); + public static native long openServer(byte[] path, boolean writable) throws DebugEngineException; - public static native Object[] query(long handle, String sql, Object[] args, long offset, int maxRows, int maxTextBytes, + public static native Object[] query(long handle, String sql, Object[] args, byte[][] names, long offset, int maxRows, int maxTextBytes, int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; - public static native long[] execute(long handle, String sql, Object[] args, long deadlineMillis) throws DebugEngineException; + public static native Object[] execute(long handle, String sql, Object[] args, byte[][] names, int maxRows, int maxTextBytes, + int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; public static native void close(long handle); } diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin index 0441b91500..ababd9573d 100644 Binary files a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin and b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin differ diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv index 4405849603..ea1b3835af 100644 --- a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv +++ b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv @@ -1,21 +1,26 @@ -426616 1 1 10289 1794545527187098386 -1 0 CREATE TABLE fx(a) -426617 2 1 10289 1794545527188573325 1000000 0 CREATE TABLE fx(a) -426618 1 1 10289 1794545527188596333 -1 0 INSERT INTO fx VALUES(?) -426619 2 1 10289 1794545527189296629 1000000 0 INSERT INTO fx VALUES(?) -426620 1 1 10289 1794545527189303467 -1 2 INSERT INTO fx VALUES(6) -426621 2 1 10289 1794545527190447975 1000000 2 INSERT INTO fx VALUES(6) -426622 1 1 10289 1794545527190472305 -1 0 SELECT 'héllo € 😀' -426623 2 1 10289 1794545527190474851 0 0 SELECT 'héllo € 😀' -426624 1 1 10289 1794545527190557276 -1 0 CREATE TABLE fxlog(a) -426625 2 1 10289 1794545527191607925 1000000 0 CREATE TABLE fxlog(a) -426626 1 1 10289 1794545527191694489 -1 1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA -426627 2 1 10289 1794545527192759261 1000000 1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA -426628 1 1 10289 1794545527192791863 -1 0 INSERT INTO fx VALUES(1) -426629 1 1 10289 1794545527192835643 -1 0 -- TRIGGER fxt -426630 1 1 10289 1794545527192836209 -1 0 -- INSERT INTO fxlog VALUES(new.a) -426631 2 1 10289 1794545527193623084 1000000 0 INSERT INTO fx VALUES(1) -426632 1 1 10289 1794545527193646993 -1 1 SELECT '€€€€€€€€€€€€€€€€€€ -426633 2 1 10289 1794545527193649365 0 1 SELECT '€€€€€€€€€€€€€€€€€€ -426634 1 3616 10289 1794545527193782816 -1 0 SELECT 1 -426635 2 3616 10289 1794545527193784200 0 0 SELECT 1 -426636 3 3616 10289 1794545527193785154 -1 0 +311944 1 1 2686304 1796115342580727290 -1 0 -1 -1 311944 CREATE TABLE fx(a) +311945 2 1 2686304 1796115342581566995 1000000 0 0 0 311944 CREATE TABLE fx(a) +311946 1 1 2686304 1796115342581631602 -1 0 -1 -1 311946 INSERT INTO fx VALUES(?) +311947 2 1 2686304 1796115342581799931 0 0 0 1 311946 INSERT INTO fx VALUES(?) +311948 1 1 2686304 1796115342581819456 -1 2 -1 -1 311948 INSERT INTO fx VALUES(6) +311949 2 1 2686304 1796115342581945136 0 2 0 1 311948 INSERT INTO fx VALUES(6) +311950 1 1 2686304 1796115342582013836 -1 0 -1 -1 311950 SELECT 'héllo € 😀' +311951 2 1 2686304 1796115342582020062 0 0 1 -1 311950 SELECT 'héllo € 😀' +311952 1 1 2686304 1796115342582198105 -1 0 -1 -1 311952 CREATE TABLE fxlog(a) +311953 2 1 2686304 1796115342582625717 0 0 0 0 311952 CREATE TABLE fxlog(a) +311954 1 1 2686304 1796115342582807243 -1 1 -1 -1 311954 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +311955 2 1 2686304 1796115342583158810 1000000 1 0 0 311954 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +311956 1 1 2686304 1796115342583228502 -1 0 -1 -1 311956 INSERT INTO fx VALUES(1) +311957 1 1 2686304 1796115342583301956 -1 0 -1 -1 0 -- TRIGGER fxt +311958 1 1 2686304 1796115342583304166 -1 0 -1 -1 0 -- INSERT INTO fxlog VALUES(new.a) +311959 2 1 2686304 1796115342583424767 0 0 0 1 311956 INSERT INTO fx VALUES(1) +311960 1 1 2686304 1796115342583481472 -1 1 -1 -1 311960 SELECT '€€€€€€€€€€€€€€€€€€ +311961 2 1 2686304 1796115342583487595 0 1 1 -1 311960 SELECT '€€€€€€€€€€€€€€€€€€ +311962 1 2612 2686304 1796115342583898175 -1 0 -1 -1 311962 SELECT 1 +311963 2 2612 2686304 1796115342583903116 0 0 1 -1 311962 SELECT 1 +311964 3 2612 2686304 1796115342583906609 -1 0 -1 -1 0 +311965 1 1 2686304 1796115342584039276 -1 3 -1 -1 311965 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +311966 4 1 2686304 1796115342584050652 -1 1 1 -1 311965 5/5|i:7,f:2.5,t*:hél,b*:0a0b0c0d,n: +311967 2 1 2686304 1796115342584058221 0 7 2 -1 311965 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +311968 1 1 2686304 1796115342584084398 -1 0 -1 -1 311968 DELETE FROM fxlog +311969 2 1 2686304 1796115342584272160 0 0 0 1 311968 DELETE FROM fxlog diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh index ce80e1702a..279bfd1506 100755 --- a/subprojects/sqlite-debugger/test.sh +++ b/subprojects/sqlite-debugger/test.sh @@ -86,7 +86,7 @@ run_jni () { # 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" \ "$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[@]}" \ + build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -fvisibility=hidden -DSQLITEDBG_TEST -I"$AMAL" -I"$CPP" "${jinc[@]}" \ "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_jni.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" \