# Turso > ## Documentation Index --- # Source: https://docs.turso.tech/cli/group/aws-migration/abort.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # group aws-migration abort You can abort the AWS migration process by using the following command: ```bash theme={null} turso group aws-migration abort ``` --- # Source: https://docs.turso.tech/sdk/rust/guides/actix.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Turso + Actix > Set up Turso in your Actix project in minutes Actix banner ## Prerequisites Before you start, make sure you: * [Install the Turso CLI](/cli/installation) * [Sign up or login to Turso](/cli/authentication#signup) * Have an Actix app β€” [learn more](https://actix.rs/docs/getting-started) You will need an existing database to continue. If you don't have one, [create one](/quickstart). You will want to store these as environment variables. ```sh theme={null} cargo add libsql ``` Optionally, you can add a package such as [`dotenvy`](https://docs.rs/dotenvy/latest/dotenvy) to help you work with `.env` files: ```sh theme={null} cargo add dotenvy ``` ```rust theme={null} #[tokio::main] #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| App::new().route("/", web::get().to(index)).route("/items", web::get().to(get_items))) .bind(("127.0.0.1", 8080))? .run() .await } async fn get_items() -> Result { dotenv().expect(".env file not found"); let db_url = env::var("TURSO_DATABASE_URL").unwrap(); let auth_token = env::var("TURSO_AUTH_TOKEN").unwrap(); let db_file = env::var("LOCAL_DB").unwrap(); let db = Builder::new_remote_replica(db_file, url, auth_token) .read_your_writes(true) .build() .await .unwrap(); let conn = db.connect().unwrap(); let mut results = conn.query("SELECT * FROM items", ()).await.unwrap(); let mut items: Vec = Vec::new(); while let Some(row) = results.next().await.unwrap() { let item: Item = Item { task: row.get(0).unwrap(), }; items.push(item); } Ok(HttpResponse::Ok().json(items)) } ``` ## Examples See the full source code --- # Source: https://docs.turso.tech/cli/org/members/add.md # Source: https://docs.turso.tech/api-reference/organizations/members/add.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Add Member > Add an existing Turso user to an organization. If you want to add someone who is not a registered Turso user, you can [create an invite](/api-reference/organizations/invites/create) instead. You must be an `owner` or `admin` to add other members. **You can only add users to a team and not your personal account.** ## OpenAPI ````yaml POST /v1/organizations/{organizationSlug}/members openapi: 3.0.1 info: title: Turso Platform API description: API description here license: name: MIT version: 0.1.0 servers: - url: https://api.turso.tech description: Turso's Platform API security: [] paths: /v1/organizations/{organizationSlug}/members: post: summary: Add Member description: Add an existing Turso user to an organization. operationId: addOrganizationMember parameters: - $ref: '#/components/parameters/organizationSlug' requestBody: description: The member you want to add. required: true content: application/json: schema: type: object properties: username: type: string description: The username of an existing Turso user. role: type: string enum: - admin - member - viewer description: The role given to the user. default: member required: - email responses: '200': description: Successful response content: application/json: schema: type: object properties: member: 98c6fa96-b891-4120-a419-04c0bce4a437 role: 53851d0f-d772-48da-abd0-98e806e38616 '404': description: Member not found content: application/json: schema: type: object properties: error: type: string description: The error message example: could not find user [username] '409': description: Conflict content: application/json: schema: type: object properties: error: type: string description: The error message example: >- user [username] is already a member of organization [organizationSlug] components: parameters: organizationSlug: in: path name: organizationSlug required: true schema: type: string description: The slug of the organization or user account. ```` --- # Source: https://docs.turso.tech/guides/agent-databases.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Agent Databases Looking for a complete agent state management solution? Check out [AgentFS](/agentfs/introduction) - our specialized SDK designed specifically for AI agents, offering filesystem operations, key-value storage, and automatic tool call tracking in a single database file. AI agents need databases to store context, track state, and maintain memory across executions. Turso Database offers two powerful approaches: * **Embedded Databases** for local-first agent processing, and * **Turso Sync** for distributed agent coordination with cloud persistence. ## Embedded Databases (Local-First) Use embedded databases for agents that process data locally within a single workflow, need offline-capable access, or work with temporary data without sharing state with other agents. Local data pipelines, on-device processing of sensitive data, development/testing workflows, and single-agent analysis tasks. ```javascript theme={null} import { connect } from "@tursodatabase/database"; // Create a local embedded database for this agent const db = await connect("agent-workflow.db"); // Agent can now store and query data locally const stmt = db.prepare(` CREATE TABLE IF NOT EXISTS steps ( id INTEGER PRIMARY KEY AUTOINCREMENT, action TEXT NOT NULL, result TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP ) `); stmt.run(); // Track agent workflow steps db.prepare("INSERT INTO steps (action, result) VALUES (?, ?)").run( "fetch_data", "success", ); ``` Benefit from zero network latency, full offline capability, complete data privacy, and simple single-file deployment. Data is isolated to this agent instance with no built-in multi-agent collaboration or cross-session persistence (unless you manage the file yourself). ## Turso Sync (Cloud-Connected) Use Turso Sync for agents that need persistent memory across sessions, coordinate with other agents, or require cloud-backed durability for long-running workflows. πŸ’‘ Conversational agents with session memory, multi-agent coordination systems, long-running workflows with recovery needs, and agents reporting to central systems. ```javascript theme={null} import { connect } from "@tursodatabase/database"; // Connect to a synced database (embedded locally, synced to Turso Cloud) const db = await connect({ path: "agent-memory.db", url: "https://your-database.turso.io", authToken: "your-auth-token", sync: "full", // Bidirectional sync }); // Agent can access data from previous sessions or other agents const previousContext = db .prepare("SELECT * FROM conversation_history WHERE session_id = ?") .all("session-123"); // New data is automatically synced to cloud and other agent instances db.prepare("INSERT INTO agent_actions (agent_id, action) VALUES (?, ?)").run( "agent-1", "processed_document", ); // Manually trigger sync if needed await db.sync(); ``` πŸ’‘ Persistent memory across restarts, multi-agent coordination via shared state, cloud backup and durability, with fast local reads and background sync. **Sync modes:** `sync` (bidirectional), `pull` (cloud β†’ agent), `push` (agent β†’ cloud). ## Multi-Agent Architectures ### Pattern 1: Isolated Agent Databases Each agent gets its own embedded database. Best for independent agents with no shared state. ```javascript theme={null} // Agent 1 const agent1DB = await connect("agent-1.db"); // Agent 2 const agent2DB = await connect("agent-2.db"); ``` Independent agents performing separate tasks with no coordination needs and maximum isolation. ### Pattern 2: Shared Database with Sync Multiple agents connect to the same synced database. Best for coordinated agent systems. ```javascript theme={null} // Agent 1 connects and writes tasks const agent1DB = await connect({ path: "agent-1-local.db", url: "https://shared-tasks.turso.io", authToken: process.env.TURSO_TOKEN, sync: "full", }); agent1DB.prepare("INSERT INTO tasks (status) VALUES (?)").run("pending"); // Agent 2 connects to same database and reads tasks const agent2DB = await connect({ path: "agent-2-local.db", url: "https://shared-tasks.turso.io", // Same database authToken: process.env.TURSO_TOKEN, sync: "full", }); const pendingTasks = agent2DB .prepare("SELECT * FROM tasks WHERE status = ?") .all("pending"); ``` πŸ’‘ Agents coordinating work through shared task queues or a common knowledge base. ### Pattern 3: Hub-and-Spoke A central synced database with agents pushing results and pulling new tasks. ```javascript theme={null} // Worker agents push results only const workerDB = await connect({ path: "worker-local.db", url: "https://hub.turso.io", authToken: process.env.WORKER_TOKEN, sync: "push", // Only push results to cloud }); // Coordinator agent pulls from all workers const coordinatorDB = await connect({ path: "coordinator-local.db", url: "https://hub.turso.io", authToken: process.env.COORDINATOR_TOKEN, sync: "pull", // Only pull data from cloud }); ``` πŸ’‘ Many worker agents feeding results to a central coordinator for monitoring or aggregation with unidirectional data flow. ## Database-Per-Agent Pattern For systems managing many agents, you can create individual databases for each agent using the [Platform API](https://docs.turso.tech/api-reference): ```javascript theme={null} import { createClient } from "@tursodatabase/api"; const turso = createClient({ token: process.env.TURSO_PLATFORM_API_TOKEN, org: process.env.TURSO_ORG_NAME, }); // Create a dedicated database for each agent async function provisionAgentDatabase(agentId) { const database = await turso.databases.create(`agent-${agentId}`, { group: "default", }); console.log(`Database created for agent ${agentId}: ${database.Name}`); return database; } ``` Complete isolation between agents, independent scaling per agent, improved security (compromised agent only affects one database), and easy cleanup when agents are retired. ## Examples Explore these examples to see agent database patterns in action: * [sync-node](https://github.com/tursodatabase/turso/blob/main/examples/javascript/sync-node) β€” Node.js with bidirectional sync to Turso Cloud * [sync-wasm-vite](https://github.com/tursodatabase/turso/blob/main/examples/javascript/sync-wasm-vite) β€” Browser (WASM) with bidirectional sync to Turso Cloud * [database-node](https://github.com/tursodatabase/turso/blob/main/examples/javascript/database-node) β€” Node.js, local file database (no sync) * [database-wasm-vite](https://github.com/tursodatabase/turso/blob/main/examples/javascript/database-wasm-vite) β€” Browser (WASM), local database in the browser --- # Source: https://docs.turso.tech/features/ai-and-embeddings.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # AI & Embeddings > Vector Similarity Search is built into Turso and libSQL Server as a native feature. Turso and libSQL enable vector search capability without an extension. ## How it works * Create a table with one or more vector columns (e.g. `FLOAT32`) * Provide vector values in binary format or convert text representation to binary using the appropriate conversion function (e.g. `vector32(...)`) * Calculate vector similarity between vectors in the table or from the query itself using dedicated vector functions (e.g. `vector_distance_cos`) * Create a special vector index to speed up nearest neighbors queries (use the `libsql_vector_idx(column)` expression in the `CREATE INDEX` statement to create vector index) * Query the index with the special `vector_top_k(idx_name, q_vector, k)` [table-valued function](https://www.sqlite.org/vtab.html#table_valued_functions) # Vectors ### Types LibSQL uses the native SQLite BLOB [storage class](https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes) for vector columns. To align with SQLite [affinity rules](https://www.sqlite.org/datatype3.html#determination_of_column_affinity), all type names have two alternatives: one that is easy to type and another with a `_BLOB` suffix that is consistent with affinity rules. We suggest library authors use type names with the `_BLOB` suffix to make results more generic and universal. For regular applications, developers can choose either alternative, as the type name only serves as a **hint** for SQLite and external extensions. As LibSQL does not introduce a new storage class, all metadata about vectors is also encoded in the `BLOB` itself. This comes at the cost of a few bytes per row but greatly simplifies the design of the feature. The table below lists six vector types currently supported by LibSQL. Types are listed from more precise and storage-heavy to more compact but less precise alternatives (the number of dimensions in vector $D$ is used to estimate storage requirements for a single vector). | Type name | Storage (bytes) | Description | | --------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `FLOAT64` \| `F64_BLOB` | $8D + 1$ | Implementation of [IEEE 754 double precision format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) for 64-bit floating point numbers | | `FLOAT32` \| `F32_BLOB` | $4D$ | Implementation of [IEEE 754 single precision format](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) for 32-bit floating point numbers | | `FLOAT16` \| `F16_BLOB` | $2D + 1$ | Implementation of [IEEE 754-2008 half precision format](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) for 16-bit floating point numbers | | `FLOATB16` \| `FB16_BLOB` | $2D + 1$ | Implementation of [bfloat16 format](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format) for 16-bit floating point numbers | | `FLOAT8` \| `F8_BLOB` | $D + 14$ | LibSQL specific implementation which compresses each vector component to single `u8` byte `b` and reconstruct value from it using simple transformation: $\texttt{shift} + \texttt{alpha} \cdot b$ | | `FLOAT1BIT` \| `F1BIT_BLOB` | $\lceil \frac{D}{8} \rceil + 3$ | LibSQL-specific implementation which compresses each vector component down to 1-bit and packs multiple components into a single machine word, achieving a very compact representation | For most applications, the `FLOAT32` type should be a good starting point, but you may want to explore more compact options if your table has a large number of rows with vectors. While `FLOAT16` and `FLOATB16` use the same amount of storage, they provide different trade-offs between speed and accuracy. Generally, operations over `bfloat16` are faster but come at the expense of lower precision. ### Functions To work with vectors, LibSQL provides several functions that operate in the vector domain. Each function understands vectors in binary format aligned with the six types described above or in text format as a single JSON array of numbers. Currently, LibSQL supports the following functions: | Function name | Description | | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `vector64` \| `vector32` \| `vector16` \| `vectorb16` \| `vector8` \| `vector1bit` | Conversion function which accepts a valid vector and converts it to the corresponding target type | | `vector` | Alias for `vector32` conversion function | | `vector_extract` | Extraction function which accepts valid vector and return its text representation | | `vector_distance_cos` | Cosine distance (1 - [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity)) function which operates over vector of **same type** with **same dimensionality** | | `vector_distance_l2` | Euclidean distance function which operates over vector of **same type** with **same dimensionality** | ### Vectors usage Begin by declaring a column used for storing vectors with the `F32_BLOB` datatype: ```sql theme={null} CREATE TABLE movies ( title TEXT, year INT, embedding F32_BLOB(4) -- 4-dimensional f32 vector ); ``` The number in parentheses `(4)` specifies the dimensionality of the vector. This means each vector in this column will have exactly 4 components. Once you generate embeddings for your data (via an LLM), you can insert them into your table: ```sql theme={null} INSERT INTO movies (title, year, embedding) VALUES ('Napoleon', 2023, vector32('[0.800, 0.579, 0.481, 0.229]')), ('Black Hawk Down', 2001, vector32('[0.406, 0.027, 0.378, 0.056]')), ('Gladiator', 2000, vector32('[0.698, 0.140, 0.073, 0.125]')), ('Blade Runner', 1982, vector32('[0.379, 0.637, 0.011, 0.647]')); ``` Popular tools like [LangChain](https://www.langchain.com), [Hugging Face](https://huggingface.co) or [OpenAI](https://turso.tech/blog/how-to-generate-and-store-openai-vector-embeddings-with-turso) can be used to generate embeddings. You can now write queries combining vectors and standard SQLite data: ```sql theme={null} SELECT title, vector_extract(embedding), vector_distance_cos(embedding, vector32('[0.064, 0.777, 0.661, 0.687]')) AS distance FROM movies ORDER BY distance ASC; ``` ### Understanding Distance Results The `vector_distance_cos` function calculates the cosine distance, which is defined as: * CosineΒ Distance = 1 β€” [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) The cosine distance ranges from 0 to 2, where: * A distance close to 0 indicates that the vectors are nearly identical or exactly matching. * A distance close to 1 indicates that the vectors are orthogonal (perpendicular). * A distance close to 2 indicates that the vectors are pointing in opposite directions. Very small negative numbers close to zero (for example, `-10^-14`) may occasionally appear due to floating-point arithmetic precision. These should be interpreted as effectively zero, indicating an exact or near-exact match between vectors. ```sql theme={null} SELECT vector_distance_cos('[1000]', '[1000]'); -- Output: -2.0479999918166e-09 ``` ### Vector Limitations * Euclidean distance is **not supported** for 1-bit `FLOAT1BIT` vectors * LibSQL can only operate on vectors with no more than 65536 dimensions ## Indexing Nearest neighbors (NN) queries are popular for various AI-powered applications ([RAG](https://en.wikipedia.org/wiki/Retrieval-augmented_generation) uses NN queries to extract relevant information, and recommendation engines can suggest items based on embedding similarity). LibSQL implements [DiskANN](https://turso.tech/blog/approximate-nearest-neighbor-search-with-diskann-in-libsql) algorithm in order to speed up approximate nearest neighbors queries for tables with vector columns. The DiskANN algorithm trades search accuracy for speed, so LibSQL queries may return slightly suboptimal neighbors for tables with a large number of rows. ### Vector Index LibSQL introduces a custom index type that helps speed up nearest neighbors queries against a fixed distance function (cosine similarity by default). From a syntax perspective, the vector index differs from ordinary application-defined B-Tree indices in that it must wrap the vector column into a `libsql_vector_idx` marker function like this ```sql theme={null} CREATE INDEX movies_idx ON movies (libsql_vector_idx(embedding)); ``` Vector index works only for column with one of the vector types described above The vector index is fully integrated into the LibSQL core, so it inherits all operations and most features from ordinary indices: * An index created for a table with existing data will be automatically populated with this data * All updates to the base table will be **automatically** reflected in the index * You can rebuild index from scratch using `REINDEX movies_idx` command * You can drop index with `DROP INDEX movies_idx` command * You can create [partial](https://www.sqlite.org/partialindex.html) vector index with a custom filtering rule: ```sql theme={null} CREATE INDEX movies_idx ON movies (libsql_vector_idx(embedding)) WHERE year >= 2000; ``` ### Query At the moment vector index must be queried **explicitly** with special `vector_top_k(idx_name, q_vector, k)` [table-valued function](https://www.sqlite.org/vtab.html#table_valued_functions). The function accepts index name, query vector and amount of neighbors to return. This function searches for `k` approximate nearest neighbors and returns `ROWID` of these rows or `PRIMARY KEY` if base index [does not have ROWID](https://www.sqlite.org/withoutrowid.html). In order for table-valued function to work query vector **must** have the same vector type and dimensionality. ### Settings LibSQL vector index optionally can accept settings which must be specified as variadic parameters of the `libsql_vector_idx` function as strings in the format `key=value`: ```sql theme={null} CREATE INDEX movies_idx ON movies(libsql_vector_idx(embedding, 'metric=l2', 'compress_neighbors=float8')); ``` At the moment LibSQL supports the following settings: | Setting key | Value type | Description | | -------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `metric` | `cosine` \| `l2` | Which distance function to use for building the index.
Default: `cosine` | | `max_neighbors` | positive integer | How many neighbors to store for every node in the DiskANN graph. The lower the setting -- the less storage index will use in exchange to search precision.
Default: $3 \sqrt{D}$ where $D$ -- dimensionality of vector column | | `compress_neighbors` | `float1bit`\|`float8`\|
`float16`\|`floatb16`\|
`float32` | Which vector type must be used to store neighbors for every node in the DiskANN graph. The more compact vector type is used for neighbors -- the less storage index will use in exchange to search precision.
Default: **no compression** (neighbors has same type as base table) | | `alpha` | positive float $\geq 1$ | "Density" parameter of general sparse neighborhood graph build during DiskANN algorithm. The lower parameter -- the more sparse is DiskANN graph which can speed up query speed in exchange to lower search precision.
Default: `1.2` | | `search_l` | positive integer | Setting which limits the amount of neighbors visited during vector search. The lower the setting -- the faster will be search query in exchange to search precision.
Default: `200` | | `insert_l` | positive integer | Setting which limits the amount of neighbors visited during vector insert. The lower the setting -- the faster will be insert query in exchange to DiskANN graph navigability properties.
Default: `70` | Vector index for column of type `T1` with `max_neighbors=M` and `compress_neighbors=T2` will approximately use $\texttt{N} (Storage(\texttt {T1}) + \texttt{M} \cdot Storage(\texttt{T2}))$ storage bytes for `N` rows. ### Index usage Begin by declaring a column used for storing vectors with the `F32_BLOB` datatype: ```sql theme={null} CREATE TABLE movies ( title TEXT, year INT, embedding F32_BLOB(4) -- 4-dimensional f32 vector ); ``` The number in parentheses `(4)` specifies the dimensionality of the vector. This means each vector in this column will have exactly 4 components. Once you generate embeddings for your data (via an LLM), you can insert them into your table: ```sql theme={null} INSERT INTO movies (title, year, embedding) VALUES ('Napoleon', 2023, vector32('[0.800, 0.579, 0.481, 0.229]')), ('Black Hawk Down', 2001, vector32('[0.406, 0.027, 0.378, 0.056]')), ('Gladiator', 2000, vector32('[0.698, 0.140, 0.073, 0.125]')), ('Blade Runner', 1982, vector32('[0.379, 0.637, 0.011, 0.647]')); ``` Popular tools like [LangChain](https://www.langchain.com), [Hugging Face](https://huggingface.co) or [OpenAI](https://turso.tech/blog/how-to-generate-and-store-openai-vector-embeddings-with-turso) can be used to generate embeddings. Create an index using the `libsql_vector_idx` function: ```sql theme={null} CREATE INDEX movies_idx ON movies(libsql_vector_idx(embedding)); ``` This creates an index optimized for vector similarity searches on the `embedding` column. The `libsql_vector_idx` marker function is **required** and used by libSQL to distinguish `ANN`-indices from ordinary B-Tree indices. ```sql theme={null} SELECT title, year FROM vector_top_k('movies_idx', vector32('[0.064, 0.777, 0.661, 0.687]'), 3) JOIN movies ON movies.rowid = id WHERE year >= 2020; ``` This query uses the `vector_top_k` [table-valued function](https://www.sqlite.org/vtab.html#table_valued_functions) to efficiently find the top 3 most similar vectors to `[0.064, 0.777, 0.661, 0.687]` using the index. ### Index limitations * Vector index works only for tables **with** `ROWID` or with singular `PRIMARY KEY`. Composite `PRIMARY KEY` without `ROWID` is not supported --- # Source: https://docs.turso.tech/sdk/ts/guides/astro.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Astro + Turso > Set up Turso in your Astro project in minutes. Astro banner ## Prerequisites To get the most out of this guide, you'll need to: * [Install the Turso CLI](/cli/installation) * [Sign up or login to Turso](/cli/authentication#signup) * Have an Astro project β€” [learn more](https://docs.astro.build/en/install/auto/#1-run-the-setup-wizard) ```ts src/turso.ts theme={null} import { createClient } from "@libsql/client/web"; export const turso = createClient({ url: import.meta.env.TURSO_DATABASE_URL!, authToken: import.meta.env.TURSO_AUTH_TOKEN, }); ``` Astro will soon introduce a new ENV API. [Take a look](https://docs.astro.build/en/reference/configuration-reference/#experimentalenv). ```ts theme={null} --- import { turso } from './turso' const { rows } = await turso.execute('SELECT * FROM table_name') --- ``` ## Examples See the full source code --- # Source: https://docs.turso.tech/features/attach-database.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Attach Database (Deprecated) > Attach and read data across multiple databases. This feature is now deprecated for all new users. Existing paid users can continue to use `ATTACH` β€” [read the announcement](https://turso.tech/blog/upcoming-changes-to-the-turso-platform-and-roadmap) The `ATTACH` statement enables you to link multiple databases within a single transaction, which is ideal for: * Organizing data in a modular way * Streamlining data access and enhancing scalability * Aggregating data ## How it works 1. You enable the `ATTACH` feature on the databases you want to connect to. 2. You retrieve the **Database ID** for the database you want to `ATTACH`. 3. You connect to the database * **CLI**: `--attach` flag to automatically create a token with the correct permissions. * **SDK**: Create a token with the `attach` permission for the database you want to attach. 4. You invoke `ATTACH` to connect to the other databases within the database shell or SDK. ## Usage You can use the `ATTACH` statement to connect to other databases within a transaction using the CLI, or libSQL SDK. Once attached, you can query the attached databases as if they were part of the current database using the assigned alias. ### Turso CLI Make sure you have the [Turso CLI](/cli/installation) installed, and [logged in](/cli/auth/login). You will first need to enable the `ATTACH` feature on the database(s) you want to attach: ```bash theme={null} turso db config attach allow ``` You now need to retrieve the **Database ID** for the database you want to `ATTACH`: ```bash theme={null} turso db show ``` Now pass the names of the databases via the `--attach` flag when connecting to your database(s): ```bash theme={null} turso db shell --attach <...database-name(s)> ``` Now once connected to the database you can invoke an `ATTACH` statement to connect the other database(s): ```sql theme={null} ATTACH "" AS my_db; ``` Execute a query using the alias for any attached database(s): ```sql theme={null} SELECT * FROM my_db.my_table; ``` ### libSQL SDKs You can use one of the libSQL client SDKs with [TypeScript](/sdk/ts), [Rust](/sdk/rust), [Go](/sdk/go), [Python](/sdk/python), or over [HTTP](/sdk/http). You will first need to enable the `ATTACH` feature on the database(s) you want to attach: ```bash theme={null} turso db config attach allow ``` You now need to retrieve the **Database ID** for the database you want to `ATTACH`: ```bash theme={null} turso db show ``` Now create a token for the libSQL client with the `attach` permission for the database you want to attach: ```bash theme={null} turso db tokens create --attach ``` Use a [Client SDK](/sdk) to attach the desired database within a read transaction: ```ts @libsql/client theme={null} import { createClient } from "@libsql/client"; const client = createClient({ syncUrl: "libsql://...", authToken: "...", }); const txn = await db.transaction("read"); await txn.execute('ATTACH "" AS my_db'); const rs = await txn.execute("SELECT * FROM my_db.my_table"); ``` ## Things to know * You can only attach databases that have the `attach` feature enabled. * You can only attach databases belonging to a group, and in the same group. * There is a maximum of 10 databases that can be attached to a single transaction. * The attached databases are read only. * `ATTACH` statement can be used only within transactions. * `ATTACH` doesn't support [Embedded Replicas](/features/embedded-replicas) --- # Source: https://docs.turso.tech/agentfs/guides/auditing.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Audit Filesystem Changes > Inspect and analyze what an agent did during a session AgentFS records every file operation and tool call, giving you complete visibility into agent behavior. This is essential for debugging, compliance, and understanding how agents work. ## Viewing the Timeline See a chronological list of tool calls: ```bash theme={null} agentfs timeline my-session ``` Output: ``` ID TOOL STATUS DURATION STARTED 4 execute_code pending -- 2024-01-05 09:44:20 3 api_call error 300ms 2024-01-05 09:44:15 2 read_file success 50ms 2024-01-05 09:44:10 1 web_search success 1200ms 2024-01-05 09:43:45 ``` ### Filtering Results Show only specific tool types: ```bash theme={null} agentfs timeline my-session --filter web_search ``` Show only errors: ```bash theme={null} agentfs timeline my-session --status error ``` Limit number of entries: ```bash theme={null} agentfs timeline my-session --limit 20 ``` ### JSON Output For programmatic analysis: ```bash theme={null} agentfs timeline my-session --format json ``` ```json theme={null} [ { "id": 1, "name": "web_search", "status": "success", "started_at": 1704447825, "completed_at": 1704447826, "duration_ms": 1200, "parameters": {"query": "AI agents"}, "result": {"results": ["result1", "result2"]} } ] ``` ## Inspecting Files List all files in a session: ```bash theme={null} agentfs fs ls my-session ``` Output: ``` d artifacts f config.json f output.txt ``` List a subdirectory: ```bash theme={null} agentfs fs ls my-session /artifacts ``` Read file contents: ```bash theme={null} agentfs fs cat my-session /output.txt ``` ## Viewing Changes (Diff) See what changed compared to the original filesystem: ```bash theme={null} agentfs diff my-session ``` This shows: * New files created * Modified files * Deleted files ## Querying with SQL Since AgentFS uses SQLite, you can run arbitrary queries: ```bash theme={null} tursodb .agentfs/my-session.db ``` ```bash theme={null} sqlite3 .agentfs/my-session.db ``` Example queries: ```sql theme={null} -- Find all tool calls that took longer than 1 second SELECT name, duration_ms FROM toolcalls WHERE duration_ms > 1000; -- Count tool usage by type SELECT name, COUNT(*) as count FROM toolcalls GROUP BY name ORDER BY count DESC; -- Find files modified in the last hour SELECT path, mtime FROM fs_inode WHERE mtime > strftime('%s', 'now', '-1 hour'); -- Get total bytes written SELECT SUM(size) as total_bytes FROM fs_inode WHERE mode & 0170000 = 0100000; -- regular files only ``` ## Use Cases ### Debugging Agent Failures When an agent fails, use the timeline to understand what happened: ```bash theme={null} # See recent activity agentfs timeline my-session --limit 20 # Focus on errors agentfs timeline my-session --status error # Check what files were created/modified agentfs fs ls my-session ``` ### Performance Analysis Find slow operations: ```sql theme={null} SELECT name, AVG(duration_ms) as avg_ms, COUNT(*) as count FROM toolcalls GROUP BY name ORDER BY avg_ms DESC; ``` ### Compliance Auditing Export a complete record of agent activity: ```bash theme={null} agentfs timeline my-session --format json > audit-log.json ``` ## Next Steps Understanding copy-on-write Sync sessions to Turso Cloud --- # Source: https://docs.turso.tech/sdk/authentication.md # Source: https://docs.turso.tech/cli/authentication.md # Source: https://docs.turso.tech/api-reference/authentication.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Authentication The Turso API uses API tokens to authenticate requests. You can create and revoke API tokens using the [Turso CLI](/cli) and [Authentication API](/api-reference/tokens/create). API tokens allow access to manage all API resources, including creating and destroying database. * Use environment variables when working with API tokens. * Never share your API token in public, including repositories, and CI/CD Actions. Turso uses Bearer authentication, and requires your API token to be passed with all protected requests in the `Authorization` header: ```bash theme={null} Authorization: Bearer TOKEN ``` ## Base URL The Turso API is located at the following URL: ```bash theme={null} https://api.turso.tech ``` --- # Source: https://docs.turso.tech/connect/authorization.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Authorization Quickstart This guide shows you how to configure authorization for your Turso databases using JSON Web Key Sets (JWKS) and an authentication provider. ## Overview Turso supports authorization through JWT tokens issued by your authentication provider. You can either: * Create database or group tokens via Turso CLI * Let your authentication provider issue tokens using JWKS This quickstart focuses on the JWKS approach, which allows you to leverage your existing authentication infrastructure. During the Turso Beta, we only support Clerk & Auth0 as OIDC providers. First, configure your authentication provider to issue JWT tokens. This example uses [Clerk](https://clerk.com). ### Configure JWT Permissions Use the Turso CLI to generate a JWT template with fine-grained permissions: ```bash theme={null} # Full access to all tables in a database turso org jwks template --database --scope full-access # Read-only access to all tables in a group turso org jwks template --group --scope read-only # Fine-grained permissions for specific tables in a database turso org jwks template \ --database \ --permissions all:data_read \ --permissions comments:data_add \ --permissions posts:data_add,data_update ``` Available flags: * `--database` or `-d`: Specify the database name (required if `--group` not specified) * `--group` or `-g`: Specify the group name (required if `--database` not specified) * `--scope` or `-s`: Set scope to `full-access` or `read-only` * `--permissions` or `-p`: Define table-level permissions in format `:,` Available actions for `--permissions`: * `data_read` - Read data from tables * `data_update` - Update existing data * `data_add` - Insert new data * `data_delete` - Delete data * `schema_update` - Modify table schemas * `schema_add` - Create new tables * `schema_delete` - Drop tables `data_read` is allowed on SQLite system tables (e.g., `sqlite_master`, `sqlite_schema`) by default, allowing users to query database metadata. Either `--database` or `--group` must be specified when generating a JWT template. ### Configure JWT Template Set up a JWT template in your auth provider to include permissions based on user metadata. This allows you to control access at the table and action level. For example, you can configure your JWT template to: * Grant admin users `data_delete` permissions * Grant moderator users `data_update` and `data_read` permissions * Grant regular users `data_read` permissions only The permissions are based on user metadata (e.g., role, group membership) and embedded in the JWT token. If you don't setup a JWT template with specific permissions, the generated tokens will have access to **all databases in all groups** by default. Add your authentication provider's JWKS endpoint to your Turso organization. ### Using the CLI ```bash theme={null} turso org jwks save ``` Example: ```bash theme={null} turso org jwks save clerk https://your-app.clerk.accounts.dev/.well-known/jwks.json ``` ### Using the Dashboard Navigate to your organization settings in the [Turso Dashboard](https://turso.tech/app) and add the JWKS endpoint URL. Pass the JWT token from your authentication provider when creating the database client: ```javascript theme={null} import { createClient } from "@tursodatabase/serverless"; // Get the JWT token from your auth provider const authToken = await getAuthToken(); // e.g., from Clerk, Auth0, etc. const db = createClient({ url: "https://.turso.io", authToken, // Use the JWT from your auth provider }); // Now all database operations use the authorization token const result = await db.execute("SELECT * FROM users"); ``` The `authToken` can be: * A JWT token issued by your authentication provider (via JWKS) * A database token created with `turso db tokens create ` * A group token for accessing multiple databases ## Managing JWKS Endpoints ### List JWKS Endpoints ```bash theme={null} turso org jwks list ``` ### Remove JWKS Endpoint ```bash theme={null} turso org jwks remove ``` --- # Source: https://docs.turso.tech/sdk/rust/guides/axum.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Turso + Axum > Set up Turso in your Axum project in minutes Axum banner ## Prerequisites Before you start, make sure you: * [Install the Turso CLI](/cli/installation) * [Sign up or login to Turso](/cli/authentication#signup) * Have an Axum app β€” [learn more](https://github.com/tokio-rs/axum) You will need an existing database to continue. If you don't have one, [create one](/quickstart). You will want to store these as environment variables. ```sh theme={null} cargo add libsql ``` Optionally, you can add a package such as [`dotenvy`](https://docs.rs/dotenvy/latest/dotenvy) to help you work with `.env` files: ```sh theme={null} cargo add dotenvy ``` ```rust theme={null} use libsql::{Builder, Connection, Database, Result}; #[tokio::main] async fn main() -> Result<()> { dotenv().ok(); let db_url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let auth_token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set"); let db = Builder::new_remote(db_url, auth_token) .build() .await?; let conn = db.connect()?; // Execute a query let mut rows = conn.query("SELECT * FROM users", ()).await?; while let Some(row) = rows.next().await? { let id: i64 = row.get(0)?; let name: String = row.get(1)?; println!("User: {} - {}", id, name); } Ok(()) } ``` ```rust theme={null} use axum::{ extract::State, routing::get, Json, Router, }; use libsql::{Builder, Connection, Database}; use serde::Serialize; #[derive(Clone)] struct AppState { db: Database, } #[derive(Serialize)] struct User { id: i64, name: String, } async fn get_users(State(state): State) -> Json> { let conn = state.db.connect().unwrap(); let mut rows = conn.query("SELECT id, name FROM users", ()).await.unwrap(); let mut users = Vec::new(); while let Some(row) = rows.next().await.unwrap() { users.push(User { id: row.get(0).unwrap(), name: row.get(1).unwrap(), }); } Json(users) } #[tokio::main] async fn main() { let db_url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let auth_token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set"); let db = Builder::new_remote(db_url, auth_token) .build() .await .unwrap(); let app_state = AppState { db }; let app = Router::new() .route("/users", get(get_users)) .with_state(app_state); axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) .serve(app.into_make_service()) .await .unwrap(); } ``` This example creates a shared `Database` instance in the application state, which is then used in the handler to execute queries. --- # Source: https://docs.turso.tech/cli/org/billing.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # org billing To open the billing portal for your organization: ```bash theme={null} turso org billing ``` --- # Source: https://docs.turso.tech/cli/contact/bookmeeting.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # contact bookmeeting You can book a meeting with the Turso team to discuss your project and requirements using the following command: ```bash theme={null} turso contact bookmeeting ``` You will be redirected to a webpage where you can select a date and time for the meeting. --- # Source: https://docs.turso.tech/features/branching.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Branching A branch is a separate database instance that is created from an existing database. You can also create a branch from a [point-in-time](/features/point-in-time-recovery) snapshot of a database. Branches are useful for development and testing, because they allow you to make changes to the database without affecting the original database. ## How it works 1. You create a new database from an existing database using the CLI or API. 2. You connect to the new database using the group API token. 3. Make changes to the new schema using a migration tool (optional). 4. Apply the changes to the original database using a migration tool when merging using a GitHub Action (optional). 5. Delete the database when you no longer need it. ## Usage You can create a new database from an existing database using the CLI or API: ```bash CLI theme={null} turso db create my-new-database-branch --from-db my-existing-database ``` ```bash Platform API theme={null} curl -L -X POST 'https://api.turso.tech/v1/organizations/{organizationSlug}/databases' \ -H 'Authorization: Bearer TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "name": "new-database", "group": "default", "seed": { "type:": "database", "name": "my-existing-database" } }' ``` Refer to the following references for more details about all arguments: ## Things to know * Database branches are completely separate from the original database. This means that you need to handle merging any schema changes or data manually using a migration tool. * You will need to [create a new token](/cli/db/tokens/create) (or use a group token) to connect to the new database. * You will need to manually delete the database branch when you no longer need it. * Branches count towards your plan's database quota. ## CI/CD Automating branching is useful for creating a new database for each pull request. This allows you to test changes without affecting the original database. Here's an example of what that might look like using the [Platform API](/api-reference/databases/create): ```yml .github/workflows/create-database-branch.yml theme={null} name: Create Database on: create jobs: triggerAPI: runs-on: ubuntu-latest steps: - name: Generate Branch Name id: branch_name run: | BRANCH_NAME=$(echo "${{ github.ref_name }}" | tr -cd '[:alnum:]' | sed 's/./\L&/g' | cut -c 1-32) echo "::set-output name=branch_name::$BRANCH_NAME" - name: Create Database run: | curl -X POST \ -H "Authorization: Bearer ${{ secrets.API_TOKEN }}" \ -H "Content-Type: application/json" \ -d '{"name": "${{ steps.branch_name.outputs.branch_name }}", "group": "default", "seed": {"type": "database", "name": "${{ secrets.DATABASE_NAME }}"} }' \ "https://api.turso.tech/v1/organizations/${{ secrets.ORGANIZATION_NAME }}/databases" ``` --- # Source: https://docs.turso.tech/agentfs/reference/cli.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # CLI Reference > Complete reference for the AgentFS command-line interface Complete reference for the `agentfs` command-line tool. For the latest reference, see [MANUAL.md](https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md) in the repository. ## Installation ```bash theme={null} curl -fsSL https://github.com/tursodatabase/agentfs/releases/latest/download/agentfs-installer.sh | sh ``` ## Commands ### agentfs init Initialize a new agent filesystem. ```bash theme={null} agentfs init [OPTIONS] [ID] ``` **Arguments:** * `ID` - Agent identifier (default: `agent-{timestamp}`) **Options:** | Option | Description | | ------------------------- | ------------------------------------- | | `--force` | Overwrite existing agent filesystem | | `--base ` | Base directory for overlay filesystem | | `--sync-remote-url ` | Remote Turso database URL | **Example:** ```bash theme={null} agentfs init my-agent agentfs init my-overlay --base /path/to/project ``` *** ### agentfs run Execute a program in a sandboxed environment. ```bash theme={null} agentfs run [OPTIONS] [ARGS]... ``` **Options:** | Option | Description | | ------------------------ | ----------------------------------- | | `--session ` | Named session for persistence | | `--allow ` | Allow write access to directory | | `--no-default-allows` | Disable default allowed directories | | `--experimental-sandbox` | Use ptrace sandbox (Linux) | | `--strace` | Show intercepted syscalls | **Examples:** ```bash theme={null} agentfs run /bin/bash agentfs run --session my-project python3 agent.py agentfs run --allow /tmp --allow ~/.cache /bin/bash ``` *** ### agentfs mount Mount an agent filesystem or list mounts. ```bash theme={null} agentfs mount [OPTIONS] [ID_OR_PATH] [MOUNT_POINT] ``` Without arguments, lists all mounted filesystems. **Options:** | Option | Description | | -------------------- | ----------------------------- | | `-a, --auto-unmount` | Automatically unmount on exit | | `--allow-root` | Allow root user access | | `-f, --foreground` | Run in foreground | | `--uid ` | User ID for files | | `--gid ` | Group ID for files | **Examples:** ```bash theme={null} agentfs mount # List mounts agentfs mount my-agent ./mnt # Mount agent agentfs mount my-agent ./mnt -a -f # Foreground with auto-unmount ``` **Unmounting:** * Linux: `fusermount -u ` * macOS: `umount ` *** ### agentfs serve mcp Start an MCP (Model Context Protocol) server. ```bash theme={null} agentfs serve mcp [OPTIONS] ``` **Options:** | Option | Description | | ----------------- | ----------------------------- | | `--tools ` | Comma-separated list of tools | **Available Tools:** | Category | Tools | | ---------- | ----------------------------------------------------------------------------------- | | Filesystem | `read_file`, `write_file`, `readdir`, `mkdir`, `remove`, `rename`, `stat`, `access` | | Key-Value | `kv_get`, `kv_set`, `kv_delete`, `kv_list` | **Examples:** ```bash theme={null} agentfs serve mcp my-agent agentfs serve mcp my-agent --tools read_file,readdir,stat ``` *** ### agentfs serve nfs Start an NFS server. ```bash theme={null} agentfs serve nfs [OPTIONS] ``` **Options:** | Option | Description | | --------------- | --------------------------------- | | `--bind ` | IP to bind (default: `127.0.0.1`) | | `--port ` | Port (default: `11111`) | **Example:** ```bash theme={null} agentfs serve nfs my-agent --bind 0.0.0.0 --port 2049 ``` **Mounting:** ```bash theme={null} mount -t nfs -o vers=3,tcp,port=11111,mountport=11111,nolock localhost:/ /mnt ``` *** ### agentfs sync Synchronize with a remote Turso database. ```bash theme={null} agentfs sync ``` **Subcommands:** | Command | Description | | ------------ | -------------------- | | `pull` | Pull remote changes | | `push` | Push local changes | | `stats` | View sync statistics | | `checkpoint` | Create checkpoint | **Example:** ```bash theme={null} agentfs sync my-agent pull agentfs sync my-agent push ``` *** ### agentfs fs Filesystem operations on agent databases. #### agentfs fs ls ```bash theme={null} agentfs fs ls [FS_PATH] ``` List files. Output: `f ` for files, `d ` for directories. #### agentfs fs cat ```bash theme={null} agentfs fs cat ``` Display file contents. #### agentfs fs write ```bash theme={null} agentfs fs write ``` Write content to a file. **Examples:** ```bash theme={null} agentfs fs ls my-agent agentfs fs cat my-agent /config.json agentfs fs write my-agent /hello.txt "Hello, world!" ``` *** ### agentfs diff Show filesystem changes in overlay mode. ```bash theme={null} agentfs diff ``` *** ### agentfs timeline Display agent action timeline. ```bash theme={null} agentfs timeline [OPTIONS] ``` **Options:** | Option | Description | | ------------------- | ------------------------------------- | | `--limit ` | Limit entries (default: 100) | | `--filter ` | Filter by tool name | | `--status ` | Filter: `pending`, `success`, `error` | | `--format ` | Output: `table`, `json` | **Examples:** ```bash theme={null} agentfs timeline my-agent agentfs timeline my-agent --filter web_search --status error agentfs timeline my-agent --format json ``` *** ### agentfs completions Manage shell completions. ```bash theme={null} agentfs completions install [SHELL] agentfs completions uninstall [SHELL] agentfs completions show ``` Supported: `bash`, `zsh`, `fish`, `powershell` ## Environment Variables Variables set inside the sandbox: | Variable | Description | | ----------------- | ------------------------- | | `AGENTFS` | Set to `1` inside sandbox | | `AGENTFS_SANDBOX` | Sandbox type | | `AGENTFS_SESSION` | Session ID | ## Files | Path | Description | | -------------------- | ------------------------- | | `.agentfs/.db` | Agent filesystem database | | `~/.config/agentfs/` | Configuration directory | ## See Also Installation instructions Running agents in sandboxes --- # Source: https://docs.turso.tech/api-reference/locations/closest-region.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Closest Region > Returns the closest region to the user's location. #### Response The location code for the server responding. The location code for the client request. ```bash cURL theme={null} curl https://region.turso.io ``` ```ts Node.js theme={null} import { createClient } from "@tursodatabase/api"; const turso = createClient({ org: "...", token: "", }); const { server, client } = await turso.locations.closest(); ``` ```json 200 theme={null} { "server": "lhr", "client": "lhr" } ``` --- # Source: https://docs.turso.tech/api-reference/groups/configuration.md # Source: https://docs.turso.tech/api-reference/databases/configuration.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Retrieve Database Configuration > Retrieve an individual database configuration belonging to the organization or user. ```bash cURL theme={null} curl -L -X GET 'https://api.turso.tech/v1/organizations/{organizationSlug}/databases/{databaseName}/configuration' \ -H 'Authorization: Bearer TOKEN' ``` ## OpenAPI ````yaml GET /v1/organizations/{organizationSlug}/databases/{databaseName}/configuration openapi: 3.0.1 info: title: Turso Platform API description: API description here license: name: MIT version: 0.1.0 servers: - url: https://api.turso.tech description: Turso's Platform API security: [] paths: /v1/organizations/{organizationSlug}/databases/{databaseName}/configuration: get: summary: Retrieve Database Configuration description: >- Retrieve an individual database configuration belonging to the organization or user. operationId: getDatabaseConfiguration parameters: - $ref: '#/components/parameters/organizationSlug' - $ref: '#/components/parameters/databaseName' responses: '200': description: Successful response content: application/json: schema: $ref: '#/components/schemas/DatabaseConfigurationResponse' components: parameters: organizationSlug: in: path name: organizationSlug required: true schema: type: string description: The slug of the organization or user account. databaseName: name: databaseName in: path required: true schema: type: string description: The name of the database. schemas: DatabaseConfigurationResponse: type: object properties: size_limit: type: string description: >- The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb. example: '10000' allow_attach: type: boolean description: Allow or disallow attaching databases to the current database. example: true deprecated: true block_reads: type: boolean description: The current status for blocked reads. example: false block_writes: type: boolean description: The current status for blocked writes. example: false delete_protection: type: boolean description: Prevent the database from being deleted. example: true ```` --- # Source: https://docs.turso.tech/api-reference/groups/create-token.md # Source: https://docs.turso.tech/api-reference/databases/create-token.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Generate Database Auth Token > Generates an authorization token for the specified database. ```bash cURL theme={null} curl -L -X POST 'https://api.turso.tech/v1/organizations/{organizationSlug}/databases/{databaseName}/auth/tokens?expiration=2w&authorization=full-access' \ -H 'Authorization: Bearer TOKEN' ``` ```ts Node.js theme={null} import { createClient } from "@tursodatabase/api"; const turso = createClient({ org: "...", token: "", }); const token = await turso.databases.createToken("my-db", { expiration: "2w", authorization: "full-access", }); ``` ```json theme={null} { "jwt": "TOKEN" } ``` ## OpenAPI ````yaml POST /v1/organizations/{organizationSlug}/databases/{databaseName}/auth/tokens openapi: 3.0.1 info: title: Turso Platform API description: API description here license: name: MIT version: 0.1.0 servers: - url: https://api.turso.tech description: Turso's Platform API security: [] paths: /v1/organizations/{organizationSlug}/databases/{databaseName}/auth/tokens: post: summary: Generate Database Auth Token description: Generates an authorization token for the specified database. operationId: createDatabaseToken parameters: - $ref: '#/components/parameters/organizationSlug' - $ref: '#/components/parameters/databaseName' - name: expiration in: query schema: type: string default: never description: Expiration time for the token (e.g., 2w1d30m). - name: authorization in: query schema: type: string default: full-access enum: - full-access - read-only description: Authorization level for the token (full-access or read-only). requestBody: description: Additional context such as claims required for the token. required: false content: application/json: schema: $ref: '#/components/schemas/CreateTokenInput' responses: '200': description: Successful response content: application/json: schema: type: object properties: jwt: type: string description: The generated authorization token (JWT). '400': description: Bad Request content: application/json: schema: type: object properties: error: type: string description: The error message example: Invalid expiration format '404': $ref: '#/components/responses/DatabaseNotFoundResponse' components: parameters: organizationSlug: in: path name: organizationSlug required: true schema: type: string description: The slug of the organization or user account. databaseName: name: databaseName in: path required: true schema: type: string description: The name of the database. schemas: CreateTokenInput: type: object properties: permissions: type: object description: The permissions for the token. properties: read_attach: type: object description: Read `ATTACH` permission for the token. properties: databases: type: array items: type: string responses: DatabaseNotFoundResponse: description: Database not found content: application/json: schema: type: object properties: error: type: string description: The error message example: >- could not find database with name [databaseName]: record not found ```` --- # Source: https://docs.turso.tech/cli/org/create.md # Source: https://docs.turso.tech/cli/group/tokens/create.md # Source: https://docs.turso.tech/cli/group/create.md # Source: https://docs.turso.tech/cli/db/tokens/create.md # Source: https://docs.turso.tech/cli/db/create.md # Source: https://docs.turso.tech/api-reference/tokens/create.md # Source: https://docs.turso.tech/api-reference/organizations/invites/create.md # Source: https://docs.turso.tech/api-reference/groups/create.md # Source: https://docs.turso.tech/api-reference/databases/create.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Create Database > Creates a new database in a group for the organization or user. ```bash cURL theme={null} curl -L -X POST 'https://api.turso.tech/v1/organizations/{organizationSlug}/databases' \ -H 'Authorization: Bearer TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "name": "new-database", "group": "default" }' ``` ```ts Node.js theme={null} import { createClient } from "@tursodatabase/api"; const turso = createClient({ org: "...", token: "", }); const database = await turso.databases.create("new-database", { group: "default", }); ``` ## OpenAPI ````yaml POST /v1/organizations/{organizationSlug}/databases openapi: 3.0.1 info: title: Turso Platform API description: API description here license: name: MIT version: 0.1.0 servers: - url: https://api.turso.tech description: Turso's Platform API security: [] paths: /v1/organizations/{organizationSlug}/databases: post: summary: Create Database description: Creates a new database in a group for the organization or user. operationId: createDatabase parameters: - $ref: '#/components/parameters/organizationSlug' requestBody: description: Database data to create a new database required: true content: application/json: schema: $ref: '#/components/schemas/CreateDatabaseInput' responses: '200': description: Successful response content: application/json: schema: type: object properties: database: $ref: '#/components/schemas/CreateDatabaseOutput' description: The newly created database '400': description: Bad Request content: application/json: schema: type: object properties: error: type: string description: The error message example: group not found '409': description: Conflict content: application/json: schema: type: object properties: error: type: string description: The error message example: database with name [databaseName] already exists components: parameters: organizationSlug: in: path name: organizationSlug required: true schema: type: string description: The slug of the organization or user account. schemas: CreateDatabaseInput: type: object properties: name: type: string description: >- The name of the new database. Must contain only lowercase letters, numbers, dashes. No longer than 64 characters. group: type: string description: >- The name of the group where the database should be created. **The group must already exist.** seed: type: object properties: type: type: string enum: - database - database_upload description: The type of seed to be used to create a new database. example: database name: type: string description: >- The name of the existing database when `database` is used as a seed type. example: my-db timestamp: type: string description: >- A formatted [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) recovery point to create a database from. This must be within the last 24 hours, or 30 days on the scaler plan. example: '2023-12-20T09:46:08Z' size_limit: type: string description: >- The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb. required: - name - group CreateDatabaseOutput: type: object properties: DbId: a0e7e55a-5eb4-49ec-8e29-e946e241d99f Hostname: b6d47bb5-e1cb-4e26-b40a-dd263ec0914a Name: ba7319ab-30c6-4763-9d34-517e949e55dc ```` --- # Source: https://docs.turso.tech/connect/dart.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Connect to Turso using Dart Add the turso\_dart package to your `pubspec.yaml`: ```yaml theme={null} dependencies: turso_dart: ``` Then run: ```bash theme={null} dart pub get ``` Create a client connection. You can connect to an in-memory database or a local file: ```dart theme={null} import 'package:turso_dart/turso_dart.dart'; // In memory final client = TursoClient.memory(); // Or local file final client = TursoClient.local('/path/to/local.db'); await client.connect(); ``` Create a table for customers: ```dart theme={null} await client.execute( "CREATE TABLE IF NOT EXISTS customers (id INTEGER PRIMARY KEY, name TEXT)" ); ``` Insert some data into the customers table: ```dart theme={null} await client.query("INSERT INTO customers(name) VALUES ('John Doe')"); await client.query("INSERT INTO customers(name) VALUES ('Jane Smith')"); ``` Query all customers from the table: ```dart theme={null} final result = await client.query("SELECT * FROM customers"); print(result); ``` Use prepared statements for better performance and security: ```dart theme={null} final statement = await client.prepare("SELECT * FROM customers WHERE id = ?"); final result = await statement.query(positional: [1]); print(result); ``` --- # Source: https://docs.turso.tech/data-and-connections.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Data & Connections > Learn how data consistency and connections work with Turso databases. Turso, an extension of [libSQL](/libsql) (a SQLite fork), modifies the consistency model due to its network-accessible and replicated nature, deviating from SQLite's strictly serializable standard. ## Establishing Connections Database operations begin with a client establishing either an HTTP or websocket connection to a database. Following this, an internal SQLite database connection is set up within the server to facilitate the operations. ## Data Consistency Database operations are tightly controlled to maintain order and data integrity. ### Primary Database Operations * All operations are linearizable, maintaining an ordered history. * Writes are fully serialized, with subsequent writes awaiting transaction completion. * Users should exercise caution with long-running or abandoned transactions to prevent blocking other writes. ## Transactional Consistency * Transactions in libSQL, encompassing both batch and interactive transactions, adhere to SQLite's transaction semantics. * libSQL provides snapshot isolation for read operations, ensuring immediate visibility of writes within the same process. This guarantees serializability and isolation from other transactions. --- # Source: https://docs.turso.tech/features/data-edge.md > ## Documentation Index > Fetch the complete documentation index at: https://docs.turso.tech/llms.txt > Use this file to discover all available pages before exploring further. # Data Edge (Deprecated) > Allow your users to reach local replicas of your database, wherever they are. This feature is now deprecated for all new users. Existing users can continue to use Edge Replicas on Fly β€” [read the announcement](https://turso.tech/blog/upcoming-changes-to-the-turso-platform-and-roadmap) For those seeking the ultimate in speed, Turso enables the [embedding of databases](/features/embedded-replicas) directly within your application on the same node. This configuration eliminates inter-regional request hopping, effectively bringing latency down to zero.