diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 236123db27..c8371a91d7 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,6 +30,13 @@ 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). +**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 a statement that changed nothing has 0 (a CREATE TABLE, which `sqlite3_changes64` alone would report with the previous write'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. +- 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). 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. +- 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. @@ -39,7 +46,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **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 is 3 since the row and change fields, ADFA-7296), 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..cf60e234d8 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -22,14 +22,31 @@ 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 72u +#define ROW_HEADER_BYTES 8u +#define ROW_VALUE_BYTES 12u _Static_assert(sizeof(sqlitedbg_event_record) == RECORD_HEADER_BYTES, "event record layout"); +_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 +} stmt_slot; + typedef struct conn_state { struct conn_state *prev, *next; uint64_t id; @@ -38,6 +55,10 @@ 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; } conn_state; // Taken only for the fields below; never while SQLite runs. @@ -49,6 +70,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 +154,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 void 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) { 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,9 +174,11 @@ 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; + 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; @@ -160,6 +186,94 @@ static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns pthread_mutex_unlock(&g_lock); } +static void 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) { + size_t kept = utf8_cut(sql, sql_len, g_max_sql); + if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; + add_record(kind, connection_id, duration_ns, rows, changes, flags, sql, kept); +} + +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 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); + 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; + 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. 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 void record_row(conn_state *cs, sqlite3_stmt *stmt, int64_t number) { + 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; + unsigned char *data = (unsigned char *)malloc(budget); + if (!data) return; + 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) { + // For TEXT, sqlite3_column_text first and then sqlite3_column_bytes, as SQLite advises. + const void *p = type == SQLITE_TEXT ? (const void *)sqlite3_column_text(stmt, i) : sqlite3_column_blob(stmt, i); + size_t full = (size_t)sqlite3_column_bytes(stmt, i); + size_t limit = room < max_value ? room : max_value; + // p is NULL 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); + free(data); +} + // sqlite3_trace_v2 callback. C is the connection's conn_state, which lives until SQLite frees the // connection, so it outlives every callback. static int trace_cb(unsigned type, void *c, void *p, void *x) { @@ -194,15 +308,51 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { } } 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; + if (is_stmt) { + // SQLite's own nested statements (the schema read a CREATE TABLE runs, for one) are traced + // with "--" text like a trigger, so they get no slot and their rows are never recorded. + if (!is_trigger) claim_slot(cs, stmt)->total_changes = sqlite3_total_changes64(sqlite3_db_handle(stmt)); + } else { + stmt_slot *slot = find_slot(cs, stmt); + if (slot) { + rows = slot->rows; + 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. + sqlite3 *db = sqlite3_db_handle(stmt); + changes = sqlite3_total_changes64(db) == slot->total_changes ? 0 : sqlite3_changes64(db); + } + memset(slot, 0, sizeof *slot); + } + } + add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, rows, changes, + flags, sql, strlen(sql)); if (expanded) sqlite3_free(expanded); break; } + case SQLITE_TRACE_ROW: { + sqlite3_stmt *stmt = (sqlite3_stmt *)p; + stmt_slot *slot = find_slot(cs, stmt); + if (!slot) break; + 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; + } + slot->recorded++; + record_row(cs, stmt, slot->rows); + 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); break; } return 0; @@ -230,6 +380,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 +439,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 +544,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..71c2b23d0f 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -23,7 +23,7 @@ extern "C" { #endif // The interface version. Raise it when anything below changes shape. -#define SQLITEDBG_INTERFACE_VERSION 2 +#define SQLITEDBG_INTERFACE_VERSION 3 // 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 +85,70 @@ 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 because the statement returned more than + // the per-statement limit while row recording was on. + 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 for a read-only statement, for the + // other kinds, and when rows is -1. + int64_t changes; +} sqlitedbg_event_record; // 72 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) +} 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 +176,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..0c3fa07de0 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,37 @@ 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 and for the other kinds. + */ + val changes: Long? = null, + /** [EventKind.PROFILE]: rows went unrecorded because the statement returned more than the per-statement limit. */ + val rowsCut: Boolean = false, + /** [EventKind.ROW] only: the row's values. */ + val row: RowValues? = 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..e49421a8c8 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 = 72 private const val OFFSET_RECORD_BYTES = 0 private const val OFFSET_KIND = 4 @@ -19,10 +20,23 @@ 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 FLAG_TRUNCATED = 1 private const val FLAG_EXPANDED = 2 + private const val FLAG_ROWS_CUT = 4 + + private const val ROW_HEADER_BYTES = 8 + private 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 +54,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 +64,10 @@ 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 } events += Event( seq = buffer.getLong(offset + OFFSET_SEQ), @@ -58,12 +76,71 @@ 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, ) 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" } + 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" } + 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" } + 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..a6300732b8 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -66,12 +66,15 @@ 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; + 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 +104,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 +119,11 @@ 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->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 +192,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 +229,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 +260,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 +350,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 +369,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 +384,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 +400,355 @@ 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; +} + +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); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r")->rows, 5); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r")->flags, 0); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT i FROM r WHERE i < 3")->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)"); + batch b; + read_all(cur, &b); + 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}, + }; + 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'}; + 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); + } + k++; + } + CHECK_EQ(k, 5); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 10 UNION ALL SELECT 20")->rows, 2); + CHECK_EQ(find_event(&b, SQLITEDBG_EVENT_PROFILE, "SELECT 'x' UNION ALL SELECT 'y' UNION ALL SELECT 'z'")->rows, 3); + 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 second row had no slot + 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); + 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); +} + static void test_burst(void) { uint64_t cur = cursor_now(); const int stmts = 2000; @@ -513,7 +868,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 +1171,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 +1199,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 +1210,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++; } @@ -885,8 +1243,8 @@ static void *reader_main(void *arg) { 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; prev = rec->seq; off += rec->record_bytes; @@ -896,9 +1254,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; } @@ -926,11 +1287,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 +1300,63 @@ 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, 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", (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); + 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 +1383,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 +1420,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 +1495,12 @@ 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(); 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..1b47cf84ef 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, 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 = 10) } private fun resource(name: String): ByteArray = checkNotNull(javaClass.getResourceAsStream(name)) { "missing fixture $name" }.use { it.readBytes() } @@ -34,7 +34,42 @@ 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 }) + if (event.kind == EventKind.ROW) { + assertThat(event.sql).isEmpty() + assertRow(event.row, row[9]) + } else { + assertThat(event.row).isNull() + assertThat(event.sql).isEqualTo(row[9]) + } + } + } + + // 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,6 +80,19 @@ 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() @@ -89,4 +137,36 @@ 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") + } } 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..a1b0e7d07a 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..94a033c800 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 +449760 1 1 1139 1795576849764877244 -1 0 -1 -1 CREATE TABLE fx(a) +449761 2 1 1139 1795576849767385554 3000000 0 0 0 CREATE TABLE fx(a) +449762 1 1 1139 1795576849767428350 -1 0 -1 -1 INSERT INTO fx VALUES(?) +449763 2 1 1139 1795576849768441548 1000000 0 0 1 INSERT INTO fx VALUES(?) +449764 1 1 1139 1795576849768454479 -1 2 -1 -1 INSERT INTO fx VALUES(6) +449765 2 1 1139 1795576849769429166 1000000 2 0 1 INSERT INTO fx VALUES(6) +449766 1 1 1139 1795576849769467830 -1 0 -1 -1 SELECT 'héllo € 😀' +449767 2 1 1139 1795576849769470941 0 0 1 -1 SELECT 'héllo € 😀' +449768 1 1 1139 1795576849769551873 -1 0 -1 -1 CREATE TABLE fxlog(a) +449769 2 1 1139 1795576849770495943 1000000 0 0 0 CREATE TABLE fxlog(a) +449770 1 1 1139 1795576849770577649 -1 1 -1 -1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +449771 2 1 1139 1795576849771426369 1000000 1 0 0 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +449772 1 1 1139 1795576849771458485 -1 0 -1 -1 INSERT INTO fx VALUES(1) +449773 1 1 1139 1795576849771502214 -1 0 -1 -1 -- TRIGGER fxt +449774 1 1 1139 1795576849771502704 -1 0 -1 -1 -- INSERT INTO fxlog VALUES(new.a) +449775 2 1 1139 1795576849772343290 1000000 0 0 1 INSERT INTO fx VALUES(1) +449776 1 1 1139 1795576849772372693 -1 1 -1 -1 SELECT '€€€€€€€€€€€€€€€€€€ +449777 2 1 1139 1795576849772375404 0 1 1 -1 SELECT '€€€€€€€€€€€€€€€€€€ +449778 1 3765 1139 1795576849772556358 -1 0 -1 -1 SELECT 1 +449779 2 3765 1139 1795576849772558632 0 0 1 -1 SELECT 1 +449780 3 3765 1139 1795576849772559491 -1 0 -1 -1 +449781 1 1 1139 1795576849772612443 -1 3 -1 -1 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +449782 4 1 1139 1795576849772617397 -1 1 1 -1 5/5|i:7,f:2.5,t*:hél,b*:0a0b0c0d,n: +449783 2 1 1139 1795576849772619972 0 7 2 -1 SELECT 7, 2.5, 'héllo', x'0a0b0c0d0e', NULL UNION ALL SELECT -9 +449784 1 1 1139 1795576849772628067 -1 0 -1 -1 DELETE FROM fxlog +449785 2 1 1139 1795576849773550011 1000000 0 0 1 DELETE FROM fxlog