diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index d55b3aae62..ff7594e431 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -39,11 +39,21 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han **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). +- `SQLITEDBG_EVENT_ROW` records one row's values: the first N rows of each statement, while a client is connected and `sqlitedbg_set_row_capture` is on. Recording is off by default; `get_events` turns it on (see "Results and bound parameters"). - Each value is read with the accessor of its own type, after `sqlite3_column_type`. `sqlite3_column_text` on every column would convert values in place: on a BLOB, the app's own `sqlite3_column_type` then returns TEXT. TEXT and BLOB values are cut at a per-value limit, and a row's data at a per-row limit (at most 64 KiB, `SQLITEDBG_MAX_ROW_BYTES`, so a row record always fits the 256 KiB the server reads at a time); both are marked. A TEXT or BLOB larger than 1 MiB that does not fit the limits is not read at all (size recorded, no bytes, marked cut): `sqlite3_column_blob` would otherwise materialize it on the app's own statement (a zeroblob is virtual until read), costing its size in memory and risking `SQLITE_NOMEM` there. The size comes from `sqlite3_column_bytes` first. Accepted limit: in a UTF-16 database, recording rows converts each TEXT value to UTF-8 in full (`sqlite3_column_bytes`) before the 1 MiB guard applies, so a large value costs its full size in memory and time on the app's thread, for each row recorded while a client is connected (measured with a 25-million-character TEXT: a 100 MB allocation and about 230 ms for one row, against about 54 ms with recording off). Android's own databases and Room use UTF-8, which has no such copy. Decided not to change (David). - The extension follows up to 16 statements per connection (`SQLITEDBG_STATEMENT_SLOTS`) from their start to their PROFILE event. Rows of a statement it did not see start are not recorded, which drops the rows of SQLite's own nested statements (a CREATE TABLE's schema read returns one; those reads are traced as ROW only and are ignored). Limit: a connection that steps more than 16 statements in turn loses the oldest, whose remaining rows go unrecorded and whose PROFILE event has `rows` and `changes` -1. A step that returns `SQLITE_BUSY` before any row fires a PROFILE event (rows 0, changes -1) and SQLite fires no other for that execution when it resumes; the slot is kept, so the rows that follow are still numbered and recorded, but they have no PROFILE event of their own. A row that cannot be recorded (the row limit is below a row header, or an allocation failed) is not counted as recorded and sets `ROWS_CUT`. - Rows are counted on every statement, client or not: `SQLITE_TRACE_ROW` is part of the trace mask from the connection's open. Adding it when a client connects would take a `sqlite3_trace_v2` call on each app connection, which the server's thread may not make while the app uses the connection (`SQLITE_THREADSAFE=2`). The cost per row is one callback and a lookup in 16 slots. On a Galaxy J7 (Android 9, armeabi-v7a), with no client connected, a SELECT returning 20 rows took about 1.1 microseconds longer than before ADFA-7296 (71.6 against 70.5), and a one-row SELECT 0.6 longer (37.5 against 36.9); recording rows, once on, costs about 2.9 microseconds per row (native benchmark, PR #2311). +### Results and bound parameters (ADFA-7297) + +What the server gives a client so it can format results as the sqlite3 shell would (`.mode`, `.nullvalue` and the rest stay client-side): +- **Values.** A NULL is JSON `null`. A BLOB is `{hex, bytes, truncated}`, lowercase hex (base64 before). An integer beyond 2^53 is a decimal string, and a NaN or infinite REAL is `"NaN"`, `"Infinity"` or `"-Infinity"`, as before. +- **Storage classes.** JSON alone cannot tell a REAL 2.0 from an INTEGER 2 (org.json writes both as `2`), or a big integer from TEXT, so `query` returns `storage_classes`, one string per row with a letter per column: `i` INTEGER, `r` REAL, `t` TEXT, `b` BLOB, `n` NULL. Row events carry the same string. +- **Declared types.** `query` returns `column_types`, each column's `sqlite3_column_decltype`, `null` for an expression. +- **Bound parameters (`.parameter`).** `query` and `explain_query_plan` take `args` as an array, bound by position (`?`, and `?NNN` by its number), or as an object bound by name (`:name`, `@name`, `$name`, `?NNN`). A key is written as in the SQL or bare: `id` matches `:id`, `@id` and `$id`, so SQL holding two of those gets the same value for both. Every parameter needs a value and every key must name a parameter, so a misspelt name fails rather than binding NULL, and the error names the key even when a parameter is also left without a value; an anonymous `?`, or a gap in the `?NNN` numbers, has no name and needs the array form. Names reach the JNI layer as UTF-8 and are matched there (`bind_named`), against `sqlite3_bind_parameter_name`. +- **Rows and changes in `get_events`.** A `profile` event carries `rows` (the rows the statement returned), `changes` (the rows it changed itself; `null` for a read) and `rows_cut`. Every event has `execution_id` (ADFA-7379): a `statement` event's own `seq`, and on that run's `profile` and `row` events the same number, so rows of two statements stepped in turn are told apart; it is `null` for `close`, a trigger's statements, a statement an app function runs inside a callback, an EXPLAIN's `profile`, a statement whose start was not seen, and the later `profile` and `row` events of a statement pushed out of its slot. One run can have more than one `profile`, such as one with `rows` 0 from a step that met a busy lock, before the run's rows (the event format above lists every case). A `row` event carries `row_number`, `column_count`, `values`, `storage_classes` and `cut_values`. `get_events` turns row recording on (`DebugEngine.setRowCapture`): the first 10 rows of each statement, TEXT and BLOB values cut at 256 bytes, a row's data at 4 KiB (`DatabaseTools.EVENT_*`). It costs the app about 2.9 microseconds a row on a Galaxy J7 (above), so `include_rows: false` turns it off and leaves row events out, and it goes off with bound-value recording, 60 s after the last `get_events`, and when the server stops. Only rows the app's statements return after the call are recorded. +- **Limits.** `execute` (ADFA-7298, a separate PR) binds positional `args` only until the two PRs meet. Row recording is one switch for the process: the last `get_events` call decides it. + ## 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. @@ -63,7 +73,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 8d19317ff2..b8ae3dec8f 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -166,6 +166,13 @@ static void bridge_set_client_connected(JNIEnv *env, jclass cls, jboolean connec sqlitedbg_set_client_connected(connected ? 1 : 0); } +static void bridge_set_row_capture(JNIEnv *env, jclass cls, jint max_rows, jint max_value_bytes, jint max_row_bytes) { + (void)env; + (void)cls; + sqlitedbg_set_row_capture(max_rows > 0 ? (uint32_t)max_rows : 0, max_value_bytes > 0 ? (uint32_t)max_value_bytes : 0, + max_row_bytes > 0 ? (uint32_t)max_row_bytes : 0); +} + // server connections static jlong bridge_open_server(JNIEnv *env, jclass cls, jbyteArray path, jboolean writable) { @@ -220,49 +227,166 @@ static int progress_cb(void *p) { return 1; } -// Binds args[i] to parameter i + 1. Returns SQLITE_OK or a code with *message set. -static int bind_args(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { +// Binds v (null, Long, Double, String or byte[]) to parameter idx (from 1). +static int bind_value(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, int idx, jobject v, const char **message) { + int rc; + if (!v) { + rc = sqlite3_bind_null(st, idx); + } else if ((*env)->IsInstanceOf(env, v, g_long)) { + jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); + rc = sqlite3_bind_int64(st, idx, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_double)) { + jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); + rc = sqlite3_bind_double(st, idx, (*env)->CallDoubleMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_string)) { + jsize len = (*env)->GetStringLength(env, (jstring)v); + const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); + if (!chars) return SQLITE_NOMEM; + rc = sqlite3_bind_text16(st, idx, chars, len * 2, SQLITE_TRANSIENT); + (*env)->ReleaseStringChars(env, (jstring)v, chars); + } else { + jclass bytes_class = (*env)->FindClass(env, "[B"); + int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); + if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); + if (!is_bytes) { + *message = "unsupported argument type"; + return SQLITE_MISUSE; + } + jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); + void *copy = malloc(len ? (size_t)len : 1); + if (!copy) return SQLITE_NOMEM; + (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); + rc = sqlite3_bind_blob64(st, idx, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); + free(copy); + } + if (rc != SQLITE_OK) { + *message = sqlite3_errmsg(db); + return rc; + } + return (*env)->ExceptionCheck(env) ? SQLITE_ERROR : SQLITE_OK; +} + +// Binds args by position, ? and ?NNN alike: args[i] to parameter i + 1. Their number must be the +// statement's parameter count: a missing one would be bound as NULL and the query would run, +// returning a plausible empty result. +static int bind_positional(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { + int wanted = sqlite3_bind_parameter_count(st); jsize count = (*env)->GetArrayLength(env, args); + if (count != wanted) { + char msg[96]; + snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)count); + throw_engine(env, SQLITE_RANGE, msg); + return SQLITE_RANGE; + } for (jsize i = 0; i < count; i++) { jobject v = (*env)->GetObjectArrayElement(env, args, i); - int rc; - if (!v) { - rc = sqlite3_bind_null(st, i + 1); - } else if ((*env)->IsInstanceOf(env, v, g_long)) { - jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); - rc = sqlite3_bind_int64(st, i + 1, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); - } else if ((*env)->IsInstanceOf(env, v, g_double)) { - jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); - rc = sqlite3_bind_double(st, i + 1, (*env)->CallDoubleMethod(env, v, m)); - } else if ((*env)->IsInstanceOf(env, v, g_string)) { - jsize len = (*env)->GetStringLength(env, (jstring)v); - const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); - if (!chars) return SQLITE_NOMEM; - rc = sqlite3_bind_text16(st, i + 1, chars, len * 2, SQLITE_TRANSIENT); - (*env)->ReleaseStringChars(env, (jstring)v, chars); - } else { - jclass bytes_class = (*env)->FindClass(env, "[B"); - int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); - if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); - if (!is_bytes) { - *message = "unsupported argument type"; - return SQLITE_MISUSE; + int rc = bind_value(env, db, st, i + 1, v, message); + if (v) (*env)->DeleteLocalRef(env, v); + if (rc != SQLITE_OK) return rc; + } + return SQLITE_OK; +} + +typedef struct { + char *name; // UTF-8, not terminated + size_t len; + int used; +} bind_key; + +// Whether SQLite's parameter name (":id", "@id", "$id" or "?3") is key: written the same, or key +// without the prefix (":", "@" or "$"). +static int key_matches(const char *param, const bind_key *key) { + size_t plen = strlen(param); + if (plen == key->len && memcmp(param, key->name, plen) == 0) return 1; + if (key->len == 0 || strchr(":@$?", key->name[0])) return 0; + return strchr(":@$", param[0]) && plen - 1 == key->len && memcmp(param + 1, key->name, key->len) == 0; +} + +// Binds args by name: names[i] (UTF-8) names the parameter args[i] goes to. Every parameter must +// get exactly one value and every name must be used, so a misspelt name fails instead of leaving a +// NULL. The error names a name that matches no parameter even when a parameter also has no value, +// since that name is most likely the parameter's, misspelt. +static int bind_named(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, jobjectArray names, + const char **message) { + jsize n = (*env)->GetArrayLength(env, names); + if ((*env)->GetArrayLength(env, args) != n) { + *message = "names and args differ in length"; + return SQLITE_MISUSE; + } + bind_key *keys = calloc(n ? (size_t)n : 1, sizeof *keys); + if (!keys) return SQLITE_NOMEM; + int rc = SQLITE_OK; + char msg[320]; + const char *missing = NULL; // the first parameter with no value; SQLite owns the string + for (jsize i = 0; i < n && rc == SQLITE_OK; i++) { + jbyteArray b = (jbyteArray)(*env)->GetObjectArrayElement(env, names, i); + if (!b) { + *message = "a parameter name is null"; + rc = SQLITE_MISUSE; + break; + } + jsize len = (*env)->GetArrayLength(env, b); + keys[i].name = malloc(len ? (size_t)len : 1); + if (!keys[i].name) rc = SQLITE_NOMEM; + else { + (*env)->GetByteArrayRegion(env, b, 0, len, (jbyte *)keys[i].name); + keys[i].len = (size_t)len; + } + (*env)->DeleteLocalRef(env, b); + } + int count = sqlite3_bind_parameter_count(st); + for (int p = 1; p <= count && rc == SQLITE_OK; p++) { + const char *param = sqlite3_bind_parameter_name(st, p); + if (!param) { + snprintf(msg, sizeof msg, + "parameter %d has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", p); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; + } + jsize found = -1; + for (jsize i = 0; i < n; i++) { + if (!key_matches(param, &keys[i])) continue; + if (found >= 0) { + snprintf(msg, sizeof msg, "parameter %.100s is given more than once", param); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + break; } - jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); - void *copy = malloc(len ? (size_t)len : 1); - if (!copy) return SQLITE_NOMEM; - (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); - rc = sqlite3_bind_blob64(st, i + 1, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); - free(copy); + found = i; + } + if (rc != SQLITE_OK) break; + if (found < 0) { + if (!missing) missing = param; + continue; } + keys[found].used = 1; + jobject v = (*env)->GetObjectArrayElement(env, args, found); + rc = bind_value(env, db, st, p, v, message); if (v) (*env)->DeleteLocalRef(env, v); - if (rc != SQLITE_OK) { - *message = sqlite3_errmsg(db); - return rc; + } + jsize unused = -1; + for (jsize i = 0; i < n && unused < 0; i++) { + if (!keys[i].used) unused = i; + } + if (rc == SQLITE_OK && unused >= 0) { + int shown = keys[unused].len > 100 ? 100 : (int)keys[unused].len; + if (missing) { + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s, and no value was given for parameter %.100s", + shown, keys[unused].name, missing); + } else { + snprintf(msg, sizeof msg, "the statement has no parameter named %.*s", shown, keys[unused].name); } - if ((*env)->ExceptionCheck(env)) return SQLITE_ERROR; + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; + } else if (rc == SQLITE_OK && missing) { + snprintf(msg, sizeof msg, "no value was given for parameter %.100s", missing); + throw_engine(env, SQLITE_RANGE, msg); + rc = SQLITE_RANGE; } - return SQLITE_OK; + for (jsize i = 0; i < n; i++) free(keys[i].name); + free(keys); + return rc; } // A UTF-8 prefix of at most max bytes ending on a character boundary. @@ -348,7 +472,8 @@ static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, } } -static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong offset, +static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, + jobjectArray names, jlong offset, jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; @@ -392,31 +517,31 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sqlite3_progress_handler(db, 1000, progress_cb, &dl); handler_set = 1; - // A missing argument would be bound as NULL and the query would run, returning a plausible empty result. - int wanted = sqlite3_bind_parameter_count(st); - jsize given = (*env)->GetArrayLength(env, args); - if (given != wanted) { - char msg[96]; - snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)given); - throw_engine(env, SQLITE_RANGE, msg); - goto done; - } - rc = bind_args(env, db, st, args, &message); + rc = names ? bind_named(env, db, st, args, names, &message) : bind_positional(env, db, st, args, &message); if (rc != SQLITE_OK) { if (!(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); goto done; } int ncols = sqlite3_column_count(st); - jobjectArray names = (*env)->NewObjectArray(env, ncols, g_string, NULL); - jobject rows = names ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; + jobjectArray columns = (*env)->NewObjectArray(env, ncols, g_string, NULL); + // The declared type of each column, null for an expression (sqlite3_column_decltype) + jobjectArray decltypes = columns ? (*env)->NewObjectArray(env, ncols, g_string, NULL) : NULL; + jobject rows = decltypes ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; if (!rows) goto done; for (int c = 0; c < ncols; c++) { const char *name = sqlite3_column_name(st, c); jstring s = utf8_string(env, name ? name : "", name ? (int)strlen(name) : 0); if (!s) goto done; - (*env)->SetObjectArrayElement(env, names, c, s); + (*env)->SetObjectArrayElement(env, columns, c, s); (*env)->DeleteLocalRef(env, s); + const char *decl = sqlite3_column_decltype(st, c); + if (decl) { + jstring d = utf8_string(env, decl, (int)strlen(decl)); + if (!d) goto done; + (*env)->SetObjectArrayElement(env, decltypes, c, d); + (*env)->DeleteLocalRef(env, d); + } } int has_more = 0, row_count = 0; @@ -486,14 +611,15 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring // {cut cell count, hasMore, then the index of each cut cell} jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); - result = counts ? (*env)->NewObjectArray(env, 3, g_object, NULL) : NULL; + result = counts ? (*env)->NewObjectArray(env, 4, g_object, NULL) : NULL; if (!result) goto done; jlong head[2] = {(jlong)cut_n, has_more}; (*env)->SetLongArrayRegion(env, counts, 0, 2, head); if (cut_n) (*env)->SetLongArrayRegion(env, counts, 2, (jsize)cut_n, cut_cells); - (*env)->SetObjectArrayElement(env, result, 0, names); + (*env)->SetObjectArrayElement(env, result, 0, columns); (*env)->SetObjectArrayElement(env, result, 1, rows); (*env)->SetObjectArrayElement(env, result, 2, counts); + (*env)->SetObjectArrayElement(env, result, 3, decltypes); done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); @@ -550,7 +676,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"readEvents", "(J[B[J)V", (void *)bridge_read_events}, {"setClientConnected", "(Z)V", (void *)bridge_set_client_connected}, {"openServer", "([BZ)J", (void *)bridge_open_server}, - {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"setRowCapture", "(III)V", (void *)bridge_set_row_capture}, + {"query", "(JLjava/lang/String;[Ljava/lang/Object;[[BJIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index e2cf8e382c..614a54b7af 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -29,9 +29,20 @@ interface DebugEngine { maxBytes: Int, ): EventBatch - /** While true, statements are recorded with their bound values written in. */ + /** While true, statements are recorded with their bound values written in, and rows if [setRowCapture] is on. */ fun setClientConnected(connected: Boolean) + /** + * Records the first [maxRowsPerStatement] rows of each statement as [EventKind.ROW] events while a + * client is connected; 0 turns it off, as at install. TEXT and BLOB values are cut at [maxValueBytes] + * and a row's data at [maxRowBytes] (`sqlitedbg_set_row_capture`). + */ + fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) + /** * Opens [path] for the server: read-only (with an authorizer refusing writes) unless * [writable]. Only a path one of [connections] has open may be passed: opening a database that @@ -55,12 +66,17 @@ interface ServerConnection : Closeable { * progress handler on this server connection) once [deadlineMillis] (System.currentTimeMillis * clock) has passed. * + * [argNames] null binds [args] by position, `?NNN` by its number; otherwise `argNames[i]` names the + * parameter `args[i]` goes to, written as in the SQL (`:id`, `@id`, `$id`, `?3`) or bare (`id`, for + * any of `:`, `@` and `$`). Every parameter must get exactly one value and every name must be used. + * * @throws DebugEngineException for SQLite errors, SQL with no statement or more than one, a - * refused write, or the deadline. + * refused write, the deadline, or arguments that do not match the parameters (SQLITE_RANGE). */ fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -189,6 +205,8 @@ data class QueryResult( * is whole and not listed, one byte more is. [truncatedCells] is its size. */ val truncatedCellIndexes: Set = emptySet(), + /** Each column's declared type, as `sqlite3_column_decltype` gives it; null for an expression. */ + val declaredTypes: List = List(columns.size) { null }, ) { fun isTruncated( row: Int, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 2aee5d390a..6450b1c403 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -24,6 +24,17 @@ internal object NativeBridge { @JvmStatic external fun setClientConnected(connected: Boolean) + /** + * Turns row recording on (`maxRowsPerStatement` > 0) or off (0): `sqlitedbg_set_row_capture`. A value + * or row limit of 0 takes the extension's default. + */ + @JvmStatic + external fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) + /** A handle for [query] and [close]. Throws [DebugEngineException]. */ @JvmStatic external fun openServer( @@ -32,15 +43,17 @@ internal object NativeBridge { ): Long /** - * `[Array, ArrayList>, LongArray]`: the column names, the rows, and - * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column). - * Throws [DebugEngineException]. + * `[Array, ArrayList>, LongArray, Array]`: the column names, the rows, + * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column), and each + * column's declared type. [names] null binds [args] by position; otherwise `names[i]` (UTF-8) names + * the parameter `args[i]` goes to. Throws [DebugEngineException]. */ @JvmStatic external fun query( handle: Long, sql: String, args: Array, + names: Array?, offset: Long, maxRows: Int, maxTextBytes: Int, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index de4217fb02..9b4130b98d 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -70,6 +70,12 @@ class NativeDebugEngine : DebugEngine { override fun setClientConnected(connected: Boolean) = NativeBridge.setClientConnected(connected) + override fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) = NativeBridge.setRowCapture(maxRowsPerStatement, maxValueBytes, maxRowBytes) + override fun openServerConnection( path: String, writable: Boolean, @@ -81,12 +87,14 @@ class NativeDebugEngine : DebugEngine { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult { check(handle != 0L) { "the connection is closed" } require(offset >= 0) { "offset $offset is negative" } + require(argNames == null || argNames.size == args.size) { "${argNames?.size} names for ${args.size} args" } require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0 && limits.maxTotalBytes > 0) { "bad limits $limits" } @@ -95,6 +103,7 @@ class NativeDebugEngine : DebugEngine { handle, sql, Array(args.size) { bindable(args[it]) }, + argNames?.map { it.toByteArray(Charsets.UTF_8) }?.toTypedArray(), offset, limits.maxRows, limits.maxTextBytes, @@ -111,7 +120,16 @@ class NativeDebugEngine : DebugEngine { val counts = result[2] as LongArray val cut = HashSet() for (i in 2 until counts.size) cut += counts[i] - return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L, truncatedCellIndexes = cut) + @Suppress("UNCHECKED_CAST") + val declaredTypes = (result[3] as Array).asList() + return QueryResult( + columns, + rows, + truncatedCells = counts[0].toInt(), + hasMore = counts[1] != 0L, + truncatedCellIndexes = cut, + declaredTypes = declaredTypes, + ) } override fun close() { diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index ac343b44af..fd8107fd00 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -3,6 +3,8 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.Event +import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult import org.appdevforall.sqlitedebugger.engine.ServerConnection @@ -70,11 +72,23 @@ class DatabaseTools internal constructor( /** Bound values stop being recorded this long after the last get_events call. */ const val EVENTS_IDLE_MS = 60_000L + /** get_events' row recording: rows per statement, bytes per TEXT or BLOB value, and bytes per row. */ + const val EVENT_ROWS_PER_STATEMENT = 10 + const val EVENT_VALUE_BYTES = 256 + const val EVENT_ROW_BYTES = 4096 + private const val MAX_SAFE_INTEGER = 9007199254740992L // 2^53 private val SIDE_FILE_SUFFIXES = listOf("-wal", "-shm", "-journal") const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + /** How a cell is written, said by every tool that returns cells. */ + const val VALUES_NOTE = + "A NULL is JSON null; a BLOB is {hex, bytes, truncated}; an integer beyond 2^53 is a decimal string, and a " + + "NaN or infinite REAL is the string \"NaN\", \"Infinity\" or \"-Infinity\". storage_classes gives each row's " + + "SQLite storage classes, one letter per column: i INTEGER, r REAL, t TEXT, b BLOB, n NULL (JSON writes a REAL " + + "such as 2.0 as 2)." + /** Said by the tools that return cells whose TEXT and BLOB values the server can cut. */ private const val CUT_CELLS_NOTE = "truncated_cells counts the cut cells and truncated_cell_indexes lists each as [row, column], both from 0 and " + @@ -128,7 +142,7 @@ class DatabaseTools internal constructor( is ByteArray -> { JSONObject() - .put("base64", McpHttp.base64(value, urlSafe = false, pad = true)) + .put("hex", hex(value)) .put("bytes", value.size) .put("truncated", truncated) } @@ -138,6 +152,29 @@ class DatabaseTools internal constructor( } } + private val HEX_DIGITS = "0123456789abcdef".toCharArray() + + fun hex(bytes: ByteArray): String { + val out = CharArray(bytes.size * 2) + bytes.forEachIndexed { i, b -> + out[i * 2] = HEX_DIGITS[(b.toInt() shr 4) and 0xf] + out[i * 2 + 1] = HEX_DIGITS[b.toInt() and 0xf] + } + return String(out) + } + + /** One letter per value: i INTEGER, r REAL, t TEXT, b BLOB, n NULL (see [VALUES_NOTE]). */ + fun storageClasses(values: List): String = + values.joinToString("") { + when (it) { + null -> "n" + is Long, is Int -> "i" + is Double -> "r" + is ByteArray -> "b" + else -> "t" + } + } + fun encodeLong(value: Long): Any = if (value > MAX_SAFE_INTEGER || value < -MAX_SAFE_INTEGER) value.toString() else value fun quoteIdentifier(name: String) = "\"" + name.replace("\"", "\"\"") + "\"" @@ -146,6 +183,7 @@ class DatabaseTools internal constructor( private val lock = Any() private val serverConnections = HashMap() private var clientConnected = false + private var rowCapture = false private var lastEventsCallMs = 0L private var cancelIdleCheck: (() -> Unit)? = null private var idleCheckGeneration = 0 @@ -182,9 +220,17 @@ class DatabaseTools internal constructor( clientConnected = false engine.setClientConnected(false) } + setRowCaptureLocked(false) } } + /** Row recording costs the app time on every row it reads, so it is on only while a get_events client asks for rows. [lock] held. */ + private fun setRowCaptureLocked(on: Boolean) { + if (on == rowCapture) return + rowCapture = on + if (on) engine.setRowCapture(EVENT_ROWS_PER_STATEMENT, EVENT_VALUE_BYTES, EVENT_ROW_BYTES) else engine.setRowCapture(0, 0, 0) + } + /** * Stops recording bound values once [EVENTS_IDLE_MS] have passed since the last get_events call: * expanding every statement costs memory, and nobody is reading. Checked on every tool call and @@ -196,6 +242,7 @@ class DatabaseTools internal constructor( if (clientConnected && clock() - lastEventsCallMs >= EVENTS_IDLE_MS) { clientConnected = false engine.setClientConnected(false) + setRowCaptureLocked(false) } } @@ -249,7 +296,8 @@ class DatabaseTools internal constructor( tool( "query", "Run a query", - "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + + "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS), " + + "with each column's declared_type in column_types (null for an expression). $VALUES_NOTE " + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES: $CUT_CELLS_NOTE " + "A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + @@ -257,7 +305,7 @@ class DatabaseTools internal constructor( "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), + "args" to argsSchema(), "offset" to prop("integer", "Rows to skip. Default 0."), "max_rows" to prop("integer", "Rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), required = listOf("sql"), @@ -270,7 +318,7 @@ class DatabaseTools internal constructor( "A cell cut at $MAX_TEXT_BYTES bytes is listed as in query: $CUT_CELLS_NOTE $APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), - "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), + "args" to argsSchema(), required = listOf("sql"), ), ) { call, args -> explain(call, args) }, @@ -302,7 +350,25 @@ class DatabaseTools internal constructor( "as run to continue; dropped counts events that left the buffer unread. reset true means the app restarted " + "(run differs, or after is past the newest event), and events are read from the start. " + "The first call starts recording bound values into the SQL; " + - "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while watching.", + "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while " + + "watching. " + + "kind is statement (one starts; a trigger's SQL starts with --), profile (one finished: duration_nanos; rows, the " + + "rows it returned; changes, the rows it changed itself, not through triggers, null for a read; null when the " + + "statement's start was not seen), close, or row. execution_id names one run of a statement: a statement event's " + + "own seq, and on that run's profile and row events the same number, so rows of statements stepped in turn " + + "are told apart by it. It is null for close, a trigger's statements, a statement an app function runs inside a " + + "callback (its SQL also starts with --), an EXPLAIN's profile, and a statement whose start was not seen; a " + + "statement pushed out after more than 16 were stepped in turn keeps its id on its statement event, but its " + + "later profile and row events have null. A run can have more than one profile (a retry after a schema " + + "change, or a profile with rows 0 from a step that met a busy lock, before the run's rows), or none at its " + + "end. " + + "With include_rows true (the default), the app's statements " + + "after the call also record their first $EVENT_ROWS_PER_STATEMENT rows as row events: row_number (from 1), " + + "column_count, values, storage_classes and cut_values (indexes of TEXT and BLOB values cut at " + + "$EVENT_VALUE_BYTES bytes); a row's data stops at ${EVENT_ROW_BYTES / 1024} KiB, and then values holds fewer " + + "than column_count and truncated is true. A profile's rows_cut says rows went unrecorded past the limit. " + + "$VALUES_NOTE Recording rows costs the app a few microseconds a row, so pass include_rows false when you need " + + "only the SQL; it then stops, and row events are left out.", JSONObject() .put("type", "object") .put("additionalProperties", false) @@ -313,7 +379,7 @@ class DatabaseTools internal constructor( .put( "run", prop("string", "The run from the last call. If it differs from the current, the read starts from 0."), - ), + ).put("include_rows", prop("boolean", "Record and return rows the app's statements return. Default true.")), ).put("required", JSONArray()), ) { _, args -> getEvents(args) }, ) @@ -335,6 +401,16 @@ class DatabaseTools internal constructor( description: String, ) = JSONObject().put("type", type).put("description", description) + private fun argsSchema() = + JSONObject() + .put("type", JSONArray(listOf("array", "object"))) + .put( + "description", + "Values to bind: null, numbers or strings. An array binds by position (? and ?NNN, by number); an object binds " + + "by name (:name, @name, \$name, ?NNN), with keys written as in the SQL. A key without a prefix, such as id, " + + "matches :id, @id and \$id; a ?NNN key keeps its ?. Every parameter needs a value, and every key a parameter.", + ) + private fun databaseSchema( vararg extra: Pair, required: List = emptyList(), @@ -394,7 +470,7 @@ class DatabaseTools internal constructor( call, args, "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", - emptyList(), + Bind.NONE, 0, QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) @@ -456,7 +532,7 @@ class DatabaseTools internal constructor( val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) val path = checkedPath(call, args) - fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", emptyList(), 0, limits).rows.firstOrNull()?.firstOrNull() + fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", Bind.NONE, 0, limits).rows.firstOrNull()?.firstOrNull() val pageCount = pragma("page_count") as? Long val pageSize = pragma("page_size") as? Long val out = @@ -470,7 +546,7 @@ class DatabaseTools internal constructor( call, path, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", - emptyList(), + Bind.NONE, 0, limits, ).rows @@ -484,7 +560,7 @@ class DatabaseTools internal constructor( call, path, "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", - emptyList(), + Bind.NONE, 0, limits, ).rows.firstOrNull()?.firstOrNull() @@ -513,7 +589,7 @@ class DatabaseTools internal constructor( else -> throw McpToolError("full must be true or false.") } val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" - val result = run(call, args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) + val result = run(call, args, pragma, Bind.NONE, 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } return JSONObject() .put("check", if (full) "integrity_check" else "quick_check") @@ -531,9 +607,16 @@ class DatabaseTools internal constructor( is String -> v else -> throw McpToolError("run must be a string.") } + val includeRows = + when (val v = args.opt("include_rows")) { + null, JSONObject.NULL -> true + is Boolean -> v + else -> throw McpToolError("include_rows must be true or false.") + } val otherRun = run != null && run != engine.runId synchronized(lock) { lastEventsCallMs = clock() + setRowCaptureLocked(includeRows) if (!clientConnected) { engine.setClientConnected(true) clientConnected = true @@ -548,18 +631,8 @@ class DatabaseTools internal constructor( } val events = JSONArray() for (e in batch.events) { - events.put( - JSONObject() - .put("seq", encodeLong(e.seq)) - .put("kind", e.kind.name.lowercase()) - .put("connection_id", encodeLong(e.connectionId)) - .put("thread_id", encodeLong(e.threadId)) - .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) - .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) - .put("sql", e.sql) - .put("truncated", e.truncated) - .put("expanded", e.expanded), - ) + if (e.kind == EventKind.ROW && !includeRows) continue + events.put(encodeEvent(e)) } return JSONObject() .put("run", engine.runId) @@ -569,6 +642,44 @@ class DatabaseTools internal constructor( .put("events", events) } + private fun encodeEvent(e: Event): JSONObject { + val out = + JSONObject() + .put("seq", encodeLong(e.seq)) + .put("kind", e.kind.name.lowercase()) + .put("connection_id", encodeLong(e.connectionId)) + .put("execution_id", e.executionId?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("thread_id", encodeLong(e.threadId)) + .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) + .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("sql", e.sql) + .put("truncated", e.truncated) + .put("expanded", e.expanded) + when (e.kind) { + EventKind.PROFILE -> { + out + .put("rows", e.rows?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("changes", e.changes?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("rows_cut", e.rowsCut) + } + + EventKind.ROW -> { + val row = e.row + out.put("row_number", e.rows?.let { encodeLong(it) } ?: JSONObject.NULL) + if (row != null) { + out + .put("column_count", row.columnCount) + .put("values", JSONArray(row.values.mapIndexed { i, v -> encodeValue(v, i in row.cutIndexes) })) + .put("storage_classes", storageClasses(row.values)) + .put("cut_values", JSONArray(row.cutIndexes.sorted())) + } + } + + else -> {} + } + return out + } + private fun encodeResult( result: QueryResult, offset: Long, @@ -580,7 +691,9 @@ class DatabaseTools internal constructor( val out = JSONObject() .put("columns", JSONArray(result.columns)) + .put("column_types", JSONArray().also { a -> result.declaredTypes.forEach { a.put(it ?: JSONObject.NULL) } }) .put("rows", rows) + .put("storage_classes", JSONArray(result.rows.map { storageClasses(it) })) .put("row_count", result.rows.size) .put("offset", encodeLong(offset)) .put("has_more", result.hasMore) @@ -639,7 +752,7 @@ class DatabaseTools internal constructor( call: Call, args: JSONObject, sql: String, - bind: List, + bind: Bind, offset: Long, limits: QueryLimits, ): QueryResult = runChecked(call, checkedPath(call, args), sql, bind, offset, limits) @@ -648,7 +761,7 @@ class DatabaseTools internal constructor( call: Call, path: String, sql: String, - bind: List, + bind: Bind, offset: Long, limits: QueryLimits, ): QueryResult = @@ -666,7 +779,7 @@ class DatabaseTools internal constructor( if (ids.isEmpty()) throw unknownDatabase(path, knownPaths(live)) CachedConnection(engine.openServerConnection(path, writable = false), ids) }.connection - conn.query(sql, bind, offset, limits, call.deadline) + conn.query(sql, bind.values, bind.names, offset, limits, call.deadline) } catch (e: DebugEngineException) { val error = engineError(e) // The time limit counts the call's waits for the lock, so a quick query can run out of time @@ -734,18 +847,51 @@ class DatabaseTools internal constructor( return l } - private fun bindArgs(args: JSONObject): List { - val raw = args.opt("args") - if (raw == null || raw == JSONObject.NULL) return emptyList() - val arr = raw as? JSONArray ?: throw McpToolError("args must be an array.") - return (0 until arr.length()).map { i -> - when (val v = arr.opt(i)) { + /** Values to bind: by position when [names] is null, else `names[i]` names the parameter of `values[i]`. */ + private class Bind( + val values: List, + val names: List?, + ) { + companion object { + val NONE = Bind(emptyList(), null) + } + } + + private fun bindArgs(args: JSONObject): Bind { + fun value( + v: Any?, + what: String, + ): Any? = + when (v) { null, JSONObject.NULL -> null is Int, is Long, is Short -> (v as Number).toLong() is Number -> v.toDouble() is String -> v is Boolean -> if (v) 1L else 0L - else -> throw McpToolError("args[$i] must be null, a number or a string.") + else -> throw McpToolError("$what must be null, a number or a string.") + } + return when (val raw = args.opt("args")) { + null, JSONObject.NULL -> { + Bind.NONE + } + + is JSONArray -> { + Bind((0 until raw.length()).map { i -> value(raw.opt(i), "args[$i]") }, null) + } + + is JSONObject -> { + val names = + raw + .keys() + .asSequence() + .sorted() + .toList() + names.forEach { if (it.isEmpty()) throw McpToolError("args has an empty name.") } + Bind(names.map { value(raw.opt(it), "args.$it") }, names) + } + + else -> { + throw McpToolError("args must be an array or an object.") } } } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 19ef46f335..ed583dad90 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 @@ -29,6 +29,13 @@ class FakeDebugEngine( var clientConnected = false private set + /** Each setRowCapture call, in order: rows per statement, value bytes, row bytes. */ + val rowCaptureCalls = mutableListOf>() + + /** The argNames of the last query: null when its args were bound by position. */ + var lastArgNames: List? = null + private set + val openedServerConnections = mutableListOf>() /** How many times the server asked to open one, counted before any refusal: [openedServerConnections] holds only successes. */ @@ -52,6 +59,12 @@ class FakeDebugEngine( ) } + /** Adds the event [make] builds for the next number, for the kinds and fields [addEvent] does not set. */ + fun addEvent(make: (seq: Long) -> Event) { + lastSeq++ + buffered.addLast(make(lastSeq)) + } + /** Adds [event] as the next one, numbered after the events before it whatever its own [Event.seq]. */ fun addEvent(event: Event) { lastSeq++ @@ -105,6 +118,14 @@ class FakeDebugEngine( clientConnected = connected } + override fun setRowCapture( + maxRowsPerStatement: Int, + maxValueBytes: Int, + maxRowBytes: Int, + ) { + rowCaptureCalls += Triple(maxRowsPerStatement, maxValueBytes, maxRowBytes) + } + override fun openServerConnection( path: String, writable: Boolean, @@ -123,11 +144,13 @@ class FakeDebugEngine( override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, ): QueryResult { check(!closed) { "closed" } + lastArgNames = argNames val all = answer(path, writable, sql, args) val skip = offset.toInt().coerceAtMost(all.rows.size) val rest = all.rows.drop(skip) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index c804bb99c1..efc469d9ca 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -3,10 +3,13 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.Event +import org.appdevforall.sqlitedebugger.engine.EventDecoder import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.appdevforall.sqlitedebugger.engine.RowValues import org.appdevforall.sqlitedebugger.engine.ServerConnection import org.json.JSONArray import org.json.JSONObject @@ -359,6 +362,8 @@ class DatabaseToolsTest { bad("sql" to "x", "max_rows" to 1.5) bad("sql" to "x", "args" to "nope") bad("sql" to "x", "args" to JSONArray().put(JSONObject())) + bad("sql" to "x", "args" to JSONObject().put("a", JSONArray())) + bad("sql" to "x", "args" to JSONObject().put("", 1)) assertTrue(engine.openedServerConnections.isEmpty()) assertEquals(0, engine.openAttempts) } @@ -383,6 +388,7 @@ class DatabaseToolsTest { ), ) assertEquals(listOf(null, 3L, 2.5, "s", 1L), got) + assertEquals("an array binds by position", null, engine.lastArgNames) } @Test fun queryErrorsCarryTheSqliteCode() { @@ -409,12 +415,13 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: org.appdevforall.sqlitedebugger.engine.QueryLimits, deadlineMillis: Long, ): QueryResult { deadline = deadlineMillis - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -434,6 +441,7 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -444,7 +452,7 @@ class DatabaseToolsTest { "the time limit passed before the query started", ) } - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -514,6 +522,7 @@ class DatabaseToolsTest { override fun query( sql: String, args: List, + argNames: List?, offset: Long, limits: QueryLimits, deadlineMillis: Long, @@ -527,7 +536,7 @@ class DatabaseToolsTest { throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the query ran past its time limit") } now += runMs - return c.query(sql, args, offset, limits, deadlineMillis) + return c.query(sql, args, argNames, offset, limits, deadlineMillis) } } } @@ -672,7 +681,7 @@ class DatabaseToolsTest { assertEquals("-9007199254740993", row.get(4)) assertEquals(9_007_199_254_740_992L, row.getLong(5)) val blob = row.getJSONObject(6) - assertEquals("AQID", blob.getString("base64")) + assertEquals("010203", blob.getString("hex")) assertEquals(3, blob.getInt("bytes")) assertFalse(blob.getBoolean("truncated")) assertTrue(row.isNull(7)) @@ -1086,6 +1095,233 @@ class DatabaseToolsTest { t.onServerStopped() } + @Test fun queryBindsAnObjectByName() { + engine.appConnections += conn(1, "/data/a.db") + var got: List = emptyList() + engine.answer = { _, _, _, a -> + got = a + QueryResult(emptyList(), emptyList(), 0, false) + } + ok( + "query", + db().put("sql", "x").put( + "args", + JSONObject() + .put(":b", "s") + .put("a", 1) + .put("\$c", JSONObject.NULL) + .put("?2", 2.5), + ), + ) + val byName = engine.lastArgNames!!.zip(got).toMap() + assertEquals(mapOf("a" to 1L, ":b" to "s", "\$c" to null, "?2" to 2.5), byName) + ok("explain_query_plan", db().put("sql", "x").put("args", JSONObject().put("id", 7))) + assertEquals(listOf("id"), engine.lastArgNames) + assertEquals(listOf(7L), got) + ok("query", db().put("sql", "x").put("args", JSONObject())) + assertEquals("an empty object still binds by name: a parameter left out is an error", emptyList(), engine.lastArgNames) + ok("query", db().put("sql", "x")) + assertEquals("no args", null, engine.lastArgNames) + } + + @Test fun queryDescribesBothArgForms() { + val query = tools.tools().single { it.name == "query" } + val args = query.inputSchema.getJSONObject("properties").getJSONObject("args") + assertEquals(listOf("array", "object"), args.getJSONArray("type").let { a -> (0 until a.length()).map { a.getString(it) } }) + for (form in listOf(":name", "@name", "\$name", "?NNN")) assertTrue(form, args.getString("description").contains(form)) + } + + @Test fun queryReturnsDeclaredTypesAndStorageClasses() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> + QueryResult( + listOf("id", "r", "s", "b", "e"), + listOf(listOf(1L, 2.0, "x", byteArrayOf(0x0f, -1), null), listOf("t", null, 3L, 1.5, byteArrayOf())), + 0, + false, + declaredTypes = listOf("INTEGER", "REAL", "TEXT", "BLOB", null), + ) + } + val r = ok("query", db().put("sql", "x")) + val types = r.getJSONArray("column_types") + val declared = (0 until types.length()).map { if (types.isNull(it)) null else types.get(it) } + assertEquals(listOf("INTEGER", "REAL", "TEXT", "BLOB", null), declared) + val classes = r.getJSONArray("storage_classes").let { a -> (0 until a.length()).map { a.getString(it) } } + assertEquals(listOf("irtbn", "tnirb"), classes) + assertTrue( + "a REAL 2.0 reads as 2 in JSON, so only the storage class tells it from an INTEGER", + r.toString().contains("[1,2,\"x\""), + ) + assertEquals( + "0fff", + r + .getJSONArray("rows") + .getJSONArray(0) + .getJSONObject(3) + .getString("hex"), + ) + assertTrue(r.getJSONArray("rows").getJSONArray(0).isNull(4)) + val description = tools.tools().single { it.name == "query" }.description + assertTrue(description.contains("storage_classes") && description.contains("column_types") && description.contains("hex")) + } + + @Test fun queryResultWithoutDeclaredTypesGivesNullForEachColumn() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> QueryResult(listOf("a", "b"), listOf(listOf(1L, 2L)), 0, false) } + val types = ok("query", db().put("sql", "x")).getJSONArray("column_types") + assertEquals(2, types.length()) + assertTrue(types.isNull(0) && types.isNull(1)) + } + + private fun rowEvent( + seq: Long, + number: Long, + values: List, + cut: Set = emptySet(), + columns: Int = values.size, + ) = Event(seq, EventKind.ROW, 1, 1, seq, null, "", values.size < columns, true, rows = number, row = RowValues(columns, values, cut)) + + @Test fun getEventsReturnsRowsAndChangeCounts() { + engine.addEvent(EventKind.STATEMENT, "SELECT id, b FROM t") + engine.addEvent { rowEvent(it, 1, listOf(1L, byteArrayOf(1, 2)), cut = setOf(1)) } + engine.addEvent { rowEvent(it, 2, listOf("x"), columns = 2) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "SELECT id, b FROM t", false, true, rows = 12, rowsCut = true) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "DELETE FROM t", false, true, rows = 0, changes = 3) } + engine.addEvent { Event(it, EventKind.PROFILE, 1, 1, it, 5, "SELECT 1", false, true) } + val events = ok("get_events").getJSONArray("events") + assertEquals(6, events.length()) + val row1 = events.getJSONObject(1) + assertEquals("row", row1.getString("kind")) + assertEquals(1, row1.getInt("row_number")) + assertEquals(2, row1.getInt("column_count")) + assertEquals(1L, row1.getJSONArray("values").getLong(0)) + assertEquals("0102", row1.getJSONArray("values").getJSONObject(1).getString("hex")) + assertTrue(row1.getJSONArray("values").getJSONObject(1).getBoolean("truncated")) + assertEquals("ib", row1.getString("storage_classes")) + assertEquals(1, row1.getJSONArray("cut_values").getInt(0)) + assertFalse(row1.getBoolean("truncated")) + val row2 = events.getJSONObject(2) + assertEquals("a row whose data reached its limit keeps fewer values", 1, row2.getJSONArray("values").length()) + assertEquals(2, row2.getInt("column_count")) + assertTrue(row2.getBoolean("truncated")) + val select = events.getJSONObject(3) + assertEquals(12, select.getInt("rows")) + assertTrue("a read has no change count", select.isNull("changes")) + assertTrue(select.getBoolean("rows_cut")) + val delete = events.getJSONObject(4) + assertEquals(3, delete.getInt("changes")) + assertEquals(0, delete.getInt("rows")) + assertFalse(delete.getBoolean("rows_cut")) + val unseen = events.getJSONObject(5) + assertTrue("a statement whose start was not seen", unseen.isNull("rows") && unseen.isNull("changes")) + val statement = events.getJSONObject(0) + assertFalse("only a profile carries counts", statement.has("rows") || statement.has("changes") || statement.has("values")) + } + + @Test fun getEventsTurnsRowRecordingOnUnlessToldNotTo() { + val t = tools + ok("get_events", t = t) + assertEquals( + listOf(Triple(DatabaseTools.EVENT_ROWS_PER_STATEMENT, DatabaseTools.EVENT_VALUE_BYTES, DatabaseTools.EVENT_ROW_BYTES)), + engine.rowCaptureCalls, + ) + ok("get_events", t = t) + assertEquals("already on: no second call", 1, engine.rowCaptureCalls.size) + engine.addEvent(EventKind.STATEMENT, "SELECT 1") + engine.addEvent { rowEvent(it, 1, listOf(1L)) } + val r = ok("get_events", JSONObject().put("include_rows", false), t) + assertEquals(Triple(0, 0, 0), engine.rowCaptureCalls.last()) + assertEquals("row events are left out", listOf("statement"), kinds(r)) + assertEquals("the cursor still passes them", 2, r.getInt("next")) + ok("get_events", JSONObject().put("include_rows", true), t) + assertEquals(DatabaseTools.EVENT_ROWS_PER_STATEMENT, engine.rowCaptureCalls.last().first) + t.onServerStopped() + assertEquals("the server stopping turns it off", Triple(0, 0, 0), engine.rowCaptureCalls.last()) + assertTrue(runTool(tools, "get_events", JSONObject().put("include_rows", "yes")).getBoolean("isError")) + } + + @Test fun rowRecordingStopsWithTheIdleClient() { + val t = tools + ok("get_events", t = t) + now += DatabaseTools.EVENTS_IDLE_MS + t.expireIdleClient() + assertFalse(engine.clientConnected) + assertEquals(Triple(0, 0, 0), engine.rowCaptureCalls.last()) + ok("get_events", t = t) + assertEquals("the next get_events turns it on again", DatabaseTools.EVENT_ROWS_PER_STATEMENT, engine.rowCaptureCalls.last().first) + t.onServerStopped() + } + + @Test fun getEventsDescribesWhatIsCapped() { + val description = tools.tools().single { it.name == "get_events" }.description + for (text in listOf( + "first ${DatabaseTools.EVENT_ROWS_PER_STATEMENT} rows", + "${DatabaseTools.EVENT_VALUE_BYTES} bytes", + "${DatabaseTools.EVENT_ROW_BYTES / 1024} KiB", + "include_rows false", + "changes", + )) { + assertTrue(text, description.contains(text)) + } + } + + @Test fun getEventsEncodesTheEventsDecodedFromTheFixture() { + val bytes = checkNotNull(EventDecoder::class.java.getResourceAsStream("events.bin")).use { it.readBytes() } + val decoded = EventDecoder.decode(bytes, bytes.size) + assertTrue("the fixture has row events", decoded.any { it.kind == EventKind.ROW }) + assertTrue("and execution ids", decoded.any { it.kind == EventKind.ROW && it.executionId != null }) + assertTrue("and a change count", decoded.any { it.changes != null }) + decoded.forEach { e -> engine.addEvent { e.copy(seq = it) } } + val events = ok("get_events").getJSONArray("events") + assertEquals(decoded.size, events.length()) + decoded.forEachIndexed { i, e -> + val json = events.getJSONObject(i) + assertEquals(e.kind.name.lowercase(), json.getString("kind")) + assertTrue("execution_id is always present", json.has("execution_id")) + assertEquals(e.executionId, if (json.isNull("execution_id")) null else json.getLong("execution_id")) + when (e.kind) { + EventKind.ROW -> { + val row = e.row!! + assertEquals(row.columnCount, json.getInt("column_count")) + assertEquals(DatabaseTools.storageClasses(row.values), json.getString("storage_classes")) + val values = json.getJSONArray("values") + assertEquals(row.values.size, values.length()) + row.values.forEachIndexed { c, v -> + val got = values.get(c) + when (v) { + null -> assertTrue(values.isNull(c)) + is ByteArray -> assertEquals(DatabaseTools.hex(v), values.getJSONObject(c).getString("hex")) + is Double -> assertEquals(DatabaseTools.encodeValue(v), (got as? Number)?.toDouble() ?: got) + else -> assertEquals(DatabaseTools.encodeValue(v), if (got is Int) got.toLong() else got) + } + } + val cut = json.getJSONArray("cut_values") + assertEquals(row.cutIndexes.sorted(), (0 until cut.length()).map { cut.getInt(it) }) + } + + EventKind.PROFILE -> { + assertEquals(e.rows, if (json.isNull("rows")) null else json.getLong("rows")) + assertEquals(e.changes, if (json.isNull("changes")) null else json.getLong("changes")) + assertEquals(e.rowsCut, json.getBoolean("rows_cut")) + } + + else -> { + assertEquals(e.sql, json.getString("sql")) + } + } + } + } + + @Test fun hexIsLowercaseAndCoversEveryByte() { + assertEquals("00017f80ff", DatabaseTools.hex(byteArrayOf(0, 1, 127, -128, -1))) + assertEquals("", DatabaseTools.hex(ByteArray(0))) + } + + private fun kinds(r: JSONObject): List { + val events = r.getJSONArray("events") + return (0 until events.length()).map { events.getJSONObject(it).getString("kind") } + } + private class FakeIdleScheduler : IdleScheduler { class Check( val task: Runnable, diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 5e47180211..5fe064fcf2 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -44,12 +44,25 @@ static class Result { long truncated; boolean hasMore; Set cut = new HashSet<>(); + String[] declaredTypes; } @SuppressWarnings("unchecked") static Result query(long h, String sql, Object[] args, long offset, int maxRows, int maxText, int maxBlob, int maxTotal, long deadline) throws DebugEngineException { - Object[] r = NativeBridge.query(h, sql, args, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + return named(h, sql, args, null, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + } + + /** As query, with args bound by name when names is not null. */ + @SuppressWarnings("unchecked") + static Result named(long h, String sql, Object[] args, String[] names, long offset, int maxRows, int maxText, int maxBlob, + int maxTotal, long deadline) throws DebugEngineException { + byte[][] nameBytes = null; + if (names != null) { + nameBytes = new byte[names.length][]; + for (int i = 0; i < names.length; i++) nameBytes[i] = names[i].getBytes(StandardCharsets.UTF_8); + } + Object[] r = NativeBridge.query(h, sql, args, nameBytes, offset, maxRows, maxText, maxBlob, maxTotal, deadline); Result out = new Result(); out.columns = (String[]) r[0]; out.rows = (List) r[1]; @@ -58,6 +71,8 @@ static Result query(long h, String sql, Object[] args, long offset, int maxRows, out.hasMore = counts[1] != 0; eq(counts.length, 2 + (int) counts[0], "one index per cut cell"); for (int i = 2; i < counts.length; i++) out.cut.add(counts[i]); + out.declaredTypes = (String[]) r[3]; + eq(out.declaredTypes.length, out.columns.length, "one declared type per column"); return out; } @@ -74,6 +89,59 @@ static int codeOf(long h, String sql, Object[] args, long deadline) { } } + /** The row events (kind 4) in the buffer, read from the start; the records' layout is in sqlitedbg.h. */ + static long rowEvents() { + byte[] buf = new byte[1 << 20]; + long[] out = new long[4]; + NativeBridge.readEvents(0, buf, out); + java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + long rows = 0; + for (int at = 0; at < out[2]; at += b.getInt(at)) { + if (b.getInt(at + 4) == 4) rows++; + } + return rows; + } + + /** + * ADFA-7379: whether the newest row event names a statement event in the buffer by its execution_id (offset 72), + * which is that statement event's seq (offset 8). + */ + /** + * The SQL of the STATEMENT event the newest ROW event names by execution_id, or null. The named event must be the + * newest STATEMENT before that row, and its seq must equal the id. + */ + static String newestRowStatementSql() { + byte[] buf = new byte[1 << 20]; + long[] out = new long[4]; + NativeBridge.readEvents(0, buf, out); + java.nio.ByteBuffer b = java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + long lastSeq = 0, rowExec = 0, rowStatementSeq = 0; + String lastSql = null, rowStatementSql = null; + for (int at = 0; at < out[2]; at += b.getInt(at)) { + int kind = b.getInt(at + 4); + if (kind == 1) { + lastSeq = b.getLong(at + 8); + lastSql = new String(buf, at + 80, b.getInt(at + 52), StandardCharsets.UTF_8); + } + if (kind == 4) { + rowExec = b.getLong(at + 72); + rowStatementSeq = lastSeq; + rowStatementSql = lastSql; + } + } + return rowExec != 0 && rowExec == rowStatementSeq ? rowStatementSql : null; + } + + /** "code message" of a refused query with args bound by name, or null when it ran. */ + static String namedRefusal(long h, String sql, Object[] args, String[] names) { + try { + named(h, sql, args, names, 0, 100, 4096, 1024, MAX, FAR); + return null; + } catch (DebugEngineException e) { + return e.sqliteCode + " " + e.getMessage(); + } + } + /** "code message" of the refusal, or null when the query ran. */ static String refusal(long h, String sql) { try { @@ -195,6 +263,20 @@ public static void main(String[] a) throws Exception { eq(((String[]) conns[1]).length, 1, "one app connection"); eq(((String[]) conns[1])[0], path, "its path"); + // setRowCapture reaches the extension: rows are recorded only while it is on (and a client is connected) + NativeBridge.setClientConnected(true); + long rowsBefore = rowEvents(); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off"); + eq(rowEvents(), rowsBefore, "no row events while row recording is off"); + NativeBridge.setRowCapture(1, 0, 0); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording on"); + eq(rowEvents(), rowsBefore + 1, "one row event: one row per statement"); + eq(newestRowStatementSql(), "SELECT id FROM t WHERE id < 3", "the row event names its own statement event (ADFA-7379)"); + NativeBridge.setRowCapture(0, 0, 0); + eq(Helper.exec(app, "SELECT id FROM t WHERE id < 3"), 0, "read with row recording off again"); + eq(rowEvents(), rowsBefore + 1, "off again"); + NativeBridge.setClientConnected(false); + byte[] bytes = path.getBytes(StandardCharsets.UTF_8); long srv = NativeBridge.openServer(bytes, false); check(srv != 0, "server handle"); @@ -297,6 +379,39 @@ public static void main(String[] a) throws Exception { } eq(codeOf(srv, "SELECT ?", new Object[] {1L, 2L}, FAR), 25, "too many args: SQLITE_RANGE"); eq(codeOf(srv, "SELECT ?", new Object[] {new Object()}, FAR), 21, "unsupported arg type: SQLITE_MISUSE"); + r = query(srv, "SELECT ?2, ?1", new Object[] {"one", "two"}, 0, 10, 4096, 1024, MAX, FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("two", "one"), "?NNN in an array binds by number"); + + // by name: each prefix, written with it or bare + r = named(srv, "SELECT :a, @b, $c, :a", new Object[] {1L, "x", null}, new String[] {":a", "b", "$c"}, 0, 10, 4096, 1024, MAX, + FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList(1L, "x", null, 1L), "named: :a, @b, $c, and :a again"); + r = named(srv, "SELECT ?2, ?1", new Object[] {"one", "two"}, new String[] {"?1", "?2"}, 0, 10, 4096, 1024, MAX, FAR); + eq(Arrays.asList(r.rows.get(0)), Arrays.asList("two", "one"), "named: ?NNN by its own name"); + r = named(srv, "SELECT :€", new Object[] {9L}, new String[] {"€"}, 0, 10, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 9L, "named: a non-ASCII name"); + r = named(srv, "SELECT 1", new Object[0], new String[0], 0, 10, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 1L, "named: no parameters, no names"); + eq(namedRefusal(srv, "SELECT :a, :b", new Object[] {1L}, new String[] {"a"}), "25 no value was given for parameter :b", + "named: a parameter left out"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L, 2L}, new String[] {"a", "zz"}), + "25 the statement has no parameter named zz", "named: a misspelt name"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L, 2L}, new String[] {"a", ":a"}), "25 parameter :a is given more than once", + "named: bare and prefixed"); + eq(namedRefusal(srv, "SELECT :a, ?", new Object[] {1L}, new String[] {"a"}), + "25 parameter 2 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: an anonymous ?"); + eq(namedRefusal(srv, "SELECT ?2", new Object[] {1L}, new String[] {"?2"}), + "25 parameter 1 has no name (a ? or a gap in the ?NNN numbers): pass args as an array instead", "named: a gap in ?NNN"); + eq(namedRefusal(srv, "SELECT :a", new Object[] {1L}, new String[] {":b"}), + "25 the statement has no parameter named :b, and no value was given for parameter :a", + "named: a prefixed key matches only that prefix"); + eq(namedRefusal(srv, "SELECT id FROM t WHERE id = :id", new Object[] {1L}, new String[] {"idx"}), + "25 the statement has no parameter named idx, and no value was given for parameter :id", + "named: a misspelt key is named although a parameter also has no value"); + + // declared types: the column's, or null for an expression + r = q(srv, "SELECT id, r, s, b, id + 1, NULL FROM t LIMIT 1"); + eq(Arrays.asList(r.declaredTypes), Arrays.asList("INTEGER", "REAL", "TEXT", "BLOB", null, null), "declared types"); eq(codeOf(srv, "SELEKT 1", new Object[0], FAR), 1, "syntax error: SQLITE_ERROR"); // one statement per call: SQLite compiles only the first, so a second is refused, not dropped diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index bc4ee25852..7e3e3dcd42 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -16,9 +16,11 @@ private NativeBridge() {} public static native void setClientConnected(boolean connected); + public static native void setRowCapture(int maxRowsPerStatement, int maxValueBytes, int maxRowBytes); + public static native long openServer(byte[] path, boolean writable) throws DebugEngineException; - public static native Object[] query(long handle, String sql, Object[] args, long offset, int maxRows, int maxTextBytes, + public static native Object[] query(long handle, String sql, Object[] args, byte[][] names, long offset, int maxRows, int maxTextBytes, int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException;