# Command-line usage

## Run the CLI

Place the supplied `dexsql` executable (`dexsql.exe` on Windows) in a directory
on your `PATH`, or invoke it by its full path. Examples use `dexsql`:

```bash
dexsql --version
dexsql --help
dexsql query --help
```

Each command's `--help` lists its options. Global options work before or after
the command name. Examples with `\` line continuations use a POSIX shell;
in PowerShell or Command Prompt, put the command on one line.

## Commands

- `tables --input app.apk`: print built-in table names, columns, and SQL types.
  The schema is fixed; the input flag is required for compatibility, but the
  file is not read.
- `query --input app.apk --sql "..."`: run one-shot SQL over the input. By
  default only the data needed by the supplied SQL is prepared; results are identical to
  `--full`.
- `query --input app.apk`: an editable terminal session with history, or a
  prompt-free batch when stdin is a pipe or file. `--interactive` / `--repl`
  remain compatibility aliases and are no longer needed.
- `prepare-cache --input app.apk --output app.dexsql-cache`: parse once
  and write `cache.dxc2` inside the output directory for repeated queries.
- `query-cache --cache-file app.dexsql-cache/cache.dxc2 --sql "..."`:
  query a prepared cache container file.
- `decode --input app.apk --method 'Lcom/example/Foo;->bar(I)V'`: disassemble
  a method; see [smali decoding](smali.md).
- `mcp`: serve MCP tools and documentation over stdio. The client opens
  datasets through `open_dataset`; see [MCP setup](../mcp/index.md).
- `extract licenses --output THIRD_PARTY_NOTICES`: export the third-party
  copyright and license notices embedded in this executable. Omit `--output`
  to print them to stdout. Existing files are not overwritten; no APK, network
  connection or source tree is needed. Notices cover program dependencies and
  runtimes, excluding build dependencies, procedural macros, compilers and linkers.

## Options

- `--threads N`: set worker thread count. `0` and the default use all
  available logical CPUs.
- `--full` (`query` only): prepare all metadata, method references, and opcode
  data instead of only the data needed by the supplied SQL. Results are the
  same. Interactive mode always prepares the full dataset, so `--full` has no
  effect there. Use `prepare-cache` to save a cache for later invocations.
- `--cache NAME=SQL`: name a `SELECT` body for later queries. It is request-scoped
  on `query --sql` and `query-cache`, and a lazy session definition on
  `query` reading stdin.
- `--limit N`: cap returned rows per statement (unlimited by default), not
  the work done by the query.
- `--timing`: print load, parse, data preparation, cache, and SQL timing (a
  per-query line in interactive sessions) to stderr.
- `--trusted-input`: for environments where inputs and caches are controlled.
  Some validation is skipped, including strict source-input freshness checks
  for `query-cache`. This option is off by default.

Without `--sql`, `query` reads stdin and requires at least one `--input`.
Repeat `--input` for multiple DEX/APK files; with `--sql`, input remains optional
for SQL that does not read DEX/APK data, such
as `dexsql query --sql "SELECT 1"`. Pass one statement per `--sql`; multiple
`--sql` arguments run in order and share one loaded DEX session:

```bash
dexsql query \
  --input app.apk \
  --sql "select count(*) as class_count from classes" \
  --sql "select count(*) as method_count from class_methods"
