diff --git a/common/src/main/java/com/itsaky/androidide/templates/ProjectTemplatePebble.kt b/common/src/main/java/com/itsaky/androidide/templates/ProjectTemplatePebble.kt new file mode 100644 index 0000000000..80bf0c5e87 --- /dev/null +++ b/common/src/main/java/com/itsaky/androidide/templates/ProjectTemplatePebble.kt @@ -0,0 +1,37 @@ +package com.itsaky.androidide.templates + +import io.pebbletemplates.pebble.PebbleEngine +import io.pebbletemplates.pebble.lexer.Syntax +import io.pebbletemplates.pebble.loader.StringLoader + +/** + * The Pebble settings of Code on the Go's project templates, shared with the SQL templates the SQLite debugger's + * `.read` renders (ADFA-7302), so both read a template the same way. + */ +object ProjectTemplatePebble { + const val PRINT_OPEN = "\${{" + const val PRINT_CLOSE = "}}" + const val EXECUTE_OPEN = "\${%" + const val EXECUTE_CLOSE = "%}" + const val COMMENT_OPEN = "\${#" + const val COMMENT_CLOSE = "#}" + + fun syntax(): Syntax = + Syntax + .Builder() + .setPrintOpenDelimiter(PRINT_OPEN) + .setPrintCloseDelimiter(PRINT_CLOSE) + .setExecuteOpenDelimiter(EXECUTE_OPEN) + .setExecuteCloseDelimiter(EXECUTE_CLOSE) + .setCommentOpenDelimiter(COMMENT_OPEN) + .setCommentCloseDelimiter(COMMENT_CLOSE) + .build() + + /** A template is its own text ([StringLoader]), an unknown variable is an error, and newline trimming is Pebble's default (on). */ + fun engineBuilder(): PebbleEngine.Builder = + PebbleEngine + .Builder() + .loader(StringLoader()) + .strictVariables(true) + .syntax(syntax()) +} diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 22e515e2d9..ad079f3e26 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -36,6 +36,28 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). ### 26.48 — unreleased +- **added — Render the project's SQL templates for the SQLite debugger** _(ADFA-7302)_ **[verified]** + `SqlTemplateService.render(templatePath, variables, functions, timeoutMillis)` renders a Pebble template of the open + project (a path relative to its root, ending in `.peb`, inside it once links are resolved) and returns the SQL, at + most 4 Mi characters. It uses the engine and settings of Code on the Go's project templates: the `${{ }}`, `${% %}` + and `${# #}` delimiters, strict variables and Pebble's newline trimming. One difference: autoescaping is off. Two + filters quote what a template splices in: `sql_ident` (`"..."`) and `sql_literal` (`'...'`, a number as is but a + negative one in parentheses, a boolean as 1 or 0, null as `NULL`). Every render gets `project` (`name`, `path`) and + `render_time` (ISO 8601, UTC); a caller may not pass those names. A variable may be a `java.util.function.Supplier`, + read the first time the template uses it and never when it does not, and a `SqlTemplateFunction` runs each time the + template calls it, with its arguments in order (a named argument fails the render). The render runs on a thread of its + own under one time limit (at most `MAX_TIMEOUT_MILLIS`, 120 s); when it passes, the thread is interrupted (a function + that ignores that keeps running). A function that fails, or a template error, throws the checked + `SqlTemplateException` with a message to show as it is. Pebble's `range` is limited to 100,000 values here (more fails + the render), so is a string a template builds past 4 MiB (4,194,304 characters) or a list or map past 1,000,000 + entries (the render fails, naming the operation and the limit). That does not make a render safe: chaining filters in one + expression (such as `base64encode` or `urlencode` repeated many times on a long string) or nesting a list in itself + and printing or joining it can still run the app out of memory, so render only templates you trust. A `for` loop, a macro and an include end when the render is stopped. `listTemplates()` lists the + project's `*.sql.peb` files, and `getRoomSchemas()` the schemas Room exported (`RoomSchema`: class name from the + folder, version, identity hash, path, entities and views with Room's JSON keys, `indices`, `foreignKeys` and `views` + present even where Room left them out). Both skip build output and hidden folders. Every call needs + `debugger.endpoints` and throws `SecurityException` without it, and `IllegalStateException` on the main thread. Both + lists stop at 2,000 entries (the first in their order). Floor `plugin.min_ide_version` at `26.48`. - **added — Show the IDE's own documentation from a plugin** _(ADFA-7134)_ `IdeTooltipService.showTooltip(anchorView, category, tag)` now reads the IDE's documentation when `category` is `ide`, `java`, `kotlin` or `xml`, for example diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index 2160356e70..d577dedc3f 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -343,7 +343,7 @@ Defined by `PluginPermission` in `plugin-api/src/main/kotlin/com/itsaky/androidi | `project.structure` | Modify project structure | | `native.code` | Execute native machine code | | `ide.environment.write` | Write to IDE-managed directories (Android SDK, NDK, cache) | -| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers, and so query the apps' databases (read-only for now) | +| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers, and so query the apps' databases (read-only for now); render the project's SQL templates (`SqlTemplateService`) | Plugins run in Code on the Go's process. A permission declares what a plugin means to do, and the services check it on every call, but it cannot stop a plugin that reaches into the host by diff --git a/docs/plugin-api.md b/docs/plugin-api.md index 40e729aebf..49f2c8f2e7 100644 --- a/docs/plugin-api.md +++ b/docs/plugin-api.md @@ -11,7 +11,7 @@ The surface a plugin binds to is broader than one module. All of the following a - **The `:plugin-api` module** — package `com.itsaky.androidide.plugins.*`: - Core: `IPlugin` (lifecycle), `PluginContext`, `PluginLogger`, `ServiceRegistry`, `ResourceManager`. - Extension interfaces plugins **implement**: `UIExtension`, `EditorExtension`, `EditorTabExtension`, `DocumentationExtension`, `BuildActionExtension`, `SnippetExtension`, `ProjectExtension`, `FileOpenExtension`, `SettingsExtension`, `LanguageExtension`. - - IDE service interfaces plugins **call** (via `ServiceRegistry.get(X::class.java)`): `IdeProjectService`, `IdeEditorService`, `IdeFileService`, `IdeEnvironmentService`, `IdeArchiveService`, `IdeBuildService`, `IdeLogService`, `IdeUIService`, `IdeEditorTabService`, `IdeTooltipService`, `IdeThemeService`, `IdeFeatureFlagService` (the overall experiments switch only - see [EXPERIMENTS.md](../EXPERIMENTS.md#plugins)), `IdeCommandService`, `IdeTerminalService`, `IdeTemplateService`, `IdeSnippetService`, `IdeSidebarService`, `DebuggerEndpointService` (with `DebuggerEndpoint`, the value type it returns: one app's SQLite debugger port and token). + - IDE service interfaces plugins **call** (via `ServiceRegistry.get(X::class.java)`): `IdeProjectService`, `IdeEditorService`, `IdeFileService`, `IdeEnvironmentService`, `IdeArchiveService`, `IdeBuildService`, `IdeLogService`, `IdeUIService`, `IdeEditorTabService`, `IdeTooltipService`, `IdeThemeService`, `IdeFeatureFlagService` (the overall experiments switch only - see [EXPERIMENTS.md](../EXPERIMENTS.md#plugins)), `IdeCommandService`, `IdeTerminalService`, `IdeTemplateService`, `IdeSnippetService`, `IdeSidebarService`, `DebuggerEndpointService` (with `DebuggerEndpoint`, the value type it returns: one app's SQLite debugger port and token), `SqlTemplateService` (with `SqlTemplateFunction`, `SqlTemplateException` and `RoomSchema`: renders the project's SQL templates for the SQLite debugger's `.read`). - Cross-plugin service interfaces, where **one plugin implements what another calls** (via `SharedServices`): `LlmInferenceService` — implemented by ai-core, called by every AI plugin — together with the types nested in it that a *backend* plugin implements (`LlmBackend`, `HistoryCapableBackend`, `ToolCallingBackend`, `CancellableBackend`, `ConfigurableBackend`, `EmbeddingBackend`) and the value types either side constructs (`ChatMessage`, `LlmConfig`, `LlmResponse`, `SystemPromptRequest`, `ToolDefinition`, `ToolCallRequest`). Also `ToolSourceRegistry` — implemented by ai-core, called by any plugin contributing tools to the agent — with `ToolSource` and `ToolSpec`, which a *contributing* plugin implements, `ToolInvocation`, which ai-core constructs and passes to `ToolSource.invoke`, and `ToolOutcome`, which the source returns. - Utility classes plugins **instantiate**: `KeystoreSecretStore` (AES/GCM over the Android Keystore, alias supplied by the caller); the AI prompt config engine in `ai.prompt` (`PromptTemplateEngine`, `PromptConfigLoader`, `PromptConfigStore`, `PromptConfigDocument`, `PromptConfigObject`, `AssetPromptConfigSource`), generic over a plugin's own config type through `PromptConfigParser` and `PromptConfigProvider`, which a plugin implements; and the settings-pane helpers in `ai.ui` (`SecretRevealController` with `RevealToggle`, `applyPaneStyling` with `PaneStyle`, `ButtonColors` and `FieldColors`). Host-side implementations rather than interfaces, so plugins share one copy in the process instead of compiling their own. - Data classes plugins **construct** (e.g. `MenuItem`, `TabItem`, `EditorTabItem`, `NavigationItem`, `ToolbarAction`, `FabAction`, `PluginBuildAction`, `SnippetContribution`, `PluginTooltipEntry`, `PluginSettingsEntry`, `LanguageDefinition`, `TreeSitterGrammar`, `LanguageServerDefinition`). diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index 011c7d8ee4..39ba81ef49 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -2421,6 +2421,19 @@ public final class com/itsaky/androidide/plugins/services/QuickBuildUnavailableR public static fun values ()[Lcom/itsaky/androidide/plugins/services/QuickBuildUnavailableReason; } +public final class com/itsaky/androidide/plugins/services/RoomSchema { + public fun (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/util/List;)V + public fun equals (Ljava/lang/Object;)Z + public fun getClassName ()Ljava/lang/String; + public fun getEntities ()Ljava/util/List; + public fun getIdentityHash ()Ljava/lang/String; + public fun getPath ()Ljava/lang/String; + public fun getVersion ()I + public fun getViews ()Ljava/util/List; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class com/itsaky/androidide/plugins/services/SelectionRange { public fun (IIII)V public final fun component1 ()I @@ -2446,6 +2459,22 @@ public final class com/itsaky/androidide/plugins/services/SharedServices { public final fun unregister (Ljava/lang/Class;)V } +public class com/itsaky/androidide/plugins/services/SqlTemplateException : java/lang/Exception { + public fun (Ljava/lang/String;Ljava/lang/Throwable;)V +} + +public abstract interface class com/itsaky/androidide/plugins/services/SqlTemplateFunction { + public abstract fun call (Ljava/util/List;)Ljava/lang/Object; +} + +public abstract interface class com/itsaky/androidide/plugins/services/SqlTemplateService { + public static final field CONTRACT_VERSION I + public static final field MAX_TIMEOUT_MILLIS J + public abstract fun getRoomSchemas ()Ljava/util/List; + public abstract fun listTemplates ()Ljava/util/List; + public abstract fun render (Ljava/lang/String;Ljava/util/Map;Ljava/util/Map;J)Ljava/lang/String; +} + public abstract class com/itsaky/androidide/plugins/services/TerminalCommandResult { } diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/RoomSchema.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/RoomSchema.java new file mode 100644 index 0000000000..21d504fd9d --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/RoomSchema.java @@ -0,0 +1,129 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * One schema file Room exported into the open project ({@code exportSchema} on): {@code //.json}. Immutable. + * + *

