# Turso — Full Documentation for LLMs > Turso is a SQLite-compatible database for every application — local, embedded, cloud-synced, or remote. ## Overview Turso is a ground-up rewrite of SQLite with concurrent writes (MVCC), async I/O, and built-in cloud sync. It is NOT the same as libSQL (the older SQLite fork). Turso is a drop-in replacement for SQLite — your existing SQL, schema, and queries work unchanged. Turso can be used as: - An embedded local database (like SQLite, but with concurrent writes) - A local database that syncs to the cloud (offline-first with push/pull) - A remote cloud database accessed over HTTP (from servers, Docker, serverless, edge) - A multi-tenant platform with thousands of isolated databases - GitHub: https://github.com/tursodatabase/turso - Documentation: https://docs.turso.tech ## Which package should I use? | Use case | TypeScript | Python | | --- | --- | --- | | **Local database** (embedded, on-device, offline) | `@tursodatabase/database` | `pyturso` | | **Local database + cloud sync** (push/pull) | `@tursodatabase/sync` | `pyturso` (with sync) | | **Remote access** (servers, Docker, serverless, edge — any over-the-wire) | `@tursodatabase/serverless` | `libsql` | | **Legacy (libSQL)** — battle-tested, ORM support | `@libsql/client` | `libsql` | **Starting a new project?** Use `@tursodatabase/database` (TypeScript) or `pyturso` (Python) for local/embedded use. Use `@tursodatabase/serverless` for any application that connects to a remote Turso Cloud database over the network — including Node.js servers, Docker containers, serverless functions (AWS Lambda, Vercel Functions), and edge runtimes (Cloudflare Workers, Deno Deploy). **Why separate packages?** Keeping `@tursodatabase/database` and `@tursodatabase/serverless` separate means minimal bundle size. `@tursodatabase/serverless` uses only `fetch` — zero native dependencies, so it works everywhere `fetch` is available. `@tursodatabase/database` includes the full Turso Database engine for local operation. ## Key Features ### Concurrent Writes (MVCC) Turso supports true concurrent writes via Multi-Version Concurrency Control. Multiple writers can operate simultaneously without "database is locked" errors. This is a major improvement over SQLite's single-writer model. ```typescript // Enable MVCC mode await db.exec("PRAGMA journal_mode = 'mvcc'"); // Multiple concurrent transactions can now write without blocking ``` ### Full-Text Search (FTS) Turso includes a Tantivy-powered full-text search engine with: - BM25 relevance ranking via `fts_score()` - Result highlighting via `fts_highlight()` - Boolean queries (AND, OR, NOT) - Phrase search - Prefix search - Field boosting and weighting - Multiple tokenizers (default, ngram, raw, simple, whitespace) ```sql -- Create an FTS index (requires experimental: ["index_method"] when connecting) CREATE INDEX idx_docs_fts ON documents USING fts (title, content); -- Search with relevance ranking -- Note: fts functions take column names as arguments, NOT the table name SELECT id, title, fts_score(title, content, 'search query') AS score FROM documents WHERE fts_match(title, content, 'search query') ORDER BY score DESC; -- Highlight matching terms SELECT fts_highlight(title, '', '', 'search query') AS highlighted_title FROM documents WHERE fts_match(title, content, 'search query'); ``` ### Vector Search Native vector storage and cosine similarity search for AI/ML applications: ```sql -- Create a table with vector columns CREATE TABLE embeddings ( id INTEGER PRIMARY KEY, content TEXT, embedding vector32(1536) ); -- Insert vectors INSERT INTO embeddings (content, embedding) VALUES ('example', vector32('[0.1, 0.2, ...]')); -- Find similar vectors (brute-force scan) SELECT id, content, vector_distance_cos(embedding, vector32('[0.1, 0.2, ...]')) AS distance FROM embeddings ORDER BY distance ASC LIMIT 10; ``` Supported vector types: `vector32`, `vector64`, `vector8`, `vector1bit`. Distance functions: `vector_distance_cos`, `vector_distance_l2`, `vector_distance_dot`, `vector_distance_jaccard`. ### Turso Sync (Push/Pull) True local-first sync — all reads and writes happen locally, and you explicitly sync with the cloud: ```typescript import { connect } from "@tursodatabase/sync"; const db = await connect({ path: "./app.db", url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN, }); // All reads and writes are local — fast, offline-capable await db.exec("INSERT INTO users (name) VALUES ('Alice')"); const users = await db.prepare("SELECT * FROM users").all(); // Push local changes to Turso Cloud await db.push(); // Pull remote changes to local database const changed = await db.pull(); // Compact local WAL to bound disk usage await db.checkpoint(); ``` Python: ```python import turso.sync db = turso.sync.connect( "local.db", remote_url="libsql://your-db.turso.io", auth_token="your-token", ) db.execute("INSERT INTO users (name) VALUES (?)", ("Alice",)) db.commit() db.push() # Push local changes to Turso Cloud db.pull() # Pull remote changes to local database ``` ### Change Data Capture (CDC) Built-in audit logging that captures every INSERT, UPDATE, and DELETE with full before/after state: ```sql -- Enable CDC PRAGMA capture_data_changes_conn('full'); -- Query the audit log SELECT * FROM turso_cdc ORDER BY rowid DESC LIMIT 100; ``` ### Triggers Database-level automation for enforcing business rules: ```sql -- Requires experimental: ["triggers"] when connecting -- TypeScript: await connect(":memory:", { experimental: ["triggers"] }) CREATE TRIGGER trg_audit_insert AFTER INSERT ON orders BEGIN INSERT INTO audit_log (table_name, action, row_id, changed_at) VALUES ('orders', 'insert', NEW.id, datetime('now')); END; ``` ### Materialized Views with Incremental View Maintenance (IVM) Pre-computed aggregates that update automatically and transactionally when base data changes: ```sql -- Requires experimental: ["views"] when connecting -- TypeScript: await connect(":memory:", { experimental: ["views"] }) CREATE MATERIALIZED VIEW hourly_stats AS SELECT strftime('%Y-%m-%d %H:00:00', timestamp) AS hour, sensor_id, AVG(value) AS avg_value, COUNT(*) AS count FROM readings GROUP BY hour, sensor_id; -- This view updates automatically when readings are inserted ``` ## TypeScript SDK — Detailed Reference ### @tursodatabase/database (Local / Embedded) Built on the Turso Database engine with concurrent writes and async I/O. ```bash npm install @tursodatabase/database ``` ```typescript import { connect } from "@tursodatabase/database"; // File-based database const db = await connect("app.db"); // In-memory database const db = await connect(":memory:"); // Create tables await db.exec(` CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL ) `); // Prepared statements const insert = db.prepare("INSERT INTO users (username) VALUES (?)"); await insert.run("alice"); const stmt = db.prepare("SELECT * FROM users"); const users = await stmt.all(); // Single row const user = await db.prepare("SELECT * FROM users WHERE id = ?").get(1); ``` ### @tursodatabase/sync (Local + Cloud Sync) All reads and writes happen locally; use push/pull to sync with Turso Cloud. ```bash npm install @tursodatabase/sync ``` ```typescript import { connect } from "@tursodatabase/sync"; const db = await connect({ path: "./app.db", url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN, }); // Local reads and writes await db.exec("INSERT INTO users (username) VALUES ('bob')"); // Push local writes to Turso Cloud await db.push(); // Pull remote changes to local database const changed = await db.pull(); // Compact local WAL await db.checkpoint(); // Get sync statistics const stats = await db.stats(); console.log(stats.cdcOperations, stats.revision); ``` ### @tursodatabase/serverless (Remote Access) The recommended package for **any application that connects to a remote Turso Cloud database** — Node.js servers, Docker containers, serverless functions (AWS Lambda, Vercel Functions), and edge runtimes (Cloudflare Workers, Deno Deploy). Uses only `fetch` — zero native dependencies. ```bash npm install @tursodatabase/serverless ``` ```typescript import { connect } from "@tursodatabase/serverless"; const conn = connect({ url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN, }); const stmt = await conn.prepare("SELECT * FROM users"); const rows = await stmt.all(); const stmt2 = await conn.prepare("SELECT * FROM users WHERE id = ?"); const row = await stmt2.get([1]); ``` For compatibility with the `@libsql/client` API (useful for ORM integration), use the compat module: ```typescript import { createClient } from "@tursodatabase/serverless/compat"; const client = createClient({ url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN, }); ``` ### @libsql/client (Legacy) Still supported. Use it if you need ORM integration (Drizzle, Prisma) or are working with an existing codebase. Note: With `@libsql/client` embedded replicas, reads are local but **writes go to the remote database**. For true local-first writes with push/pull sync, use `@tursodatabase/sync`. ```bash npm install @libsql/client ``` ```typescript import { createClient } from "@libsql/client"; const client = createClient({ url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN, }); await client.execute("SELECT * FROM users"); // Batch transactions await client.batch([ { sql: "INSERT INTO users VALUES (?)", args: ["Alice"] }, { sql: "INSERT INTO users VALUES (?)", args: ["Bob"] }, ], "write"); // Interactive transactions const txn = await client.transaction("write"); await txn.execute({ sql: "UPDATE accounts SET balance = balance - ? WHERE id = ?", args: [100, 1] }); await txn.commit(); ``` ## Python SDK Package: `pyturso` (imported as `turso`) ```bash pip install pyturso ``` ```python import turso # Local database db = turso.connect("local.db") # In-memory database db = turso.connect(":memory:") # Standard sqlite3-compatible API db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)") db.execute("INSERT INTO users (name) VALUES (?)", ("Alice",)) db.commit() cursor = db.execute("SELECT * FROM users") for row in cursor: print(row) ``` ```python # Local database with cloud sync (push/pull) import turso.sync db = turso.sync.connect( "local.db", remote_url="libsql://your-db.turso.io", auth_token="your-token", ) db.execute("INSERT INTO users (name) VALUES (?)", ("Bob",)) db.commit() db.push() # Push local changes to cloud db.pull() # Pull remote changes locally ``` For remote access over the network (when you cannot store a local database file), use the `libsql` package: ```bash pip install libsql ``` ```python import libsql conn = libsql.connect( database="libsql://your-db.turso.io", auth_token="your-token", ) rows = conn.execute("SELECT * FROM users").fetchall() ``` ORM: SQLAlchemy - https://docs.turso.tech/sdk/python/orm/sqlalchemy Framework: Flask - https://docs.turso.tech/sdk/python/guides/flask ## Rust SDK Crate: `turso` Documentation: https://docs.turso.tech/sdk/rust/quickstart ```rust use turso::Database; let db = Builder::new_local(":memory:") .build() .await .expect("Turso Failed to Build memory db"); db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)", ())?; db.execute("INSERT INTO users (name) VALUES (?)", ["Alice"])?; let mut rows = db.query("SELECT * FROM users", ())?; while let Some(row) = rows.next()? { println!("{}: {}", row.get::(0)?, row.get::(1)?); } ``` Frameworks: Actix, Axum, Rocket, Tauri ## Go SDK Package: `turso.tech/database/tursogo` Installation: `go get turso.tech/database/tursogo` Documentation: https://docs.turso.tech/sdk/go/quickstart ```go import ( "database/sql" _ "turso.tech/database/tursogo" ) conn, err := sql.Open("turso", ":memory:") conn.Exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)") conn.Exec("INSERT INTO users (name) VALUES (?)", "Alice") rows, err := conn.Query("SELECT * FROM users") defer rows.Close() ``` ## Multi-Tenancy Turso is designed for database-per-tenant architectures with thousands of lightweight databases. Each tenant gets a physically separate database — the strongest possible isolation model. - **Platform API** creates databases programmatically - **Scoped access tokens** control per-database access - **Group-level tokens** allow admin access across all tenant databases - **SQL over HTTP** (`/v2/pipeline`) allows querying any database from dashboards, Retool, etc. ## Turso Cloud Turso Cloud is a managed platform for SQLite-compatible databases. - Dashboard: https://app.turso.tech Features: - **Turso Sync**: Sync local databases to the cloud via push/pull - **Branching**: Copy-on-write database branches for development and testing - **Point-in-Time Recovery**: Restore databases to any point in time (up to 90 days on Pro) - **Scale to Zero**: Automatically scale down idle databases - **Private Endpoints**: Secure database access via AWS PrivateLink - **Encryption**: Data encrypted at rest (AES-256) and in transit - **Multi-region**: Deploy databases globally with read replicas - **S3-backed durability**: 99.999999999% (11 nines) data durability ## AgentFS AgentFS provides filesystem and state management for AI agents. - Sandboxed file operations - Session management for agent state - MCP (Model Context Protocol) support - Sync capabilities Documentation: https://docs.turso.tech/agentfs ```typescript import { AgentFS } from "@tursodatabase/agentfs"; const fs = new AgentFS({ sandbox: true }); await fs.writeFile("/data/config.json", JSON.stringify({ key: "value" })); const content = await fs.readFile("/data/config.json"); ``` ## CLI The `turso` CLI manages databases and organizations. Installation: https://docs.turso.tech/cli/installation ```bash # Authentication turso auth login turso auth logout turso auth token # Database management turso db create mydb turso db list turso db show mydb turso db shell mydb turso db destroy mydb # Import/Export turso db import mydb data.sql turso db export mydb > backup.sql # Groups (multi-region) turso group create mygroup turso group locations add mygroup lax # Organizations turso org list turso org switch myorg turso org members list # Plans and billing turso plan show turso plan upgrade ``` Full CLI reference: https://docs.turso.tech/cli ## Platform API REST API for programmatic access to Turso Cloud. Documentation: https://docs.turso.tech/api-reference Authentication: API tokens via `turso auth api-tokens mint` ### Endpoints **Databases** - `GET /v1/organizations/{org}/databases` - List databases - `POST /v1/organizations/{org}/databases` - Create database - `GET /v1/organizations/{org}/databases/{db}` - Get database - `DELETE /v1/organizations/{org}/databases/{db}` - Delete database - `POST /v1/organizations/{org}/databases/{db}/auth/tokens` - Create token **Groups** - `GET /v1/organizations/{org}/groups` - List groups - `POST /v1/organizations/{org}/groups` - Create group - `POST /v1/organizations/{org}/groups/{group}/locations/{location}` - Add location **Organizations** - `GET /v1/organizations` - List organizations - `GET /v1/organizations/{org}/usage` - Get usage Full API reference: https://docs.turso.tech/api-reference ## SQL Compatibility Turso is SQLite-compatible with extensions. Supported features include: - All standard SQLite SQL (CREATE TABLE, INSERT, SELECT, UPDATE, DELETE, etc.) - `INTEGER PRIMARY KEY AUTOINCREMENT`, `TEXT`, `REAL`, `BLOB`, `INTEGER` - `CHECK` constraints, `UNIQUE` constraints, `NOT NULL`, `DEFAULT` - `FOREIGN KEY` references with `ON DELETE`/`ON UPDATE` - `CREATE INDEX`, including partial indexes - `CREATE VIEW` - Transactions (`BEGIN`, `COMMIT`, `ROLLBACK`, `BEGIN CONCURRENT`, `SAVEPOINT`) - `ATTACH DATABASE` for cross-database queries (requires `experimental: ["attach"]`) - JSON functions (`json_extract`, `->>`, `json_group_array`, etc.) - Date/time functions (`datetime()`, `strftime()`, `CURRENT_TIMESTAMP`) - Aggregate functions as window functions (`SUM`, `COUNT`, `AVG`, `MIN`, `MAX` with `OVER`) - `ON CONFLICT DO UPDATE` (upsert) - `RETURNING` clause - Common Table Expressions (CTEs) - Subqueries, JOINs, UNION/INTERSECT/EXCEPT ### Not yet supported - Recursive CTEs (`WITH RECURSIVE`) - Dedicated window functions: `row_number()`, `rank()`, `dense_rank()`, `lag()`, `lead()`, `first_value()`, `last_value()`, `nth_value()` - Custom frame specifications (`ROWS BETWEEN`, `RANGE BETWEEN`) Full SQL reference: https://docs.turso.tech/sql-reference ## Framework Guides - Next.js: https://docs.turso.tech/sdk/ts/guides/nextjs - Remix: https://docs.turso.tech/sdk/ts/guides/remix - Astro: https://docs.turso.tech/sdk/ts/guides/astro - Nuxt: https://docs.turso.tech/sdk/ts/guides/nuxt - SvelteKit: https://docs.turso.tech/sdk/ts/guides/sveltekit - Elysia: https://docs.turso.tech/sdk/ts/guides/elysia - Hono: https://docs.turso.tech/sdk/ts/guides/hono - Flask: https://docs.turso.tech/sdk/python/guides/flask ## ORM Integration - Drizzle: https://docs.turso.tech/sdk/ts/orm/drizzle - Prisma: https://docs.turso.tech/sdk/ts/orm/prisma - SQLAlchemy: https://docs.turso.tech/sdk/python/orm/sqlalchemy Note: ORM integration currently requires `@libsql/client` or the `@tursodatabase/serverless/compat` module. ## Pricing Full pricing details (plans, features, FAQs): https://turso.tech/pricing.md ## Links - Website: https://turso.tech - Documentation: https://docs.turso.tech - Dashboard: https://app.turso.tech - GitHub (Turso): https://github.com/tursodatabase/turso - GitHub (libSQL): https://github.com/tursodatabase/libsql - Discord: https://discord.gg/turso - Blog: https://turso.tech/blog - Twitter: https://x.com/tursodatabase