### AgentFS Python SDK Quick Start Source: https://docs.turso.tech/agentfs/sdk/python A quick start example demonstrating how to open an agent filesystem, use the key-value store, perform filesystem operations, and track tool calls. ```python import asyncio from agentfs_sdk import AgentFS, AgentFSOptions async def main(): # Open an agent filesystem agent = await AgentFS.open(AgentFSOptions(id='my-agent')) # Use key-value store await agent.kv.set('config', {'debug': True}) config = await agent.kv.get('config') # Use filesystem await agent.fs.write_file('/notes.txt', 'Hello, AgentFS!') content = await agent.fs.read_file('/notes.txt') # Track tool calls call_id = await agent.tools.start('search', {'query': 'Python'}) await agent.tools.success(call_id, {'results': ['result1']}) await agent.close() asyncio.run(main()) ``` -------------------------------- ### AgentFS Quick Start Example Source: https://docs.turso.tech/agentfs/sdk/rust Demonstrates how to open persistent or ephemeral AgentFS databases and use the core APIs for key-value storage, filesystem operations, and tool tracking. ```rust use agentfs::{AgentFS, AgentFSOptions}; use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { // Persistent storage with identifier let agent = AgentFS::open(AgentFSOptions::with_id("my-agent")).await?; // Creates: .agentfs/my-agent.db // Or use ephemeral in-memory database let ephemeral = AgentFS::open(AgentFSOptions::ephemeral()).await?; // Use the three main APIs agent.kv.set("key", "value").await?; agent.fs.write_file("/file.txt", b"data").await?; agent.tools.record(...).await?; Ok(()) } ``` -------------------------------- ### Local Sync Example in Rust Source: https://docs.turso.tech/sdk/rust/examples Demonstrates setting up a local LibSQL database that can synchronize with a remote database using Rust. This example focuses on the local setup for replication. ```rust use libsql_client::anyhow::Result; use libsql_client::Database; #[tokio::main] async fn main() -> Result<()> { // Open a local database with a replica URL and authentication token let db = Database::open_with_replicas( "file:local_replica.db?encryption_key=my_secret_key", &["libsql://your-remote-db.turso.io"], "your-auth-token" ).await?; db.execute("CREATE TABLE IF NOT EXISTS items (name TEXT)", ()).await?; db.execute("INSERT INTO items (name) VALUES (?)", ("widget",)).await?; // Trigger synchronization db.sync().await?; println!("Local database synchronized with remote replica."); Ok(()) } ``` -------------------------------- ### Setup libSQL Source: https://docs.turso.tech/sdk/c/reference Call the setup function before using libSQL. This is a one-time setup for the library. ```c libsql_setup((libsql_config_t){0}); ``` -------------------------------- ### Complete AgentFS Python Example Source: https://docs.turso.tech/agentfs/sdk/python This example demonstrates how to use the AgentFS Python SDK to open an agent, store configuration, write a file, track a tool call, and list created files and tool statistics. Ensure you have the agentfs_sdk installed and an agent ID available. ```python import asyncio import time from agentfs_sdk import AgentFS, AgentFSOptions async def main(): async with await AgentFS.open(AgentFSOptions(id='demo-agent')) as agent: # Store configuration await agent.kv.set('agent:config', { 'model': 'gpt-4', 'temperature': 0.7 }) # Create a research document research = """ # Research Notes ## Topic: AgentFS AgentFS provides persistent storage for AI agents. """ await agent.fs.write_file('/research/agentfs.md', research) # Track a simulated tool call call_id = await agent.tools.start('web_search', { 'query': 'AgentFS documentation' }) # Simulate some work await asyncio.sleep(0.1) await agent.tools.success(call_id, { 'results_count': 5, 'top_result': 'https://docs.turso.tech/agentfs' }) # List what we created files = await agent.fs.readdir('/research') print(f"Files: {files}") # Get tool stats stats = await agent.tools.get_stats() for stat in stats: print(f"{stat.name}: {stat.total_calls} calls") asyncio.run(main()) ``` -------------------------------- ### Start Local Sync Server Source: https://docs.turso.tech/sdk/go Start a local sync server for testing without a Turso Cloud account. This command starts a sync server on `127.0.0.1:8080`. ```bash tursodb :memory: --sync-server 127.0.0.1:8080 ``` -------------------------------- ### Install @libsql/client Source: https://docs.turso.tech/sdk/ts/quickstart Install the @libsql/client package using npm or yarn. ```bash npm install @libsql/client yarn add @libsql/client ``` -------------------------------- ### Basic Example Source: https://docs.turso.tech/sdk/ts/examples A simple example demonstrating how to connect to a LibSQL database and execute a query. ```javascript import { createClient } from '@libsql/client/remote'; async function main() { const client = createClient({ url: 'ws://localhost:8080', }); const rs = await client.execute('SELECT 1'); console.log(rs); } main(); ``` -------------------------------- ### Install @libsql/client Source: https://docs.turso.tech/integrations/vercel Install the production-ready libSQL client for use in Vercel deployments. ```bash npm install @libsql/client ``` -------------------------------- ### Setup Function Source: https://docs.turso.tech/sdk/c/reference Before using libSQL, you must call the setup function. This initializes the library for use. ```APIDOC ## Setup Function ### Description Initializes the libSQL C library. This must be called before any other libSQL functions. ### Code ```c libsql_setup((libsql_config_t){0}); ``` ``` -------------------------------- ### Install Turso CLI on Windows using WSL Source: https://docs.turso.tech/cli/installation First, open WSL in PowerShell, then execute the installation script to install the Turso CLI. ```bash wsl ``` ```bash curl -sSfL https://get.tur.so/install.sh | bash ``` -------------------------------- ### Install libSQL SDK and Prisma Driver (npm) Source: https://docs.turso.tech/sdk/ts/orm/prisma Install the necessary packages for using Prisma with Turso using npm. ```bash npm install @libsql/client @prisma/adapter-libsql ``` -------------------------------- ### Install @libsql/client Source: https://docs.turso.tech/sdk/http Install the @libsql/client package using npm. This is a production-ready libSQL driver. ```bash npm install @libsql/client ``` -------------------------------- ### Install Drizzle and libSQL SDK Source: https://docs.turso.tech/sdk/ts/orm/drizzle Install Drizzle ORM, the libSQL client, and dotenv for environment variables. Also install drizzle-kit as a development dependency. ```bash npm i drizzle-orm @libsql/client dotenv npm i -D drizzle-kit ``` ```bash pnpm add drizzle-orm @libsql/client dotenv pnpm add -D drizzle-kit ``` ```bash yarn add drizzle-orm @libsql/client dotenv yarn add -D drizzle-kit ``` -------------------------------- ### List Databases using Node.js Client Source: https://docs.turso.tech/api-reference/databases/list This Node.js example demonstrates how to list databases using the Turso client library. Ensure you have the '@tursodatabase/api' package installed and provide your organization and token. ```typescript import { createClient } from "@tursodatabase/api"; const turso = createClient({ org: "...", token: "", }); const databases = await turso.databases.list(); ``` -------------------------------- ### Install @tursodatabase/sync Source: https://docs.turso.tech/sdk/ts Install the package for syncing local databases with Turso Cloud. ```bash npm install @tursodatabase/sync ``` -------------------------------- ### Install @tursodatabase/vercel-experimental Source: https://docs.turso.tech/integrations/vercel Install the experimental package for in-function SQLite replication on Vercel. ```bash npm install @tursodatabase/vercel-experimental ``` -------------------------------- ### Install libSQL SDK and Prisma Driver (pnpm) Source: https://docs.turso.tech/sdk/ts/orm/prisma Install the necessary packages for using Prisma with Turso using pnpm. ```bash pnpm add @libsql/client @prisma/adapter-libsql ``` -------------------------------- ### Basic Example in Rust Source: https://docs.turso.tech/sdk/rust/examples A fundamental example demonstrating the creation of a database, table, insertion of data, and retrieval of records using LibSQL in Rust. ```rust use libsql_client::anyhow::Result; use libsql_client::Database; #[tokio::main] async fn main() -> Result<()> { // Open a local SQLite database file let db = Database::open("file:example.db").await?; // Create a table if it doesn't exist db.execute("CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY, title TEXT)", ()).await?; // Insert a new record db.execute("INSERT INTO posts (title) VALUES (?)", ("My first post",)).await?; // Query all records from the table let mut rows = db.execute("SELECT * FROM posts", ()).await?; while let Some(row) = rows.rows().next() { println!("Post: {:?}", row); } Ok(()) } ``` -------------------------------- ### Quick Install AgentFS CLI Source: https://docs.turso.tech/agentfs/installation Use this command to quickly install the AgentFS CLI on Linux, macOS, and Windows. It downloads and executes an installation script. ```bash curl -fsSL https://github.com/tursodatabase/agentfs/releases/latest/download/agentfs-installer.sh | sh ``` -------------------------------- ### Install Gems Source: https://docs.turso.tech/sdk/activerecord/guides/rails Run bundle install after adding the gem to your Gemfile. ```bash bundle install ``` -------------------------------- ### Start Local Sync Server Source: https://docs.turso.tech/sync/local-sync-server Pass `--sync-server` with an address to start the sync server. The database argument specifies where the server stores its data. ```bash tursodb ./server.db --sync-server 0.0.0.0:8080 ``` -------------------------------- ### Install libSQL SDK and Prisma Driver (yarn) Source: https://docs.turso.tech/sdk/ts/orm/prisma Install the necessary packages for using Prisma with Turso using yarn. ```bash yarn add @libsql/client @prisma/adapter-libsql ``` -------------------------------- ### Install libsql-client-go Package Source: https://docs.turso.tech/sdk/go Install the `libsql-client-go` package for direct remote access to Turso Cloud databases over the libSQL wire protocol. This is useful for stateless environments where a local database file cannot be stored. ```go go get github.com/tursodatabase/libsql-client-go/libsql ``` -------------------------------- ### Install libSQL Rubygem Source: https://docs.turso.tech/sdk/ruby/quickstart Install the turso_libsql Rubygem using Bundler. ```bash bundle add turso_libsql ``` -------------------------------- ### Install @tursodatabase/database Source: https://docs.turso.tech/sdk/ts Install the recommended package for local and embedded use cases. ```bash npm install @tursodatabase/database ``` -------------------------------- ### Install libsql-client-go Package Source: https://docs.turso.tech/sdk/go/quickstart Install the libsql-client-go package for direct remote access to Turso Cloud databases over the libSQL wire protocol. This is useful for stateless environments like web servers or serverless functions. ```bash go get github.com/tursodatabase/libsql-client-go/libsql ``` -------------------------------- ### Install AgentFS SDK with bun Source: https://docs.turso.tech/agentfs/sdk Install the AgentFS SDK using bun for projects using the bun runtime. ```bash bun add agentfs-sdk ``` -------------------------------- ### Start Sync Server Source: https://docs.turso.tech/sql-reference/cli/getting-started Starts the Turso CLI as a sync server for database replication. This allows for data synchronization between different Turso instances. ```bash tursodb --sync-server 0.0.0.0:8080 mydata.db ``` -------------------------------- ### Running LibSQL Dart Example Source: https://docs.turso.tech/sdk/flutter/examples Instructions on how to run the LibSQL Dart example. Ensure you have a Turso database (remote or local) and configure your environment variables. ```bash flutter run --debug --dart-define-from-file=.env ``` -------------------------------- ### Install @tursodatabase/serverless Source: https://docs.turso.tech/integrations/vercel Install the serverless package for edge and serverless runtimes using npm. ```bash npm install @tursodatabase/serverless ``` -------------------------------- ### Install libsql with uv Source: https://docs.turso.tech/sdk/python/quickstart Install the libsql package using the uv package manager for remote database access. ```bash uv add libsql ``` -------------------------------- ### Start Local Turso Development Server Source: https://docs.turso.tech/cli/dev Run this command to start a local libSQL server managed by the Turso CLI. A new database will be created for development purposes. ```bash turso dev ``` -------------------------------- ### Starting Transactions Source: https://docs.turso.tech/sql-reference/statements/transactions Examples of starting explicit transactions with different lock types. The TRANSACTION keyword is optional. ```sql -- Start a deferred transaction (default) BEGIN; -- Start an immediate transaction BEGIN IMMEDIATE; -- The TRANSACTION keyword is optional BEGIN IMMEDIATE TRANSACTION; ``` -------------------------------- ### Install turso_dart package Source: https://docs.turso.tech/connect/dart Run 'dart pub get' after updating pubspec.yaml to download and install the package. ```bash dart pub get ``` -------------------------------- ### Get Help for a Specific Turso CLI Command Source: https://docs.turso.tech/cli/help To get detailed information about a specific command, including its arguments, use the `--help` flag with that command. For example, to get help for the `turso auth` command, run `turso auth --help`. ```bash turso auth --help ``` ```bash turso db create --help ``` -------------------------------- ### Install Turso Go Package Source: https://docs.turso.tech/connect/go Add the Turso package to your Go project using the go get command. ```bash go get turso.tech/database/tursogo ``` -------------------------------- ### Products Controller Example Source: https://docs.turso.tech/sdk/activerecord/guides/rails Implement index and create actions in the ProductsController to fetch all products and handle new product creation. ```ruby class ProductsController < ApplicationController def index @products = Product.all end def create @product = Product.new(product_params) if @product.save redirect_to @product, notice: 'Product was successfully created.' else render :new end end private def product_params params.require(:product).permit(:name, :description) end end ``` -------------------------------- ### AgentFS Backup and Recovery Example Source: https://docs.turso.tech/agentfs/guides/sync Demonstrates the workflow for backing up agent state by pushing changes and then recovering on a new machine by initializing and pulling. ```bash # After important work agentfs sync my-agent push # On a new machine agentfs init my-agent --sync-remote-url libsql://... agentfs sync my-agent pull ``` -------------------------------- ### Start AgentFS MCP Server Source: https://docs.turso.tech/agentfs/guides/mcp Starts an MCP server that exposes AgentFS tools over stdio. Use this to allow AI assistants to interact with your filesystem. ```bash agentfs serve mcp my-agent ``` -------------------------------- ### Initialize libSQL and Connect to Local Database Source: https://docs.turso.tech/sdk/c/quickstart Initialize libSQL and establish a connection to a local-only database. This setup only requires the database path. ```c #include "libsql.h" libsql_setup((libsql_config_t){0}); libsql_database_t db = libsql_database_init((libsql_database_desc_t){ .path = "local.db" }); libsql_connection_t conn = libsql_database_connect(db); ``` -------------------------------- ### Install libSQL Client (TypeScript) Source: https://docs.turso.tech/sdk/ts/guides/elysia Install the libSQL client for TypeScript. This is the first step in setting up Turso with your Elysia project. ```bash npm install libsql-ts ``` -------------------------------- ### OpenAPI Specification for List Locations Source: https://docs.turso.tech/api-reference/locations/list This OpenAPI 3.0.1 specification defines the GET /v1/locations endpoint, detailing its purpose, parameters, and response structure, including example location data. ```yaml 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/locations: get: summary: List Locations description: Returns a list of locations where you can create or replicate databases. operationId: listLocations responses: '200': description: Successful response content: application/json: schema: type: object properties: locations: type: object additionalProperties: type: string description: A mapping of location codes to location names. example: locations: aws-ap-northeast-1: AWS AP NorthEast (Tokyo) aws-ap-south-1: AWS AP South (Mumbai) aws-eu-west-1: AWS EU West (Ireland) aws-us-east-1: AWS US East (Virginia) aws-us-east-2: AWS US East (Ohio) aws-us-west-2: AWS US West (Oregon) ``` -------------------------------- ### Start of Period Modifiers Source: https://docs.turso.tech/sql-reference/functions/date-time Use 'start of day', 'start of month', or 'start of year' to reset the time component to midnight and adjust the date to the beginning of the respective period. ```sql SELECT datetime('2025-06-15 14:30:00', 'start of day'); -- '2025-06-15 00:00:00' ``` ```sql SELECT date('2025-06-15', 'start of month'); -- '2025-06-01' ``` ```sql SELECT date('2025-06-15', 'start of year'); -- '2025-01-01' ``` -------------------------------- ### Install libSQL PHP Client Source: https://docs.turso.tech/sdk/php/quickstart Install the libSQL PHP client using Composer. This command adds the necessary package to your project's dependencies. ```console composer require turso/libsql ``` -------------------------------- ### Replica Example in Rust Source: https://docs.turso.tech/sdk/rust/examples Demonstrates how to set up and use a LibSQL replica database in Rust. This allows for read-only copies of your database to improve read performance. ```rust use libsql_client::anyhow::Result; use libsql_client::Database; #[tokio::main] async fn main() -> Result<()> { // Open a local database configured as a replica let db = Database::open_with_replicas( "file:replica.db?encryption_key=my_secret_key", &["libsql://your-remote-db.turso.io"], "your-auth-token" ).await?; // The replica will automatically fetch updates from the primary // You can then query the local replica database db.execute("CREATE TABLE IF NOT EXISTS messages (content TEXT)", ()).await?; db.execute("INSERT INTO messages (content) VALUES (?)", ("Hello replica!",)).await?; let mut rows = db.execute("SELECT * FROM messages", ()).await?; println!("Replica rows: {:?}", rows.rows().next()); Ok(()) } ``` -------------------------------- ### Install AgentFS CLI on Linux Source: https://docs.turso.tech/agentfs/installation Installs the AgentFS CLI on Linux using a curl command. Ensure FUSE is installed. After installation, restart your terminal or source your shell configuration file. ```bash curl -fsSL https://github.com/tursodatabase/agentfs/releases/latest/download/agentfs-installer.sh | sh ``` ```bash source ~/.bashrc # or ~/.zshrc ``` -------------------------------- ### Start MCP Server Source: https://docs.turso.tech/agentfs/reference/cli Starts a Model Context Protocol (MCP) server for a given agent. You can specify a comma-separated list of tools to enable, such as filesystem operations or key-value store access. ```bash agentfs serve mcp [OPTIONS] ``` ```bash agentfs serve mcp my-agent ``` ```bash agentfs serve mcp my-agent --tools read_file,readdir,stat ``` -------------------------------- ### Example V2 in Rust Source: https://docs.turso.tech/sdk/rust/examples An alternative or updated basic example for LibSQL in Rust, potentially showcasing newer features or a slightly different approach to common operations. ```rust use libsql_client::anyhow::Result; use libsql_client::Database; #[tokio::main] async fn main() -> Result<()> { // Open a local database file let db = Database::open("file:example_v2.db").await?; // Create a table db.execute("CREATE TABLE IF NOT EXISTS products (sku TEXT PRIMARY KEY, name TEXT)", ()).await?; // Insert data db.execute("INSERT INTO products (sku, name) VALUES (?, ?)", ("ABC-123", "Gadget")).await?; // Select data let mut rows = db.execute("SELECT name FROM products WHERE sku = ?", ("ABC-123",)).await?; if let Some(row) = rows.rows().next() { println!("Product name: {:?}", row.get("name")); } Ok(()) } ``` -------------------------------- ### Initialize libSQL and Connect to Remote Database Source: https://docs.turso.tech/sdk/c/quickstart Initialize libSQL and establish a connection to a remote Turso database. This setup requires the database URL and authentication token. ```c #include "libsql.h" libsql_setup((libsql_config_t){0}); libsql_database_t db = libsql_database_init((libsql_database_desc_t){ .url = "TURSO_DATABASE_URL", .auth_token = "TURSO_AUTH_TOKEN" }); libsql_connection_t conn = libsql_database_connect(db); ``` -------------------------------- ### @tursodatabase/sync - Installation Source: https://docs.turso.tech/sdk/ts/reference Install the @tursodatabase/sync package using npm. ```APIDOC ## @tursodatabase/sync - Installation ### Description Install the `@tursodatabase/sync` package using npm. ### Method ```bash npm install @tursodatabase/sync ``` ``` -------------------------------- ### @tursodatabase/database - Installation Source: https://docs.turso.tech/sdk/ts/reference Install the @tursodatabase/database package using npm. ```APIDOC ## @tursodatabase/database - Installation ### Description Install the `@tursodatabase/database` package using npm. ### Method ```bash npm install @tursodatabase/database ``` ``` -------------------------------- ### Create Directories Source: https://docs.turso.tech/agentfs/sdk/rust Demonstrates creating a single directory and creating nested directories using `mkdir_p`. ```rust agent.fs.mkdir("/reports").await?; agent.fs.mkdir_p("/reports/2024/Q4").await?; ``` -------------------------------- ### Install pyturso with pip Source: https://docs.turso.tech/sdk/python/quickstart Install the pyturso package using pip. ```bash pip install pyturso ``` -------------------------------- ### Initialize libSQL and Connect to Embedded Replica Source: https://docs.turso.tech/sdk/c/quickstart Initialize libSQL and establish a connection to an embedded replica database. This setup includes database path, URL, and authentication token. ```c #include "libsql.h" libsql_setup((libsql_config_t){0}); libsql_database_t db = libsql_database_init((libsql_database_desc_t){ .path = "local.db", .url = "TURSO_DATABASE_URL", .auth_token = "TURSO_AUTH_TOKEN", .sync_interval = 300 }); libsql_connection_t conn = libsql_database_connect(db); ``` -------------------------------- ### Install Turso CLI with Script (macOS, Linux, Windows/WSL) Source: https://docs.turso.tech/cli/installation Execute this script to install the Turso CLI on macOS, Linux, or within WSL on Windows. Ensure you have curl installed. ```bash curl -sSfL https://get.tur.so/install.sh | bash ``` -------------------------------- ### List Database Instances using Turso SDK Source: https://docs.turso.tech/api-reference/databases/list-instances This Node.js example demonstrates how to use the Turso SDK to fetch a list of instances for a database. Ensure you have initialized the client with your organization and token. ```typescript import { createClient } from "@tursodatabase/api"; const turso = createClient({ org: "...", token: "", }); const instances = await turso.databases.listInstances("my-db"); ``` -------------------------------- ### Install AgentFS CLI on macOS Source: https://docs.turso.tech/agentfs/installation Installs the AgentFS CLI on macOS using a curl command. After installation, you may need to restart your terminal or source your shell configuration file. ```bash curl -fsSL https://github.com/tursodatabase/agentfs/releases/latest/download/agentfs-installer.sh | sh ``` ```bash source ~/.zshrc # or ~/.bashrc ``` -------------------------------- ### Query with Positional Placeholder (Rust Example) Source: https://docs.turso.tech/sdk/php/reference Example of executing a query with a positional placeholder using Rust syntax. Note: This example uses Rust syntax but is presented in a PHP context. ```rust conn->query("SELECT * FROM users WHERE id = ?", [1]); ``` -------------------------------- ### Initializing LibsqlClient Source: https://docs.turso.tech/sdk/flutter/reference Demonstrates how to create a database client instance using the LibsqlClient constructor. Supports in-memory, local SQLite, remote Turso/libSQL, and embedded replica configurations. ```APIDOC ## Initializing LibsqlClient Call `LibsqlClient` constructor to create the database client. Different configurations are supported, allowing connection to in-memory database, local sqlite file, remote Turso / libSQL database, or embedded replica. ### In-Memory Databases libSQL supports connecting to [in-memory databases](https://www.sqlite.org/inmemorydb.html) for cases where you don't require persistence: ```dart final client = LibsqlClient(":memory:"); ``` ### Local Development You can work locally using an SQLite file and passing the path to `LibsqlClient`: ```dart final dir = await getApplicationCacheDirectory(); final path = '${dir.path}/local.db'; final client = LibsqlClient(path); ``` ### Remote You can work with remote database by passing your Turso Database URL: ```dart final client = LibsqlClient('') ..authToken = ''; ``` ### Embedded Replicas You can work with embedded replicas by passing your Turso Database URL to `syncUrl`: ```dart final dir = await getApplicationCacheDirectory(); final path = '${dir.path}/local.db'; final client = LibsqlClient(path) ..authToken = '' ..syncUrl = '' ..readYourWrites = true; ``` ### Encryption at rest To enable encryption on a SQLite file, pass the `encryptionKey`: ```dart final dir = await getApplicationCacheDirectory(); final path = '${dir.path}/local.db'; final client = LibsqlClient(path)..encryptionKey = ''; ``` ``` -------------------------------- ### Local Sync Workflow: Client A Write and Push (Go) Source: https://docs.turso.tech/sync/local-sync-server Example of writing data and pushing it to the local sync server using Go. Ensure the sync server is running before executing. ```go clientA, err := turso.NewTursoSyncDb(ctx, turso.TursoSyncDbConfig{ Path: "./client-a.db", RemoteUrl: "http://localhost:8080", }) if err != nil { return err } connA, _ := clientA.Connect(ctx) connA.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, body TEXT)") connA.ExecContext(ctx, "INSERT INTO notes VALUES ('n1', 'hello from client A')") clientA.Push(ctx) ``` -------------------------------- ### Execute with Named Placeholder (Rust Example) Source: https://docs.turso.tech/sdk/php/reference Example of executing an insert statement with a named placeholder using Rust syntax. Note: This example uses Rust syntax but is presented in a PHP context. ```rust conn->execute("INSERT INTO users (name) VALUES (:name)", [ ":name" => "Iku" ]); ``` -------------------------------- ### Complete FTS Example: Create, Index, Insert, Query Source: https://docs.turso.tech/sql-reference/functions/fts Demonstrates the full lifecycle of using FTS in Turso: creating a table, adding an FTS index with weights, inserting data, performing simple and ranked searches, and highlighting results. Also shows combining FTS with regular SQL filters. ```sql -- Create a table CREATE TABLE articles ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT, author TEXT ); -- Create an FTS index on title and body with field weights CREATE INDEX idx_articles_fts ON articles USING fts (title, body) WITH (weights = 'title=2.0,body=1.0'); -- Insert sample data INSERT INTO articles VALUES (1, 'Introduction to Databases', 'Databases store and organize data for efficient retrieval.', 'Alice'); INSERT INTO articles VALUES (2, 'Full-Text Search in Practice', 'Full-text search allows finding documents by content.', 'Bob'); INSERT INTO articles VALUES (3, 'Database Performance Tuning', 'Optimizing database queries requires understanding indexes.', 'Alice'); INSERT INTO articles VALUES (4, 'Getting Started with Rust', 'Rust is a systems programming language focused on safety.', 'Carol'); -- Simple search: find articles mentioning "database" SELECT id, title FROM articles WHERE fts_match(title, body, 'database'); -- 1 | Introduction to Databases -- 3 | Database Performance Tuning -- Ranked search: order by relevance SELECT id, title, fts_score(title, body, 'database') AS score FROM articles WHERE fts_match(title, body, 'database') ORDER BY score DESC LIMIT 10; -- Highlighted results SELECT id, fts_highlight(title, '', '', 'database') AS title, fts_highlight(body, '', '', 'database') AS body FROM articles WHERE fts_match(title, body, 'database'); -- Combine FTS with regular SQL filters SELECT id, title, author, fts_score(title, body, 'database') AS score FROM articles WHERE fts_match(title, body, 'database') AND author = 'Alice' ORDER BY score DESC; ``` -------------------------------- ### Get string or blob length Source: https://docs.turso.tech/sql-reference/functions/scalar Use `length` to get the number of characters in text or bytes in a blob. Use `octet_length` to always get the length in bytes. Both return NULL for NULL input. ```sql SELECT length('Hello'); -- 5 SELECT length(x'AABBCC'); -- 3 (bytes for blob) SELECT length(12345); -- 5 (text representation) SELECT octet_length('Hello'); -- 5 (ASCII, 1 byte per char) ``` -------------------------------- ### Install @tursodatabase/database Source: https://docs.turso.tech/sdk/ts/quickstart Install the Turso database package for local and embedded use cases. ```bash npm install @tursodatabase/database ``` -------------------------------- ### Start Drizzle Studio Source: https://docs.turso.tech/sdk/ts/orm/drizzle Launch Drizzle Studio using the 'db:studio' script for visual database management. ```bash npm run db:studio ``` ```bash pnpm run db:studio ``` -------------------------------- ### Install Sentry Integration Source: https://docs.turso.tech/sdk/ts/integrations/sentry Install the Sentry integration package for @libsql/client using npm. ```bash npm install sentry-integration-libsql-client ``` -------------------------------- ### Create, Insert, and Query with tursogo Source: https://docs.turso.tech/sdk/go/reference Example of creating a table, inserting data, and querying records using the database/sql interface with tursogo. ```go _, err = db.Exec(`CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL )`) _, err = db.Exec("INSERT INTO users (name) VALUES (?)", "Alice") rows, err := db.Query("SELECT * FROM users") defer rows.Close() for rows.Next() { var id int var name string ows.Scan(&id, &name) fmt.Printf("User: %d %s\n", id, name) } ``` -------------------------------- ### Install pyturso with uv Source: https://docs.turso.tech/sdk/python/quickstart Install the pyturso package using the uv package manager. ```bash uv add pyturso ``` -------------------------------- ### Sync Example Source: https://docs.turso.tech/sdk/ts/examples Demonstrates how to use the synchronization feature to keep local data consistent with the remote database. ```javascript import { createClient } from '@libsql/client/sync'; async function main() { const client = createClient({ url: 'ws://localhost:8080', syncUrl: 'ws://localhost:8081', }); const rs = await client.execute('SELECT 1'); console.log(rs); } main(); ``` -------------------------------- ### Install libsql_dart Source: https://docs.turso.tech/sdk/flutter/quickstart Install the libsql_dart package using Flutter's package manager. ```bash flutter pub add libsql_dart ``` -------------------------------- ### Start Local Turso Sync Server Source: https://docs.turso.tech/sdk/go/quickstart Start a local sync server for testing Turso sync functionality without a Turso Cloud account. This command sets up a local server that can be used as a remote URL for the sync driver. ```bash tursodb :memory: --sync-server 127.0.0.1:8080 ``` -------------------------------- ### Install Turso CLI on macOS Source: https://docs.turso.tech/cli/group/locations/add Use Homebrew to install the Turso CLI on macOS. ```bash brew install tursodatabase/tap/turso ``` -------------------------------- ### Initialize and Mount an Overlay Filesystem Source: https://docs.turso.tech/agentfs/guides/overlay Explicitly initializes a named overlay filesystem with a specified base directory and then mounts it to a local workspace directory. This is useful for setting up persistent, named overlay environments. ```bash agentfs init my-overlay --base /path/to/project ``` ```bash agentfs mount my-overlay ./workspace ``` -------------------------------- ### Turso CLI Signup Command (Headless) Source: https://docs.turso.tech/cli/auth/signup Use the `--headless` flag when signing up from environments without a system web browser, such as Windows with WSL or remote CI/CD systems. ```bash turso auth signup --headless ``` -------------------------------- ### Install AgentFS Python SDK Source: https://docs.turso.tech/agentfs/sdk/python Install the AgentFS Python SDK using pip. ```bash pip install agentfs-sdk ``` -------------------------------- ### Install AgentFS CLI Source: https://docs.turso.tech/agentfs/introduction Installs the AgentFS command-line interface using a curl script. ```bash curl -fsSL https://agentfs.ai/install | bash ``` -------------------------------- ### Create PHP Project Directory Source: https://docs.turso.tech/sdk/php/orm/doctrine-dbal Set up a new directory for your PHP project and navigate into it. ```bash mkdir your-awesome-php-project cd your-awesome-php-project ``` -------------------------------- ### CSV Data Example Source: https://docs.turso.tech/sql-reference/cli/shell-commands Example content of a CSV file used for data import. ```csv name,age Alice,30 Bob,25 Charlie,35 ``` -------------------------------- ### Connect to Local Database and Execute Queries Source: https://docs.turso.tech/sdk/rust/quickstart Demonstrates connecting to a local Turso database, creating a table, inserting data, and querying it using Rust. ```rust use turso::Builder; #[tokio::main] async fn main() -> Result<(), Box> { let db = Builder::new_local("app.db").build().await?; let conn = db.connect()?; conn.execute( "CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL )", (), ).await?; conn.execute("INSERT INTO users (name) VALUES (?)", ("Alice",)).await?; 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(()) } ``` -------------------------------- ### Turso Crate: Connecting to a Local Database Source: https://docs.turso.tech/sdk/rust/reference Example of how to build and connect to a local Turso database file using the 'turso' crate. ```APIDOC ## Connecting ```rust use turso::Builder; let db = Builder::new_local("app.db").build().await?; let conn = db.connect()?; ``` ``` -------------------------------- ### Install SQLAlchemy libSQL dialect Source: https://docs.turso.tech/sdk/python/orm/sqlalchemy Install the necessary library for SQLAlchemy to interact with libSQL databases. ```bash pip install sqlalchemy-libsql ``` -------------------------------- ### Install libsql with pip Source: https://docs.turso.tech/sdk/python/quickstart Install the libsql package using pip for remote database access. ```bash pip install libsql ``` -------------------------------- ### Instantiate AppDatabase with LibSQL Source: https://docs.turso.tech/sdk/flutter/integrations/drift Create an instance of your AppDatabase, providing the database file path, sync URL, authentication token, and configuration for read-your-writes and sync interval. ```dart final db = AppDatabase(DriftLibsqlDatabase( "${dir.path}/replica.db", syncUrl: url, authToken: token, readYourWrites: true, syncIntervalSeconds: 3, )); ``` -------------------------------- ### Install AgentFS SDK with npm Source: https://docs.turso.tech/agentfs/sdk Install the AgentFS SDK using npm for Node.js projects. ```bash npm install agentfs-sdk ``` -------------------------------- ### Execute a SQL Query Source: https://docs.turso.tech/sdk/c/quickstart Prepare and execute a SQL query against the database connection. This example selects all columns from the 'users' table. ```c libsql_statement_t stmt = libsql_connection_prepare(conn, "SELECT * FROM users"); libsql_rows_t rows = libsql_statement_query(stmt); ``` -------------------------------- ### libsql Crate: Installing for Remote Access Source: https://docs.turso.tech/sdk/rust/reference Instructions for adding the 'libsql' crate with the 'remote' feature for over-the-wire access to Turso Cloud. ```APIDOC ## libsql (Remote) Use the `libsql` crate with the `remote` feature for over-the-wire access to Turso Cloud. This uses pure Rust HTTP — no C compiler needed. ### Installing ```bash cargo add libsql --features remote ``` ``` -------------------------------- ### Extract Sub-array using Array Slice in SQL Source: https://docs.turso.tech/sql-reference/functions/array The `array_slice` function extracts a portion of an array based on start and end indices. The start index is inclusive, and the end index is exclusive. NULL for start defaults to 0. ```sql SELECT array_slice('[1, 2, 3, 4]', 1, 3); -- [2,3] SELECT array_slice('[1, 2, 3, 4]', NULL, 2); -- [1,2] ``` -------------------------------- ### Verify AgentFS Installation Source: https://docs.turso.tech/agentfs/installation Run this command after installation to verify that the agentfs binary is accessible and to check its version. ```bash agentfs --version ``` -------------------------------- ### Create a Turso Database Source: https://docs.turso.tech/agentfs/guides/sync Use the `turso db create` command to create a new database for your agent. This is the first step in setting up synchronization. ```bash turso db create my-agent-db ``` -------------------------------- ### Start NFS Server for AgentFS Source: https://docs.turso.tech/agentfs/guides/nfs Starts an NFS server for a specified AgentFS agent. By default, it listens on localhost. ```bash agentfs serve nfs my-agent ``` -------------------------------- ### Install Turso CLI on Windows Source: https://docs.turso.tech/tursodb/quickstart Installs the Turso CLI using PowerShell. Alternatively, download the executable manually. ```powershell irm https://github.com/tursodatabase/turso/releases/latest/download/turso_cli-installer.ps1 | iex ``` -------------------------------- ### Connect to Local Database and Execute Queries (tursogo) Source: https://docs.turso.tech/sdk/go Connect to a local Turso database file (`app.db`) using the `tursogo` driver. This snippet demonstrates creating a table, inserting data, and querying records. ```go package main import ( "database/sql" "fmt" _ "turso.tech/database/tursogo" ) func main() { db, _ := sql.Open("turso", "app.db") defer db.Close() db.Exec(`CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL ) `) db.Exec("INSERT INTO users (name) VALUES (?)", "Alice") rows, _ := db.Query("SELECT * FROM users") defer rows.Close() for rows.Next() { var id int var name string rows.Scan(&id, &name) fmt.Printf("User: %d %s\n", id, name) } } ``` -------------------------------- ### Connect to Local Turso Database and Execute Queries Source: https://docs.turso.tech/sdk/rust Demonstrates connecting to a local Turso database file, creating a table, inserting data, and querying records using the `turso` crate. ```rust use turso::Builder; #[tokio::main] async fn main() -> Result<(), Box> { let db = Builder::new_local("app.db").build().await?; let conn = db.connect()?; conn.execute( "CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL )", (), ).await?; conn.execute("INSERT INTO users (name) VALUES (?)", ("Alice",)).await?; 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(()) } ``` -------------------------------- ### Open AgentFS with Options Source: https://docs.turso.tech/agentfs/sdk/typescript Demonstrates opening an AgentFS database with options, including persistent storage using an ID and ephemeral in-memory storage. ```typescript interface AgentFSOptions { /** * Optional unique identifier for the agent. * - If provided: Creates persistent storage at `.agentfs/{id}.db` * - If omitted: Uses ephemeral in-memory database */ id?: string; } // Persistent storage const agent = await AgentFS.open({ id: 'my-agent' }); // Creates: .agentfs/my-agent.db // Ephemeral in-memory database const ephemeralAgent = await AgentFS.open(); ``` -------------------------------- ### Install SQLAlchemy LibSQL and Python Dotenv Source: https://docs.turso.tech/sdk/python/guides/flask Install the required Python packages for SQLAlchemy and environment variable management. ```bash pip install sqlalchemy-libsql python-dotenv ```