diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 236123db27..d55b3aae62 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,16 +30,30 @@ 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, and nothing turns it on yet; the server will (ADFA-7297). +- 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). + ## 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 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; 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 after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), 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 still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool 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; 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. 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 after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), 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 still run SQL, so the token is the boundary. - **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 while a statement waits for a lock the app holds (the busy wait, up to 3 s, `SQLITEDBG_SERVER_BUSY_MS`) or inside one long VM instruction, so a result can arrive up to about 3 s after its limit (the client waits 60 s). 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). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index d55c47afac..f2a72a9273 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); +} + static int server_authorizer(void *unused, int action, const char *a1, const char *a2, const char *db, const char *trigger) { (void)unused; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 4b342ce878..6d098bc592 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/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 0225492399..e2cf8e382c 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 @@ -91,6 +91,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( @@ -103,10 +109,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( 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/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 5f3d6c637d..03f323abe0 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 @@ -816,6 +1890,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; @@ -843,6 +1918,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 @@ -853,6 +1929,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++; } @@ -865,6 +1942,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; @@ -874,20 +1952,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; } @@ -896,9 +1998,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; } @@ -914,6 +2019,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; @@ -926,11 +2032,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); @@ -938,17 +2045,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) { @@ -975,6 +2129,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) { @@ -1004,11 +2166,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); @@ -1076,6 +2241,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 f889ba3684..19ef46f335 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 @@ -44,14 +44,32 @@ 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 [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() @@ -74,8 +92,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 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/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