[](https://crates.io/crates/firestore-cli)
# fsq
A command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, a full-screen
collection browser, and a scripting mode with JSON output. It is built on the
[firestore](https://github.com/abdolence/firestore-rs) crate, which translates SQL into Firestore pipelines, the
query format of the Enterprise edition. The SQL dialect is documented in the
[firestore book](https://firestore-rust.abdolence.dev).

* **SQL REPL:** highlighting, completion of collections and fields, statements across several lines and a history,
see [The REPL](#the-repl);
* **Results as tables:** nested values in compact cells, an expanded view and a detail view of every field, see
[Results](#results);
* **Query plans:** `EXPLAIN` draws the plan as a tree, with a warning when it reads every document, see
[Query plans](#query-plans);
* **Collection browser:** `fsq browse` shows the documents of a collection full screen, opens maps, arrays and
subcollections, and filters with the end of a `SELECT`, see [Browsing a collection](#browsing-a-collection);
* **Collections and fields:** `\l` and `\d` list the collections and the field paths of a collection, see
[Exploring collections](#exploring-collections);
* **Export and import:** documents as JSON lines that read back to the same Firestore types, see
[Export and import](#export-and-import);
* **Indexes:** index statements in SQL, and `fsq index` to plan and sync the `firestore.indexes.json` of the Firebase CLI,
see [Indexes](#indexes);
* **Fluent Rust code:** `fsq codegen` shows the code of the firestore crate's fluent API for a `SELECT`, see
[Fluent Rust code](#fluent-rust-code);
* **Scripting:** a statement or a script without the REPL, with `json` or `jsonl` output for other tools, see
[Scripting](#scripting).
## Installation
### Cargo
```sh
cargo install firestore-cli --locked
```
The crate is `firestore-cli`, and the binary it installs is `fsq`.
### Binary releases
Archives for macOS, Linux, FreeBSD and Windows are on [the GitHub releases](https://github.com/abdolence/firestore-cli-rs/releases).
The Linux x86_64 and aarch64 archives need glibc, so on musl systems such as Alpine use Cargo.
### Install script
```sh
```powershell
The script downloads the latest release for your system, checks its SHA-256 digest and installs `fsq` into
`~/.local/bin`, or `%LOCALAPPDATA%\Programs\fsq` on Windows. Run it again to upgrade. `FSQ_VERSION` (such as
`v0.2.0`) and `FSQ_INSTALL_DIR` override the release and the directory.
## Connecting
```sh
fsq -p my-project -d my-database
```
This opens the [REPL](#the-repl). To run one statement and exit, use [scripting](#scripting):
```sh
fsq -p my-project -d my-database sql -e 'SELECT title FROM books LIMIT 10'
```
* `-p`, `--project`: the Google Cloud project. Without it fsq uses the project the firestore crate detects: the first
of the `GCP_PROJECT`, `PROJECT_ID`, `GCP_PROJECT_ID` and `GOOGLE_CLOUD_PROJECT` environment variables that is set,
then the project the Application Default Credentials file names, then the project of the metadata server. The
project `gcloud config set project` sets is not read;
* `-d`, `--database`: the database ID, `(default)` by default;
* `FIRESTORE_EMULATOR_HOST`: connects to the Firestore emulator at that address instead.
fsq authenticates with Application Default Credentials (ADC), the credentials Google client libraries look up
on their own: the file `GOOGLE_APPLICATION_CREDENTIALS` names, the file `gcloud auth application-default login`
writes, or the metadata server on Google Cloud. `gcloud auth login` authorises only the `gcloud` tool, not fsq.
The prompt shows `project/database (edition)`, and `\c <database>` connects to another database of the project.
### Editions
SQL needs a database of the Firestore Enterprise edition. On a Standard edition database Firestore refuses `SELECT` and
the SQL writes, and fsq shows its answer. These work on both editions:
* `\l`, `\d`, `SHOW COLLECTIONS`, `SHOW INDEXES` and the index statements;
* `browse` and `export` of a collection, without a filter or `--sql`;
* `codegen --offline`.
When it connects, fsq sends Firestore a pipeline that reads nothing and costs no read units. When Firestore refuses it,
the REPL says that SQL may need an Enterprise edition database. Any other failure of the pipeline shows nothing.
## The REPL
A statement ends with `;` and can span several lines. A line that starts with `\` is a meta-command:
| `\l [--recursive]` | lists the collections under the root, as `SHOW COLLECTIONS` does; see [Listing subcollections](#listing-subcollections) |
| `\d <collection>` | lists the field paths of a collection; see [Describing a collection](#describing-a-collection) |
| `\browse <collection> [filter]` | browses a collection full screen; see [Browsing a collection](#browsing-a-collection) |
| `\x [on\|off\|auto\|full [N]]` | switches the expanded view, or shows every field; see [Expanded and full views](#expanded-and-full-views) |
| `\c <database>` | connects to another database of the project |
| `\timing [on\|off]` | adds the round trip time and the execution stats to the footer |
| `\wait [on\|off]` | waits for `CREATE INDEX` and `ALTER COLLECTION` to finish, on by default |
| `\gen ['SELECT']` | shows the fluent Rust code of a `SELECT`, or of the last one that ran; see [Fluent Rust code](#fluent-rust-code) |
| `\?` | lists the meta-commands |
| `\q` | quits, as Ctrl-D does |
`INSERT`, `UPDATE` and `DELETE` run as typed, with no confirmation, and print how many documents they modified.
* Tab completes a collection after `FROM`, `JOIN`, `INTO`, `UPDATE`, `COLLECTION`, `\d` and the `ON` of
`CREATE INDEX`, a meta-command at the start of a line, and otherwise a keyword or a field of the rows and
descriptions shown so far;
* Ctrl-C stops a running statement; a write that reached Firestore before it may still apply;
* the arguments of `\l`, `\d` and `\gen` are split as a shell splits them, so text that holds spaces or quotes is
quoted;
* the history is kept in the `fsq` directory of the platform's data directory, such as `~/.local/share/fsq` on Linux;
* a call that waits on Firestore for more than a moment shows a spinner on stderr, unless stderr is not a terminal or
the results are JSON written to a pipe.
## Results
A `SELECT` shows its rows as a table, with a footer that gives the rows, the time the statement took and its notes,
such as `more rows remain`.
### Cells
* the columns are the union of the fields of the rows shown: `__name__` first when the rows have document names,
then the columns in the order the statement selects them, then the other fields by name;
* a map shows its keys, such as `{city, zip}`, an array its length, such as `[3 items]`, and a string longer than
40 characters is cut in the middle with `…`, so that its start and end show. A reference is shown relative to the
database, as `__name__` is;
* an empty cell is a field the document lacks, and `NULL` is a field that holds null. Firestore keeps the two
apart, see the [semantics](https://firestore-rust.abdolence.dev/editions/semantics.html) of pipelines;
* a table wider than the terminal is cut to fit it, the longest cells first, in the middle with `…`; a table that is
piped is not cut;
* a statement that returns no documents prints the footer alone, `0 rows`, and `--format json` an empty array.
### Paging
* a statement without `LIMIT` shows a page that fits the terminal and asks before the next one. A statement with
`LIMIT` shows all its rows, and `EXPLAIN` is never paged, since its plan arrives with the last row;
* a result taller than the terminal goes through `$PAGER`, or `less -RFX` when it is unset; an empty `PAGER` turns the
pager off;
* when `LESS` is not set, fsq sets it to `FRX` for the pager alone, as git does, so that `less` keeps the output on
screen after `q`, does not page what fits on one screen and shows colours. A `LESS` that is set, even to nothing,
is left as it is.
### Expanded and full views
`\x` shows each document as a block, with nested values pretty-printed, and `\x auto` does so only for a table wider
than the terminal. `\x` without an argument toggles between `off` and `on`.
`\x full` shows every field of every document, in a block with a row for each value: its path, its type and the whole
value, wrapped inside the value column at the terminal width and never cut. `\x full N` shows row N of the last
result, counting from 1 across the pages shown, and runs no statement. It fails when no rows have been shown or the
result has fewer than N rows.
```
my-project/my-database (enterprise)> \x full 2
─[ books/dune ]─────────────────────────────────────────
field type value
title string Dune
address.city string London
address.zip string N1 9GU
tags[0] string sf
tags[1] string classic
tags[2] string epic
published timestamp 2023-11-14T22:13:20Z
__create_time__ timestamp 2026-11-04T17:51:52.549531Z
__update_time__ timestamp 2026-11-04T17:51:52.549531Z
```
* nested maps and arrays are flattened into paths, `address.city` and `tags[0]`, written as SQL reads them, so that a
path can be pasted into a `WHERE`; an empty map or array is a row of its own;
* the types are those `\d` shows, and bytes are shown in base64;
* the fields come in the order the statement selects them, then by name, and `__create_time__` and `__update_time__`
close the block when the result carries them;
* in the REPL, the hint `\x full N shows every field of row N` follows the footer when the table cut a cell, showed a
map, an array or bytes in summary, or was cut to fit the terminal. A table that showed every value whole has no hint,
and neither have a script, piped input or `--format json` and `jsonl`.
## Query plans
`EXPLAIN SELECT ..` shows the plan Firestore chose, without reading any document, and `EXPLAIN ANALYZE SELECT ..`
also returns the rows and what the run read. The plan is drawn as a tree, followed by a warning for a *table scan*:
a read of every document of the collection, instead of an index. When Firestore returns no plan, as the emulator
does, fsq says so.
`\timing on` runs every `SELECT` with `ANALYZE` and adds to the footer the round trip time, the documents read and
the read units. A *read unit* is how the Enterprise edition bills reads: 4 KiB of the data a read processes.
```
2 rows · 189 ms · round trip 187 ms · 3 documents read · 1 read unit
```
## Exploring collections
### Browsing a collection
```sh
fsq -p my-project -d my-database browse books --filter 'WHERE pages > 100'
```
`\browse books WHERE pages > 100` in the REPL opens the same browser. It takes the
whole terminal: the documents of the collection on the left, and the fields of the selected document on the right as a
tree, where a map or an array opens to show what it holds, at any depth.
The main keys are below, and `?` in the browser lists them all:
| ↑ and ↓, `k` and `j` | moves the cursor |
| →, `l` | opens the map, array or subcollection under the cursor; in the documents, moves to the tree |
| ←, `h` | closes the map or array under the cursor, or moves up a level |
| Enter | opens a closed map, array or subcollection, and in the documents moves to the tree; on a leaf or an open map or array, shows the value whole in a popup that Esc closes |
| Tab | switches between the documents and the tree |
| `/` | edits the filter; ↑ and ↓ recall the filters that ran, Enter runs it and Esc closes the editor |
| `f` | opens the filter editor with `WHERE <path> = <value>` for the leaf under the cursor |
| `y`, `Y` | copies the value under the cursor, or its path, to the clipboard |
| `e` | edits the value under the cursor, or in the popup of a value, on one line, or in `$VISUAL` or `$EDITOR` when the value does not fit on one; in the documents, edits the selected document |
| `E` | edits the value under the cursor, or in the popup of a value, in `$VISUAL` or `$EDITOR` as tagged JSON |
| `d` | deletes the field under the cursor, or in the popup of a value, or in the documents the selected document, once the change is confirmed; `R` at the confirmation also deletes every document under it |
| `a` | adds a field next to the one under the cursor or in the popup of its value, or inside the open map under it or the map of a popup: its name, its type, then its value, once the change is confirmed |
| `n` | in the documents, creates a document in `$VISUAL` or `$EDITOR`, once the change is confirmed |
| `D` | in the documents, copies the selected document under a new ID, once the change is confirmed |
| `r` | reads the documents again |
| `q` | quits, and in the REPL returns to the prompt; Ctrl-C does the same when nothing is loading and nothing is open |
| `?` | lists every key in a popup |
**Filter**
* the filter is the end of a `SELECT` after its `FROM`, such as `WHERE`, `ORDER BY`, `LIMIT` and `OFFSET`. fsq runs
``SELECT * FROM `<collection>` `` with the filter after it, and adds `LIMIT 100` when the filter has no `LIMIT` of its
own;
* in the REPL the rest of the line after the collection is the filter, kept as typed, so a string in it needs no extra
quoting, and `--filter` is not a flag there. `fsq browse` takes it with `--filter`. A `;` at the end of the filter is
dropped;
* the filter runs as a pipeline, which needs an Enterprise edition database. On a Standard edition database the browser
without a filter shows the first 100 documents by ID, and a filter shows the refusal.
**Errors**
* a filter that fails opens in the editor with its error under it, and the documents read before it stay. `/` opens
the filter that failed again;
* the first read without a filter, such as a subcollection opened, and `r` over documents already read leave the editor
closed when they fail, and the error shows under the keys at the bottom;
* Ctrl-G shows any error whole.
**Subcollections**
* the last row of the tree is `subcollections`. Opening it lists the collections under the document, and opening one
of them browses it without a filter. Esc returns to the document as it was left.
**Editing**
* every change shows before it is written: the path of the document and of the field, then the value before and after
as a line diff. `y` writes it, `e` goes back to the editor with the text as it was left, and `n` or Esc discards it.
When the two values differ only in type, or in what the diff does not show, such as spaces at the end of a string,
the diff is of their tagged JSON, which names the type;
* `e` edits a string, a number, a boolean, a timestamp, a reference or a geopoint on one line, from the tree or from
the popup of the value. The editor opens with the value as the tree shows it, and the text keeps the type of the
field: `4` in a double field writes the double `4.0`. Enter shows the change, and a text that reads as the value the
field holds closes the editor and writes nothing;
* an integer is an int64, and a double also takes `NaN`, `inf` and `-inf`, or `Infinity`. A timestamp is RFC 3339 with
any offset, such as `2023-11-15T00:13:20+02:00`, and is stored in UTC. A reference is the path of a document from
the root of the database, such as `authors/herbert`, and a geopoint is `(latitude, longitude)` in degrees;
* a text that does not read as a value of the type of the field shows its error under the editor, which stays open
with the text;
* `e` on a map, an array, bytes or a string over several lines opens `$VISUAL`, else `$EDITOR`, else `vi`, on a
temporary file that holds the value, and the browser comes back as it was left once the editor exits. A string is
its text, bytes are the hex dump the popup shows, and any other value is the tagged JSON `y` copies. When a hex dump
is read back, whitespace is left out, and so is the offset that starts a line, eight hex digits and two spaces as the
dump writes it. Eight digits typed without the two spaces are four bytes, and so is an offset left alone on its line
once an editor strips the spaces after it: delete the line whole with its bytes;
* `e` on an element of an array edits the whole array. `e` does nothing on a null;
* `E` edits any value as tagged JSON, which names the type, so `{"$int": "5"}` in place of a string writes an
integer and `null` writes a null;
* `e` in the documents edits the selected document as the tagged JSON document `fsq export` writes, `__name__`
included, and the write replaces the whole document. A changed `__name__` is refused, since an edit keeps the ID, and
`D` copies a document under a new one;
* a file that does not read shows its error. `e` opens the editor again on the text as it was saved, and `n` discards
it. A file that reads as the value the document holds, or an editor that exits with an error, such as `:cq` in Vim,
writes nothing. An editor that returns at once, such as `code` without `--wait`, reads back the file as it opened,
so nothing is written;
* `n` in the documents opens `$VISUAL` or `$EDITOR` on a new document of the collection on show, a subcollection
included: `{"__name__": "books/"}`, with no fields. The ID goes after the `/`. A `__name__` left as the collection
path and a `/`, left empty or left out, gives the document a new UUID v7, which the confirmation shows in the path
before the write. A `__name__` in another collection, or deeper down, is refused;
* `D` in the documents opens the same editor on the fields of the selected document, with `__name__` left for a new
ID. A file saved as it opened writes the copy, while the `n` template saved as it opened writes nothing;
* a new document is written only while no document has its name, so it never replaces one. When the ID is taken,
nothing is written, and `e` goes back to the editor with the text as it was left. The confirmation shows no value
before the change;
* after the write the new document shows under the cursor and takes the selection, or takes the place of a row of the
same name, and its tree is marked "new, may not match the filter" until `r` reads the documents again;
* `d` deletes the field under the cursor, or in the documents the selected document. An element of an array is not
deleted alone, since arrays are written whole. `y` deletes the document alone and leaves its subcollections, which
the confirmation names. When the document has subcollections, `R` also deletes every document under it, at any
depth;
* a delete with `R` is not atomic. It deletes the documents under the document in batches of 500, each document after
the documents under it, and the document itself last, with the update time it was read with. The documents under a
document that does not exist go too. The confirmation counts the documents deleted as it goes, and Ctrl-C stops the
delete once the batch in flight is answered. A second Ctrl-C stops waiting for that batch;
* a delete with `R` first reads the document. When it changed since it was read, nothing is deleted, and the
confirmation shows the delete over what the document holds now, as after a stale write;
* a delete with `R` that stops or fails keeps the document, and the confirmation shows how many documents under it were
deleted. A stop leaves no document under one that was deleted, and `n` closes the confirmation. After a second Ctrl-C
the batch in flight may still delete documents, the document itself among them, and `r` shows what stays;
* `a` adds a field next to the one under the cursor or in the popup of its value, or inside the open map under the
cursor or the map of a popup. On
the `subcollections` row it adds a top-level field, so a document without fields gets its first one there. In an
array `a` does nothing, since arrays are written whole;
* a new field asks for its name, then for its type from a list of string, integer, double, boolean, timestamp, null,
map, array, reference, geopoint and bytes, then for its value. An empty name is refused, and so is the name of a
field beside it. A name such as `first name` needs no quotes;
* a string, a number, a boolean, a timestamp, a reference or a geopoint opens the value editor with no text, and bytes
open `$VISUAL` or `$EDITOR` on an empty file, which saved empty writes empty bytes. A null, a map and an array go
straight to the confirmation, the map and the array empty;
* Esc at the name, the type or the value drops the new field and writes nothing. The confirmation shows no value before
the change;
* a change to a field writes that field alone, and every write carries the update time the document was read with.
When the document changed since, Firestore refuses the write, and the browser reads the document again and shows the
same change over what it holds now. When it was deleted since, a change to a field is not written, and `e` still
opens its text, while an edit of the whole document creates the document again;
* after a write the browser shows the document as Firestore returned it, with the cursor and the open maps kept, and
reads nothing else again.
**Copying**
* `y` copies a string as its text, and any other value as one line of JSON in the tagged encoding `fsq export` writes,
such as `{"$timestamp":"2023-11-14T22:13:20Z"}`. `Y` copies the path as SQL reads it, such as `address.city` or
`tags[0]`;
* the copy goes to the clipboard over OSC 52, an escape sequence that asks the terminal to set its clipboard, so it
also works over SSH. Some terminals need OSC 52 turned on, and tmux needs `set -g set-clipboard on`.
**Terminal**
* with `NO_COLOR` set, the browser draws without colours;
* the browser needs a terminal on stdin and stdout, so `\browse` in piped input, or with stdout sent to a pipe or a
file, fails with an error. In `fsq -e` and `fsq -f` at a terminal, `\browse` opens the browser, and the script goes
on after it quits.
### Describing a collection
```sh
fsq -p my-project -d my-database describe books --sample 100
```
`\d books` in the REPL lists the same: each field path of a sample of documents, nested maps included, with the
types it holds, the share of the sampled documents that have it and an example value. The sample is 500 documents
unless `--sample` sets another size. fsq asks Firestore for a random sample first. When Firestore refuses it,
as a Standard edition database does, the sample is the first documents by ID.
### Listing subcollections
`\l --recursive` lists the collections under the root and the subcollections below them, one row each, with the
columns `collection`, `path`, `depth` and `seen_under`.
Firestore lists the collections under one document at a time, so no call returns every subcollection. fsq reads a
sample of the documents of each collection and lists the collections under them:
* `--sample K` is the number of documents read per collection path, 20 by default. For `users/*/addresses` that is 20
documents in all, taken from the `addresses` collections of the sampled users;
* `--depth N` is the number of levels listed, 2 by default. Depth 1 is the root collections alone, and depth 3 reads
the documents of the collections at depths 1 and 2;
* the sample is the first documents by ID. It includes a document that does not exist and has subcollections, such
as `users/carol` when only `users/carol/orders/o1` was written;
* `path` shows each document ID on the way as `*`, `depth` is the level, and `seen_under` is how many of the sampled
documents of the collection above have this one. A subcollection that only documents outside the sample have is
not listed;
* the footer gives the number of collections, the time and the sample. `--format json` and `jsonl` give the same
rows, with `seen_under` as text, and no footer.
Each call takes several seconds on an Enterprise edition database, where a Standard edition database answers in a
fraction of a second. fsq sends the calls of one level together, so the time grows with the depth, and a listing at
depth 2 can take tens of seconds. `--depth 1` is the quick listing of the root collections.
## Scripting
```sh
fsq -p my-project -d my-database sql -e 'SELECT title FROM books LIMIT 10'
fsq -p my-project -d my-database sql -f report.sql
fsq -p my-project -d my-database --format jsonl sql -e 'SELECT * FROM books' | jq .title
echo 'SHOW COLLECTIONS; \d books' | fsq -p my-project -d my-database
```
* a script is split on `;` and runs one statement at a time, since the firestore crate takes one statement per call.
Meta-commands run in scripts too;
* `-e` and `-f` stop at the first statement that fails and exit with 1. The error names the position of that input in
the script and its first line;
* input piped to fsq runs as the REPL runs typed input: a failed statement is reported and the rest still runs, and
fsq exits with 1 when any failed;
* `--format json` prints each result as a JSON array of objects, and `--format jsonl` as JSON lines, one object per
line. The footers are left out, and notices go to stderr;
* the values use the plain JSON encoding of the firestore crate, which is for display and cannot be read back into
the same Firestore types: a timestamp is RFC 3339 text, bytes are base64, and a reference is its path relative to
the database. The [JSON conversion](https://firestore-rust.abdolence.dev/json.html) chapter lists every type. Use
[`fsq export`](#export-and-import) for output that reads back.
## Export and import
```sh
fsq -p my-project -d my-database export books -o books.jsonl
fsq -p my-project -d my-database export users --recursive -o users.jsonl
fsq -p my-project -d my-database import books.jsonl
```
### Export
`export` writes one document per line to stdout, or to the file `-o` names. A line is a JSON object with the
document's `__name__`, relative to the database, and its fields. The values use the tagged JSON encoding of the
firestore crate, which reads back to the same Firestore types: a timestamp is `{"$timestamp": "2023-11-14T22:13:20Z"}`,
bytes are `{"$bytes": ".."}`, a reference is `{"$ref": "books/dune"}` and an integer beyond 2^53 is `{"$int": ".."}`.
The [JSON conversion](https://firestore-rust.abdolence.dev/json.html) chapter of the crate lists every type.
| `<collection>` | exports a collection, by path for a subcollection such as `users/alice/orders` |
| `--group` | exports every collection with that ID, at any depth; the argument is a collection ID, and `--recursive` does not combine with it |
| `--recursive` | adds the subcollections of every document, each name with its full relative path; one extra request per document |
| `--sql '<SELECT>'` | exports the rows of a `SELECT` instead of a collection, on an Enterprise edition database; a row needs its `__name__` to be imported |
| `--with-metadata` | adds `__create_time__` and `__update_time__` to every document; `import` ignores both |
| `--plain` | writes the plain encoding, which is for reading and cannot be imported |
| `-o`, `--output` | writes to a file instead of stdout |
`--recursive` also lists the subcollections of a document that does not exist and has only subcollections, and writes
no line for that document. Unless the documents go to a terminal, a spinner on stderr shows how many documents were
written, and a line on stderr states the total.
### Import
`import` reads a file, or stdin for `-`, and writes the documents in batches through the batch writer of the
firestore crate. A batch holds at most 500 writes and about 9 MiB, and it ends before a document that it already
holds, since Firestore refuses a request that writes one document twice. A bar shows the position in the file, or a
spinner when the input is stdin.
| `--on-conflict skip` | leaves a document that exists as it is and counts it as skipped |
| `--on-conflict fail` | reports a document that exists as a failure |
| `--merge` | writes the top-level fields a line lists, and keeps the other fields of an existing document; it cannot be combined with `--on-conflict` |
| `--keep-going` | goes on after a failure and reports every one |
Without `--on-conflict` or `--merge`, import creates a document, or replaces it when it exists, so that an export
imported again gives the same documents.
Failures:
* a line that is not valid JSON, or not a document in the tagged encoding, fails with its line number and the code of
the firestore crate, such as `JSON_UNKNOWN_WRAPPER`. A document that Firestore refuses fails with its line number
and the status code;
* a batch is not atomic: each write of it is counted as written, skipped or failed, so that the other writes of a
batch with a failure are applied;
* a request that Firestore refuses as a whole fails every write of it, and the failure names the first and the last
line of the batch;
* without `--keep-going` the import stops after the request that holds the first failure, and reports every failed
write of that request. With it the import goes on after a line, a write or a request fails;
* fsq exits with 1 when any document failed. The last line on stderr counts the documents written, skipped and failed.
## Indexes
### Index statements
`CREATE INDEX`, `DROP INDEX`, `ALTER COLLECTION` and `SHOW INDEXES` run in the REPL and in scripts.
`CREATE INDEX` and `ALTER COLLECTION` start a build that takes minutes even for an empty collection. fsq waits for it
with a spinner and the elapsed time. Ctrl-C stops the wait, not the build, and `SHOW INDEXES FROM <collection>`
shows its state afterwards. `--no-wait` and `\wait off` return as soon as the build starts.
```sql
CREATE INDEX ON books (genre, rating DESC);
SHOW INDEXES FROM books;
DROP INDEX IF EXISTS `CICAgJim14AK`;
```
The statements and their options are in [Index statements](https://firestore-rust.abdolence.dev/sql/indexes.html).
### Indexes from a file
`fsq index` works on the `firestore.indexes.json` format of the Firebase CLI: the `indexes` and the `fieldOverrides`
of each collection group. It plans and syncs the collection groups of a file one after another.
```sh
fsq -p my-project index export -o firestore.indexes.json
fsq -p my-project index plan firestore.indexes.json
fsq -p my-project index sync firestore.indexes.json
fsq -p my-project index list --group books
fsq -p my-project index create books genre:asc rating:desc
fsq -p my-project index delete books genre:asc rating:desc --if-exists
```
| `plan <file> [--prune]` | prints what the file would change and writes nothing |
| `sync <file> [--prune] [--no-wait]` | applies the plan, with a spinner for each collection group while its builds run, and prints the same table |
| `list [--group <collection group>]` | lists the live indexes and field overrides, as `SHOW INDEXES` does |
| `export [-o <file>]` | writes the live indexes, field overrides and time-to-live (TTL) fields as an indexes file, to stdout without `-o` |
| `create <collection group> <field>:<mode>... [--scope collection\|group] [--if-not-exists]` | creates one composite index; the mode is `asc`, `desc` or `contains` |
| `delete <index id> [--if-exists]` | deletes one index by its ID |
| `delete <collection group> <field>:<mode>... [--scope ..] [--if-exists]` | deletes one index by its definition |
* `plan` prints one row per index, field override and TTL field that the file declares or that is live, with one
state: `create`, `update`, `enable`, `delete`, `revert`, `disable`, `unchanged`, `pending`, `reverting`,
`needs repair`, `undeclared`, `withheld` or `unrecognised`. An item that already matches the file shows as
`unchanged`, and a field override that Firestore is still reverting shows as `reverting`;
* `--no-wait` on `sync` returns once the last change is requested. Ctrl-C stops the wait, not the builds, and
`fsq index list` shows their state afterwards;
* `export` names on stderr the items the firestore crate cannot represent, such as an index with `multikey`, and
leaves them out of the file.
Without `--prune`, what the database has and the file does not declare is shown as `undeclared` and left alone,
in every collection group of the database, including the ones the file does not name. `--prune` deletes
undeclared indexes, reverts undeclared field overrides to automatic indexing and disables undeclared TTL fields.
A pruning sync deletes only after the indexes it created have finished building, even with `--no-wait`.
<details>
<summary>The indexes file</summary>
The file is the format of `firebase firestore:indexes` and `firebase deploy`, and `fsq index export` writes what
`firebase firestore:indexes` writes: `indexes`, with `collectionGroup`, `queryScope`, `fields` and `density`, and
`fieldOverrides`, with `ttl` and `indexes`. A field sets exactly one of `order`, `arrayConfig`, `searchConfig`
(a `textSpec` or a `geoSpec`) and `vectorConfig`. On a field override, an empty `indexes` exempts the field, the
`fieldPath` `*` names every field of the collection group, and `ttl: true` enables TTL on the field. `ttl: false`
declares nothing.
`density`, `unique`, `multikey` and `apiScope` are read from an index. The firestore crate declares the default
`apiScope`, `ANY_API`, and `multikey: false` only, so a file that sets another value is refused.
The Firebase CLI does not read the `fsq` keys. They hold what the Firebase format cannot carry:
| `fsq.search` on an index | `textLanguage` and `textLanguageOverrideFieldPath` of a search index | the format has no key for the language options of a search index |
| `fsq.unique` on an index | `true` for a unique index | the Firebase CLI refuses a file whose index has `unique`; fsq reads that key too and writes its own |
| `fsq.ttl` on the file | a list of `{ "collectionGroup", "fieldPath" }`, a TTL field whose indexes are inherited | the format writes `ttl` on a field override only, and an override with no `indexes` exempts the field |
```json
{
"indexes": [
{
"collectionGroup": "articles",
"queryScope": "COLLECTION",
"fields": [
{
"fieldPath": "body",
"searchConfig": {
"textSpec": { "indexSpecs": [{ "indexType": "TOKENIZED", "matchType": "MATCH_GLOBALLY" }] }
}
},
{ "fieldPath": "published", "order": "DESCENDING" }
],
"density": "SPARSE_ANY",
"fsq": { "search": { "textLanguage": "en" } }
}
],
"fieldOverrides": [
{ "collectionGroup": "sessions", "fieldPath": "expires_at", "ttl": true, "indexes": [] }
]
}
```
A key that neither the Firebase format nor `fsq` defines is refused with its path, so that no setting is dropped
without notice. A key set to `null` counts as absent.
</details>
## Fluent Rust code
```sh
fsq -p my-project -d my-database codegen \
'SELECT title, rating FROM books WHERE rating >= @min LIMIT 10' --param min=4.0
```
`codegen` prints the Rust code that the `codegen` feature of the firestore crate generates for a `SELECT`: a row
struct, and an async function that runs the equivalent pipeline of the fluent API. It is meant for porting a
statement to application code, and the output is a starting point to paste and edit. fsq prints what the crate
returns and generates nothing itself. `\gen '<SELECT>'` in the REPL does the same, and `\gen` alone uses the last
`SELECT` that ran.
| `--param name=value` | binds `@name` to a JSON literal, which gives the function argument its type: `4` is an integer, `4.0` a double, `true` a boolean and `"text"` a string; a `?` parameter cannot be bound |
| `--sample N` | runs the `SELECT` as a read of at most N rows, 100 by default, and types the fields of the row struct from them; the output does not show that limit |
| `--offline` | does not run the `SELECT` and needs no connection, so every field is typed as unknown JSON; it does not combine with `--sample` |
`\gen` takes the same options as `codegen`: `\gen ['SELECT'] [--param NAME=VALUE] [--sample N] [--offline]`. Its
`SELECT` is one argument, and a JSON string for `--param` is quoted twice, once for the JSON and once for the shell:
```
\gen 'SELECT title FROM books WHERE genre = @genre' --param 'genre="science fiction"'
```
The same quoting applies to `--param` on the command line. A `SELECT` that holds single quotes goes in double quotes.
A statement that is not a `SELECT`, and a `SELECT` with a construct the crate cannot show, fails with the crate's
error that names the construct. The [fluent code](https://firestore-rust.abdolence.dev/sql/codegen.html) chapter of
the crate lists what the output covers and how it types the fields. The sample is read with a `SELECT`, so it needs
an Enterprise edition database, and `--offline` works on any edition.
## Licence
Apache-2.0, see [LICENSE](LICENSE).
## Author
Abdulla Abdurakhmanov