+ * The entities and views keep Room's own JSON keys, so a template reads them as Room writes them: an entity has {@code tableName}, {@code createSql} (with {@code ${TABLE_NAME}} for the table name), {@code fields} (each with {@code fieldPath}, {@code columnName}, {@code affinity}, {@code notNull}), {@code primaryKey} ({@code autoGenerate}, {@code columnNames}), {@code indices} and {@code foreignKeys}; a view has {@code viewName} and {@code createSql}. Room leaves out {@code indices}, {@code foreignKeys} and {@code views} when they are empty; here they are always present, as empty lists. JSON numbers are {@link Long} or {@link Double}, objects {@link Map} and arrays {@link List}, none of them modifiable. + */ +public final class RoomSchema { + + private final String className; + private final int version; + private final String identityHash; + private final String path; + private final List> entities; + private final List> views; + + /** + * Creates a schema. The lists are kept as given, so pass unmodifiable ones. + * + * @param className + * the database class, from the folder name (Room does not write it into the JSON) + * @param version + * {@code database.version} + * @param identityHash + * {@code database.identityHash} + * @param path + * the file, relative to the project root, with {@code /} separators + * @param entities + * {@code database.entities} + * @param views + * {@code database.views}, empty when the file has none + */ + public RoomSchema(@NonNull String className, int version, @NonNull String identityHash, @NonNull String path, @NonNull List> entities, @NonNull List> views) { + this.className = Objects.requireNonNull(className, "className"); + this.version = version; + this.identityHash = Objects.requireNonNull(identityHash, "identityHash"); + this.path = Objects.requireNonNull(path, "path"); + this.entities = Collections.unmodifiableList(Objects.requireNonNull(entities, "entities")); + this.views = Collections.unmodifiableList(Objects.requireNonNull(views, "views")); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof RoomSchema)) { + return false; + } + final RoomSchema that = (RoomSchema) other; + return version == that.version && className.equals(that.className) && identityHash.equals(that.identityHash) && path.equals(that.path) && entities.equals(that.entities) && views.equals(that.views); + } + + /** + * Gets the database class, such as {@code com.example.AppDatabase}. + * + * @return the class name, from the folder that holds the file (never null) + */ + @NonNull + public String getClassName() { + return className; + } + + /** + * Gets the entities. + * + * @return {@code database.entities}, each with {@code indices} and {@code foreignKeys} present (never null) + */ + @NonNull + public List> getEntities() { + return entities; + } + + /** + * Gets the identity hash Room keeps in {@code room_master_table} of a database created with this schema. + * + * @return {@code database.identityHash} (never null) + */ + @NonNull + public String getIdentityHash() { + return identityHash; + } + + /** + * Gets where the file is. + * + * @return the path relative to the project root, with {@code /} separators (never null) + */ + @NonNull + public String getPath() { + return path; + } + + /** + * Gets the schema version, which a database created with this schema has as its {@code user_version}. + * + * @return {@code database.version} + */ + public int getVersion() { + return version; + } + + /** + * Gets the views. + * + * @return {@code database.views}, empty when the file has none (never null) + */ + @NonNull + public List> getViews() { + return views; + } + + @Override + public int hashCode() { + return Objects.hash(className, version, identityHash, path); + } + + @Override + public String toString() { + return "RoomSchema{" + className + " v" + version + ", " + path + "}"; + } +} diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateException.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateException.java new file mode 100644 index 0000000000..ddf10204eb --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateException.java @@ -0,0 +1,24 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * A SQL template could not be rendered: the file could not be read, the template has a syntax error or uses a variable it was not given, a {@link SqlTemplateFunction} failed, a filter was given a value it cannot quote, or the time limit passed. The message says which, with the template's line where Pebble gives one, and is meant to be shown to the user or the agent as it is. + */ +public class SqlTemplateException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * Creates the exception. + * + * @param message + * what went wrong (must not be null) + * @param cause + * the underlying failure, or null + */ + public SqlTemplateException(@NonNull String message, @Nullable Throwable cause) { + super(message, cause); + } +} diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateFunction.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateFunction.java new file mode 100644 index 0000000000..434b058269 --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateFunction.java @@ -0,0 +1,24 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.util.List; + +/** + * A function a SQL template calls, such as {@code row_count(db, "users")}, passed to {@link SqlTemplateService#render}. It runs only when the template calls it, on the render's thread, once per call. + */ +@FunctionalInterface +public interface SqlTemplateFunction { + + /** + * Runs the function. + * + * @param args + * the arguments in the order the template wrote them, as Pebble evaluated them (never null; empty when there are none). A literal in the template is a {@link Long}, a {@link Double}, a {@link String} or a {@link Boolean}, or null. A value that comes from a variable or another function keeps the type the caller gave it, so a number can be any {@link Number} (an {@link Integer} or a {@link java.math.BigDecimal}, say) and a {@link RoomSchema} stays a {@link RoomSchema}. A {@link java.util.Map} or {@link List} arrives as a read-only view, not the caller's own object, and its entries follow these same rules + * @return the value the template sees: null, a {@link String}, a {@link Number}, a {@link Boolean}, a {@link java.util.Map} or a {@link List} + * @throws Exception + * to stop the render: {@link SqlTemplateService#render} then throws {@link SqlTemplateException} with this function's name and the exception's message. Stop when the thread is interrupted: the render's time limit interrupts it + */ + @Nullable + Object call(@NonNull List args) throws Exception; +} diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateService.java new file mode 100644 index 0000000000..3d11184f11 --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/SqlTemplateService.java @@ -0,0 +1,97 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import java.util.List; +import java.util.Map; + +/** + * Renders the open project's SQL templates, for the SQLite debugger's {@code .read}: a plugin such as an MCP client passes the template's path, the variables it fetched from the app ({@code get_template_variables}) and the functions that read the app's data, and gets back the SQL. Rendering happens here because Code on the Go already has Pebble; the apps it builds do not. + * + *

+ * Templates are Pebble files in the project, such as {@code sqlite/report.sql.peb}, with the engine and settings of Code on the Go's project templates: the delimiters {@code ${{ }}}, {@code ${% %}} and {@code ${# #}}, strict variables (an unknown variable is an error) and Pebble's newline trimming (a closing }}, %} or #} eats the line break after it). One difference: autoescaping is off, as SQL is not HTML. A template quotes what it splices in with two filters: {@code sql_ident} writes an identifier in double quotes, doubling any inside, and {@code sql_literal} writes a literal (a string in single quotes, doubling any inside; a number as is, a negative one in parentheses so that {@code 1-x} cannot become a comment; a boolean as 1 or 0; null as NULL). A value the user supplies should not be spliced at all: write a parameter such as {@code :id} into the SQL and bind the value when running it. + * + *

+ * Every render also gets {@code project} ({@code name} and {@code path}, the project root) and {@code render_time} (ISO 8601, UTC). Caller variables may not use those names. + * + *

+ * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it. The service outlives a disable, so it is closed instead: after the plugin is disabled or unloaded every call throws {@link java.util.concurrent.CancellationException} until the plugin is enabled again. Calls read the project's files, so call from a background thread: on the main thread they throw {@link IllegalStateException}. + */ +public interface SqlTemplateService { + + /** + * Contract revision, bumped whenever a member is added here. It marks the revision and does not negotiate one; see {@link ToolSourceRegistry#CONTRACT_VERSION}. + */ + int CONTRACT_VERSION = 1; + + /** The longest time limit {@link #render} accepts, in milliseconds. */ + long MAX_TIMEOUT_MILLIS = 120_000L; + + /** + * Gets Room's exported schemas in the open project: every {@code /.json} file with {@code database.version} and {@code database.identityHash}, outside build output and hidden folders. Room writes them only when {@code exportSchema} is on, so the list can be empty; a migration from version N exists when the file for N does. + * + * @return the schemas, ordered by class name and version, at most 2,000 (the first in that order; the host logs a warning when it stops there), in a list the caller cannot modify (never null; empty when no project is open). A file Room did not write, cannot be read or cannot be parsed (JSON nested more than 64 levels, say) is skipped + * @throws SecurityException + * if the plugin lacks the {@code debugger.endpoints} permission + * @throws IllegalStateException + * if called on the main thread + * @throws java.util.concurrent.CancellationException + * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already running finds it so at its end + * @throws InterruptedException + * if the calling thread is interrupted while the project is read + */ + @NonNull + List getRoomSchemas() throws InterruptedException; + + /** + * Lists the SQL templates in the open project: the files whose names end in {@code .sql.peb}, outside build output and hidden folders. + * + * @return their paths relative to the project root, with {@code /} separators, sorted, at most 2,000 (the first in that order; the host logs a warning when it stops there), in a list the caller cannot modify (never null; empty when no project is open) + * @throws SecurityException + * if the plugin lacks the {@code debugger.endpoints} permission + * @throws IllegalStateException + * if called on the main thread + * @throws java.util.concurrent.CancellationException + * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already running finds it so at its end + * @throws InterruptedException + * if the calling thread is interrupted while the project is read + */ + @NonNull + List listTemplates() throws InterruptedException; + + /** + * Renders a template of the open project. + * + *

+ * A variable's value is null, a {@link String}, a {@link Number}, a {@link Boolean}, a {@link Map} with {@link String} keys, a {@link List} or other {@link Iterable}, a {@link RoomSchema}, or a {@link java.util.function.Supplier} of one of these. A supplier is lazy: it is called the first time the template reads the value, at most once, and not at all when the template does not; maps and lists may hold suppliers too. A function, such as {@code row_count(db, table)}, is called each time the template calls it, with its arguments, which are passed by position: a named argument such as {@code f(a=1)} fails the render. A supplier that a function returns is read once, as a variable's is. + * + *

+ * Pebble's {@code range} is limited here to 100,000 values: a larger one fails the render, as building it could exhaust the app's memory. So is a string a template builds with {@code ~}, {@code +}, {@code set}, {@code replace} or {@code join} past 4 MiB (4,194,304 characters, the most a render may write), or a list or map past 1,000,000 entries: the render fails, with a message naming the operation and the limit. These limits do not make a render safe: a template can still run the app out of memory by chaining filters in one expression (nothing is checked between them, so a filter such as {@code base64encode} or {@code urlencode} repeated many times on a long string can exhaust the heap), by nesting a list in itself through literals and then printing or joining it, or by a filter that grows its input before the next check. Render only templates you trust. A {@code for} loop's every pass, a macro call and an include check for a stopped render. + * + *

+ * The render runs on a thread of its own, with one time limit for the whole render, functions included. When it passes, that thread is interrupted (a function in progress should stop) and this throws. The template's own loops, macros and includes stop at once, but a function that ignores the interrupt keeps running on that thread after this throws, and whatever it does goes on; a function should check for the interrupt, or be short. + * + * @param templatePath + * the template, relative to the project root (as {@link #listTemplates} gives it); its name must end in {@code .peb}, it must have no NUL character, and it must be inside the project once links are resolved; the file must be a regular file of at most 8 MiB + * @param variables + * the variables, by name (not {@code project} or {@code render_time}) + * @param functions + * the functions, by name: letters, digits and {@code _}, not starting with a digit, and not a Pebble built-in function or one of the filter names + * @param timeoutMillis + * the time limit, from 1 to {@link #MAX_TIMEOUT_MILLIS} + * @return the SQL, at most 4 Mi characters + * @throws SqlTemplateException + * if the template cannot be read (it is not a regular file, such as a FIFO, or is larger than 8 MiB) or rendered, a function fails, or the time limit passes + * @throws IllegalArgumentException + * for a path outside the project, not ending in {@code .peb} or with a NUL, a reserved or invalid name, a value of another type, or a time limit out of range + * @throws SecurityException + * if the plugin lacks the {@code debugger.endpoints} permission + * @throws IllegalStateException + * if called on the main thread, when no project is open, or when the project folder cannot be resolved + * @throws java.util.concurrent.CancellationException + * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already running finds it so at its end + * @throws InterruptedException + * if the calling thread is interrupted while it waits for the render, which is then stopped + */ + @NonNull + String render(@NonNull String templatePath, @NonNull Map variables, @NonNull Map functions, long timeoutMillis) throws SqlTemplateException, InterruptedException; +} diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt index 246836d1c8..3104f3d79c 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt @@ -57,7 +57,8 @@ enum class PluginPermission( DEBUGGER_ENDPOINTS( "debugger.endpoints", "Read the port and token of the open project's SQLite debugger servers. The token lets the plugin query the " + - "databases of the project's apps: read-only for now, and later versions may allow writes. Plugins run in " + + "databases of the project's apps: read-only for now, and later versions may allow writes. Also render the " + + "project's SQL templates and read the Room schemas it exports (SqlTemplateService). Plugins run in " + "Code on the Go's process, so this declares intent and cannot stop reflection", ), } diff --git a/plugin-manager/build.gradle.kts b/plugin-manager/build.gradle.kts index 5e5bf01abb..fdd4fb7bd8 100644 --- a/plugin-manager/build.gradle.kts +++ b/plugin-manager/build.gradle.kts @@ -30,6 +30,7 @@ dependencies { implementation(projects.resources) implementation(projects.idetooltips) implementation(projects.shared) + implementation(projects.subprojects.pebble) implementation(projects.subprojects.projects) implementation(libs.androidx.appcompat) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 62549332c3..256392e4f2 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -64,6 +64,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeTooltipServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeUIServiceImpl import com.itsaky.androidide.plugins.manager.services.PluginBuildService import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents +import com.itsaky.androidide.plugins.manager.services.SqlTemplateServiceImpl import com.itsaky.androidide.plugins.manager.snippets.PluginSnippetManager import com.itsaky.androidide.plugins.manager.ui.PluginEditorTabManager import com.itsaky.androidide.plugins.services.DebuggerEndpointService @@ -85,6 +86,7 @@ import com.itsaky.androidide.plugins.services.IdeTerminalService import com.itsaky.androidide.plugins.services.IdeThemeService import com.itsaky.androidide.plugins.services.IdeTooltipService import com.itsaky.androidide.plugins.services.IdeUIService +import com.itsaky.androidide.plugins.services.SqlTemplateService import com.itsaky.androidide.projects.IProjectManager import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -826,6 +828,7 @@ class PluginManager private constructor( Result.failure(RuntimeException("Error loading plugin: $prefix${e.message}", e)) } finally { notLoadedContext?.debuggerEndpointService()?.close() + notLoadedContext?.sqlTemplateService()?.close() } } @@ -904,6 +907,7 @@ class PluginManager private constructor( try { // First: a later step can throw and end the unload. loadedPlugin.context.debuggerEndpointService()?.close() + loadedPlugin.context.sqlTemplateService()?.close() // Remove documentation if plugin implements DocumentationExtension if (loadedPlugin.plugin is DocumentationExtension) { @@ -1234,10 +1238,12 @@ class PluginManager private constructor( // The services outlive a disable, which closed the terminal and SQLite debugger endpoint services. (loadedPlugin.context.services.get(IdeTerminalService::class.java) as? IdeTerminalServiceImpl)?.reopen() loadedPlugin.context.debuggerEndpointService()?.reopen() + loadedPlugin.context.sqlTemplateService()?.reopen() // An unload that ran since the lookup above already closed these services; close them again. // Enable, disable and unload are still not serialized with each other (out of scope here). if (loadedPlugins[pluginId] !== loadedPlugin) { loadedPlugin.context.debuggerEndpointService()?.close() + loadedPlugin.context.sqlTemplateService()?.close() (loadedPlugin.context.services.get(IdeTerminalService::class.java) as? IdeTerminalServiceImpl)?.cancelAll() logger.warn("Plugin $pluginId was unloaded while it was being enabled; not activating it") return false @@ -1331,6 +1337,7 @@ class PluginManager private constructor( */ private fun markDisabled(loadedPlugin: LoadedPlugin) { loadedPlugin.context.debuggerEndpointService()?.close() + loadedPlugin.context.sqlTemplateService()?.close() loadedPlugin.isEnabled = false } @@ -1338,6 +1345,10 @@ class PluginManager private constructor( private fun PluginContext.debuggerEndpointService(): DebuggerEndpointServiceImpl? = services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl + /** The plugin's [SqlTemplateServiceImpl], closed and reopened with the debugger endpoint service. */ + private fun PluginContext.sqlTemplateService(): SqlTemplateServiceImpl? = + services.get(SqlTemplateService::class.java) as? SqlTemplateServiceImpl + sealed class CrashResult { abstract val pluginId: String abstract val pluginName: String @@ -1722,6 +1733,21 @@ class PluginManager private constructor( ) } + registerServiceWithErrorHandling( + pluginServiceRegistry, + SqlTemplateService::class.java, + pluginId, + "sql_template", + ) { + SqlTemplateServiceImpl( + pluginId = pluginId, + permissions = permissions, + projectRootProvider = ::openProjectRoot, + // As the debugger endpoint service above: closed through initialize() for a plugin saved as disabled. + startOpen = getPluginState(pluginId), + ) + } + registerServiceWithErrorHandling( pluginServiceRegistry, IdeTemplateService::class.java, diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/SqlTemplateServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/SqlTemplateServiceImpl.kt new file mode 100644 index 0000000000..48deb49841 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/SqlTemplateServiceImpl.kt @@ -0,0 +1,157 @@ +package com.itsaky.androidide.plugins.manager.services + +import android.os.Looper +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.manager.services.sqltemplate.ProjectSqlFiles +import com.itsaky.androidide.plugins.manager.services.sqltemplate.SqlTemplateRenderer +import com.itsaky.androidide.plugins.services.RoomSchema +import com.itsaky.androidide.plugins.services.SqlTemplateException +import com.itsaky.androidide.plugins.services.SqlTemplateFunction +import com.itsaky.androidide.plugins.services.SqlTemplateService +import org.slf4j.LoggerFactory +import java.io.File +import java.io.IOException +import java.time.Instant +import java.util.Collections +import java.util.EnumSet +import java.util.concurrent.CancellationException + +/** + * The [SqlTemplateService] the plugin manager registers for each plugin (ADFA-7302). It is gated on + * [PluginPermission.DEBUGGER_ENDPOINTS], the permission a plugin already needs to reach the debugger whose variables + * and functions a template uses: it reads only `.peb` templates and Room's schema files, inside the open project. + */ +internal class SqlTemplateServiceImpl( + private val pluginId: String, + permissions: Set, + private val projectRootProvider: () -> File?, + private val isMainThread: () -> Boolean = { Looper.myLooper() == Looper.getMainLooper() }, + private val clock: () -> Instant = Instant::now, + /** False for a plugin saved as disabled: it stays closed through its own initialize() until [reopen]. */ + startOpen: Boolean = true, +) : SqlTemplateService { + private val permissions: Set = + Collections.unmodifiableSet(EnumSet.noneOf(PluginPermission::class.java).apply { addAll(permissions) }) + + // Set by close, cleared by reopen. A disabled plugin keeps its services, and any thread it left running. + @Volatile + private var closed = !startOpen + + @Throws(InterruptedException::class) + override fun getRoomSchemas(): List { + checkCaller("getRoomSchemas") + val root = projectRoot() ?: return emptyList() + val found = ProjectSqlFiles.roomSchemas(root) { log.warn("getRoomSchemas for plugin {}: {}", pluginId, it) } + requireOpen() + if (found.size >= ProjectSqlFiles.MAX_MATCHES) log.warn("getRoomSchemas for plugin {} stopped at {} schemas", pluginId, found.size) + return Collections.unmodifiableList(found) + } + + @Throws(InterruptedException::class) + override fun listTemplates(): List { + checkCaller("listTemplates") + val root = projectRoot() ?: return emptyList() + val found = ProjectSqlFiles.templates(root) { log.warn("listTemplates for plugin {}: {}", pluginId, it) } + requireOpen() + if (found.size >= ProjectSqlFiles.MAX_MATCHES) log.warn("listTemplates for plugin {} stopped at {} templates", pluginId, found.size) + return Collections.unmodifiableList(found) + } + + @Throws(SqlTemplateException::class, InterruptedException::class) + override fun render( + templatePath: String, + variables: Map, + functions: Map, + timeoutMillis: Long, + ): String { + checkCaller("render") + val root = projectRoot() ?: throw IllegalStateException("No project is open") + val file = templateFile(root, templatePath) + for (name in SqlTemplateRenderer.RESERVED_VARIABLES) { + require(name !in variables) { "\"$name\" is set by Code on the Go; use another name" } + } + val text = + try { + ProjectSqlFiles.readBounded(file) + } catch (e: ProjectSqlFiles.TooLarge) { + throw SqlTemplateException("$templatePath is ${e.message}", null) + } catch (e: IOException) { + throw SqlTemplateException("$templatePath could not be read: ${e.message}", e) + } + val all = LinkedHashMap(variables) + all["project"] = mapOf("name" to root.name, "path" to root.path) + all["render_time"] = clock().toString() + val sql = SqlTemplateRenderer.render(templatePath, text, all, functions, timeoutMillis) + // Again after the render: a plugin disabled while it ran gets no SQL either. + requireOpen() + return sql + } + + /** + * Refuses every later call, and one still running when it ends, with [CancellationException] until [reopen], as + * [DebuggerEndpointServiceImpl.close] does. Called when the plugin is disabled or unloaded. A render already in progress + * is not stopped: it ends at its own time limit. + */ + fun close() { + closed = true + } + + /** Lets calls through again after [close]. Called when the plugin is enabled. */ + fun reopen() { + closed = false + } + + /** The open project's folder with links resolved, or null when none is open. */ + private fun projectRoot(): File? { + val root = projectRootProvider() ?: return null + return try { + root.canonicalFile + } catch (e: IOException) { + throw IllegalStateException("The project folder cannot be resolved: ${e.message}", e) + } + } + + /** + * The template, which must name a `.peb` file inside [root] once links are resolved. The file is then read by this + * resolved path, without following a link at its last step and only if it is a regular file, so a template that is a + * FIFO or a link cannot block or redirect the read. A swap of a folder on the path between this check and the read + * needs write access to the project, which already lets a plugin write a template, so it is not guarded against. The + * same gap holds for a Room schema that is a link: [ProjectSqlFiles.roomSchemas] checks that it resolves inside the + * project when it lists it, then reads it by its resolved path without checking again, so a link swapped between the + * two steps would be followed. + */ + private fun templateFile( + root: File, + templatePath: String, + ): File { + require('\u0000' !in templatePath) { "A template's path has no NUL character" } + require(templatePath.endsWith(".peb")) { "A template's name ends in .peb: $templatePath" } + require(!File(templatePath).isAbsolute) { "The template path is relative to the project root: $templatePath" } + val file = + try { + File(root, templatePath).canonicalFile + } catch (e: IOException) { + throw IllegalArgumentException("$templatePath is not a usable path: ${e.message}", e) + } + require(file.path.startsWith(root.path + File.separator)) { "$templatePath is outside the project" } + return file + } + + private fun requireOpen() { + if (closed) throw CancellationException("Plugin $pluginId is disabled or unloaded") + } + + private fun checkCaller(method: String) { + if (PluginPermission.DEBUGGER_ENDPOINTS !in permissions) { + throw SecurityException( + "Plugin $pluginId does not have required permissions: ${PluginPermission.DEBUGGER_ENDPOINTS.name}", + ) + } + requireOpen() + check(!isMainThread()) { "SqlTemplateService.$method() reads the project's files; call it off the main thread" } + } + + private companion object { + private val log = LoggerFactory.getLogger(SqlTemplateServiceImpl::class.java) + } +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/ProjectSqlFiles.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/ProjectSqlFiles.kt new file mode 100644 index 0000000000..6652f8f092 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/ProjectSqlFiles.kt @@ -0,0 +1,244 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.JsonPrimitive +import com.itsaky.androidide.plugins.services.RoomSchema +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.attribute.BasicFileAttributes + +/** Finds the SQL templates and Room's exported schemas in a project (ADFA-7302). Plain JVM, unit-tested without Android. */ +internal object ProjectSqlFiles { + const val TEMPLATE_SUFFIX = ".sql.peb" + + /** Folders below this depth are not searched: schemas sit about four levels down, templates wherever the user puts them. */ + const val MAX_DEPTH = 12 + + /** + * At most this many entries are returned, so a project full of JSON cannot make a call slow: the first ones in the + * documented order (templates by path; schemas by class, then version), the rest left out. + */ + const val MAX_MATCHES = 2000 + + /** Room's schemas nest about six levels; a file nested deeper than this is not read as one. */ + const val MAX_JSON_DEPTH = 64 + + /** The walk stops collecting candidates here, so the cut above is made on a sorted list, but a pathological project cannot fill memory. */ + const val MAX_CANDIDATES = 50_000 + + /** A template or schema file larger than this is not read. */ + const val MAX_FILE_BYTES = 8L * 1024 * 1024 + + /** Build output holds copies of the schemas (and of nothing a user edits); hidden folders hold Git, Gradle and IDE state. */ + private val SKIPPED = setOf("build", "node_modules") + + private val VERSION_FILE = Regex("(\\d{1,9})\\.json") + private val CLASS_NAME = Regex("[A-Za-z_$][A-Za-z0-9_$]*(\\.[A-Za-z_$][A-Za-z0-9_$]*)*") + + /** The project's `*.sql.peb` files, relative to [root], sorted. */ + fun templates( + root: File, + onSkipped: (String) -> Unit = {}, + ): List = walk(root, onSkipped) { it.name.endsWith(TEMPLATE_SUFFIX) }.map { relative(root, it) }.sorted().take(MAX_MATCHES) + + /** + * Every schema Room exported under [root], by class and version, at most [MAX_MATCHES] (the first in that order). + * A file that is not Room's, is unreadable or cannot be parsed (JSON nested too deeply, say) is skipped, and one + * that is unreadable or too large is reported to [onSkipped], as is a link that leads out of the project (see [walk]). + */ + fun roomSchemas( + root: File, + onSkipped: (String) -> Unit = {}, + ): List = + walk(root, onSkipped) { VERSION_FILE.matches(it.name) && CLASS_NAME.matches(it.parentFile?.name ?: "") } + .sortedWith(compareBy({ it.parentFile!!.name }, { versionOf(it) }, { relative(root, it) })) + .take(MAX_MATCHES) + .mapNotNull { file -> + val path = relative(root, file) + try { + // walk has checked that a link resolves inside the project, so the file is read by its resolved path. + parseRoomSchema(readBounded(file.canonicalFile), file.parentFile!!.name, path) + } catch (e: Exception) { + onSkipped("$path was skipped: ${e.message ?: e.javaClass.simpleName}") + null + } catch (e: StackOverflowError) { + // Backstop for the depth limit below, as toValue recurses once per level of nesting. + onSkipped("$path was skipped: JSON nested too deeply") + null + } + } + + private fun versionOf(file: File) = VERSION_FILE.matchEntire(file.name)!!.groupValues[1].toInt() + + /** [file] is over [MAX_FILE_BYTES]. */ + class TooLarge : IOException("larger than ${MAX_FILE_BYTES / (1024 * 1024)} MiB") + + /** + * [file]'s text (UTF-8), if it is a regular file (not a link, FIFO or device, which could block the read) of at most + * [MAX_FILE_BYTES]. The size is not taken from the file system: at most that many bytes plus one are read. + * + * @throws TooLarge for a longer file + * @throws IOException for anything else that stops the read + */ + @Throws(IOException::class) + fun readBounded(file: File): String { + val path = file.toPath() + val attributes = Files.readAttributes(path, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS) + if (!attributes.isRegularFile) throw IOException("not a regular file") + Files.newInputStream(path, LinkOption.NOFOLLOW_LINKS).use { input -> + // Not readNBytes: it needs API 33 (minSdk is 28), and desugaring does not backport it for this package. + val out = ByteArrayOutputStream() + val buffer = ByteArray(64 * 1024) + while (true) { + // At least 1, as a longer file has already thrown: at most MAX_FILE_BYTES + 1 bytes are read. + val room = minOf(buffer.size.toLong(), MAX_FILE_BYTES + 1 - out.size()).toInt() + val n = input.read(buffer, 0, room) + if (n < 0) break + out.write(buffer, 0, n) + if (out.size() > MAX_FILE_BYTES) throw TooLarge() + } + return String(out.toByteArray(), Charsets.UTF_8) + } + } + + /** + * A Room schema file, or null if it is not one (or is nested deeper than [MAX_JSON_DEPTH]): Room writes `formatVersion` and a `database` with `version` and + * `identityHash`. Room leaves out `indices`, `foreignKeys` and `views` when they are empty; they come back empty. + */ + fun parseRoomSchema( + text: String, + className: String, + path: String, + ): RoomSchema? = + try { + parse(text, className, path) + } catch (e: TooDeep) { + null + } + + private class TooDeep : RuntimeException("JSON nested more than $MAX_JSON_DEPTH levels") + + private fun parse( + text: String, + className: String, + path: String, + ): RoomSchema? { + val json = runCatching { JsonParser.parseString(text) }.getOrNull() as? JsonObject ?: return null + if (!json.has("formatVersion")) return null + val database = json.get("database") as? JsonObject ?: return null + val version = (database.get("version") as? JsonPrimitive)?.takeIf { it.isNumber }?.asInt ?: return null + val hash = (database.get("identityHash") as? JsonPrimitive)?.takeIf { it.isString }?.asString ?: return null + + @Suppress("UNCHECKED_CAST") + val entities = + ((toValue(database.get("entities")) as? List) ?: emptyList()) + .filterIsInstance>() + .map { entity -> + val e = LinkedHashMap(entity) + e.putIfAbsent("indices", emptyList()) + e.putIfAbsent("foreignKeys", emptyList()) + java.util.Collections.unmodifiableMap(e) as Map + } + + @Suppress("UNCHECKED_CAST") + val views = + ((toValue(database.get("views")) as? List) ?: emptyList()) + .filterIsInstance>() + return RoomSchema(className, version, hash, path, entities, views) + } + + /** JSON as Kotlin values: maps, lists, String, Boolean, Long for a whole number, Double otherwise; all unmodifiable. */ + private fun toValue( + e: JsonElement?, + depth: Int = 0, + ): Any? = + when { + depth > MAX_JSON_DEPTH -> { + throw TooDeep() + } + + e == null || e.isJsonNull -> { + null + } + + e is JsonObject -> { + val map = LinkedHashMap() + for ((k, v) in e.entrySet()) map[k] = toValue(v, depth + 1) + java.util.Collections.unmodifiableMap(map) + } + + e is JsonArray -> { + java.util.Collections.unmodifiableList(e.map { toValue(it, depth + 1) }) + } + + e is JsonPrimitive && e.isBoolean -> { + e.asBoolean + } + + e is JsonPrimitive && e.isNumber -> { + e.asBigDecimal.let { n -> runCatching { n.longValueExact() }.getOrElse { n.toDouble() } } + } + + else -> { + e.asString + } + } + + /** + * Files under [root] that [accept] takes, depth first, skipping build output and hidden folders. Checks for an + * interrupt between folders, so a cancelled call stops. + * + * One rule for a file that is a link: it counts if it resolves to a file inside [root] (then it is read by its + * resolved path, as `render` reads a template), and is left out, with a note to [onSkipped], if it resolves outside + * [root] or cannot be resolved. Folders that are links are never entered. + */ + fun walk( + root: File, + onSkipped: (String) -> Unit = {}, + accept: (File) -> Boolean, + ): List { + val canonicalRoot = runCatching { root.canonicalFile }.getOrDefault(root.absoluteFile) + val found = ArrayList() + val stack = ArrayDeque>() + stack.addLast(root to 0) + while (stack.isNotEmpty() && found.size < MAX_CANDIDATES) { + if (Thread.interrupted()) throw InterruptedException() + val (dir, depth) = stack.removeLast() + val children = dir.listFiles() ?: continue + for (child in children.sortedBy { it.name }) { + if (child.name.startsWith(".")) continue + // A link could lead out of the project or back into it: only real folders are entered. + if (child.isDirectory) { + if (depth < MAX_DEPTH && child.name !in SKIPPED && !isLink(child)) stack.addLast(child to depth + 1) + } else if (child.isFile && accept(child)) { + if (isLink(child)) { + val target = runCatching { child.canonicalFile }.getOrNull() + if (target == null || !target.path.startsWith(canonicalRoot.path + File.separator)) { + onSkipped("${relative(root, child)} was skipped: it is a link to a file outside the project") + continue + } + } + found += child + if (found.size >= MAX_CANDIDATES) break + } + } + } + return found + } + + private fun isLink(file: File) = + runCatching { + Files.isSymbolicLink(file.toPath()) + }.getOrDefault(true) + + fun relative( + root: File, + file: File, + ): String = file.relativeTo(root).invariantSeparatorsPath +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlBoundedParts.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlBoundedParts.kt new file mode 100644 index 0000000000..caf9a783f8 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlBoundedParts.kt @@ -0,0 +1,333 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import io.pebbletemplates.pebble.error.PebbleException +import io.pebbletemplates.pebble.extension.Filter +import io.pebbletemplates.pebble.extension.NodeVisitor +import io.pebbletemplates.pebble.extension.core.SplitFilter +import io.pebbletemplates.pebble.lexer.Token +import io.pebbletemplates.pebble.node.RenderableNode +import io.pebbletemplates.pebble.node.SetNode +import io.pebbletemplates.pebble.node.expression.AddExpression +import io.pebbletemplates.pebble.node.expression.ConcatenateExpression +import io.pebbletemplates.pebble.node.expression.Expression +import io.pebbletemplates.pebble.operator.Associativity +import io.pebbletemplates.pebble.operator.BinaryOperator +import io.pebbletemplates.pebble.operator.BinaryOperatorImpl +import io.pebbletemplates.pebble.operator.BinaryOperatorType +import io.pebbletemplates.pebble.parser.Parser +import io.pebbletemplates.pebble.template.EvaluationContext +import io.pebbletemplates.pebble.template.EvaluationContextImpl +import io.pebbletemplates.pebble.template.PebbleTemplate +import io.pebbletemplates.pebble.template.PebbleTemplateImpl +import io.pebbletemplates.pebble.tokenParser.TokenParser +import java.util.regex.Pattern + +/** + * The memory bounds of an SQL-template render (ADFA-7302). The output cap only counts what a template prints, so a + * template could still grow a string or a list that it never prints (`{% set s = s ~ s %}` in a loop reaches + * hundreds of MB in milliseconds) and take down the IDE's process. In this engine every value a template builds by `~`, + * `+`, `{% set %}`, `replace` or `join` is checked against these limits, and the render fails with a message. + * + * Not covered, so a template can still run the app out of memory by: chaining filters in one expression (nothing is checked + * between them, so `|base64encode` repeated 20 times on a 2 Mi string exhausts the heap, and `|urlencode` repeated 200 times + * takes seconds to do so); nesting a list in itself through literals (`[l, l]` again and again), which exhausts the heap when + * it is printed or joined (`{{ l }}`, `l ~ ''`); a filter that grows its input by a constant factor (`nl2br`, `urlencode`, + * `base64`) making a string up to about six times the limit for one step, as does a string with several `#{...}` + * interpolations; and `block()` or `parent()` used directly in an argument. + */ +internal object SqlLimits { + /** The longest string a template may build; the same as the output cap. */ + const val MAX_STRING_CHARS = SqlTemplateRenderer.MAX_RENDERED_CHARS + + /** The most entries a list or map a template builds may hold. */ + const val MAX_ENTRIES = 1_000_000 + + fun fail( + message: String, + lineNumber: Int, + self: PebbleTemplate?, + ): Nothing = throw PebbleException(null, message, lineNumber, self?.name) + + /** Fails when [value] is a string, list, array or map past the limits; returns it otherwise. */ + fun check( + value: T, + lineNumber: Int, + self: PebbleTemplate?, + ): T { + when (value) { + is CharSequence -> { + if (value.length > MAX_STRING_CHARS) { + fail("a string of ${value.length} characters is too long: the most is $MAX_STRING_CHARS", lineNumber, self) + } + } + + is Collection<*> -> { + if (value.size > MAX_ENTRIES) { + fail("a list of ${value.size} entries is too long: the most is $MAX_ENTRIES", lineNumber, self) + } + } + + // Pebble's `split` returns an array; its slices and merges can too. + is Array<*>, is IntArray, is LongArray, is ByteArray, is ShortArray, + is CharArray, is BooleanArray, is FloatArray, is DoubleArray, + -> { + val size = + java.lang.reflect.Array + .getLength(value) + if (size > MAX_ENTRIES) fail("a list of $size entries is too long: the most is $MAX_ENTRIES", lineNumber, self) + } + + is Map<*, *> -> { + if (value.size > MAX_ENTRIES) { + fail("a map of ${value.size} entries is too long: the most is $MAX_ENTRIES", lineNumber, self) + } + } + } + return value + } + + val binaryOperators: List = + listOf( + BinaryOperatorImpl("+", 40, { BoundedAdd() }, BinaryOperatorType.NORMAL, Associativity.LEFT), + BinaryOperatorImpl("~", 110, { BoundedConcatenate() }, BinaryOperatorType.NORMAL, Associativity.LEFT), + ) +} + +/** Pebble's `+` (numbers, strings, lists), with the result checked. */ +internal class BoundedAdd : AddExpression() { + override fun evaluate( + self: PebbleTemplateImpl, + context: EvaluationContextImpl, + ): Any? = SqlLimits.check(super.evaluate(self, context), lineNumber, self) +} + +/** Pebble's `~`, with the result checked. */ +internal class BoundedConcatenate : ConcatenateExpression() { + override fun evaluate( + self: PebbleTemplateImpl, + context: EvaluationContextImpl, + ): String = SqlLimits.check(super.evaluate(self, context), lineNumber, self) +} + +/** Pebble's `set` tag, except that the value it stores is checked. The project templates keep Pebble's own tag. */ +internal class BoundedSetTokenParser : TokenParser { + override fun getTag(): String = "set" + + override fun parse( + token: Token, + parser: Parser, + ): RenderableNode { + val stream = parser.stream + val lineNumber = token.lineNumber + stream.next() + val name = parser.expressionParser.parseNewVariableName() + stream.expect(Token.Type.PUNCTUATION, "=") + val value = parser.expressionParser.parseExpression() + stream.expect(Token.Type.EXECUTE_END) + return SetNode(lineNumber, name, CheckedExpression(value)) + } + + private class CheckedExpression( + private val inner: Expression<*>, + ) : Expression { + override fun evaluate( + self: PebbleTemplateImpl?, + context: EvaluationContextImpl?, + ): Any? = SqlLimits.check(inner.evaluate(self, context), inner.lineNumber, self) + + override fun getLineNumber(): Int = inner.lineNumber + + override fun accept(visitor: NodeVisitor?) { + inner.accept(visitor) + } + } +} + +/** Pebble's `replace` filter, but it refuses a result past [SqlLimits.MAX_STRING_CHARS] before building it. */ +internal object BoundedReplaceFilter : Filter { + private val NAMES = listOf("replace_pairs") + + override fun getArgumentNames(): List = NAMES + + override fun apply( + input: Any?, + args: Map, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any? { + if (input == null) return null + val pairs = + args["replace_pairs"] + ?: throw PebbleException(null, "The argument 'replace_pairs' is required.", lineNumber, self?.name) + var data = input.toString() + for ((k, v) in pairs as Map<*, *>) { + val target = k.toString() + val replacement = v.toString() + var count = 0L + if (target.isEmpty()) { + count = data.length + 1L + } else { + var at = data.indexOf(target) + while (at >= 0) { + count++ + at = data.indexOf(target, at + target.length) + } + } + val size = data.length + count * (replacement.length - target.length) + if (size > SqlLimits.MAX_STRING_CHARS) { + val most = SqlLimits.MAX_STRING_CHARS + SqlLimits.fail("replace would make a string of $size characters: the most is $most", lineNumber, self) + } + data = data.replace(target, replacement) + } + return data + } +} + +/** + * Pebble's `join` filter, but it stops at [SqlLimits.MAX_STRING_CHARS] characters. A list or map inside the list is + * written the way Java does (`[a, b]`, `{k=v}`), also with the limit applied, so a list nested in itself ends too. + */ +internal object BoundedJoinFilter : Filter { + private val NAMES = listOf("separator") + + override fun getArgumentNames(): List = NAMES + + override fun apply( + input: Any?, + args: Map, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any? { + if (input == null) return null + val glue = args["separator"] as String? + val items: Iterable<*> = + when { + input.javaClass.isArray -> { + List( + java.lang.reflect.Array + .getLength(input), + ) { + java.lang.reflect.Array + .get(input, it) + } + } + + input is Collection<*> -> { + input + } + + else -> { + throw PebbleException( + null, + "The 'join' filter expects that the input is either a collection or an array.", + lineNumber, + self?.name, + ) + } + } + val out = StringBuilder() + var first = true + for (item in items) { + if (!first && glue != null) out.append(glue) + first = false + append(out, item, 0, lineNumber, self) + // After each item, so the last one counts too. + if (out.length > SqlLimits.MAX_STRING_CHARS) { + SqlLimits.fail("join would make a string past ${SqlLimits.MAX_STRING_CHARS} characters", lineNumber, self) + } + } + return out.toString() + } + + private fun append( + out: StringBuilder, + value: Any?, + depth: Int, + lineNumber: Int, + self: PebbleTemplate?, + ) { + if (out.length > SqlLimits.MAX_STRING_CHARS || depth > MAX_DEPTH) { + SqlLimits.fail("join would make a string past ${SqlLimits.MAX_STRING_CHARS} characters, or nested too deep", lineNumber, self) + } + when (value) { + is Collection<*> -> { + out.append('[') + var first = true + for (v in value) { + if (!first) out.append(", ") + first = false + append(out, v, depth + 1, lineNumber, self) + } + out.append(']') + } + + is Map<*, *> -> { + out.append('{') + var first = true + for ((k, v) in value) { + if (!first) out.append(", ") + first = false + append(out, k, depth + 1, lineNumber, self) + out.append('=') + append(out, v, depth + 1, lineNumber, self) + } + out.append('}') + } + + else -> { + out.append(value) + } + } + } + + private const val MAX_DEPTH = 64 +} + +/** + * Pebble's `split` filter (its delimiter is a regular expression, as `String.split` takes), but it refuses a result of more + * than [SqlLimits.MAX_ENTRIES] pieces before building them: `s | split('')` on a 4 Mi string would build 4 million + * Strings, well over 100 MB, before any check of the stored value could run. An empty delimiter is counted without + * allocating (one piece per character); any other delimiter is split with a limit of MAX_ENTRIES + 2, so at most that many + * pieces are built, and fails when more than MAX_ENTRIES come back. With a limit of 0 Java drops trailing empty pieces, so + * a string whose pieces pass the limit only through trailing empty ones is refused too. Everything else is Pebble's own. + */ +internal object BoundedSplitFilter : Filter { + private val core = SplitFilter() + + override fun getArgumentNames(): List = core.argumentNames + + override fun apply( + input: Any?, + args: Map, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any? { + val delimiter = args["delimiter"] as? String + val limit = (args["limit"] as? Number)?.toInt() + // Up to MAX_ENTRIES + 1 pieces cannot pass the limit by more than the one the check below allows for. + val unbounded = limit == null || limit <= 0 || limit > SqlLimits.MAX_ENTRIES + 1 + if (input is String && delimiter != null && unbounded) { + val most = SqlLimits.MAX_ENTRIES + if (delimiter.isEmpty()) { + if (input.length > most) tooMany(lineNumber, self) + } else if (Pattern.compile(delimiter).split(input, most + 2).size > most) { + tooMany(lineNumber, self) + } + } + return core.apply(input, args, self, context, lineNumber) + } + + private fun tooMany( + lineNumber: Int, + self: PebbleTemplate?, + ): Nothing = + SqlLimits.fail( + "split would make a list of more than ${SqlLimits.MAX_ENTRIES} entries: the most is ${SqlLimits.MAX_ENTRIES}", + lineNumber, + self, + ) +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlPebbleParts.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlPebbleParts.kt new file mode 100644 index 0000000000..de98742ca7 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlPebbleParts.kt @@ -0,0 +1,203 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import io.pebbletemplates.pebble.error.ParserException +import io.pebbletemplates.pebble.error.PebbleException +import io.pebbletemplates.pebble.extension.AbstractNodeVisitor +import io.pebbletemplates.pebble.extension.Function +import io.pebbletemplates.pebble.extension.NodeVisitor +import io.pebbletemplates.pebble.extension.NodeVisitorFactory +import io.pebbletemplates.pebble.lexer.Token +import io.pebbletemplates.pebble.node.AbstractRenderableNode +import io.pebbletemplates.pebble.node.BodyNode +import io.pebbletemplates.pebble.node.ForNode +import io.pebbletemplates.pebble.node.RenderableNode +import io.pebbletemplates.pebble.node.expression.Expression +import io.pebbletemplates.pebble.parser.Parser +import io.pebbletemplates.pebble.template.EvaluationContext +import io.pebbletemplates.pebble.template.EvaluationContextImpl +import io.pebbletemplates.pebble.template.PebbleTemplate +import io.pebbletemplates.pebble.template.PebbleTemplateImpl +import io.pebbletemplates.pebble.tokenParser.TokenParser +import java.io.Writer +import java.math.BigInteger + +/** Thrown inside a render whose thread was interrupted (the time limit passed, or the caller was). */ +internal class RenderStopped : RuntimeException("the render was stopped") + +/** + * Puts an interrupt check at the start of every body of every template the engine compiles, included ones too. Besides + * `for`, a template repeats work only by rendering a body again: a macro that calls itself, a template that includes + * itself (a template is its own text, so it can) or `block()`. A recursive macro can make 2^40 calls that write nothing, + * so neither the output cap nor the stack ends it, and Pebble never looks at the interrupt flag. + */ +internal object InterruptCheckVisitorFactory : NodeVisitorFactory { + override fun createVisitor(template: PebbleTemplate): NodeVisitor = Visitor(template as PebbleTemplateImpl) + + private class Visitor( + template: PebbleTemplateImpl, + ) : AbstractNodeVisitor(template) { + override fun visit(node: BodyNode) { + // The parser's bodies hold an ArrayList; the only fixed-size one, embed's, is made while rendering and never visited. + node.children.add(0, InterruptCheck) + super.visit(node) + } + } + + private object InterruptCheck : AbstractRenderableNode() { + override fun render( + self: PebbleTemplateImpl?, + writer: Writer?, + context: EvaluationContextImpl?, + ) { + if (Thread.currentThread().isInterrupted) throw RenderStopped() + } + + override fun accept(visitor: NodeVisitor) { + visitor.visit(this) + } + } +} + +/** + * Pebble's `for` tag, except that the loop checks for an interrupt on every element, so a render past its time limit ends + * instead of looping on (Pebble itself never looks at the interrupt flag). Only the SQL engine registers it: the project + * templates keep Pebble's own tag. + */ +internal class InterruptibleForTokenParser : TokenParser { + override fun getTag(): String = "for" + + override fun parse( + token: Token, + parser: Parser, + ): RenderableNode { + val stream = parser.stream + val lineNumber = token.lineNumber + stream.next() + val variable = parser.expressionParser.parseNewVariableName() + stream.expect(Token.Type.NAME, "in") + val iterable = parser.expressionParser.parseExpression() + stream.expect(Token.Type.EXECUTE_END) + val body = parser.subparse { it.test(Token.Type.NAME, "else", "endfor") } + var elseBody: io.pebbletemplates.pebble.node.BodyNode? = null + if (stream.current().test(Token.Type.NAME, "else")) { + stream.next() + stream.expect(Token.Type.EXECUTE_END) + elseBody = parser.subparse { it.test(Token.Type.NAME, "endfor") } + } + if (stream.current().value == null) { + throw ParserException( + null, + "Unexpected end of template. Pebble was looking for the \"endfor\" tag", + stream.current().lineNumber, + stream.filename, + ) + } + stream.next() + stream.expect(Token.Type.EXECUTE_END) + return ForNode(lineNumber, variable, InterruptibleIterable(iterable), body, elseBody) + } + + /** Evaluates [inner], handing a collection or map to the loop as a collection that checks for an interrupt as it is walked. */ + private class InterruptibleIterable( + private val inner: Expression<*>, + ) : Expression { + override fun evaluate( + self: PebbleTemplateImpl?, + context: EvaluationContextImpl?, + ): Any? = + when (val value = inner.evaluate(self, context)) { + is Collection<*> -> Checked(value) + is Map<*, *> -> Checked(value.entries) + else -> value + } + + override fun getLineNumber(): Int = inner.lineNumber + + override fun accept(visitor: NodeVisitor?) { + inner.accept(visitor) + } + } + + private class Checked( + private val source: Collection<*>, + ) : AbstractCollection() { + override val size get() = source.size + + override fun iterator(): Iterator { + val it = source.iterator() + return object : Iterator { + override fun hasNext() = it.hasNext() + + override fun next(): Any? { + if (Thread.currentThread().isInterrupted) throw RenderStopped() + return it.next() + } + } + } + } +} + +/** + * Pebble's `range`, but it refuses to build more than [MAX_ELEMENTS] values: Pebble's builds the whole list, boxed, before the + * template can look at it, so `range(1, 9999999999)` would exhaust the app's memory. Same arguments (`start`, `end`, + * `increment`), steps, negative steps and one-character strings as Pebble's. + */ +internal object CappedRangeFunction : Function { + /** The most values one `range` call returns. */ + const val MAX_ELEMENTS = 100_000 + + private val NAMES = listOf("start", "end", "increment") + + override fun getArgumentNames(): List = NAMES + + override fun execute( + args: Map, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any { + val start = args["start"] + val end = args["end"] + val increment = args["increment"] ?: 1L + + fun fail(message: String): Nothing = throw PebbleException(null, message, lineNumber, self?.name) + if (increment !is Number) fail("The increment of the range function must be a number $increment") + val step = increment.toLong() + if (step == 0L) fail("The increment of the range function must be different than 0") + + if (start is Number && end is Number) { + val from = start.toLong() + val to = end.toLong() + val (lo, hi) = if (step > 0) from to to else to to from + val span = BigInteger.valueOf(hi).subtract(BigInteger.valueOf(lo)) + if (span.signum() < 0) return emptyList() + val count = span.divide(BigInteger.valueOf(step).abs()).add(BigInteger.ONE) + if (count > BigInteger.valueOf(MAX_ELEMENTS.toLong())) { + fail("range($from, $to, $step) would have $count values; the most is $MAX_ELEMENTS") + } + val out = ArrayList(count.toInt()) + var i = from + repeat(count.toInt()) { + out.add(i) + i += step + } + return out + } + if (start is String && end is String) { + if (start.length != 1 || end.length != 1) { + fail("Arguments of range function must be of type Number or String with a length of 1") + } + val out = ArrayList() + // A step beyond the char range ends the loop after one value either way; the clamp only keeps the Int from wrapping. + val charStep = step.coerceIn(-0x10000L, 0x10000L).toInt() + var i = start[0].code + val last = end[0].code + while (if (charStep > 0) i <= last else i >= last) { + out.add(i.toChar()) + i += charStep + } + return out + } + fail("Arguments of range function must be of type Number or String with a length of 1") + } +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlTemplateRenderer.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlTemplateRenderer.kt new file mode 100644 index 0000000000..2bbf04a581 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlTemplateRenderer.kt @@ -0,0 +1,391 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import com.itsaky.androidide.plugins.services.RoomSchema +import com.itsaky.androidide.plugins.services.SqlTemplateException +import com.itsaky.androidide.plugins.services.SqlTemplateFunction +import com.itsaky.androidide.plugins.services.SqlTemplateService +import com.itsaky.androidide.templates.ProjectTemplatePebble +import io.pebbletemplates.pebble.error.PebbleException +import io.pebbletemplates.pebble.extension.AbstractExtension +import io.pebbletemplates.pebble.extension.Filter +import io.pebbletemplates.pebble.extension.Function +import io.pebbletemplates.pebble.extension.NodeVisitorFactory +import io.pebbletemplates.pebble.operator.BinaryOperator +import io.pebbletemplates.pebble.template.EvaluationContext +import io.pebbletemplates.pebble.template.PebbleTemplate +import io.pebbletemplates.pebble.tokenParser.TokenParser +import java.io.StringWriter +import java.math.BigDecimal +import java.math.BigInteger +import java.util.concurrent.ExecutionException +import java.util.concurrent.FutureTask +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.function.Supplier + +/** + * Renders a SQL template (ADFA-7302) with the project templates' Pebble settings ([ProjectTemplatePebble]), autoescaping + * off, the two quoting filters, lazy variables and the caller's functions. Plain JVM, so it is unit-tested without Android. + * + * Pebble never looks at the interrupt flag, so in this engine only every body of a template checks for an interrupt + * when it starts ([InterruptCheckVisitorFactory]: a loop's pass, a macro call, an include), `for` checks on every pass, + * and `range` refuses more than [CappedRangeFunction.MAX_ELEMENTS] values. The strings and lists a template builds without + * printing them are bounded too (see [SqlLimits]). + */ +internal object SqlTemplateRenderer { + /** The most characters a render writes, as the documentation pages' renderer allows. */ + const val MAX_RENDERED_CHARS = 4 * 1024 * 1024 + + /** Names a caller cannot use: what every render adds. */ + val RESERVED_VARIABLES = setOf("project", "render_time") + + /** Pebble's own functions (`max`, `min`, `range`; `block` and `parent` are parsed specially, `i18n` is an extension). */ + private val PEBBLE_FUNCTIONS = setOf("max", "min", "range", "block", "parent", "i18n") + + const val IDENT_FILTER = "sql_ident" + const val LITERAL_FILTER = "sql_literal" + + private val NAME = Regex("[A-Za-z_][A-Za-z0-9_]*") + + /** + * Renders [text] (the template [name], for messages). [variables] must already include the reserved ones. + * + * The render runs on a daemon thread, and the time limit interrupts it. The template's loops, macros and includes + * honour that, but a caller's function that ignores the interrupt keeps running on that thread after this throws (the + * approved behaviour: nothing can force a thread to stop), so the function's effects go on until it returns. + * + * @throws SqlTemplateException for anything the template or a function did wrong, or the time limit + * @throws IllegalArgumentException for a bad name, value type or time limit + */ + fun render( + name: String, + text: String, + variables: Map, + functions: Map, + timeoutMillis: Long, + ): String { + require(timeoutMillis in 1..SqlTemplateService.MAX_TIMEOUT_MILLIS) { + "timeoutMillis must be from 1 to ${SqlTemplateService.MAX_TIMEOUT_MILLIS}, not $timeoutMillis" + } + for (fn in functions.keys) { + require(NAME.matches(fn)) { "\"$fn\" is not a valid function name: use letters, digits and _" } + require(fn !in PEBBLE_FUNCTIONS && fn != IDENT_FILTER && fn != LITERAL_FILTER) { "\"$fn\" is a built-in name" } + } + for ((key, value) in variables) checkValue(value, key) + + val engine = + ProjectTemplatePebble + .engineBuilder() + .autoEscaping(false) + .cacheActive(false) + .maxRenderedSize(MAX_RENDERED_CHARS) + // Lets SqlExtension replace `+` and `~` with the checked ones (SqlLimits). + .allowOverrideCoreOperators(true) + .extension(SqlExtension(functions)) + .build() + val task = + FutureTask { + val template = engine.getTemplate(text) + val out = StringWriter() + template.evaluate(out, LazyMap(variables)) + out.toString() + } + val thread = Thread(task, "sql-template-render") + thread.isDaemon = true + thread.start() + try { + return task.get(timeoutMillis, TimeUnit.MILLISECONDS) + } catch (e: TimeoutException) { + task.cancel(true) + throw SqlTemplateException("$name: the render did not finish within $timeoutMillis ms", null) + } catch (e: InterruptedException) { + task.cancel(true) + throw e + } catch (e: ExecutionException) { + throw failure(name, e.cause ?: e) + } + } + + private fun failure( + name: String, + cause: Throwable, + ): SqlTemplateException { + var t: Throwable? = cause + while (t != null) { + if (t is FunctionFailure) return SqlTemplateException("$name: ${t.message}", t.cause) + if (t is QuoteFailure) return SqlTemplateException("$name: ${t.message}", t) + t = t.cause + } + // PebbleException's message names the template's line; a template is its own name here (StringLoader), so leave + // the template text out of it. + val message = + if (cause is PebbleException) { + buildString { + append(cause.pebbleMessage ?: cause.javaClass.simpleName) + cause.lineNumber?.let { append(" (line ").append(it).append(')') } + } + } else { + cause.message ?: cause.javaClass.name + } + return SqlTemplateException("$name: $message", cause) + } + + /** Checks the documented types now, so a wrong one fails the call, not the render. Suppliers are checked when read. */ + private fun checkValue( + value: Any?, + where: String, + ) { + when (value) { + null, is String, is Number, is Boolean, is RoomSchema, is Supplier<*> -> { + Unit + } + + is Map<*, *> -> { + for ((k, v) in value) { + require(k is String) { "$where: a map key must be a String, not ${k?.javaClass?.name}" } + checkValue(v, "$where.$k") + } + } + + is Iterable<*> -> { + value.forEachIndexed { i, v -> checkValue(v, "$where[$i]") } + } + + else -> { + throw IllegalArgumentException("$where: a ${value.javaClass.name} cannot be a template value") + } + } + } + + /** A value as the template sees it: a supplier is read (once, by its holder), maps and lists are wrapped in turn. */ + private fun wrap(value: Any?): Any? = + when (value) { + is Map<*, *> -> { + @Suppress("UNCHECKED_CAST") + LazyMap(value as Map) + } + + is Iterable<*> -> { + LazyList(value.toList()) + } + + else -> { + value + } + } + + /** Resolves a supplier the first time it is read and keeps the value. Used on the render thread only. */ + private class Lazy( + private var value: Any?, + private val where: String, + ) { + private var read = false + + fun get(): Any? { + if (!read) { + val v = value + if (v is Supplier<*>) { + val got = + try { + v.get() + } catch (e: Exception) { + throw FunctionFailure("the value of $where failed: ${e.message ?: e.javaClass.name}", e) + } + try { + checkValue(got, where) + } catch (e: IllegalArgumentException) { + throw FunctionFailure(e.message ?: "bad value", e) + } + value = wrap(got) + } else { + value = wrap(v) + } + read = true + } + return value + } + } + + /** A map whose values are read lazily; Pebble reaches a variable through [get] and [containsKey]. */ + private class LazyMap( + source: Map, + ) : AbstractMap() { + private val lazies = LinkedHashMap().apply { for ((k, v) in source) put(k, Lazy(v, k)) } + + override fun containsKey(key: String): Boolean = lazies.containsKey(key) + + override fun get(key: String): Any? = lazies[key]?.get() + + override val entries: Set> + get() = + lazies.entries + .map { e -> + object : Map.Entry { + override val key = e.key + override val value get() = e.value.get() + } + }.toSet() + } + + private class LazyList( + source: List, + ) : AbstractList() { + private val lazies = source.mapIndexed { i, v -> Lazy(v, "[$i]") } + + override val size get() = lazies.size + + override fun get(index: Int): Any? = lazies[index].get() + } + + /** Carries a function's failure, with its name, past Pebble's own wrapping. */ + private class FunctionFailure( + message: String, + cause: Throwable?, + ) : RuntimeException(message, cause) + + /** A value a quoting filter refused. */ + private class QuoteFailure( + message: String, + ) : RuntimeException(message) + + private class SqlExtension( + private val callerFunctions: Map, + ) : AbstractExtension() { + override fun getFilters(): Map = + mapOf( + IDENT_FILTER to IdentFilter, + LITERAL_FILTER to LiteralFilter, + "replace" to BoundedReplaceFilter, + "join" to BoundedJoinFilter, + "split" to BoundedSplitFilter, + ) + + override fun getBinaryOperators(): List = SqlLimits.binaryOperators + + // An extension's tag and function replace Pebble's core ones of the same name (ExtensionRegistry.put). + override fun getTokenParsers(): List = listOf(InterruptibleForTokenParser(), BoundedSetTokenParser()) + + override fun getNodeVisitors(): List = listOf(InterruptCheckVisitorFactory) + + override fun getFunctions(): Map = + callerFunctions.mapValues { (name, fn) -> CallerFunction(name, fn) as Function } + ("range" to CappedRangeFunction) + } + + private class CallerFunction( + private val name: String, + private val fn: SqlTemplateFunction, + ) : Function { + // null: Pebble passes the arguments by position, keyed "0", "1"... + override fun getArgumentNames(): List? = null + + override fun execute( + args: Map, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any? { + if (Thread.currentThread().isInterrupted) { + throw FunctionFailure("$name was not called: the render was stopped", InterruptedException()) + } + val named = args.keys.filterNot { key -> key.all { it.isDigit() } } + if (named.isNotEmpty()) { + throw FunctionFailure("$name(...) at line $lineNumber: named arguments (${named.joinToString()}) are not supported", null) + } + val positional = (0 until args.size).map { args[it.toString()] } + val result = + try { + fn.call(positional) + } catch (e: Exception) { + throw FunctionFailure("$name(...) at line $lineNumber failed: ${e.message ?: e.javaClass.name}", e) + } + try { + checkValue(result, "$name(...)") + } catch (e: IllegalArgumentException) { + throw FunctionFailure(e.message ?: "bad value", e) + } + // A supplier is read here as a variable's is: once, with the value checked. + return Lazy(result, "$name(...)").get() + } + } + + private object IdentFilter : Filter { + override fun getArgumentNames(): List? = null + + override fun apply( + input: Any?, + args: Map?, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any = quoteIdentifier(input, lineNumber) + } + + private object LiteralFilter : Filter { + override fun getArgumentNames(): List? = null + + override fun apply( + input: Any?, + args: Map?, + self: PebbleTemplate?, + context: EvaluationContext?, + lineNumber: Int, + ): Any = quoteLiteral(input, lineNumber) + } + + /** `"name"`, with each `"` doubled. Only a string: a number or null as a name is a template mistake. */ + fun quoteIdentifier( + input: Any?, + lineNumber: Int = 0, + ): String { + if (input !is String) throw QuoteFailure("$IDENT_FILTER at line $lineNumber needs a string, not ${describe(input)}") + // SQLite reads SQL text only up to a NUL, so one would cut the statement short. + if ('\u0000' in input) throw QuoteFailure("$IDENT_FILTER at line $lineNumber: the name holds a NUL character") + return "\"" + input.replace("\"", "\"\"") + "\"" + } + + /** A SQL literal that reads back as [input]. */ + fun quoteLiteral( + input: Any?, + lineNumber: Int = 0, + ): String = + when (input) { + null -> { + "NULL" + } + + is String -> { + if ('\u0000' in input) { + throw QuoteFailure("$LITERAL_FILTER at line $lineNumber: the string holds a NUL character") + } + "'" + input.replace("'", "''") + "'" + } + + is Boolean -> { + if (input) "1" else "0" + } + + is Long, is Int, is Short, is Byte, is BigInteger -> { + signed(input.toString()) + } + + is Double, is Float -> { + val d = (input as Number).toDouble() + if (d.isNaN() || d.isInfinite()) throw QuoteFailure("$LITERAL_FILTER at line $lineNumber: $d has no SQL literal") + // Kotlin writes 1.0E10, which SQLite reads as a REAL; a whole number keeps its ".0", so it stays a REAL. + signed(d.toString()) + } + + is BigDecimal -> { + signed(input.toString()) + } + + else -> { + throw QuoteFailure("$LITERAL_FILTER at line $lineNumber cannot quote ${describe(input)}") + } + } + + /** A negative number in parentheses: spliced after a minus, a bare `-5` would read as the comment `--`. */ + private fun signed(number: String) = if (number.startsWith("-")) "($number)" else number + + private fun describe(value: Any?) = if (value == null) "null" else "a ${value.javaClass.simpleName}" +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index a140fb7f34..739aa996cc 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -15,6 +15,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeEditorServiceImpl import com.itsaky.androidide.plugins.services.DebuggerEndpoint import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.plugins.services.IdeTerminalService +import com.itsaky.androidide.plugins.services.SqlTemplateService import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.utils.Environment @@ -127,6 +128,55 @@ class PluginManagerDebuggerEndpointTest { assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) } + @Test + fun `a plugin with the permission gets a SqlTemplateService for the project now open, and one without is refused`() { + File(project, "sqlite").mkdirs() + File(project, "sqlite/t.sql.peb").writeText("SELECT \${{ project.name }}") + load("reader", "debugger.endpoints") + load("other", "filesystem.read") + openInEditor(project) + + val reader = sqlTemplateService("reader") + assertThat(offMainThread { reader.listTemplates() }).containsExactly("sqlite/t.sql.peb") + assertThat(offMainThread { reader.render("sqlite/t.sql.peb", emptyMap(), emptyMap(), 5_000) }) + .isEqualTo("SELECT ${project.canonicalFile.name}") + assertThrows(SecurityException::class.java) { offMainThread { sqlTemplateService("other").listTemplates() } } + } + + @Test + fun `a SqlTemplateService refuses while its plugin is disabled or unloaded, and works again once enabled`() { + File(project, "t.sql.peb").writeText("SELECT 1") + load("reader", "debugger.endpoints") + openInEditor(project) + val service = sqlTemplateService("reader") + + assertThat(pluginManager().disablePlugin("reader")).isTrue() + assertThrows(CancellationException::class.java) { offMainThread { service.listTemplates() } } + assertThrows(CancellationException::class.java) { offMainThread { service.getRoomSchemas() } } + assertThrows(CancellationException::class.java) { + offMainThread { service.render("t.sql.peb", emptyMap(), emptyMap(), 5_000) } + } + + assertThat(pluginManager().enablePlugin("reader")).isTrue() + assertThat(offMainThread { service.listTemplates() }).containsExactly("t.sql.peb") + + assertThat(pluginManager().unloadPlugin("reader")).isTrue() + assertThrows(CancellationException::class.java) { offMainThread { service.listTemplates() } } + } + + @Test + fun `a plugin loaded while disabled gets a SqlTemplateService that refuses`() { + load("reader", "debugger.endpoints") + assertThat(pluginManager().disablePlugin("reader")).isTrue() + assertThat(pluginManager().unloadPlugin("reader")).isTrue() + openInEditor(project) + + load("reader", "debugger.endpoints") + + assertThat(pluginManager().getLoadedPlugin("reader")).isNull() + assertThrows(CancellationException::class.java) { offMainThread { sqlTemplateService("reader").listTemplates() } } + } + @Test fun `a disable whose deactivate throws leaves the plugin enabled and its service open`() { val service = load("reader", "debugger.endpoints", FailingDeactivatePlugin::class.java) @@ -363,6 +413,12 @@ class PluginManagerDebuggerEndpointTest { return checkNotNull(plugin.context.services.get(DebuggerEndpointService::class.java)) { "no DebuggerEndpointService for $id" } } + /** The [SqlTemplateService] of the plugin [id], which [load] has loaded. */ + private fun sqlTemplateService(id: String): SqlTemplateService { + val plugin = pluginManager().getPlugin(id) as ContextKeepingPlugin + return checkNotNull(plugin.context.services.get(SqlTemplateService::class.java)) { "no SqlTemplateService for $id" } + } + /** Runs [block] on a worker thread: on the main thread, where Robolectric runs the test, getEndpoints throws. */ private fun offMainThread(block: () -> T): T { val result = AtomicReference>() diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/SqlTemplateServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/SqlTemplateServiceImplTest.kt new file mode 100644 index 0000000000..0740a7f149 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/SqlTemplateServiceImplTest.kt @@ -0,0 +1,176 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.manager.services.sqltemplate.ProjectSqlFiles +import com.itsaky.androidide.plugins.services.SqlTemplateException +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.File +import java.nio.file.Files +import java.time.Instant +import java.util.concurrent.CancellationException + +class SqlTemplateServiceImplTest { + private val root = Files.createTempDirectory("shop").toFile() + private val outside = Files.createTempDirectory("outside").toFile() + + @After + fun cleanUp() { + root.deleteRecursively() + outside.deleteRecursively() + } + + private fun service( + permissions: Set = setOf(PluginPermission.DEBUGGER_ENDPOINTS), + project: File? = root, + mainThread: Boolean = false, + ) = SqlTemplateServiceImpl("p", permissions, { project }, { mainThread }, { Instant.parse("2026-11-26T12:00:00Z") }) + + private fun SqlTemplateServiceImpl.renderPlain(path: String) = render(path, emptyMap(), emptyMap(), 1000) + + private fun template( + path: String, + text: String, + ) = File(root, path).apply { + parentFile!!.mkdirs() + writeText(text) + } + + @Test + fun `renders a template of the project with project and render_time added`() { + // The space keeps the line break: newline trimming eats one right after }}. + template("sqlite/t.sql.peb", "-- \${{ project.name }} at \${{ render_time }} \nSELECT \${{ n }}") + val sql = service().render("sqlite/t.sql.peb", mapOf("n" to 1L), emptyMap(), 5_000) + assertThat(sql).isEqualTo("-- ${root.canonicalFile.name} at 2026-11-26T12:00:00Z \nSELECT 1") + } + + @Test + fun `needs the debugger permission`() { + template("t.sql.peb", "SELECT 1") + val noPermission = service(permissions = setOf(PluginPermission.FILESYSTEM_READ)) + assertThrows(SecurityException::class.java) { noPermission.render("t.sql.peb", emptyMap(), emptyMap(), 1000) } + assertThrows(SecurityException::class.java) { noPermission.listTemplates() } + assertThrows(SecurityException::class.java) { noPermission.getRoomSchemas() } + } + + @Test + fun `refuses the main thread`() { + template("t.sql.peb", "SELECT 1") + val onMain = service(mainThread = true) + assertThrows(IllegalStateException::class.java) { onMain.listTemplates() } + assertThrows(IllegalStateException::class.java) { onMain.getRoomSchemas() } + assertThrows(IllegalStateException::class.java) { onMain.render("t.sql.peb", emptyMap(), emptyMap(), 1000) } + } + + /** Runs [block] on a thread of its own and fails if it has not finished in 5 s, as a read of a FIFO would not. */ + private fun within5s(block: () -> T): T { + val result = + java.util.concurrent.atomic + .AtomicReference>() + val thread = Thread { result.set(runCatching(block)) }.apply { isDaemon = true } + thread.start() + thread.join(5_000) + check(result.get() != null) { "still running after 5 s" } + return result.get().getOrThrow() + } + + @Test + fun `refuses a path outside the project, through dot-dot or a link, and a file that is not a template`() { + File(outside, "x.peb").writeText("SELECT 1") + assertThrows(IllegalArgumentException::class.java) { + service().render("../${outside.name}/x.peb", emptyMap(), emptyMap(), 1000) + } + Files.createSymbolicLink(File(root, "link").toPath(), outside.toPath()) + assertThrows(IllegalArgumentException::class.java) { service().render("link/x.peb", emptyMap(), emptyMap(), 1000) } + template("build.gradle", "x") + assertThrows(IllegalArgumentException::class.java) { service().render("build.gradle", emptyMap(), emptyMap(), 1000) } + assertThrows(IllegalArgumentException::class.java) { + service().render(File(outside, "x.peb").path, emptyMap(), emptyMap(), 1000) + } + } + + @Test + fun `a template that is a FIFO is refused, not read`() { + val fifo = File(root, "x.sql.peb") + val made = ProcessBuilder("mkfifo", fifo.path).start().waitFor() == 0 + org.junit.Assume.assumeTrue("mkfifo is not available", made) + val service = service() + val e = assertThrows(SqlTemplateException::class.java) { within5s { service.renderPlain("x.sql.peb") } } + assertThat(e).hasMessageThat().contains("x.sql.peb could not be read: not a regular file") + } + + @Test + fun `a folder named like a template is refused`() { + File(root, "d.sql.peb").mkdirs() + val e = assertThrows(SqlTemplateException::class.java) { service().render("d.sql.peb", emptyMap(), emptyMap(), 1000) } + assertThat(e).hasMessageThat().contains("d.sql.peb could not be read") + } + + @Test + fun `a template larger than the limit is refused by what is read, not by the size the file system reports`() { + template("big.sql.peb", "a".repeat(ProjectSqlFiles.MAX_FILE_BYTES.toInt() + 1)) + val e = assertThrows(SqlTemplateException::class.java) { service().renderPlain("big.sql.peb") } + assertThat(e).hasMessageThat().contains("big.sql.peb is larger than 8 MiB") + } + + @Test + fun `a link to a template inside the project is read through to the template`() { + template("real.sql.peb", "SELECT 7") + Files.createSymbolicLink(File(root, "alias.sql.peb").toPath(), File(root, "real.sql.peb").toPath()) + assertThat(service().render("alias.sql.peb", emptyMap(), emptyMap(), 1000)).isEqualTo("SELECT 7") + } + + @Test + fun `a NUL in the path or the project folder is the documented error, not an IOException`() { + template("t.sql.peb", "SELECT 1") + assertThrows(IllegalArgumentException::class.java) { service().renderPlain("a\u0000b.sql.peb") } + val nul = File("/tmp/pro\u0000ject") + assertThrows(IllegalStateException::class.java) { service(project = nul).listTemplates() } + assertThrows(IllegalStateException::class.java) { service(project = nul).getRoomSchemas() } + assertThrows(IllegalStateException::class.java) { service(project = nul).renderPlain("t.sql.peb") } + } + + @Test + fun `after close every call fails, and reopen lets them through again`() { + template("t.sql.peb", "SELECT 1") + val service = service() + service.close() + assertThrows(CancellationException::class.java) { service.renderPlain("t.sql.peb") } + assertThrows(CancellationException::class.java) { service.listTemplates() } + assertThrows(CancellationException::class.java) { service.getRoomSchemas() } + service.reopen() + assertThat(service.renderPlain("t.sql.peb")).isEqualTo("SELECT 1") + assertThat(service.listTemplates()).containsExactly("t.sql.peb") + } + + @Test + fun `a service started closed refuses until it is reopened`() { + template("t.sql.peb", "SELECT 1") + val closed = SqlTemplateServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { root }, { false }, startOpen = false) + assertThrows(CancellationException::class.java) { closed.listTemplates() } + closed.reopen() + assertThat(closed.getRoomSchemas()).isEmpty() + } + + @Test + fun `a reserved variable name is refused`() { + template("t.sql.peb", "SELECT 1") + assertThrows(IllegalArgumentException::class.java) { service().render("t.sql.peb", mapOf("project" to "x"), emptyMap(), 1000) } + } + + @Test + fun `a missing template is a template error, and no project is a state error`() { + val e = + assertThrows(SqlTemplateException::class.java) { + service().render("nope.sql.peb", emptyMap(), emptyMap(), 1000) + } + assertThat(e).hasMessageThat().contains("nope.sql.peb could not be read") + assertThrows(IllegalStateException::class.java) { + service(project = null).render("t.sql.peb", emptyMap(), emptyMap(), 1000) + } + assertThat(service(project = null).listTemplates()).isEmpty() + assertThat(service(project = null).getRoomSchemas()).isEmpty() + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/MinSdkCallsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/MinSdkCallsTest.kt new file mode 100644 index 0000000000..cd1aeb2e6f --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/MinSdkCallsTest.kt @@ -0,0 +1,125 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.manager.services.SqlTemplateServiceImpl +import com.itsaky.androidide.templates.ProjectTemplatePebble +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.DataInputStream +import java.io.File +import java.util.jar.JarFile + +/** + * The SQL template code calls no InputStream method that Android added in API 33 (ADFA-7302). minSdk is 28, desugaring + * backports none of them for these packages (app/build.gradle.kts gives JavaIOReplacements org.eclipse.jgit only), lint + * does not flag them here, and these tests run on a JDK that has them. The check reads each class file's method + * references, so the older Files.readAllBytes and FileChannel.transferTo pass. + */ +class MinSdkCallsTest { + @Test + fun `the template code calls no InputStream method that needs API 33`() { + val classes = + classFiles(ProjectSqlFiles::class.java) { it.endsWith(".class") } + + nested(SqlTemplateServiceImpl::class.java) + + nested(ProjectTemplatePebble::class.java) + assertThat(classes.keys).containsAtLeast("ProjectSqlFiles.class", "SqlTemplateServiceImpl.class", "ProjectTemplatePebble.class") + // The reader finds a call ProjectSqlFiles makes, so an empty result below is not a parse that found nothing. + assertThat(methodRefs(classes.getValue("ProjectSqlFiles.class"))).contains("java/nio/file/Files.newInputStream") + + val calls = + classes.flatMap { (name, bytes) -> + methodRefs(bytes) + .filter { it.substringBefore('.').endsWith("InputStream") && it.substringAfter('.') in API_33 } + .map { "$name: $it" } + } + assertThat(calls).isEmpty() + } + + private companion object { + val API_33 = setOf("readAllBytes", "readNBytes", "skipNBytes", "transferTo") + } + + /** [type] and its nested and lambda classes. */ + private fun nested(type: Class<*>): Map { + val simple = type.simpleName + return classFiles(type) { it == "$simple.class" || (it.startsWith("$simple$") && it.endsWith(".class")) } + } + + /** The files in [type]'s package, not its subpackages, whose names [keep] accepts, by file name. */ + private fun classFiles( + type: Class<*>, + keep: (String) -> Boolean, + ): Map { + val pkg = type.name.substringBeforeLast('.').replace('.', '/') + "/" + val source = type.protectionDomain.codeSource + val location = File(source.location.toURI()) + // A module's classes are a jar on the unit test classpath, or a folder. + if (location.isDirectory) { + return File(location, pkg).listFiles { f -> f.isFile && keep(f.name) }!!.associate { it.name to it.readBytes() } + } + return JarFile(location).use { jar -> + jar + .entries() + .toList() + .filter { it.name.startsWith(pkg) && '/' !in it.name.substring(pkg.length) && keep(it.name.substring(pkg.length)) } + .associate { it.name.substring(pkg.length) to jar.getInputStream(it).use { s -> s.readBytes() } } + } + } + + /** [classFile]'s method references, as `owner.name` with the owner in internal form, read from its constant pool. */ + private fun methodRefs(classFile: ByteArray): Set { + val input = DataInputStream(ByteArrayInputStream(classFile)) + check(input.readInt() == 0xCAFEBABE.toInt()) { "not a class file" } + input.skipBytes(4) // minor and major version + val count = input.readUnsignedShort() + val utf8 = arrayOfNulls(count) + val className = IntArray(count) + val nameOf = IntArray(count) + val refs = mutableListOf>() + var i = 1 + while (i < count) { + when (val tag = input.readUnsignedByte()) { + 1 -> { + utf8[i] = input.readUTF() + } + + 3, 4, 9, 17, 18 -> { + input.skipBytes(4) + } + + 5, 6 -> { + // A long or a double takes two entries. + input.skipBytes(8) + i++ + } + + 7 -> { + className[i] = input.readUnsignedShort() + } + + 8, 16, 19, 20 -> { + input.skipBytes(2) + } + + 10, 11 -> { + refs += input.readUnsignedShort() to input.readUnsignedShort() + } + + 12 -> { + nameOf[i] = input.readUnsignedShort() + input.skipBytes(2) + } + + 15 -> { + input.skipBytes(3) + } + + else -> { + error("unknown constant pool tag $tag") + } + } + i++ + } + return refs.mapTo(HashSet()) { (owner, nameAndType) -> "${utf8[className[owner]]}.${utf8[nameOf[nameAndType]]}" } + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/ProjectSqlFilesTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/ProjectSqlFilesTest.kt new file mode 100644 index 0000000000..f877d32846 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/ProjectSqlFilesTest.kt @@ -0,0 +1,199 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import com.google.common.truth.Truth.assertThat +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.File +import java.nio.file.Files + +class ProjectSqlFilesTest { + private val root = Files.createTempDirectory("project").toFile() + + @After + fun cleanUp() { + root.deleteRecursively() + } + + private fun write( + path: String, + text: String, + ) = File(root, path).apply { + parentFile!!.mkdirs() + writeText(text) + } + + /** Room 2.8 output for a database with one entity and nothing else: no indices, foreignKeys or views keys. */ + private fun schema( + version: Int, + hash: String, + ) = """ + { + "formatVersion": 1, + "database": { + "version": $version, + "identityHash": "$hash", + "entities": [ + { + "tableName": "User", + "createSql": "CREATE TABLE IF NOT EXISTS `${'$'}{TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`))", + "fields": [ + {"fieldPath": "id", "columnName": "id", "affinity": "INTEGER", "notNull": true}, + {"fieldPath": "name", "columnName": "name", "affinity": "TEXT"} + ], + "primaryKey": {"autoGenerate": false, "columnNames": ["id"]} + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '$hash')" + ] + } + } + """.trimIndent() + + @Test + fun `a schema missing indices, foreignKeys and views reads them as empty`() { + val s = ProjectSqlFiles.parseRoomSchema(schema(3, "abc"), "com.example.AppDatabase", "app/schemas/x/3.json")!! + assertThat(s.className).isEqualTo("com.example.AppDatabase") + assertThat(s.version).isEqualTo(3) + assertThat(s.identityHash).isEqualTo("abc") + assertThat(s.views).isEmpty() + val user = s.entities.single() + assertThat(user["tableName"]).isEqualTo("User") + assertThat(user["indices"] as List<*>).isEmpty() + assertThat(user["foreignKeys"] as List<*>).isEmpty() + assertThat(user["createSql"] as String).contains("\${TABLE_NAME}") + val fields = user["fields"] as List<*> + assertThat((fields[0] as Map<*, *>)["notNull"]).isEqualTo(true) + assertThat((user["primaryKey"] as Map<*, *>)["columnNames"]).isEqualTo(listOf("id")) + } + + @Test + fun `indices, foreignKeys and views that are there are kept`() { + val text = + """ + {"formatVersion": 1, "database": {"version": 2, "identityHash": "h", "entities": [ + {"tableName": "Book", "fields": [], "primaryKey": {"autoGenerate": true, "columnNames": ["id"]}, + "indices": [{"name": "index_Book_userId", "unique": false, "columnNames": ["userId"]}], + "foreignKeys": [{"table": "User", "onDelete": "CASCADE", "columns": ["userId"], "referencedColumns": ["id"]}]}], + "views": [{"viewName": "Names", "createSql": "CREATE VIEW `${'$'}{VIEW_NAME}` AS SELECT name FROM User"}]}} + """.trimIndent() + val s = ProjectSqlFiles.parseRoomSchema(text, "Db", "2.json")!! + val book = s.entities.single() + assertThat(((book["indices"] as List<*>).single() as Map<*, *>)["name"]).isEqualTo("index_Book_userId") + assertThat(((book["foreignKeys"] as List<*>).single() as Map<*, *>)["onDelete"]).isEqualTo("CASCADE") + assertThat(s.views.single()["viewName"]).isEqualTo("Names") + assertThat((book["primaryKey"] as Map<*, *>)["autoGenerate"]).isEqualTo(true) + } + + @Test + fun `JSON that is not Room's is not a schema`() { + assertThat(ProjectSqlFiles.parseRoomSchema("""{"version": 1}""", "a.B", "1.json")).isNull() + assertThat(ProjectSqlFiles.parseRoomSchema("""{"formatVersion": 1, "database": {"version": 1}}""", "a.B", "1.json")).isNull() + assertThat(ProjectSqlFiles.parseRoomSchema("not json", "a.B", "1.json")).isNull() + } + + @Test + fun `finds the exported schemas, skipping build output and hidden folders`() { + write("app/schemas/com.example.AppDatabase/1.json", schema(1, "h1")) + write("app/schemas/com.example.AppDatabase/2.json", schema(2, "h2")) + write("lib/schemas/com.example.CacheDb/1.json", schema(1, "c1")) + write("app/build/intermediates/room/schemas/com.example.AppDatabase/3.json", schema(3, "copy")) + write(".gradle/com.example.AppDatabase/4.json", schema(4, "hidden")) + write("app/src/main/assets/data/1.json", """{"not": "room"}""") + val found = ProjectSqlFiles.roomSchemas(root) + assertThat(found.map { "${it.className} ${it.version} ${it.identityHash} ${it.path}" }) + .containsExactly( + "com.example.AppDatabase 1 h1 app/schemas/com.example.AppDatabase/1.json", + "com.example.AppDatabase 2 h2 app/schemas/com.example.AppDatabase/2.json", + "com.example.CacheDb 1 c1 lib/schemas/com.example.CacheDb/1.json", + ).inOrder() + } + + @Test + fun `lists the sql templates`() { + write("sqlite/report.sql.peb", "SELECT 1") + write("app/sqlite/a.sql.peb", "SELECT 2") + write("sqlite/notes.peb", "not sql") + write("build/out.sql.peb", "copied") + assertThat(ProjectSqlFiles.templates(root)).containsExactly("app/sqlite/a.sql.peb", "sqlite/report.sql.peb").inOrder() + } + + @Test + fun `a schema file nested too deep is skipped and the others are still found`() { + val depth = ProjectSqlFiles.MAX_JSON_DEPTH * 2 + val head = """{"formatVersion": 1, "database": {"version": 1, "identityHash": "h", "entities": [""" + val deep = head + "[".repeat(depth) + "]".repeat(depth) + "]}}" + write("app/schemas/com.example.Deep/1.json", deep) + write("app/schemas/com.example.Fine/1.json", schema(1, "ok")) + assertThat(ProjectSqlFiles.roomSchemas(root).map { it.className }).containsExactly("com.example.Fine") + } + + @Test + fun `past the limit, the entries kept are the first in the documented order, wherever the walk met them`() { + val per = ProjectSqlFiles.MAX_MATCHES * 3 / 4 + for (dir in listOf("a", "z")) for (i in 0 until per) write("$dir/t$i.sql.peb", "x") + val all = (listOf("a", "z").flatMap { d -> (0 until per).map { "$d/t$it.sql.peb" } }).sorted() + assertThat(ProjectSqlFiles.templates(root)).containsExactlyElementsIn(all.take(ProjectSqlFiles.MAX_MATCHES)).inOrder() + } + + @Test + fun `readBounded refuses a link, a folder and a file over the limit`() { + val real = write("real.txt", "hello") + assertThat(ProjectSqlFiles.readBounded(real)).isEqualTo("hello") + val link = File(root, "link.txt") + Files.createSymbolicLink(link.toPath(), real.toPath()) + assertThrows(java.io.IOException::class.java) { ProjectSqlFiles.readBounded(link) } + assertThrows(java.io.IOException::class.java) { ProjectSqlFiles.readBounded(File(root, "nope")) } + val folder = File(root, "dir").apply { mkdirs() } + assertThrows(java.io.IOException::class.java) { ProjectSqlFiles.readBounded(folder) } + val exact = write("exact.txt", "a".repeat(ProjectSqlFiles.MAX_FILE_BYTES.toInt())) + assertThat(ProjectSqlFiles.readBounded(exact)).hasLength(ProjectSqlFiles.MAX_FILE_BYTES.toInt()) + val over = write("over.txt", "a".repeat(ProjectSqlFiles.MAX_FILE_BYTES.toInt() + 1)) + assertThrows(ProjectSqlFiles.TooLarge::class.java) { ProjectSqlFiles.readBounded(over) } + } + + // F03: one rule for a file that is a link, for listing and for reading. + @Test + fun `a schema or template that is a link inside the project is listed and read, one that leads outside is skipped with a note`() { + val real = root.canonicalFile + val outside = Files.createTempDirectory("outside").toFile() + try { + File(outside, "9.json").writeText(schema(9, "out")) + File(outside, "o.sql.peb").writeText("SELECT 1") + write("app/schemas/com.example.AppDatabase/1.json", schema(1, "h1")) + write("sql/real.sql.peb", "SELECT 1") + val schemaDir = File(real, "app/schemas/com.example.AppDatabase") + Files.createSymbolicLink(File(schemaDir, "2.json").toPath(), File(schemaDir, "1.json").toPath()) + Files.createSymbolicLink(File(schemaDir, "9.json").toPath(), File(outside, "9.json").toPath()) + Files.createSymbolicLink(File(real, "sql/inside.sql.peb").toPath(), File(real, "sql/real.sql.peb").toPath()) + Files.createSymbolicLink(File(real, "sql/outside.sql.peb").toPath(), File(outside, "o.sql.peb").toPath()) + + val notes = ArrayList() + val found = ProjectSqlFiles.roomSchemas(real) { notes += it } + assertThat(found.map { "${it.version} ${it.path}" }) + .containsExactly( + "1 app/schemas/com.example.AppDatabase/1.json", + // Read through the link, so it holds what 1.json holds. + "1 app/schemas/com.example.AppDatabase/2.json", + ).inOrder() + assertThat(notes) + .containsExactly("app/schemas/com.example.AppDatabase/9.json was skipped: it is a link to a file outside the project") + + notes.clear() + assertThat(ProjectSqlFiles.templates(real) { notes += it }).containsExactly("sql/inside.sql.peb", "sql/real.sql.peb").inOrder() + assertThat(notes).containsExactly("sql/outside.sql.peb was skipped: it is a link to a file outside the project") + } finally { + outside.deleteRecursively() + } + } + + @Test + fun `a schema that cannot be read is reported to the caller, not dropped silently`() { + write("app/schemas/com.example.AppDatabase/1.json", "a".repeat(ProjectSqlFiles.MAX_FILE_BYTES.toInt() + 1)) + val notes = ArrayList() + assertThat(ProjectSqlFiles.roomSchemas(root.canonicalFile) { notes += it }).isEmpty() + assertThat(notes.single()).startsWith("app/schemas/com.example.AppDatabase/1.json was skipped: larger than") + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlTemplateRendererTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlTemplateRendererTest.kt new file mode 100644 index 0000000000..1dce2a64b0 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/sqltemplate/SqlTemplateRendererTest.kt @@ -0,0 +1,370 @@ +package com.itsaky.androidide.plugins.manager.services.sqltemplate + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.services.SqlTemplateException +import com.itsaky.androidide.plugins.services.SqlTemplateFunction +import org.junit.Assert.assertThrows +import org.junit.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.function.Supplier + +class SqlTemplateRendererTest { + private fun render( + text: String, + variables: Map = emptyMap(), + functions: Map = emptyMap(), + timeoutMillis: Long = 5_000, + ) = SqlTemplateRenderer.render("t.sql.peb", text, variables, functions, timeoutMillis) + + private fun failure( + text: String, + variables: Map = emptyMap(), + functions: Map = emptyMap(), + timeoutMillis: Long = 5_000, + ): String = assertThrows(SqlTemplateException::class.java) { render(text, variables, functions, timeoutMillis) }.message!! + + @Test + fun `uses the project templates' delimiters and newline trimming`() { + val text = "SELECT\${% if wide %}\n *\${% else %}\n id\${% endif %}\nFROM t \${# a comment #}\n;" + // A closing %} or #} eats the line break after it, as in a project template. + assertThat(render(text, mapOf("wide" to true))).isEqualTo("SELECT *FROM t ;") + assertThat(render("\${{ a }} \${{ b }}", mapOf("a" to 1L, "b" to "x"))).isEqualTo("1 x") + } + + @Test + fun `autoescaping is off`() { + assertThat(render("\${{ s }}", mapOf("s" to "a < b && c > 'd'"))).isEqualTo("a < b && c > 'd'") + } + + @Test + fun `sql_ident quotes a name and doubles its quotes`() { + assertThat(render("SELECT * FROM \${{ t | sql_ident }}", mapOf("t" to "we\"ird table"))) + .isEqualTo("SELECT * FROM \"we\"\"ird table\"") + assertThat(failure("\${{ n | sql_ident }}", mapOf("n" to 3L))).contains("sql_ident at line 1 needs a string, not a Long") + assertThat(failure("\${{ n | sql_ident }}", mapOf("n" to null))).contains("needs a string, not null") + assertThat(failure("\${{ n | sql_ident }}", mapOf("n" to "a\u0000b"))).contains("NUL") + } + + @Test + fun `sql_literal writes literals that read back the same`() { + val variables = + mapOf( + "s" to "it's", + "n" to null, + "l" to -42L, + "d" to 2.5, + "whole" to 2.0, + "big" to 1e300, + "yes" to true, + "no" to false, + ) + val text = + "\${{ s | sql_literal }} \${{ n | sql_literal }} \${{ l | sql_literal }} \${{ d | sql_literal }} " + + "\${{ whole | sql_literal }} \${{ big | sql_literal }} \${{ yes | sql_literal }} \${{ no | sql_literal }}" + assertThat(render(text, variables)).isEqualTo("'it''s' NULL (-42) 2.5 2.0 1.0E300 1 0") + assertThat(failure("\${{ x | sql_literal }}", mapOf("x" to Double.NaN))).contains("NaN has no SQL literal") + assertThat(failure("\${{ x | sql_literal }}", mapOf("x" to "a\u0000"))).contains("NUL") + assertThat(failure("\${{ x | sql_literal }}", mapOf("x" to listOf(1L)))).contains("cannot quote") + } + + @Test + fun `an unknown variable is an error naming it and its line`() { + assertThat(failure("SELECT 1\n\${{ missing }}")).contains("missing") + assertThat(failure("SELECT 1\n\${{ missing }}")).contains("line 2") + } + + @Test + fun `a supplier is called only when the template reads it, and once`() { + val calls = AtomicInteger() + val counted = Supplier { calls.incrementAndGet() * 10L } + assertThat(render("\${% if false %}\${{ lazy }}\${% endif %}x", mapOf("lazy" to counted))).isEqualTo("x") + assertThat(calls.get()).isEqualTo(0) + assertThat(render("\${{ lazy }} \${{ lazy }}", mapOf("lazy" to counted))).isEqualTo("10 10") + assertThat(calls.get()).isEqualTo(1) + // in a map and a list too, and still once when read twice through them + val nestedCalls = AtomicInteger() + val nested = + mapOf( + "db" to + mapOf( + "tables" to + listOf( + Supplier { + nestedCalls.incrementAndGet() + "users" + }, + ), + ), + ) + assertThat(render("\${{ db.tables[0] | sql_ident }} \${{ db.tables[0] }}", nested)).isEqualTo("\"users\" users") + assertThat(nestedCalls.get()).isEqualTo(1) + // reading one element of a list, even twice, reads none of the others + val other = AtomicInteger() + val list = + mapOf( + "l" to + listOf( + Supplier { "a" }, + Supplier { + other.incrementAndGet() + "b" + }, + ), + ) + assertThat(render("\${{ l[0] }}\${{ l[0] }}", list)).isEqualTo("aa") + assertThat(other.get()).isEqualTo(0) + } + + @Test + fun `a function runs only when called, with its arguments in order`() { + val seen = mutableListOf>() + val rowCount = + SqlTemplateFunction { args -> + seen += args + 7L + } + val functions = mapOf("row_count" to rowCount) + assertThat(render("\${% if false %}\${{ row_count('a', 't') }}\${% endif %}none", functions = functions)).isEqualTo("none") + assertThat(seen).isEmpty() + assertThat(render("\${{ row_count('a.db', 'users') + 1 }}", functions = functions)).isEqualTo("8") + assertThat(seen).containsExactly(listOf("a.db", "users")) + } + + @Test + fun `a function's value can be a list of maps the template loops over`() { + val sample = SqlTemplateFunction { listOf(mapOf("id" to 1L), mapOf("id" to 2L)) } + val text = "\${% for r in sample_rows() %}\${{ r.id }},\${% endfor %}" + assertThat(render(text, functions = mapOf("sample_rows" to sample))).isEqualTo("1,2,") + } + + @Test + fun `a failing function stops the render with its name and error`() { + val fails = SqlTemplateFunction { throw IllegalStateException("no such table: t") } + val message = failure("SELECT\n\${{ row_count('a', 't') }}", functions = mapOf("row_count" to fails)) + assertThat(message).contains("row_count(...) at line 2 failed: no such table: t") + } + + @Test + fun `the time limit covers the whole render and interrupts a function`() { + val interrupted = CountDownLatch(1) + val slow = + SqlTemplateFunction { + try { + Thread.sleep(10_000) + } catch (e: InterruptedException) { + interrupted.countDown() + throw e + } + 1L + } + val started = System.nanoTime() + val message = failure("\${{ slow() }}", functions = mapOf("slow" to slow), timeoutMillis = 200) + assertThat(message).contains("did not finish within 200 ms") + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(5_000L) + assertThat(interrupted.await(5, TimeUnit.SECONDS)).isTrue() + } + + @Test + fun `bad names, values and limits are refused before rendering`() { + val fn = SqlTemplateFunction { null } + assertThrows(IllegalArgumentException::class.java) { render("x", functions = mapOf("row-count" to fn)) } + assertThrows(IllegalArgumentException::class.java) { render("x", functions = mapOf("range" to fn)) } + assertThrows(IllegalArgumentException::class.java) { render("x", functions = mapOf("sql_literal" to fn)) } + assertThrows(IllegalArgumentException::class.java) { render("x", mapOf("when" to java.util.Date())) } + assertThrows(IllegalArgumentException::class.java) { render("x", mapOf("m" to mapOf(1 to "a"))) } + assertThrows(IllegalArgumentException::class.java) { render("x", timeoutMillis = 0) } + } + + @Test + fun `a supplier or function that returns another type fails the render`() { + assertThat(failure("\${{ v }}", mapOf("v" to Supplier { Any() }))).contains("cannot be a template value") + assertThat(failure("\${{ f() }}", functions = mapOf("f" to SqlTemplateFunction { Any() }))).contains("cannot be a template value") + } + + @Test + fun `a render past the size limit fails`() { + val text = "\${% for i in range(1, 5000) %}\${{ chunk }}\${% endfor %}" + assertThat(failure(text, mapOf("chunk" to "x".repeat(1024)))).contains("Tried to write more than") + } + + private fun renderThreads() = Thread.getAllStackTraces().keys.filter { it.name == "sql-template-render" && it.isAlive } + + private fun awaitNoRenderThread(): Boolean { + val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (System.nanoTime() < until) { + if (renderThreads().isEmpty()) return true + Thread.sleep(20) + } + return false + } + + @Test + fun `a busy loop that writes nothing is stopped by the time limit and its thread ends`() { + val message = + failure("\${% for i in range(1, 100000) %}\${% for j in range(1, 100000) %}\${% endfor %}\${% endfor %}", timeoutMillis = 200) + assertThat(message).contains("did not finish within 200 ms") + assertThat(awaitNoRenderThread()).isTrue() + } + + // About 2^40 calls that write nothing, so neither the output cap nor the stack ends it. + @Test + fun `a recursive macro is stopped by the time limit and its thread ends`() { + val text = + "\${% macro f(n) %}\${% if n > 0 %}\${{ f(n - 1) }}\${{ f(n - 1) }}\${% endif %}\${% endmacro %}\${{ f(40) }}" + assertThat(failure(text, timeoutMillis = 200)).contains("did not finish within 200 ms") + assertThat(awaitNoRenderThread()).isTrue() + } + + // A template is its own text (StringLoader), so a template can include itself; the same 2^40 shape as the macro. + @Test + fun `a template that includes itself is stopped by the time limit and its thread ends`() { + val self = "\${% if n > 0 %}\${% include s with {\"n\": n - 1} %}\${% include s with {\"n\": n - 1} %}\${% endif %}" + val text = "\${% include s with {\"n\": 40} %}" + assertThat(failure(text, mapOf("s" to self), timeoutMillis = 200)).contains("did not finish within 200 ms") + assertThat(awaitNoRenderThread()).isTrue() + } + + @Test + fun `a macro and an include still render`() { + val text = "\${% macro twice(x) %}\${{ x }}\${{ x }}\${% endmacro %}\${{ twice(\"ab\") }}-\${% include s with {\"v\": 3} %}" + assertThat(render(text, mapOf("s" to "[\${{ v }}]"))).isEqualTo("abab-[3]") + } + + @Test + fun `a loop over a map or list still works, with its loop variables`() { + val text = "\${% for k in m %}\${{ k.key }}=\${{ k.value }}:\${{ loop.index }}/\${{ loop.length }},\${% endfor %}" + assertThat(render(text, mapOf("m" to mapOf("a" to 1L, "b" to 2L)))).isEqualTo("a=1:0/2,b=2:1/2,") + assertThat(render("\${% for x in l %}\${{ x }}\${% else %}none\${% endfor %}", mapOf("l" to emptyList()))).isEqualTo("none") + } + + @Test + fun `range past the cap fails with a clear error, and a normal range is unchanged`() { + val message = failure("\${% for i in range(1, 9999999999) %}\${% endfor %}") + assertThat(message).contains("the most is 100000") + assertThat(failure("\${% for i in range(0, 100000) %}\${% endfor %}")).contains("the most is 100000") + assertThat(render("\${% for i in range(1, 100000) %}\${% endfor %}ok")).isEqualTo("ok") + assertThat(render("\${% for i in range(1, 5) %}\${{ i }}\${% endfor %}")).isEqualTo("12345") + assertThat(render("\${% for i in range(10, 1, -3) %}\${{ i }},\${% endfor %}")).isEqualTo("10,7,4,1,") + assertThat(render("\${% for i in range(5, 1) %}\${{ i }}\${% endfor %}none")).isEqualTo("none") + assertThat(render("\${% for c in range('a', 'e', 2) %}\${{ c }}\${% endfor %}")).isEqualTo("ace") + assertThat(render("\${% for i in range(1, 9, increment=4) %}\${{ i }},\${% endfor %}")).isEqualTo("1,5,9,") + assertThat(failure("\${% for i in range(1, 5, 0) %}\${% endfor %}")).contains("different than 0") + assertThat(failure("\${% for i in range(1, 'z') %}\${% endfor %}")).contains("Number or String") + assertThat(failure("\${% for i in range(-9223372036854775807, 9223372036854775807) %}\${% endfor %}")).contains("the most is") + } + + // F01: strings a template builds without printing them must not exhaust memory. + @Test + fun `doubling a string by concatenation fails promptly with the limit message`() { + val started = System.nanoTime() + val message = failure("\${% set s = \"x\" %}\${% for i in range(1, 40) %}\${% set s = s ~ s %}\${% endfor %}") + assertThat(message).contains("is too long: the most is 4194304") + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(3_000) + assertThat(failure("\${% set s = \"x\" %}\${% for i in range(1, 40) %}\${% set s = s + s %}\${% endfor %}")) + .contains("is too long") + // Not stored by set: passed on to an include. + val big = mapOf("s" to "x".repeat(3_000_000), "t" to "") + assertThat(failure("\${% include t with {\"s\": s ~ s} %}", big)).contains("is too long") + assertThat(failure("\${{ f(s ~ s) }}", big, mapOf("f" to SqlTemplateFunction { "" }))).contains("is too long") + } + + @Test + fun `doubling a list or growing a string by replace or join fails with a limit message`() { + assertThat(failure("\${% set l = [1] %}\${% for i in range(1, 40) %}\${% set l = l | merge(l) %}\${% endfor %}")) + .contains("is too long") + val grow = "\${% set s = s | replace({\"x\": s}) %}" + assertThat(failure("\${% set s = \"xxxxxxxx\" %}\${% for i in range(1, 40) %}$grow\${% endfor %}")).contains("the most is 4194304") + assertThat(failure("\${{ s | replace({\"x\": s}) }}", mapOf("s" to "x".repeat(3_000)))).contains("replace would make a string") + assertThat(failure("\${{ l | join(s) }}", mapOf("l" to List(100) { "a" }, "s" to "x".repeat(100_000)))).contains("join would make") + } + + // F09: the last item and its separator count toward the limit too. + @Test + fun `join fails when the last item and separator take it one past the limit`() { + val most = SqlLimits.MAX_STRING_CHARS + val items = listOf("x".repeat(most - 1), "y") + assertThat(failure("\${{ (l | join(\"z\")) | length }}", mapOf("l" to items))).contains("join would make") + assertThat(render("\${{ (l | join(\"\")) | length }}", mapOf("l" to items))).isEqualTo(most.toString()) + } + + // An array is a list too: Pebble's split returns one. + @Test + fun `a set of a split into more than the entry limit fails, and a normal split works`() { + val big = "x".repeat(2 * 1024 * 1024) + assertThat(failure("\${% set p = s | split('') %}", mapOf("s" to big))).contains("split would make a list of more than 1000000") + val text = "\${% set p = s | split(',') %}\${{ p | length }}\${{ p | join('-') }}" + assertThat(render(text, mapOf("s" to "a,b,c"))).isEqualTo("3a-b-c") + } + + @Test + fun `split refuses too many pieces before building them, and keeps Pebble's regex and limit behaviour`() { + val big = "x".repeat(4 * 1024 * 1024) + // Not stored by set, so only the filter's own check can fail it. + assertThat(failure("\${{ (s | split('')) | length }}", mapOf("s" to big))).contains("split would make a list of more than 1000000") + assertThat(failure("\${{ (s | split('x')) | length }}", mapOf("s" to big))).contains("split would make a list of more than 1000000") + assertThat(failure("\${{ (s | split('x', -1)) | length }}", mapOf("s" to big))).contains("split would make") + // A limit within the cap is Pebble's own: at most that many pieces. + assertThat(render("\${{ (s | split('', 3)) | length }}", mapOf("s" to big))).isEqualTo("3") + assertThat(render("\${{ (s | split('[,;] *')) | join('|') }}", mapOf("s" to "a, b;c,d"))).isEqualTo("a|b|c|d") + assertThat(render("\${{ (s | split(',')) | join('|') }}", mapOf("s" to "a,b,,"))).isEqualTo("a|b") + assertThat(render("\${{ (s | split(',', -1)) | length }}", mapOf("s" to "a,b,,"))).isEqualTo("4") + assertThat(render("\${{ (s | split('')) | join('-') }}", mapOf("s" to "abc"))).isEqualTo("a-b-c") + assertThat(render("\${{ (s | split(',')) | length }}", mapOf("s" to ""))).isEqualTo("1") + } + + @Test + fun `normal concatenation, set, replace and join still work`() { + assertThat(render("\${% set s = \"a\" ~ \"b\" ~ 1 ~ null %}\${{ s }}")).isEqualTo("ab1") + assertThat(render("\${{ 1 + 2 }},\${{ \"a\" + \"b\" }}")).isEqualTo("3,ab") + assertThat(render("\${% set s = \"x\" %}\${% for i in range(1, 20) %}\${% set s = s ~ s %}\${% endfor %}\${{ s | length }}")) + .isEqualTo("1048576") + assertThat(render("\${{ \"a-b-c\" | replace({\"-\": \"+\", \"c\": \"dd\"}) }}")).isEqualTo("a+b+dd") + assertThat(render("\${{ \"abc\" | replace({\"\": \".\"}) }}")).isEqualTo(".a.b.c.") + assertThat(render("\${{ l | join(\", \") }}|\${{ l | join }}", mapOf("l" to listOf("a", 2L, null)))).isEqualTo("a, 2, null|a2null") + assertThat(render("\${{ l | join(\";\") }}", mapOf("l" to listOf(listOf(1L, 2L), mapOf("k" to "v"))))).isEqualTo("[1, 2];{k=v}") + } + + @Test + fun `a negative number is in parentheses, so a minus before it cannot make a comment`() { + assertThat(render("1-\${{ x | sql_literal }}", mapOf("x" to -5L))).isEqualTo("1-(-5)") + assertThat(render("1-\${{ x | sql_literal }}", mapOf("x" to -2.5))).isEqualTo("1-(-2.5)") + assertThat(render("1-\${{ x | sql_literal }}", mapOf("x" to java.math.BigDecimal("-0.50")))).isEqualTo("1-(-0.50)") + assertThat( + render("1-\${{ x | sql_literal }}", mapOf("x" to java.math.BigInteger("-70000000000000000000"))), + ).isEqualTo("1-(-70000000000000000000)") + assertThat(render("\${{ x | sql_literal }}", mapOf("x" to 5L))).isEqualTo("5") + } + + @Test + fun `a function called with a named argument fails the render instead of getting null`() { + val calls = AtomicInteger() + val fn = + SqlTemplateFunction { + calls.incrementAndGet() + 1L + } + val message = failure("\${{ f(a=1) }}", functions = mapOf("f" to fn)) + assertThat(message).contains("f(...) at line 1: named arguments (a) are not supported") + assertThat(failure("\${{ f(1, b=2) }}", functions = mapOf("f" to fn))).contains("named arguments (b)") + assertThat(calls.get()).isEqualTo(0) + assertThat(render("\${{ f(1, 2) }}", functions = mapOf("f" to fn))).isEqualTo("1") + } + + @Test + fun `a supplier a function returns is read once, alone or inside a list or map`() { + val calls = AtomicInteger() + val functions = + mapOf( + "one" to SqlTemplateFunction { Supplier { "x" + calls.incrementAndGet() } }, + "many" to SqlTemplateFunction { listOf(Supplier { "a" }, Supplier { "b" }) }, + "keyed" to SqlTemplateFunction { mapOf("k" to Supplier { 7L }) }, + ) + assertThat(render("\${{ one() }}", functions = functions)).isEqualTo("x1") + assertThat(render("\${% for v in many() %}\${{ v }}\${% endfor %}", functions = functions)).isEqualTo("ab") + assertThat(render("\${{ keyed().k }}", functions = functions)).isEqualTo("7") + val bad = mapOf("f" to SqlTemplateFunction { Supplier { Any() } }) + assertThat(failure("\${{ f() }}", functions = bad)).contains("cannot be a template value") + } +} diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 293b541e51..ccb1b43c0d 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -89,6 +89,23 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - The header fields no PRAGMA reads come from page 1 through `sqlite_dbpage`, when SQLite has it; otherwise `header_unavailable` says why. The host SQLite in `test.sh` has no `sqlite_dbpage`; whether requery's has it is unchecked. - Never from the file itself: closing any descriptor to it would drop the app's POSIX locks. +### SQL templates (ADFA-7302) + +`.read` with a Pebble template: AI-Agent-MCP fetches the variables here, Code on the Go renders the template (its `SqlTemplateService`), and the functions a template calls are tool calls back to this server. +- **`get_template_variables`.** What a template can use without reading the app's rows, in one call: + - **App and device**, from `DebuggerStartup`: package, `version_name`, `version_code`; API level, ABI, ABIs and locale (read on each call). + - **Per database:** path, name, `user_version`, journal mode, page size and count, and `library` for a database a library owns, by file name (only `androidx.work.workdb` so far). + - **Per table:** type (`table`, `virtual`, `shadow`), WITHOUT ROWID, columns (declared type, NOT NULL, default, primary key position, generated), primary key, indexes and foreign keys, and `error` (null, or why one of those lists could not be read). + - **Schema objects:** views (`name`), triggers (`name`, `table`), FTS tables and `sqlite_sequence`. + - **Room**, when `room_master_table` exists: `user_version` as the schema version, the identity hash (row id 42), Room's own tables (`room_master_table` and `room_table_modification_log`, when present; an app's other `room_*` tables are not listed) and its `room_fts_content_sync_` triggers. +- **How it reads.** `pragma_table_list` (SQLite 3.37 and later), `pragma_table_xinfo`, `pragma_index_list`/`pragma_index_xinfo` and `pragma_foreign_key_list`, one query each, paged to 20,000 rows (`truncated` past that), and `sqlite_master` for views, triggers and virtual-table modules. `sqlite_` tables are left out, and a virtual table's hidden columns (FTS's own) too. The lists are separate queries, each taking the lock on its own and paging with OFFSET, so they are not one snapshot: if the app changes its schema during the call, a list can miss a row or repeat one, or disagree with another list. +- **A table that cannot be read.** A virtual table whose module the server connection lacks (`no such module`) fails the join for its columns, indexes or foreign keys. The call then reads each table alone, so only that table loses the list, and its `error` says why; the rest of the database is whole. This is only for that kind of failure (SQLite's generic error naming a module or a virtual table's constructor): any other failure, such as a dropped connection or corruption, puts the whole database in `errors`, and so does every table failing. In the one-table-at-a-time read the same rule applies to each table, and the 20,000-row cap counts all tables together (`truncated` when it is reached). +- **Errors.** A database that fails, for any reason, is listed in `errors` and the others still come. When the call's time limit passes, each database not yet read is in `errors` too, with the error `not read: the call's time limit passed before this database`. +- **Not here:** + - Row counts and other reads of the data: a template calls those as functions, only when it uses them. + - The build type: AGP 8 generates no `BuildConfig` by default, and nothing else tells the library the app's variant. + - Project name and path, and the Room schemas a project exports: Code on the Go adds those. + ## 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. @@ -109,7 +126,7 @@ Capabilities of the sqlite3 shell, in the server so every client has them. All a - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. - **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, binding by name, declared types, the row-recording switch, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. -- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`), the sqlite3 shell tools (`ShellToolsTest`) and `EndpointBroadcast`, its announce receiver included. +- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`), the sqlite3 shell tools (`ShellToolsTest`), `get_template_variables` (`TemplateVariablesTest`) and `EndpointBroadcast`, its announce receiver included. - **Expert:** the C test runs `sqlitedbg_expert_run` on a read-only server connection. It checks that expert suggests the index, lists nothing, traces nothing, and leaves nothing on the server connection, and that no sampling query runs on it. The JNI test runs `suggestIndexes` and the SQL the other shell tools send, against the real SQLite. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt index 4d6598afd6..ee43cd1455 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt @@ -6,12 +6,16 @@ import android.content.Context import android.content.pm.ApplicationInfo import android.database.Cursor import android.net.Uri +import android.os.Build import android.util.Log import org.appdevforall.sqlitedebugger.engine.NativeDebugEngine import org.appdevforall.sqlitedebugger.mcp.DatabaseTools import org.appdevforall.sqlitedebugger.mcp.McpHttp import org.appdevforall.sqlitedebugger.mcp.McpProtocol +import org.json.JSONArray +import org.json.JSONObject import java.io.File +import java.util.Locale import java.util.UUID import kotlin.concurrent.thread @@ -52,7 +56,8 @@ class DebuggerStartup : ContentProvider() { engine: NativeDebugEngine, databaseDir: File, ) { - val tools = DatabaseTools(engine, databaseDir) + val app = appInfo(context) + val tools = DatabaseTools(engine, databaseDir, environment = { JSONObject().put("app", app).put("device", deviceInfo()) }) val token = McpHttp.newToken() val protocol = McpProtocol(tools.tools(), "1", { UUID.randomUUID().toString() }, postTimeLimitMs = DatabaseTools.DEADLINE_MS) val http = McpHttp(protocol, { token }, log = { Log.w(TAG, it) }) @@ -63,6 +68,39 @@ class DebuggerStartup : ContentProvider() { EndpointBroadcast.sendAndListen(context, token, http.boundPort) } + /** + * get_template_variables' app object. No build type: AGP 8 generates no BuildConfig by default, and nothing else + * tells the library the app's variant. Only the package when the package manager fails: the server still starts. + */ + private fun appInfo(context: Context): JSONObject { + val app = JSONObject().put("package", context.packageName) + val info = + try { + context.packageManager.getPackageInfo(context.packageName, 0) + } catch (e: Exception) { + Log.w(TAG, "could not read the app's version", e) + return app + } + val versionCode = + if (Build.VERSION.SDK_INT >= 28) { + info.longVersionCode + } else { + @Suppress("DEPRECATION") + info.versionCode.toLong() + } + return app + .put("version_name", info.versionName ?: JSONObject.NULL) + .put("version_code", versionCode) + } + + /** Read on each call: the user can change the locale while the app runs. */ + private fun deviceInfo(): JSONObject = + JSONObject() + .put("api_level", Build.VERSION.SDK_INT) + .put("abi", Build.SUPPORTED_ABIS.firstOrNull() ?: JSONObject.NULL) + .put("abis", JSONArray(Build.SUPPORTED_ABIS.toList())) + .put("locale", Locale.getDefault().toLanguageTag()) + override fun query( uri: Uri, projection: Array?, 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 131e98ecf4..2c1315c2dd 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 @@ -36,12 +36,18 @@ class DatabaseTools internal constructor( private val databaseDir: File?, private val clock: () -> Long, private val idleScheduler: IdleScheduler, + /** + * get_template_variables' app and device objects, read on each call (the locale can change); null on the JVM. + * Called outside the lock, so it must be quick and thread-safe. + */ + private val environment: () -> JSONObject? = { null }, ) { constructor( engine: DebugEngine, databaseDir: File? = null, clock: () -> Long = System::currentTimeMillis, - ) : this(engine, databaseDir, clock, TimerIdleScheduler()) + environment: () -> JSONObject? = { null }, + ) : this(engine, databaseDir, clock, TimerIdleScheduler(), environment) companion object { const val DEFAULT_MAX_ROWS = 100 @@ -69,6 +75,22 @@ class DatabaseTools internal constructor( const val EVENT_BATCH_BYTES = 256 * 1024 const val MAX_TABLES_FOR_COUNTS = 10 + /** get_template_variables' limit on each list it reads (tables, columns, index columns, foreign key columns). */ + const val MAX_TEMPLATE_ROWS = 20_000 + + /** Databases a library creates, by file name, and the library. */ + val LIBRARY_DATABASES = mapOf("androidx.work.workdb" to "androidx.work") + + /** The prefix of the triggers Room keeps an external-content FTS table in step with. */ + const val ROOM_FTS_SYNC_PREFIX = "room_fts_content_sync_" + + /** What get_template_variables says of a database it did not read because the call's time limit had passed. */ + const val TIME_LIMIT_SKIP = "not read: the call's time limit passed before this database" + + /** The tables Room's runtime creates itself (room-runtime 2.8.4: RoomMasterTable, InvalidationTracker); an app's `room_*` is not one. */ + val ROOM_OWN_TABLES = setOf("room_master_table", "room_table_modification_log") + private val FTS_MODULES = setOf("fts3", "fts4", "fts5") + /** Bound values stop being recorded this long after the last get_events call. */ const val EVENTS_IDLE_MS = 60_000L @@ -387,6 +409,38 @@ class DatabaseTools internal constructor( required = listOf("sql"), ), ) { call, args -> suggestIndexes(call, args) }, + tool( + "get_template_variables", + "Get template variables", + "Returns, in one call, what a SQL template (.read with a Pebble template, rendered by Code on the Go) can use " + + "without reading the app's rows: app (package, version_name, version_code) and device (api_level, abi, abis, " + + "locale), then for each database the app has open (or only database): path, name, library (the library " + + "that owns it, such as androidx.work, recognised by file name; else null), user_version, journal_mode, " + + "page_size, page_count; tables, each with type (table, virtual or shadow, the last for the tables a " + + "virtual table such as FTS keeps its data in), without_rowid, column_count, columns (name, declared_type, " + + "not_null, default as SQL text, primary_key: its position in the key from 1, else 0, generated), " + + "primary_key (column names), indexes (name, unique, origin: c CREATE INDEX, u UNIQUE, pk PRIMARY KEY; " + + "partial; columns, null for an expression) and foreign_keys (table, from, to: null names the parent's " + + "primary key, on_update, on_delete) and error (null, or why this table's columns, indexes or foreign keys could not " + + "be read, as for a virtual table whose module the server lacks; those lists are then empty); views (name) and " + + "triggers (name, table); fts_tables (virtual tables using " + + "fts3, fts4 or fts5); has_sqlite_sequence; and room, null unless the database has room_master_table: " + + "schema_version (user_version), identity_hash, own_tables (room_master_table and room_table_modification_log, " + + "when present) and fts_sync_triggers " + + "(room_fts_content_sync_ triggers). sqlite_ tables are left out. A database that cannot be read is in " + + "errors with the message, and so is each database left unread because the call's time limit passed " + + "(\"not read: ...\"). truncated is true when a list stopped at $MAX_TEMPLATE_ROWS rows. Row counts " + + "and other reads of the data are not here: a template calls them as functions. The lists are read in separate " + + "queries, so they are not one snapshot: if the app changes its schema during the call, a list can miss a row or " + + "repeat one, or disagree with another list. $NON_WAL_NOTE", + JSONObject() + .put("type", "object") + .put("additionalProperties", false) + .put( + "properties", + JSONObject().put("database", prop("string", "Only this database, as list_databases gives it. Default: all.")), + ).put("required", JSONArray()), + ) { call, args -> getTemplateVariables(call, args) }, tool( "lint_foreign_keys", "Check foreign key indexes", @@ -868,6 +922,308 @@ class DatabaseTools internal constructor( return JSONObject().put("foreign_keys", out).put("uncovered", uncovered).put("truncated", list.hasMore) } + private fun getTemplateVariables( + call: Call, + args: JSONObject, + ): JSONObject { + val paths = + if (args.opt("database") == null || args.opt("database") == JSONObject.NULL) { + knownPaths(engine.connections()).sorted() + } else { + listOf(checkedPath(call, args)) + } + val out = JSONObject() + val env = environment() + out.put("app", env?.optJSONObject("app") ?: JSONObject.NULL) + out.put("device", env?.optJSONObject("device") ?: JSONObject.NULL) + val databases = JSONArray() + val errors = JSONArray() + var truncated = false + for ((i, path) in paths.withIndex()) { + try { + val db = TemplateReader(call, path) + databases.put(db.read()) + truncated = truncated || db.truncated + } catch (e: McpToolError) { + errors.put(JSONObject().put("database", path).put("error", e.message)) + if (clock() >= call.deadline) { + // Past the time limit every later database fails the same way: stop, as the call is over, but say which were left. + for (skipped in paths.drop(i + 1)) errors.put(JSONObject().put("database", skipped).put("error", TIME_LIMIT_SKIP)) + break + } + } catch (e: InterruptedException) { + throw e + } catch (e: Exception) { + // One database's odd answer (a value of another type, say) must not lose the others. An Error still propagates. + errors.put(JSONObject().put("database", path).put("error", "${e.javaClass.simpleName}: ${e.message}")) + } + } + return out + .put("databases", databases) + .put("errors", errors) + .put("truncated", truncated) + } + + /** get_template_variables for one database. */ + private inner class TemplateReader( + val call: Call, + val path: String, + ) { + var truncated = false + + private val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) + + /** Every row of [sql], page by page, up to [MAX_TEMPLATE_ROWS]. */ + private fun rows(sql: String): List> { + val all = ArrayList>() + while (true) { + val page = runChecked(call, path, sql, Bind.NONE, all.size.toLong(), limits) + all.addAll(page.rows) + if (!page.hasMore) return all + if (page.rows.isEmpty()) { + // More was promised but none came: the list may be short. + truncated = true + return all + } + if (all.size >= MAX_TEMPLATE_ROWS) { + truncated = true + return all.subList(0, MAX_TEMPLATE_ROWS) + } + } + } + + /** + * Reads one list that joins `pragma_table_list` to a per-table pragma, handing each row to [onRow]. [sql] takes an + * extra condition on `t.name` (empty for every table). A table the pragma cannot read (a virtual table whose module + * this connection lacks fails with "no such module") would fail the whole join and blank the database, so when the + * join fails each table is read alone and only the one that fails loses this list, with the message in its `error`. + * Nothing from a failed attempt is handed over: [rows] returns only a whole list. + */ + private fun readPerTable( + tables: Map, + sql: (String) -> String, + onRow: (List) -> Unit, + ) { + try { + rows(sql("")).forEach(onRow) + } catch (e: McpToolError) { + // Past the time limit, or for a failure no single table caused (a dropped connection, an unknown database, + // corruption), the database is in errors as before: reading each table would only repeat the failure. + if (clock() >= call.deadline || !isPerTableFailure(e)) throw e + var failed = 0 + var first: McpToolError? = null + // The row cap is for the list, not for each table: what the tables read so far counts. + var total = 0 + for (table in tables.values) { + val remaining = MAX_TEMPLATE_ROWS - total + if (remaining <= 0) { + truncated = true + break + } + try { + val got = rows(sql(" AND t.name = '${table.name.replace("'", "''")}'")) + val use = + if (got.size > remaining) { + truncated = true + got.subList(0, remaining) + } else { + got + } + use.forEach(onRow) + total += use.size + } catch (inner: McpToolError) { + // A lock, corruption or the time limit is the database's failure, as for the all-tables query. + if (clock() >= call.deadline || !isPerTableFailure(inner)) throw inner + failed++ + if (first == null) first = inner + if (table.error == null) table.error = inner.message ?: "could not be read" + } + } + // Every table failing is a failure of the database, not of some tables. + if (failed > 0 && failed == tables.size) throw first!! + } + } + + /** + * True for what one table's pragma can raise alone: SQLite's generic error (code 1) for a virtual table whose module + * this connection lacks ("no such module: fts4") or whose constructor fails ("vtable constructor failed"). + */ + private fun isPerTableFailure(e: McpToolError): Boolean = + e.details?.optInt("sqlite_code") == 1 && + Regex("no such module|vtable constructor|virtual table", RegexOption.IGNORE_CASE).containsMatchIn(e.message ?: "") + + private fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", Bind.NONE, 0, limits).rows.firstOrNull()?.firstOrNull() + + fun read(): JSONObject { + val userVersion = pragma("user_version") + val db = + JSONObject() + .put("path", path) + .put("name", File(path).name) + .put("library", LIBRARY_DATABASES[File(path).name] ?: JSONObject.NULL) + .put("user_version", encodeValue(userVersion)) + .put("journal_mode", encodeValue(pragma("journal_mode"))) + .put("page_size", encodeValue(pragma("page_size"))) + .put("page_count", encodeValue(pragma("page_count"))) + + val tables = LinkedHashMap() + var hasSqliteSequence = false + for (row in rows("SELECT name, type, wr FROM pragma_table_list WHERE schema = 'main' AND type <> 'view' ORDER BY name")) { + val name = row[0] as String + if (name == "sqlite_sequence") hasSqliteSequence = true + if (isInternal(name)) continue + tables[name] = TemplateTable(name, row[1] as String, row[2] == 1L) + } + readPerTable( + tables, + { only -> + "SELECT t.name, c.name, c.type, c.\"notnull\", c.dflt_value, c.pk, c.hidden FROM pragma_table_list AS t, " + + "pragma_table_xinfo(t.name, t.schema) AS c WHERE t.schema = 'main' AND t.type <> 'view'$only ORDER BY t.name, c.cid" + }, + ) { row -> + val table = tables[row[0] as String] ?: return@readPerTable + // hidden 1 is a virtual table's hidden column (such as FTS's own); 2 and 3 are generated columns. + val hidden = row[6] as Long + if (hidden == 1L) return@readPerTable + table.columns += + JSONObject() + .put("name", row[1]) + .put("declared_type", row[2]) + .put("not_null", row[3] == 1L) + .put("default", row[4] ?: JSONObject.NULL) + .put("primary_key", row[5]) + .put("generated", hidden >= 2L) + val pk = row[5] as Long + if (pk > 0) table.primaryKey += (pk to row[1] as String) + } + readPerTable( + tables, + { only -> + "SELECT t.name, il.name, il.\"unique\", il.origin, il.partial, ii.name FROM pragma_table_list AS t, " + + "pragma_index_list(t.name, t.schema) AS il, pragma_index_xinfo(il.name, t.schema) AS ii " + + "WHERE t.schema = 'main' AND t.type = 'table' AND ii.key = 1$only ORDER BY t.name, il.name, ii.seqno" + }, + ) { row -> + val table = tables[row[0] as String] ?: return@readPerTable + val name = row[1] as String + val index = + table.indexes.getOrPut(name) { + JSONObject() + .put("name", name) + .put("unique", row[2] == 1L) + .put("origin", row[3]) + .put("partial", row[4] == 1L) + .put("columns", JSONArray()) + } + index.getJSONArray("columns").put(row[5] ?: JSONObject.NULL) + } + readPerTable( + tables, + { only -> + "SELECT t.name, f.id, f.\"table\", f.\"from\", f.\"to\", f.on_update, f.on_delete FROM pragma_table_list AS t, " + + "pragma_foreign_key_list(t.name, t.schema) AS f WHERE t.schema = 'main' AND t.type = 'table'$only " + + "ORDER BY t.name, f.id, f.seq" + }, + ) { row -> + val table = tables[row[0] as String] ?: return@readPerTable + val key = + table.foreignKeys.getOrPut(row[1] as Long) { + JSONObject() + .put("table", row[2]) + .put("from", JSONArray()) + .put("to", JSONArray()) + .put("on_update", row[5]) + .put("on_delete", row[6]) + } + key.getJSONArray("from").put(row[3]) + key.getJSONArray("to").put(row[4] ?: JSONObject.NULL) + } + + val views = JSONArray() + val triggers = JSONArray() + val ftsTables = JSONArray() + val ftsSyncTriggers = JSONArray() + // A virtual table's module is the word after USING; the statement is cut at MAX_TEXT_BYTES, well past it. + for (row in rows( + "SELECT type, name, tbl_name, CASE WHEN type = 'table' THEN sql END FROM sqlite_master " + + "WHERE type IN ('view', 'trigger') OR (type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%') ORDER BY type, name", + )) { + val name = row[1] as String + when (row[0]) { + "view" -> { + views.put(JSONObject().put("name", name)) + } + + "trigger" -> { + triggers.put(JSONObject().put("name", name).put("table", row[2])) + if (name.startsWith(ROOM_FTS_SYNC_PREFIX)) ftsSyncTriggers.put(name) + } + + "table" -> { + if (virtualModule(row[3] as String?)?.lowercase() in FTS_MODULES) ftsTables.put(name) + } + } + } + + db.put("tables", JSONArray(tables.values.map { it.toJson() })) + db.put("views", views) + db.put("triggers", triggers) + db.put("fts_tables", ftsTables) + db.put("has_sqlite_sequence", hasSqliteSequence) + db.put( + "room", + if ("room_master_table" in tables) { + // Room writes its one row with id 42 (RoomMasterTable.DEFAULT_ID). + val hash = + runChecked(call, path, "SELECT identity_hash FROM room_master_table WHERE id = 42", Bind.NONE, 0, limits) + .rows + .firstOrNull() + ?.firstOrNull() + JSONObject() + .put("schema_version", encodeValue(userVersion)) + .put("identity_hash", hash ?: JSONObject.NULL) + .put("own_tables", JSONArray(tables.keys.filter { it in ROOM_OWN_TABLES })) + .put("fts_sync_triggers", ftsSyncTriggers) + } else { + JSONObject.NULL + }, + ) + return db + } + + private fun isInternal(name: String) = name.regionMatches(0, "sqlite_", 0, 7, ignoreCase = true) + } + + private class TemplateTable( + val name: String, + val type: String, + val withoutRowid: Boolean, + ) { + val columns = mutableListOf() + val primaryKey = mutableListOf>() + val indexes = LinkedHashMap() + val foreignKeys = LinkedHashMap() + + /** Why a list of this table could not be read (a virtual table whose module is missing, say), else null. */ + var error: String? = null + + fun toJson(): JSONObject = + JSONObject() + .put("name", name) + .put("type", type) + .put("without_rowid", withoutRowid) + .put("column_count", columns.size) + .put("columns", JSONArray(columns)) + .put("primary_key", JSONArray(primaryKey.sortedBy { it.first }.map { it.second })) + .put("indexes", JSONArray(indexes.values)) + .put("foreign_keys", JSONArray(foreignKeys.values)) + .put("error", error ?: JSONObject.NULL) + } + + /** The module of a CREATE VIRTUAL TABLE statement: the word after USING. */ + private fun virtualModule(sql: String?): String? = + sql?.let { Regex("\\bUSING\\s+([A-Za-z0-9_]+)", RegexOption.IGNORE_CASE).find(it)?.groupValues?.get(1) } + /** One step of a dump: statements known up front, or a table's rows as INSERTs (see [dump]). */ private sealed class DumpUnit { class Fixed( 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 4c66cafed5..536dbfdb23 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 @@ -10,6 +10,8 @@ class FakeDebugEngine( QueryResult(emptyList(), emptyList(), 0, false) }, ) : DebugEngine { + var rawPage: (path: String, sql: String) -> QueryResult? = { _, _ -> null } + val appConnections = mutableListOf() /** Answers suggestIndexes: the path and the SQL. */ @@ -162,6 +164,8 @@ class FakeDebugEngine( check(!closed) { "closed" } lastArgNames = argNames queries += sql to limits + // A page exactly as given, for an answer the paging rule below cannot produce (an empty page with hasMore). + rawPage(path, sql)?.let { return it } 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 65bbe14c8c..d6dc6ecf0d 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 @@ -90,6 +90,7 @@ class DatabaseToolsTest { "get_stats", "integrity_check", "suggest_indexes", + "get_template_variables", "lint_foreign_keys", "dump", "export", diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/TemplateVariablesTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/TemplateVariablesTest.kt new file mode 100644 index 0000000000..0ec82219eb --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/TemplateVariablesTest.kt @@ -0,0 +1,462 @@ +package org.appdevforall.sqlitedebugger.mcp + +import org.appdevforall.sqlitedebugger.engine.AppConnection +import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine +import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * get_template_variables (ADFA-7302). The engine's answers are the rows SQLite 3.53 gave for the same SQL on this + * schema (a Room-like database with an FTS4 table kept in step by Room's triggers): + * + * ``` + * CREATE TABLE room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT); + * CREATE TABLE p(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL DEFAULT 'x', g INT GENERATED ALWAYS AS (id*2)); + * CREATE TABLE c(a INT, b INT, pid INT REFERENCES p(id) ON DELETE CASCADE, PRIMARY KEY(a,b)) WITHOUT ROWID; + * CREATE INDEX ci ON c(pid, a+1); + * CREATE UNIQUE INDEX pn ON p(name) WHERE name<>''; + * CREATE VIRTUAL TABLE f USING fts4(content='p', name); + * CREATE TRIGGER room_fts_content_sync_f_BEFORE_UPDATE BEFORE UPDATE ON p BEGIN DELETE FROM f WHERE docid=OLD.rowid; END; + * CREATE VIEW v AS SELECT * FROM p; + * ``` + */ +class TemplateVariablesTest { + private val engine = + FakeDebugEngine().also { + it.appConnections += AppConnection(1, "/data/app.db", false, false, 1, 5) + it.appConnections += AppConnection(2, "/data/androidx.work.workdb", false, false, 1, 5) + } + private var environment: JSONObject? = null + private var now = 1_000_000L + private val tools = DatabaseTools(engine, null, { now }, environment = { environment }) + + private fun call(args: JSONObject): JSONObject { + val protocol = McpProtocol(tools.tools(), "test", { "s" }, 4) + val init = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 1) + .put("method", "initialize") + .put("params", JSONObject().put("protocolVersion", "2025-06-18")) + val session = protocol.post(init.toString(), null, null).headers[McpProtocol.SESSION_HEADER]!! + val request = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 2) + .put("method", "tools/call") + .put("params", JSONObject().put("name", "get_template_variables").put("arguments", args)) + val r = JSONObject(protocol.post(request.toString(), session, null).body!!).getJSONObject("result") + assertFalse(r.toString(), r.getBoolean("isError")) + return r.getJSONObject("structuredContent") + } + + private fun rows( + vararg rows: List, + columns: Int = rows.firstOrNull()?.size ?: 1, + ) = QueryResult(List(columns) { "c$it" }, rows.toList(), 0, false) + + private val roomSchema: (String, Boolean, String, List) -> QueryResult = { path, _, sql, _ -> + when { + path != "/data/app.db" -> { + if (sql.startsWith("PRAGMA")) rows(listOf(0L)) else rows() + } + + sql == "PRAGMA user_version" -> { + rows(listOf(3L)) + } + + sql == "PRAGMA journal_mode" -> { + rows(listOf("wal")) + } + + sql == "PRAGMA page_size" -> { + rows(listOf(4096L)) + } + + sql == "PRAGMA page_count" -> { + rows(listOf(12L)) + } + + sql.startsWith("SELECT name, type, wr FROM pragma_table_list") -> { + rows( + listOf("c", "table", 1L), + listOf("f", "virtual", 0L), + listOf("f_docsize", "shadow", 0L), + listOf("p", "table", 0L), + listOf("room_master_table", "table", 0L), + listOf("sqlite_schema", "table", 0L), + listOf("sqlite_sequence", "table", 0L), + ) + } + + sql.startsWith("SELECT t.name, c.name") -> { + rows( + listOf("c", "a", "INT", 1L, null, 1L, 0L), + listOf("c", "b", "INT", 1L, null, 2L, 0L), + listOf("c", "pid", "INT", 0L, null, 0L, 0L), + listOf("f", "name", "", 0L, null, 0L, 0L), + listOf("f", "f", "", 0L, null, 0L, 1L), + listOf("f", "docid", "", 0L, null, 0L, 1L), + listOf("f_docsize", "docid", "INTEGER", 0L, null, 1L, 0L), + listOf("f_docsize", "size", "BLOB", 0L, null, 0L, 0L), + listOf("p", "id", "INTEGER", 0L, null, 1L, 0L), + listOf("p", "name", "TEXT", 1L, "'x'", 0L, 0L), + listOf("p", "g", "INT", 0L, null, 0L, 2L), + listOf("room_master_table", "id", "INTEGER", 0L, null, 1L, 0L), + listOf("room_master_table", "identity_hash", "TEXT", 0L, null, 0L, 0L), + listOf("sqlite_sequence", "name", "", 0L, null, 0L, 0L), + ) + } + + sql.startsWith("SELECT t.name, il.name") -> { + rows( + listOf("c", "ci", 0L, "c", 0L, "pid"), + listOf("c", "ci", 0L, "c", 0L, null), + listOf("c", "sqlite_autoindex_c_1", 1L, "pk", 0L, "a"), + listOf("c", "sqlite_autoindex_c_1", 1L, "pk", 0L, "b"), + listOf("p", "pn", 1L, "c", 1L, "name"), + ) + } + + sql.startsWith("SELECT t.name, f.id") -> { + rows(listOf("c", 0L, "p", "pid", "id", "NO ACTION", "CASCADE")) + } + + sql.startsWith("SELECT type, name, tbl_name") -> { + rows( + listOf("table", "f", "f", "CREATE VIRTUAL TABLE f USING fts4(content='p', name)"), + listOf("trigger", "room_fts_content_sync_f_BEFORE_UPDATE", "p", null), + listOf("view", "v", "v", null), + ) + } + + sql.startsWith("SELECT identity_hash FROM room_master_table") -> { + rows(listOf("abc123")) + } + + else -> { + rows() + } + } + } + + private fun JSONArray.objects() = (0 until length()).map { getJSONObject(it) } + + private fun JSONArray.values() = (0 until length()).map { get(it) } + + @Test fun readsEveryListOfARoomDatabase() { + engine.answer = roomSchema + val db = call(JSONObject().put("database", "/data/app.db")).getJSONArray("databases").getJSONObject(0) + assertEquals("app.db", db.getString("name")) + assertTrue(db.isNull("library")) + assertEquals(3, db.getInt("user_version")) + assertEquals("wal", db.getString("journal_mode")) + assertEquals(4096, db.getInt("page_size")) + assertEquals(12, db.getInt("page_count")) + + val tables = db.getJSONArray("tables").objects().associateBy { it.getString("name") } + // sqlite_ tables are left out; the shadow table is listed with its type. + assertEquals(listOf("c", "f", "f_docsize", "p", "room_master_table"), tables.keys.toList()) + assertEquals("shadow", tables.getValue("f_docsize").getString("type")) + + val c = tables.getValue("c") + assertTrue(c.getBoolean("without_rowid")) + assertEquals(listOf("a", "b"), c.getJSONArray("primary_key").values()) + val ci = c.getJSONArray("indexes").objects().first { it.getString("name") == "ci" } + // An expression in an index is a null column. + assertEquals(listOf("pid", JSONObject.NULL), ci.getJSONArray("columns").values()) + assertEquals( + "pk", + c + .getJSONArray("indexes") + .objects() + .first { it.getString("name") == "sqlite_autoindex_c_1" } + .getString("origin"), + ) + val fk = c.getJSONArray("foreign_keys").getJSONObject(0) + assertEquals("p", fk.getString("table")) + assertEquals(listOf("pid"), fk.getJSONArray("from").values()) + assertEquals("CASCADE", fk.getString("on_delete")) + + // A virtual table's hidden columns are left out; a generated column is kept and marked. + assertEquals(1, tables.getValue("f").getInt("column_count")) + val p = tables.getValue("p") + assertEquals(3, p.getInt("column_count")) + val name = p.getJSONArray("columns").getJSONObject(1) + assertEquals("TEXT", name.getString("declared_type")) + assertTrue(name.getBoolean("not_null")) + assertEquals("'x'", name.getString("default")) + assertTrue(p.getJSONArray("columns").getJSONObject(2).getBoolean("generated")) + assertTrue(p.getJSONArray("indexes").getJSONObject(0).getBoolean("partial")) + + assertEquals(listOf("f"), db.getJSONArray("fts_tables").values()) + assertEquals("v", db.getJSONArray("views").getJSONObject(0).getString("name")) + assertEquals("p", db.getJSONArray("triggers").getJSONObject(0).getString("table")) + assertTrue(db.getBoolean("has_sqlite_sequence")) + + val room = db.getJSONObject("room") + assertEquals(3, room.getInt("schema_version")) + assertEquals("abc123", room.getString("identity_hash")) + assertEquals(listOf("room_master_table"), room.getJSONArray("own_tables").values()) + assertEquals(listOf("room_fts_content_sync_f_BEFORE_UPDATE"), room.getJSONArray("fts_sync_triggers").values()) + } + + @Test fun aDatabaseWithoutRoomMasterTableHasNoRoomAndALibraryIsNamed() { + engine.answer = roomSchema + val out = call(JSONObject()) + val byName = out.getJSONArray("databases").objects().associateBy { it.getString("name") } + assertEquals(setOf("app.db", "androidx.work.workdb"), byName.keys) + val work = byName.getValue("androidx.work.workdb") + assertEquals("androidx.work", work.getString("library")) + assertTrue(work.isNull("room")) + assertFalse(work.getBoolean("has_sqlite_sequence")) + assertEquals(0, out.getJSONArray("errors").length()) + // Only the identity hash read touches a table's rows, and only for Room's own table. + assertTrue(engine.queries.none { it.first.contains("count(", ignoreCase = true) }) + } + + @Test fun appAndDeviceComeFromTheEnvironmentAndAreNullWithoutOne() { + engine.answer = roomSchema + assertTrue(call(JSONObject()).isNull("app")) + environment = + JSONObject() + .put("app", JSONObject().put("package", "com.example")) + .put("device", JSONObject().put("api_level", 34)) + val out = call(JSONObject()) + assertEquals("com.example", out.getJSONObject("app").getString("package")) + assertEquals(34, out.getJSONObject("device").getInt("api_level")) + } + + @Test fun aDatabaseThatFailsIsAnErrorAndTheOthersStillCome() { + engine.answer = { path, w, sql, a -> + if (path == "/data/androidx.work.workdb" && sql.startsWith("SELECT name, type")) { + throw DebugEngineException(11, "database disk image is malformed") + } + roomSchema(path, w, sql, a) + } + val out = call(JSONObject()) + assertEquals(1, out.getJSONArray("databases").length()) + val error = out.getJSONArray("errors").getJSONObject(0) + assertEquals("/data/androidx.work.workdb", error.getString("database")) + assertTrue(error.getString("error"), error.getString("error").contains("malformed")) + } + + // F04: a virtual table whose module the server connection lacks fails pragma_table_xinfo ("no such module"). + @Test fun aTableThatCannotBeReadLosesOnlyItsOwnListsAndSaysWhy() { + engine.answer = { path, w, sql, a -> + val bulk = sql.startsWith("SELECT t.name, c.name") && !sql.contains("AND t.name = ") + val forBad = sql.startsWith("SELECT t.name, c.name") && sql.contains("AND t.name = 'f'") + if (path == "/data/app.db" && (bulk || forBad)) throw DebugEngineException(1, "no such module: fts4") + if (path == "/data/app.db" && sql.startsWith("SELECT t.name, c.name")) { + val table = Regex("AND t.name = '([^']*)'").find(sql)!!.groupValues[1] + QueryResult( + List(7) { "c$it" }, + roomSchema(path, w, "SELECT t.name, c.name", a).rows.filter { it[0] == table }, + 0, + false, + ) + } else { + roomSchema(path, w, sql, a) + } + } + val out = call(JSONObject().put("database", "/data/app.db")) + assertEquals(0, out.getJSONArray("errors").length()) + val tables = + out + .getJSONArray("databases") + .getJSONObject(0) + .getJSONArray("tables") + .objects() + .associateBy { it.getString("name") } + val bad = tables.getValue("f") + assertEquals(0, bad.getJSONArray("columns").length()) + assertTrue(bad.getString("error"), bad.getString("error").contains("no such module")) + val good = tables.getValue("p") + assertTrue(good.isNull("error")) + assertEquals(listOf("id", "name", "g"), good.getJSONArray("columns").objects().map { it.getString("name") }) + assertEquals( + listOf("a", "b", "pid"), + tables + .getValue("c") + .getJSONArray("columns") + .objects() + .map { it.getString("name") }, + ) + } + + private fun failColumnsWith(error: DebugEngineException) { + engine.answer = { path, w, sql, a -> + if (path == "/data/app.db" && sql.startsWith("SELECT t.name, c.name")) throw error + roomSchema(path, w, sql, a) + } + } + + // F08: only the per-table kind of failure falls back to reading each table alone. + @Test fun aFailureNoSingleTableCausedPutsTheDatabaseInErrors() { + for (error in listOf( + DebugEngineException(14, "unable to open database file"), + DebugEngineException(11, "database disk image is malformed"), + DebugEngineException(1, "near \"FROM\": syntax error"), + )) { + failColumnsWith(error) + val out = call(JSONObject().put("database", "/data/app.db")) + assertEquals(0, out.getJSONArray("databases").length()) + val e = out.getJSONArray("errors").getJSONObject(0) + assertEquals("/data/app.db", e.getString("database")) + assertTrue(e.getString("error"), e.getString("error").contains(error.message!!)) + } + } + + @Test fun everyTableFailingPutsTheDatabaseInErrorsNotSuccess() { + failColumnsWith(DebugEngineException(1, "no such module: fts4")) + val out = call(JSONObject().put("database", "/data/app.db")) + assertEquals(0, out.getJSONArray("databases").length()) + assertTrue( + out + .getJSONArray("errors") + .getJSONObject(0) + .getString("error") + .contains("no such module"), + ) + } + + // F3/F4: in the one-table-at-a-time read a database-wide error is the database's, not that table's. + @Test fun aLockOnOneTableInTheFallbackPutsTheDatabaseInErrors() { + engine.answer = { path, w, sql, a -> + val q = sql.startsWith("SELECT t.name, c.name") && path == "/data/app.db" + when { + q && !sql.contains("AND t.name = ") -> throw DebugEngineException(1, "no such module: fts4") + q && sql.contains("AND t.name = 'f'") -> throw DebugEngineException(1, "no such module: fts4") + q && sql.contains("AND t.name = 'p'") -> throw DebugEngineException(5, "database is locked") + q -> QueryResult(List(7) { "c$it" }, emptyList(), 0, false) + else -> roomSchema(path, w, sql, a) + } + } + val out = call(JSONObject().put("database", "/data/app.db")) + assertEquals(0, out.getJSONArray("databases").length()) + assertTrue( + out + .getJSONArray("errors") + .getJSONObject(0) + .getString("error") + .contains("database is locked"), + ) + } + + // F5: the row cap is for the whole list, not each table read alone. + @Test fun theRowCapCountsAllTablesTogetherInTheFallback() { + engine.answer = { path, w, sql, a -> + val q = sql.startsWith("SELECT t.name, c.name") && path == "/data/app.db" + if (q && !sql.contains("AND t.name = ")) throw DebugEngineException(1, "no such module: fts4") + if (q) { + val table = Regex("AND t.name = '([^']*)'").find(sql)!!.groupValues[1] + val n = if (table == "c" || table == "p") 12_000 else 0 + QueryResult(List(7) { "c$it" }, List(n) { listOf(table, "col$it", "INT", 0L, null, 0L, 0L) }, 0, false) + } else { + roomSchema(path, w, sql, a) + } + } + val out = call(JSONObject().put("database", "/data/app.db")) + val db = out.getJSONArray("databases").getJSONObject(0) + val columns = db.getJSONArray("tables").objects().sumOf { it.getJSONArray("columns").length() } + assertEquals(DatabaseTools.MAX_TEMPLATE_ROWS, columns) + assertTrue(out.getBoolean("truncated")) + } + + @Test fun aListPastTheLimitIsCutAndSaysSo() { + val many = (0..DatabaseTools.MAX_TEMPLATE_ROWS).map { listOf("t%05d".format(it), "table", 0L) } + engine.answer = { path, w, sql, a -> + if (sql.startsWith("SELECT name, type, wr")) { + QueryResult(listOf("name", "type", "wr"), many, 0, false) + } else { + roomSchema(path, w, sql, a) + } + } + val out = call(JSONObject().put("database", "/data/app.db")) + assertTrue(out.getBoolean("truncated")) + assertEquals( + DatabaseTools.MAX_TEMPLATE_ROWS, + out + .getJSONArray("databases") + .getJSONObject(0) + .getJSONArray("tables") + .length(), + ) + } + + @Test fun aListOfExactlyTheLimitIsWhole() { + val exact = (1..DatabaseTools.MAX_TEMPLATE_ROWS).map { listOf("t%05d".format(it), "table", 0L) } + engine.answer = { path, w, sql, a -> + if (sql.startsWith("SELECT name, type, wr")) { + QueryResult(listOf("name", "type", "wr"), exact, 0, false) + } else { + roomSchema(path, w, sql, a) + } + } + assertFalse(call(JSONObject().put("database", "/data/app.db")).getBoolean("truncated")) + } + + @Test fun databasesLeftUnreadWhenTheTimeLimitPassesAreInErrors() { + // The paths sort as androidx.work.workdb, then app.db: the limit passes while the first is read. + val read = mutableSetOf() + engine.answer = { path, w, sql, a -> + read += path + if (path == "/data/androidx.work.workdb" && sql.startsWith("PRAGMA user_version")) { + now += DatabaseTools.DEADLINE_MS + 1 + throw DebugEngineException(9, "interrupted") + } + roomSchema(path, w, sql, a) + } + val out = call(JSONObject()) + assertEquals(0, out.getJSONArray("databases").length()) + val errors = out.getJSONArray("errors").objects() + assertEquals(listOf("/data/androidx.work.workdb", "/data/app.db"), errors.map { it.getString("database") }) + assertEquals(DatabaseTools.TIME_LIMIT_SKIP, errors[1].getString("error")) + assertEquals(setOf("/data/androidx.work.workdb"), read) + } + + @Test fun anOddAnswerFromOneDatabaseIsItsErrorAndTheOthersStillCome() { + engine.answer = { path, w, sql, a -> + if (path == "/data/androidx.work.workdb" && sql.startsWith("SELECT name, type, wr")) { + rows(listOf(5L, "table", 0L)) + } else { + roomSchema(path, w, sql, a) + } + } + val out = call(JSONObject()) + assertEquals(listOf("app.db"), out.getJSONArray("databases").objects().map { it.getString("name") }) + val error = out.getJSONArray("errors").getJSONObject(0) + assertEquals("/data/androidx.work.workdb", error.getString("database")) + assertTrue(error.getString("error"), error.getString("error").startsWith("ClassCastException")) + } + + @Test fun onlyRoomsOwnTablesAreListedAsRoomsEvenWhenAnAppTableStartsWithRoom() { + engine.answer = { path, w, sql, a -> + if (path == "/data/app.db" && sql.startsWith("SELECT name, type, wr")) { + rows( + listOf("room_booking", "table", 0L), + listOf("room_master_table", "table", 0L), + listOf("room_table_modification_log", "table", 0L), + ) + } else { + roomSchema(path, w, sql, a) + } + } + val room = call(JSONObject().put("database", "/data/app.db")).getJSONArray("databases").getJSONObject(0).getJSONObject("room") + assertEquals(listOf("room_master_table", "room_table_modification_log"), room.getJSONArray("own_tables").values()) + } + + @Test fun aPageThatIsEmptyButSaysThereIsMoreMarksTheResultTruncated() { + engine.answer = roomSchema + engine.rawPage = { _, sql -> + if (sql.startsWith("SELECT name, type, wr")) QueryResult(listOf("name", "type", "wr"), emptyList(), 0, true) else null + } + assertTrue(call(JSONObject().put("database", "/data/app.db")).getBoolean("truncated")) + } +} diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index d8830888ca..eb899df569 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -512,6 +512,34 @@ public static void main(String[] a) throws Exception { eq(r.rows.get(0)[3], "SEARCH notes USING COVERING INDEX notes_pcode (pcode=?)", "lint: a covered key, as the shell's glob expects"); r = query(srv, "SELECT name, hidden FROM pragma_table_xinfo(?)", new Object[] {"g"}, 0, 100, 4096, 1024, MAX, FAR); eq(r.rows.get(1)[1], 2L, "dump: a virtual generated column is hidden 2"); + // get_template_variables (ADFA-7302): its SQL, as DatabaseTools.TemplateReader sends it, through the authorizer + r = q(srv, "SELECT name, type, wr FROM pragma_table_list WHERE schema = 'main' AND type <> 'view' ORDER BY name"); + List listed = new ArrayList<>(); + for (Object[] tl : r.rows) listed.add(tl[0] + ":" + tl[1] + ":" + tl[2]); + check(listed.contains("w:table:1") && listed.contains("parent:table:0"), "template: table list with WITHOUT ROWID " + listed); + r = q(srv, "SELECT t.name, c.name, c.type, c.\"notnull\", c.dflt_value, c.pk, c.hidden FROM pragma_table_list AS t, " + + "pragma_table_xinfo(t.name, t.schema) AS c WHERE t.schema = 'main' AND t.type <> 'view' ORDER BY t.name, c.cid"); + boolean sawGenerated = false; + for (Object[] col : r.rows) sawGenerated |= "g".equals(col[0]) && "b".equals(col[1]) && Long.valueOf(2).equals(col[6]); + check(sawGenerated, "template: columns, a generated one hidden 2"); + r = q(srv, "SELECT t.name, il.name, il.\"unique\", il.origin, il.partial, ii.name FROM pragma_table_list AS t, " + + "pragma_index_list(t.name, t.schema) AS il, pragma_index_xinfo(il.name, t.schema) AS ii " + + "WHERE t.schema = 'main' AND t.type = 'table' AND ii.key = 1 ORDER BY t.name, il.name, ii.seqno"); + List indexed = new ArrayList<>(); + for (Object[] ix : r.rows) indexed.add(ix[0] + "." + ix[1] + "." + ix[3] + "." + ix[5]); + check(indexed.contains("notes.notes_pcode.c.pcode") && indexed.contains("parent.sqlite_autoindex_parent_1.u.code"), + "template: index columns " + indexed); + r = q(srv, "SELECT t.name, f.id, f.\"table\", f.\"from\", f.\"to\", f.on_update, f.on_delete FROM pragma_table_list AS t, " + + "pragma_foreign_key_list(t.name, t.schema) AS f WHERE t.schema = 'main' AND t.type = 'table' " + + "ORDER BY t.name, f.id, f.seq"); + eq(r.rows.size(), 2, "template: foreign keys"); + eq(r.rows.get(0)[6], "NO ACTION", "template: on_delete"); + for (String pragma : new String[] {"user_version", "journal_mode", "page_size", "page_count"}) { + check(q(srv, "PRAGMA " + pragma).rows.size() == 1, "template: PRAGMA " + pragma + " reads"); + } + r = q(srv, "SELECT type, name, tbl_name, CASE WHEN type = 'table' THEN sql END FROM sqlite_master " + + "WHERE type IN ('view', 'trigger') OR (type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%') ORDER BY type, name"); + check(r.rows.isEmpty() || r.rows.get(0).length == 4, "template: views, triggers and virtual tables"); // dump of a virtual table: its shadow tables are found by name and type 'shadow', and the server's authorizer allows it eq(Helper.exec(app, "CREATE VIRTUAL TABLE docs USING fts5(body)"), 0, "fts5 table"); eq(Helper.exec(app, "CREATE TABLE docs_extra(a)"), 0, "a plain table that starts with the virtual table's name"); diff --git a/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipRecipeExecutor.kt b/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipRecipeExecutor.kt index 859fd452a8..d8f8be0d0e 100644 --- a/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipRecipeExecutor.kt +++ b/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipRecipeExecutor.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.templates.Language import com.itsaky.androidide.templates.ModuleTemplateData import com.itsaky.androidide.templates.Parameter import com.itsaky.androidide.templates.ProjectTemplateData +import com.itsaky.androidide.templates.ProjectTemplatePebble import com.itsaky.androidide.templates.ProjectTemplateRecipeResult import com.itsaky.androidide.templates.RecipeExecutor import com.itsaky.androidide.templates.TemplateRecipe @@ -17,8 +18,6 @@ import dalvik.system.DexClassLoader import io.pebbletemplates.pebble.PebbleEngine import io.pebbletemplates.pebble.error.PebbleException import io.pebbletemplates.pebble.extension.Extension -import io.pebbletemplates.pebble.lexer.Syntax -import io.pebbletemplates.pebble.loader.StringLoader import org.adfa.constants.ANDROID_GRADLE_PLUGIN_VERSION import org.adfa.constants.KOTLIN_VERSION import org.adfa.constants.Sdk @@ -103,18 +102,7 @@ class ZipRecipeExecutor( zipProvider().use { zip -> - val customSyntax = - Syntax - .Builder() - .setPrintOpenDelimiter(DELIM_PRINT_OPEN) - .setPrintCloseDelimiter(DELIM_PRINT_CLOSE) - .setExecuteOpenDelimiter(DELIM_EXECUTE_OPEN) - .setExecuteCloseDelimiter(DELIM_EXECUTE_CLOSE) - .setCommentOpenDelimiter(DELIM_COMMENT_OPEN) - .setCommentCloseDelimiter(DELIM_COMMENT_CLOSE) - .build() - - val builder = PebbleEngine.Builder() + val builder = ProjectTemplatePebble.engineBuilder() val extensionsEntry = zip.getEntry(META_EXTENSION_JAR) if (extensionsEntry != null) { @@ -125,11 +113,7 @@ class ZipRecipeExecutor( } val pebbleEngine = - builder - .loader(StringLoader()) - .strictVariables(true) - .syntax(customSyntax) - .build() + builder.build() val className = data.name.replace(CLASS_NAME_PATTERN, "") val (baseIdentifiers, warnings) = diff --git a/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateConstants.kt b/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateConstants.kt index b73ec63c28..0713e612b3 100644 --- a/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateConstants.kt +++ b/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateConstants.kt @@ -11,13 +11,6 @@ const val DEX_OPT_FOLDER = "dex_opt" const val TEMPLATE_EXTENSION = ".peb" -const val DELIM_PRINT_OPEN = "\${{" -const val DELIM_PRINT_CLOSE = "}}" -const val DELIM_EXECUTE_OPEN = "\${%" -const val DELIM_EXECUTE_CLOSE = "%}" -const val DELIM_COMMENT_OPEN = "\${#" -const val DELIM_COMMENT_CLOSE = "#}" - const val KEY_PACKAGE_NAME = "PACKAGE_NAME" const val KEY_APP_NAME = "APP_NAME" const val KEY_CLASS_NAME = "CLASS_NAME"