Teaches the CLI sync server to serve a directory of databases from one
process and one port. Today `tursodb --sync-server <addr> <file>` serves
exactly one database; running N local databases means N processes and N
ports.
```bash
tursodb --sync-server 127.0.0.1:8080 --sync-dir ./dbs
```
Each database is addressed by name beneath `/db/{name}`:
```
http://localhost:8080/db/{name}/v2/pipeline
http://localhost:8080/db/{name}/pull-updates
```
A request to `/db/db1` reads and writes `./dbs/db1/data` — each database
gets its own directory, so on disk the files appear as `data`, `data-
wal`, `data-shm` (and `data.db-log` under MVCC), matching sqld's per-
database layout. Databases are created on first request (matching
single-database mode, which also auto-creates), except under
`--readonly`, where a missing database is a `404`. Single-database mode
is unchanged, and `/db/...` returns `404` there.
Names must match `^[A-Za-z0-9_-]+$` (max 128 chars). Since `.`, `/`,
`\`, and `%` are all outside the charset, path traversal — including
percent-encoded traversal — is rejected without ever URL-decoding.
Windows reserved device names (`con`, `nul`, `com1`…) are rejected on
every platform. A URL segment never reaches the filesystem unvalidated,
and this is unit-tested.
One commit per idea, in review order:
1. **`cli/sync_server: thread a database handle through request
handlers`** — pure refactor, no behavior change: replaces the server's
global `conn` + `db_path` with a `DbHandle` passed through the handlers.
The per-database `Mutex` this introduces is the same guard single-
database mode has today.
2. **`cli/sync_server: parse request routes into a Route enum`** — pure
functions plus unit tests, no wiring.
3. **`cli: serve a directory of databases with --sync-dir`** — the
feature: a lazy-opening, cached database registry keyed by validated
name, the clap flag, and integration tests.
4. **`cli: cap the databases a --sync-dir server keeps open`** —
`--sync-max-databases` (default 256); a request that would exceed it
gets `503` rather than exhausting file descriptors.
5. **`bindings/rust: exercise the sync test suite against --sync-dir`**
— the env-gated `LOCAL_SYNC_SERVER` sync suite gains a
`LOCAL_SYNC_SERVER_DIR` mode so every existing sync test (page-based and
MVCC logical-log) also runs against directory mode; CI runs it on Linux.
6. **`docs: document --sync-dir multi-database sync serving`** — CLI
reference, getting-started, and README, including the limitations below.
7. **`cli/sync_server: log client statement failures at debug, not
error`** — a client's bad SQL is not a server error; keeps multi-client
server logs readable. (Happy to split this into its own PR if
preferred.)
### Known limitations (documented in the CLI reference)
- Requests are handled one at a time across all databases — same serial
loop as today's server. Per-database concurrency is a planned follow-up
PR (thread-per-connection; the per-database mutex from commit 1 is
already the right lock), kept out of this one so each PR argues one
idea.
- Open handles are cached for the process lifetime, never evicted or
revalidated; deleting a served database's directory requires a restart.
- Any client that can reach the port can create databases by requesting
new names; there is no auth or multi-tenancy. Directory mode targets
local and development use.
- **Open question for reviewers:** with `--experimental-attach`, a
client can `ATTACH` an arbitrary filesystem path, escaping the served
directory. The docs currently warn about the combination — should the
CLI reject `--experimental-attach --sync-dir` outright instead?
The sync server is the local/dev story for Turso sync, and one-database-
per-process stops being workable as soon as an app or test suite has
more than one database. This lets you point one server at a folder and
address each database by name — the same shape the hosted service
exposes — with no new dependencies and no protocol changes.
## Testing
- Unit tests for route parsing, name validation (traversal, encoding,
device names), and path resolution — including that two databases can
never resolve to the same `.db`/`.db-log` paths (the guard against one
database serving another's logical log).
- `cli/tests/multi_sync.rs`: 7 integration tests spawning the real
binary — two-database isolation (pipeline and pull-updates), invalid-
name rejection, single-mode `/db/...` 404, the open-handle cap, and the
flag coupling (`--sync-dir` requires `--sync-server` and rejects a
positional database).
- The full env-gated bindings sync suite passes in **both** modes
locally (19 tests each, single-database and `--sync-dir`), demonstrating
the handler refactor changed no behavior and directory mode serves the
existing protocol faithfully; CI now also runs the directory-mode pass
on Linux.
- `cargo fmt`, `cargo clippy --workspace --all-features --all-targets --
--deny=warnings`, and the `turso_cli` test suites all pass on the
rebased branch (rebased onto `main` after #8071 merged; the two
histories touched the same request-parsing code).
This PR was developed with Claude Code driving most of the design
exploration, implementation, tests, and docs under my direction, over
multiple sessions: an initial design spec verified against the code,
implementation in reviewable commits, an adversarial pre-PR review pass
that cut ~50 non-test lines, and a rebase after the prerequisite header-
hardening PR merged. I reviewed and take responsibility for every line.
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Reviewed-by: Pere Diaz Bou <pere-altea@homail.com>
Closes #8346
Turso
Turso is an embedded database engine that runs anywhere — on servers, in browsers, or on-device. It's a drop-in replacement for SQLite, rewritten in Rust for concurrent access and async I/O.
This package provides the turso CLI — an interactive SQL shell, a local sync server, and an MCP server for AI assistants.
Install
npm install -g turso
Or run directly without installing:
npx turso
Quick Start
# Start an interactive shell with an in-memory database
npx turso
# Open or create a database file
npx turso myapp.db
# Execute a SQL statement directly
npx turso myapp.db "SELECT * FROM users;"
Features Beyond SQLite
Turso is a drop-in replacement for SQLite, but adds features that SQLite doesn't have:
- Concurrent Writers —
BEGIN CONCURRENTallows multiple writers without blocking, powered by MVCC - Native Vector Search —
vector32/vector64types with distance functions (vector_distance_cos,vector_distance_l2) - Change Data Capture — track row-level changes per connection with
PRAGMA capture_data_changes_conn - MCP Server — run as a Model Context Protocol server for AI assistants (
--mcp) - Local Sync Server — serve a database over HTTP for client SDKs to sync against (
--sync-server), or serve a whole directory of databases at once (--sync-dir) - Array Types — array columns in STRICT tables with operators like
@>,<@,|| - Built-in Extensions — crypto, regexp, fuzzy matching, IP address functions, CSV, percentile
Experimental Features
These features are available behind --experimental-* flags:
- Materialized Views — incrementally maintained views with automatic change tracking
- Custom Types — user-defined types with
CREATE TYPE, custom encode/decode and operators - At-Rest Encryption — transparent database encryption (AES-GCM, AEGIS ciphers)
- Full-Text Search — Tantivy-powered FTS with custom index methods
- Generated Columns — virtual and stored computed columns
- Triggers —
CREATE TRIGGER/DROP TRIGGER - Attach —
ATTACH DATABASE/DETACH DATABASE - Autovacuum — automatic database compaction
Run npx turso --help for the full list of flags.
Examples
Interactive Shell
npx turso myapp.db
turso> CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
turso> INSERT INTO users VALUES (1, 'Alice', 'alice@example.com');
turso> SELECT * FROM users;
┌────┬───────┬───────────────────┐
│ id │ name │ email │
├────┼───────┼───────────────────┤
│ 1 │ Alice │ alice@example.com │
└────┴───────┴───────────────────┘
One-Shot Queries
# Run a query and exit
npx turso myapp.db "SELECT count(*) FROM users;"
# Pipe-friendly list output
npx turso -q -m list myapp.db "SELECT * FROM users;"
Embedded Database
Use Turso directly as an embedded database in your Node.js application with @tursodatabase/database:
import { connect } from "@tursodatabase/database";
const db = await connect("local.db");
await db.exec(`
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
`);
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
await insert.run(["Alice", "alice@example.com"]);
const select = db.prepare("SELECT * FROM users");
console.log(await select.all());
Local Sync Server
Start a local HTTP server that implements the Turso sync protocol. The @tursodatabase/sync SDK can sync against it:
npx turso myapp.db --sync-server "0.0.0.0:8080"
To serve a directory of databases instead of a single file, pass --sync-dir. Each database is addressed by name at /db/{name} and created on first request:
npx turso --sync-server "127.0.0.1:8080" --sync-dir ./dbs
A client syncing against http://localhost:8080/db/db1 reads and writes ./dbs/db1/data. Names must match ^[a-z0-9_-]+$. This mode has no authentication and is meant for local development; see the CLI documentation for the full details and limits.
MCP Server
Start an MCP server so AI assistants can query your databases:
npx turso --mcp
Shell Commands
Inside the interactive shell, use .commands for database operations:
| Command | Description |
|---|---|
.open <FILE> |
Open a different database |
.tables |
List all tables |
.schema [TABLE] |
Show table schema |
.mode <MODE> |
Switch output mode (pretty, list, line) |
.import <FILE> <TABLE> |
Import data from a file into a table |
.dump |
Dump the database as SQL |
.quit |
Exit the shell |
Supported Platforms
| Platform | Architecture |
|---|---|
| macOS | ARM64, x64 |
| Linux (glibc) | ARM64, x64 |
| Windows | ARM64, x64 |
Links
License
MIT