```

Terminal sessions retain the complete dataset across queries. Use arrow keys to
edit or recall input and Ctrl-R to search history. Continuation lines use `   ...> `.
Ctrl-C clears the current unfinished SQL; Ctrl-D exits without submitting it.
History is saved in `~/.dexsql_history`. Set `DEXSQL_HISTORY` to another path, or
set it to an empty string to disable history. Unwritable history produces a warning
and does not prevent SQL execution. Pipe/file input never loads or saves history.

```bash
dexsql query --input app.apk
dexsql query --input app.apk < queries.sql
printf 'SELECT count(*) FROM methods;\n' | dexsql query --input app.apk
```

In both modes, a line ending in `;` or an empty line submits the accumulated SQL.
Batch EOF submits any remaining SQL. Dot commands are processed as individual
lines when no SQL is pending. `.exit` and `.quit` end the session; `exit` and `quit`
remain supported for compatibility. Statements after an exit command are ignored.
Errors are printed to stderr and later submissions continue. Any failed SQL or dot
command makes the final exit status nonzero, including when `.quit` follows it.

Batch mode reads all stdin before preparation, then uses `PrepareMode::Auto` with
the expected SQL to build only required data. `--full` forces the complete dataset.
`--cache`, TEMP TABLE/VIEW definitions, non-query input and `.smali` conservatively
use Full: the session API requires a complete dataset to preserve lazy definitions
and their dependencies across CREATE, redefinition and DROP. Planning failures also
fall back to Full so they cannot prevent later submissions from running.

In terminal and batch sessions, `CREATE VIEW`, `CREATE TEMP VIEW`,
`CREATE TEMP TABLE`, and `--cache` definitions survive submissions. `CREATE`
replaces an existing definition after validation; `IF NOT EXISTS` keeps it.
`DROP VIEW` or `DROP TABLE` removes it. All session definitions are lazy, including
TEMP TABLE; their rows are read only when a query needs them. Closing the session
drops them. The explicit `--sql` path retains its existing request-scoped semantics.

### Session commands

| Command | Behavior |
| --- | --- |
| `.tables [PATTERN]` | Sorted built-in table, VIEW and TEMP table names; optional SQL LIKE pattern (`%`, `_`, ASCII case insensitive). |
| `.schema [TABLE]` | Columns and types, using the same built-in catalog as `dexsql tables`; includes current session definitions. |
| `.mode table\|csv\|json\|line` | Select output format. Default `table` preserves the previous text table bytes. |
| `.headers on\|off` | Show/hide column names; default on. JSON omits `columns` when off; line mode omits labels. |
| `.timer on\|off` | Toggle the same per-submission stderr timing as `--timing`. |
| `.smali DESCRIPTOR` | Decode a method or class using the currently open dataset, in the `dexsql decode` format. Does not reopen a dataset; the decoder may reload released source bytes. |
| `.help` | List all commands. |
| `.exit`, `.quit` | Exit. |

Lazy session columns may report `sqlite_dynamic` when their type depends on runtime values.

Unknown dot commands report an error and suggest `.help`; they are never sent to SQL.
These commands affect stdin sessions only. `--sql` continues to output text tables.

CSV writes a header row unless disabled, decimal integers with all digits, lowercase
hex BLOBs in double quotes, and NULL as an unquoted empty field. Text is always quoted
(including empty text); embedded quotes double and embedded line breaks are preserved.
CSV does not carry runtime type tags: consumers must not round integer fields, and
hex text and BLOBs require schema information to distinguish.

JSON emits one object per result, with `columns` (names, including duplicates) and
`rows` (arrays). Cells follow MCP compact runtime types: signed/unsigned integers are
`["i","decimal"]` / `["u","decimal"]`, BLOBs are `["b","lowercase hex"]`, NULL is
`null`, text is a string, and finite floats are numbers. Nonfinite floats use
`["f","NaN"]`, `["f","Infinity"]` or `["f","-Infinity"]`. This avoids integer rounding
and distinguishes empty BLOB, empty text, and NULL. `line` prints `column = value`
with blank lines between rows, using the existing table cell representations.

Named relations are useful for repeated joins:

```bash
dexsql query \
  --input app.apk \
  --cache "refs_per_method=select file_id, method_idx, count(*) ref_count from method_refs group by file_id, method_idx" \
  --sql "select m.descriptor, r.ref_count from methods m join refs_per_method r using (file_id, method_idx) order by r.ref_count desc limit 20"
```

## Input files

DEX, APK, JAR and ZIP paths are supported. Repeat `--input` to combine inputs. Archives may contain non-contiguous `classes*.dex` names; a malformed DEX member is skipped while later readable members remain available. Archive corruption or decompression-budget failures still return errors, and SQL input loading requires at least one readable DEX.

For repeated sessions across process launches, use [prepared caches](cache.md). On-demand method disassembly is documented under [smali](smali.md).

## Connect an AI client

Configure a local stdio MCP connection with the absolute path to the executable:

```json
{
  "mcpServers": {
    "dexsql": {
      "command": "/absolute/path/to/dexsql",
      "args": ["mcp"]
    }
  }
}
```

On Windows, use a JSON-escaped path such as `"D:\\Tools\\dexsql.exe"`.
The client launches the process. Local input paths must be accessible to it.
The [MCP reference](../mcp/index.md) gives the connected agent its tool workflow.

---

Copyright (c) 2026 LSPosed. Documentation licensed under [MIT](../license.md).
