### Turso CLI Quickstart for Rust Source: https://docs.turso.tech/sdk/rust Get started with Turso and Rust using the `turso` CLI for local development and cloud synchronization. This approach simplifies setup and provides a seamless development experience. ```rust use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { let db = turso::Connection::connect("file://my_db.sqlite").await?; // Create a table db.execute( "CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL )", [], ).await?; // Insert a row let res = db.execute("INSERT INTO messages (text) VALUES (?)", ["Hello Turso!"]) .await?; println!("Inserted row with ID: {}", res.last_insert_rowid()); // Query rows let mut rows = db.execute("SELECT * FROM messages", []).await?; while let Some(row) = rows.next()? { println!("Message: {}", row.get::<_, String>(0)?); } Ok(()) } ``` -------------------------------- ### Quickstart: Recommended tursogo (Local + Cloud Sync) Source: https://docs.turso.tech/sdk/go This snippet demonstrates how to get started with Turso and Go using the `tursogo` library for local development and cloud synchronization. ```go package main import ( "context" "fmt" "log" "github.com/tursodatabase/go-sdk" ) func main() { // Create a new Turso client // Replace with your actual database URL and token client, err := go_sdk.NewClient(go_sdk.WithToken("YOUR_AUTH_TOKEN")) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Use the client to interact with your database ctx := context.Background() rows, err := client.Execute(ctx, "SELECT count(*) FROM messages") if err != nil { log.Fatalf("Failed to execute query: %v", err) } var count int rows.Next(&count) fmt.Printf("Number of messages: %d\n", count) } ``` -------------------------------- ### Install libsql-client-go Source: https://docs.turso.tech/sdk/go/quickstart Install the libsql-client-go package using go get. ```bash go get github.com/tursodatabase/libsql-client-go/libsql ``` -------------------------------- ### Full Quickstart Example Source: https://docs.turso.tech/sdk/go/quickstart Combines connection, table creation, data insertion, and data retrieval into a single executable Go program. This provides a complete end-to-end example. ```go package main import ( "context" "fmt" "log" "os" "github.com/tursodatabase/go-sdk" ) func main() { url := os.Getenv("TURSO_URL") authToken := os.Getenv("TURSO_AUTH_TOKEN") if url == "" || authToken == "" { log.Fatal("Please set TURSO_URL and TURSO_AUTH_TOKEN environment variables.") } db, err := turso.Open(url, authToken) if err != nil { log.Fatalf("Failed to open Turso database: %v", err) } ctx := context.Background() // Create table err = createTable(ctx, db) if err != nil { log.Fatalf("Error creating table: %v", err) } fmt.Println("Table 'users' created or already exists.") // Insert data err = insertUser(ctx, db, "Alice", "alice@example.com") if err != nil { log.Printf("Warning: Could not insert Alice (might already exist): %v", err) } else { fmt.Println("Inserted user Alice.") } err = insertUser(ctx, db, "Bob", "bob@example.com") if err != nil { log.Printf("Warning: Could not insert Bob (might already exist): %v", err) } else { fmt.Println("Inserted user Bob.") } // Select data fmt.Println("\nFetching users:") err = getUsers(ctx, db) if err != nil { log.Fatalf("Error fetching users: %v", err) } } func createTable(ctx context.Context, db *turso.Database) error { _, err := db.Exec(ctx, "CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL )") if err != nil { return fmt.Errorf("failed to create users table: %w", err) } return nil } func insertUser(ctx context.Context, db *turso.Database, name, email string) error { _, err := db.Exec(ctx, "INSERT INTO users (name, email) VALUES (?, ?)", name, email) if err != nil { return fmt.Errorf("failed to insert user: %w", err) } return nil } func getUsers(ctx context.Context, db *turso.Database) error { rows, err := db.Query(ctx, "SELECT id, name, email FROM users") if err != nil { return fmt.Errorf("failed to query users: %w", err) } defer rows.Close() for rows.Next() { var id int var name, email string if err := rows.Scan(&id, &name, &email); err != nil { return fmt.Errorf("failed to scan user row: %w", err) } fmt.Printf("ID: %d, Name: %s, Email: %s\n", id, name, email) } if err := rows.Err(); err != nil { return fmt.Errorf("error iterating user rows: %w", err) } return nil } ``` -------------------------------- ### Example Table Setup Source: https://docs.turso.tech/sql-reference/functions/aggregate SQL code defining a sample table used for demonstrating aggregate function examples. ```sql CREATE TABLE items ( id INTEGER PRIMARY KEY, name TEXT, quantity INTEGER, price REAL ); INSERT INTO items (name, quantity, price) VALUES ('apple', 10, 0.50), ('banana', 20, 0.25), ('orange', 15, 0.75), ('apple', 5, 0.50), ('banana', 10, 0.25); ``` -------------------------------- ### AgentFS Python SDK Quick Start Source: https://docs.turso.tech/llms-full.txt A quick start example demonstrating how to use the AgentFS Python SDK. It covers opening an agent filesystem, performing key-value operations, writing and reading files, and tracking 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()) ``` -------------------------------- ### Complete AgentFS Example with Tool Call Tracking Source: https://docs.turso.tech/llms-full.txt A full example demonstrating AgentFS initialization, KV storage, file system operations, and tool call tracking (start, success). Includes asynchronous operations and basic output. ```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()) ``` -------------------------------- ### Install the Turso Go SDK Source: https://docs.turso.tech/sdk/go/quickstart Install the Turso Go SDK using the go get command. This command fetches and installs the latest version of the SDK. ```bash go get github.com/turso/go-sdk ``` -------------------------------- ### Install Turso Go SDK Source: https://docs.turso.tech/sdk/go/quickstart Install the Turso Go SDK using the `go get` command. This command fetches and installs the necessary packages for your Go project. ```shellscript go get github.com/turso-dev/go-sdk ``` -------------------------------- ### Starting an HTTP Connection Source: https://docs.turso.tech/sdk/http Initiates an HTTP connection to the Turso database. This example shows how to construct the necessary parameters for starting a connection, including hostname, port, and SSL usage. ```shell response = Net:HTTP.start( uri.hostname, uri.port, use_ssl: uri.scheme == 'https' ) |> http ``` -------------------------------- ### Full Encryption Setup Example Source: https://docs.turso.tech/llms-full.txt Demonstrates setting both the cipher and hexadecimal key before creating tables. This ensures all subsequent data is encrypted. ```sql -- Set cipher and key before creating tables PRAGMA cipher = 'aegis256'; PRAGMA hexkey = '2d7a30108d3eb3e45c90a732041fe54778bdcf707c76749fab7da335d1b39c1d'; CREATE TABLE secrets (id INTEGER PRIMARY KEY, data TEXT); INSERT INTO secrets VALUES (1, 'sensitive data'); ``` -------------------------------- ### Install and Use the TypeScript SDK Source: https://docs.turso.tech/api-reference/groups/add-location Install the `@tursodatabase/api` package and use the `createClient` function to interact with the Turso Platform API. This example demonstrates creating a database, generating a token, and deleting the database. ```bash npm install @tursodatabase/api ``` ```typescript import { createClient } from "@tursodatabase/api"; const turso = createClient({ org: process.env.TURSO_ORG!, token: process.env.TURSO_PLATFORM_TOKEN!, }); // Create a database const db = await turso.databases.create("user-abc123", { group: "default" }); // Generate a scoped auth token for that database const { jwt } = await turso.databases.createToken("user-abc123"); // Delete it when no longer needed await turso.databases.delete("user-abc123"); ``` -------------------------------- ### Go Example: Basic Turso Database Connection Source: https://docs.turso.tech/local-development Demonstrates how to import necessary packages and establish a connection to a local Turso database using Go. Ensure you have the go-libsql library installed. ```go package main import ( "database/sql" "fmt" os" _ "github.com/tursodatabase/go-libsql" ) func main() { dbName := "file:./local.db" ``` -------------------------------- ### Turso SDK Initialization Example Source: https://docs.turso.tech/sdk/ts/reference Demonstrates how to initialize the Turso SDK with a database URL and authentication token. This is a common setup for applications using the Turso SDK. ```typescript import { createClient } from "@tursodatabase/sdk"; const db = createClient("http://localhost:8080", { headers: { Authorization: "Bearer YOUR_AUTH_TOKEN", }, }); const { rows } = await db.execute("SELECT 1"); ``` -------------------------------- ### Turso CLI - Example Usage Source: https://docs.turso.tech/cli This snippet demonstrates a typical usage pattern for the Turso CLI, showing how to list databases and then select one for further operations. It's useful for initial setup and exploration. ```bash turso db list turso db show my-db ``` -------------------------------- ### AgentFS Backup and Recovery Example Source: https://docs.turso.tech/llms-full.txt Demonstrates the workflow for backing up agent state to Turso Cloud and recovering it on a new machine. This involves pushing local changes and then pulling them on a new setup. ```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 ``` -------------------------------- ### Connect to Local Database (Go) Source: https://docs.turso.tech/local-development Connect to a local Turso database file using the Go client. This example demonstrates basic import and connection setup. ```go package main import ( "turso" ) func main() { db := turso.NewClient( turso.WithURL("file:local.db"), turso.WithAuthToken(""), ) db.Close() } ``` -------------------------------- ### Turso CLI - Managing Database Table Extensions (List All Versions Available) Source: https://docs.turso.tech/cli This example shows how to list the versions of all available extensions that can be installed in a Turso database. This helps in choosing the appropriate version. ```bash turso db extensions versions-available ``` -------------------------------- ### Turso CLI - Managing Database Table Extensions Source: https://docs.turso.tech/cli This example shows how to list all installed extensions for a Turso database. Extensions add new functionalities to your database. ```bash turso db extensions --db my-db ``` -------------------------------- ### Installing tursogo Source: https://docs.turso.tech/sdk/go/reference Install the tursogo package using go get. ```APIDOC ## Installing tursogo ### Description Install the tursogo package using go get. ### Command ```bash go get turso.tech/database/tursogo ``` ``` -------------------------------- ### Turso CLI - Managing Database Table Extensions (Info) Source: https://docs.turso.tech/cli This example shows how to get detailed information about a specific extension for a Turso database. This includes description, dependencies, and available functions. ```bash turso db extensions info "uuid-ossp" --db my-db ``` -------------------------------- ### Starting a New Project Guidance Source: https://docs.turso.tech/sdk/rust/reference Guidance on choosing between the 'turso' and 'libsql' crates for new projects based on whether local/embedded use or remote access is required. ```markdown **Starting a new project?** Use `turso` for local/embedded use or sync. Use `libsql` with the `remote` feature for over-the-wire access (no C compiler needed). ``` -------------------------------- ### Transaction Example: Insert and Commit Source: https://docs.turso.tech/sql-reference/statements/transactions This example demonstrates starting a transaction, inserting a record, and then committing the changes. ```sql BEGIN; INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); COMMIT; ``` -------------------------------- ### Create Table Example Source: https://docs.turso.tech/sql-reference/statements/alter-table This example demonstrates the creation of a 'products' table with an 'id', 'product_name', and 'price' column. ```sql CREATE TABLE products ( id INTEGER PRIMARY KEY, product_name TEXT NOT NULL, price REAL ); ``` -------------------------------- ### Connect to Turso Database with Go SDK Source: https://docs.turso.tech/sdk/go/reference Demonstrates how to initialize the Go SDK and connect to a Turso database using a local database file, a primary URL, and an authentication token. It also shows how to create a temporary directory for the database. ```go func main() { dbName := "local.db" primaryUrl := "libsql://[DATABASE].turso.io" authToken := "..." dir, err := os.MkdirTemp("", "libsql-*") if err != nil { // Handle error } // ... rest of the code } ``` -------------------------------- ### GET /v1/jobs/:id Request Example Source: https://docs.turso.tech/sdk/http/reference Example of how to retrieve detailed information about a specific migration job using its ID. ```shellscript curl "https://turso.tech/api/v1/jobs/39" \ -H "Authorization: Bearer YOUR_AUTH_TOKEN" ``` -------------------------------- ### Starting Turso SQL Transactions Source: https://docs.turso.tech/llms-full.txt Examples of how to start different types of transactions in Turso. The default transaction type is DEFERRED. ```sql -- Start a deferred transaction (default) BEGIN; ``` ```sql -- Start an immediate transaction BEGIN IMMEDIATE; ``` ```sql -- The TRANSACTION keyword is optional BEGIN IMMEDIATE TRANSACTION; ``` -------------------------------- ### Start AgentFS MCP Server Source: https://docs.turso.tech/llms-full.txt Starts an MCP server that exposes AgentFS tools over stdio. This is the basic command to get the server running. ```bash agentfs serve mcp my-agent ``` -------------------------------- ### Initialize Turso Project with Python Source: https://docs.turso.tech/quickstart Set up a new Python project and install the Turso client library. This prepares your application to interact with Turso. ```bash python3 -m venv venv source venv/bin/activate pip install libsql-client ``` -------------------------------- ### Transaction Example: Insert and Rollback Source: https://docs.turso.tech/sql-reference/statements/transactions This example shows starting a transaction, inserting a record, and then rolling back the changes, effectively canceling the insert. ```sql BEGIN; INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com'); ROLLBACK; ``` -------------------------------- ### Initialize libSQL Source: https://docs.turso.tech/llms-full.txt Before using libSQL, you must call the setup function. This initializes the library with default configuration. ```c libsql_setup((libsql_config_t){0}); ``` -------------------------------- ### Integrate with Python Source: https://docs.turso.tech/tursodb/quickstart Example of connecting to a Turso database using the Turso Python SDK. Ensure you have the SDK installed (`pip install libsql-client`). ```python from libsql_client import Client client = Client(host=".turso.io", auth_token="YOUR_AUTH_TOKEN") result = client.execute("SELECT * FROM users WHERE name = 'Bob'") print(result.rows) ``` -------------------------------- ### Complete Schema Evolution Example Source: https://docs.turso.tech/sql-reference/statements/alter-table This example demonstrates a sequence of ALTER TABLE operations to evolve a table schema, starting from creation and adding/modifying columns. ```sql -- Create initial table CREATE TABLE articles ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT ); -- Add a new column ALTER TABLE articles ADD COLUMN active INTEGER DEFAULT 1; -- Drop the 'body' column ALTER TABLE articles DROP COLUMN body; -- Rename the 'active' column to 'is_active' ALTER TABLE articles RENAME COLUMN active TO is_active; -- Change the data type of 'is_active' to TEXT ALTER TABLE articles ALTER COLUMN is_active TYPE TEXT; -- Set 'is_active' to NOT NULL ALTER TABLE articles ALTER COLUMN is_active SET NOT NULL; -- Set a default value for 'is_active' ALTER TABLE articles ALTER COLUMN is_active SET DEFAULT '1'; -- Drop the default value for 'is_active' ALTER TABLE articles ALTER COLUMN is_active DROP DEFAULT; -- Add a new column 'created_at' with a default timestamp ALTER TABLE articles ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP; -- Verify the schema PRAGMA table_info(articles); ``` -------------------------------- ### Example: Adding a Location to a Group Source: https://docs.turso.tech/cli/group/locations/add This example demonstrates adding the 'eu-central-1' location to a group named 'my-group'. Ensure you have the Turso CLI installed and authenticated. ```bash turso group locations add my-group eu-central-1 ``` -------------------------------- ### Turso Database Connection Example Source: https://turso.tech/ Demonstrates how to establish a connection to a Turso database using a connection string. ```go package main import ( "context" "fmt" "log" "github.com/libsql/client-go/turso" ) func main() { // Replace with your actual database URL and authentication token db, err := turso.New("file:./my.db?mode=memory&cache=shared", "YOUR_AUTH_TOKEN") if err != nil { log.Fatalf("failed to create database client: %s", err) } ctx := context.Background() // Example query res, err := db.Execute(ctx, "SELECT count(*) FROM users") if err != nil { log.Fatalf("failed to execute query: %s", err) } fmt.Printf("Query result: %v\n", res) } ``` -------------------------------- ### Integrate with JavaScript (Node.js) Source: https://docs.turso.tech/tursodb/quickstart Example of connecting to a Turso database using the Turso JavaScript SDK in a Node.js environment. Ensure you have the SDK installed (`npm install @libsql/client`). ```javascript import { createClient } from '@libsql/client'; const client = createClient({ url: "libsql://.turso.io", authToken: process.env.TURSO_AUTH_TOKEN, }); async function main() { const result = await client.execute("SELECT * FROM users WHERE name = 'Alice'"); console.log(result.rows); } main(); ``` -------------------------------- ### Initialize Turso Project with Node.js Source: https://docs.turso.tech/quickstart Set up a new Node.js project and install the Turso client library. This prepares your application to interact with Turso. ```bash mkdir my-turso-app && cd my-turso-app npm init -y npm install @libsql/sqlite3 ``` -------------------------------- ### Get Database Schema Source: https://docs.turso.tech/sdk/http/reference Example of an HTTP request to retrieve the schema definition for a specific database. ```http GET /v2/databases/my-db-name/schema HTTP/1.1 Host: Authorization: Bearer ``` -------------------------------- ### Initialize Turso Client with Sync DB Config Source: https://docs.turso.tech/sdk/go/reference Demonstrates how to initialize the Turso client using `TursoSyncDbConfig` with path, remote URL, and authentication token. This is useful for setting up a client that synchronizes with a remote database. ```go db, err := turso.Dial( TursoSyncDbConfig{ Path: "app.db", RemoteUrl: os.Getenv("TURSO_DATABASE_URL"), AuthToken: os.Getenv("TURSO_AUTH_TOKEN"), }, ) if err != nil { panic(err) } ``` -------------------------------- ### Get Database Details Source: https://docs.turso.tech/sdk/http/reference Example of an HTTP request to retrieve details for a specific Turso database. ```http GET /v2/databases/my-db-name HTTP/1.1 Host: Authorization: Bearer ``` -------------------------------- ### Initialize and Mount Overlay Filesystem Source: https://docs.turso.tech/llms-full.txt Explicitly create an overlay filesystem using `agentfs init --base` and then mount it to a directory for use. ```bash agentfs init my-overlay --base /path/to/project agentfs mount my-overlay ./workspace ``` -------------------------------- ### SQL over HTTP Card Source: https://docs.turso.tech/sdk Displays a card for the SQL over HTTP feature, linking to its quickstart guide. ```jsx _jsx(Card, { horizontal: true, title: "SQL over HTTP", icon: _jsxs(_components.svg, { viewBox: "0 0 216 216", xmlns: "http://www.w3.org/2000/svg", children: [_jsx(_components.path, { d: "m25.3 114.3 15.9 48c1.5 4.5 5 8 9.5 9.5l48 15.9c5.3 1.8 11.2.4 15.2-3.6l76.7-76.7c3-3 4.6-7.1 4.3-11.4l-3.7-64c-.3-5.5-4.7-10-10.3-10.3l-64-3.7c-4.2-.2-8.4 1.3-11.4 4.3l-76.6 76.8c-4 4-5.4 9.9-3.6 15.2z", fill: "none", stroke: "#1ebca1", "stroke-miterlimit": "10", "stroke-width": "19.2" }), _jsx(_components.path, { d: "m119.2 82.2 6.5-1.5c2.9-.7 5.8 1.2 6.5 4.1.2.8.2 1.6 0 2.4l-1.5 6.5c-3.3 12.4-21.1 8.4-18.8-4.2.8-3.8 3.8-6.5 7.3-7.3z", fill: "#1ebca1" }), _jsx(_components.path, { d: "m21.1 191.8 99.8-99.8", fill: "none", stroke: "#1ebca1", "stroke-linecap": "round", "stroke-linejoin": "round", "stroke-width": "19.2" }), _jsxs(_components.g, { fill: "#1ebca1", children: [_jsx(_components.path, { d: "m141.8 142.4c-1.4 1.4-3.5 1.9-5.4 1.3l-13.3-4.4c-2-.7-4.3-.1-5.8 1.4l-8.9 8.9c-1.8 1.8-1.1 4.8 1.3 5.6l20.6 6.8c8.9 2.9 18.4.6 25-5.9" }), _jsx(_components.path, { d: "m107 177.2c-1.4 1.4-3.5 1.9-5.4 1.3l-14.6-4.8c-1.2-.4-2.5 0-3.4.8l-9.9 9.9c-1.8 1.8-1.1 4.8 1.3 5.6l20.6 6.8c8.9 2.9 18.4.6 25-5.9" }), _jsx(_components.path, { d: "m175.2 109c-1.4 1.4-3.5 1.9-5.4 1.3l-13.3-4.4c-2-.7-4.3-.1-5.8 1.4l-8.9 8.9c-1.8 1.8-1.1 4.8 1.3 5.6l20.6 6.8c8.9 2.9 18.4.6 25-5.9" })] })] }), href: "/sdk/http/quickstart" }) ``` -------------------------------- ### Database Connection and Query Example Source: https://turso.tech/ Demonstrates how to connect to a Turso database and execute a query. ```python import os from libsql_experimental import Client # Ensure TURSO_URL and TURSO_AUTH_TOKEN are set in your environment # For example: # export TURSO_URL="libsql://.turso.io" # export TURSO_AUTH_TOKEN="" client = Client(url=os.environ.get("TURSO_URL"), auth_token=os.environ.get("TURSO_AUTH_TOKEN")) result = client.execute("SELECT 1") print(result.rows) ``` -------------------------------- ### Example Transaction Workflow Source: https://docs.turso.tech/sql-reference/statements/transactions This example demonstrates a typical transaction workflow: starting a transaction, performing insert operations, and then committing the changes. If an error were to occur, `ROLLBACK` would be used instead of `COMMIT`. ```sql BEGIN; INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); INSERT INTO posts (user_id, title, content) VALUES (1, 'First Post', 'Hello, Turso!'); COMMIT; ``` -------------------------------- ### Initialize libSQL Client for Web Source: https://docs.turso.tech/llms-full.txt Create a libSQL client instance using environment variables for database URL and authentication token. ```javascript import { createClient } from "@libsql/client/web"; const turso = createClient({ url: import.meta.env.VITE_TURSO_DATABASE_URL, authToken: import.meta.env.VITE_TURSO_AUTH_TOKEN, }); ``` -------------------------------- ### Create and Insert Data for UPDATE Example Source: https://docs.turso.tech/sql-reference/statements/update These SQL statements create an 'employees' table and insert sample data. This setup is necessary to demonstrate the UPDATE statement's functionality in subsequent examples. ```sql CREATE TABLE employees ( id INTEGER PRIMARY KEY, name TEXT, salary REAL, department TEXT ); ``` ```sql INSERT INTO employees (id, name, salary, department) VALUES (1, 'Alice', 90000, 'Engineering'); ``` -------------------------------- ### Fetch a Single Value Source: https://docs.turso.tech/sdk/rust/quickstart Fetch a single value from a query result. This example gets the count of users. ```rust use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { let db = turso::Connection::from_env()?; // Ensure table and data exist from previous example db.execute("CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL )").await?; db.execute("INSERT INTO users (name) VALUES ('Alice'), ('Bob')").await?; let mut rows = db.execute("SELECT COUNT(*) AS count FROM users").await?; if let Some(row) = rows.next().await? { let count: i64 = row.get("count")?; println!("Total users: {}", count); } Ok(()) } ``` -------------------------------- ### Go Example: Initializing and Using an Embedded Replica Source: https://docs.turso.tech/features/embedded-replicas This Go code demonstrates how to initialize an embedded replica, handle potential errors during connection, and defer closing the connection. It shows how to open a database connection using the initialized replica. ```go func main() { // Create a new embedded replica connector, err := turso.NewConnector(turso.WithLocalReplica()) if err != nil { fmt.Println("Error creating connector:", err) os.Exit(1) } defer connector.Close() db := sql.Open("turso", connector) } ``` -------------------------------- ### libsql_setup Source: https://docs.turso.tech/llms-full.txt Initializes the libSQL library. This function must be called before using any other libSQL functions. ```APIDOC ## libsql_setup ### Description Initializes the libSQL library. This function must be called before using any other libSQL functions. ### Function Signature ```c void libsql_setup(libsql_config_t config); ``` ### Parameters #### Request Body - **config** (libsql_config_t) - Configuration structure for libSQL. Initialize with `{0}` for default settings. ### Request Example ```c libsql_setup((libsql_config_t){0}); ``` ``` -------------------------------- ### Install turso_dart package Source: https://docs.turso.tech/llms-full.txt Run 'dart pub get' after adding the turso_dart dependency to your pubspec.yaml to fetch the package. ```bash dart pub get ``` -------------------------------- ### Connect and Query with Go SDK Source: https://docs.turso.tech/sdk/go Example of connecting to a Turso database and executing a query using the Go SDK. Ensure environment variables are set before running. ```go package main import ( "context" "fmt" "log" "os" "github.com/tursodatabase/libsql-client-go/libsql" ) func main() { db, err := libsql.NewDatabase( libsql.WithURL(os.Getenv("TURSO_DATABASE_URL")), libsql.WithAuthToken(os.Getenv("TURSO_AUTH_TOKEN")), ) if err != nil { log.Fatalf("failed to create database: %v", err) } ctx := context.Background() // Example: Create a table _, err = db.Execute(ctx, "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)") if err != nil { log.Fatalf("failed to create table: %v", err) } // Example: Insert data _, err = db.Execute(ctx, "INSERT INTO users (name) VALUES ('Alice')") if err != nil { log.Fatalf("failed to insert data: %v", err) } // Example: Query data res, err := db.Execute(ctx, "SELECT * FROM users") if err != nil { log.Fatalf("failed to query data: %v", err) } fmt.Println("Query results:") for _, row := range res.Rows { fmt.Printf(" ID: %v, Name: %v\n", row[0], row[1]) } } ``` -------------------------------- ### Get API Rate Limits Source: https://docs.turso.tech/sdk/http/reference Example of an HTTP request to check the current API rate limits and usage for the authenticated account. ```http GET /v2/rate-limit HTTP/1.1 Host: Authorization: Bearer ``` -------------------------------- ### Connect and Query with Go SDK Source: https://docs.turso.tech/sdk/go Demonstrates how to establish a connection to a Turso database and execute a query using the Go SDK. Ensure you have imported the necessary packages. ```go package main import ( "database/sql" "fmt" os" "github.com/tursodatabase/libsql-client-go/libsql" ) func main() { // Initialize the database connection db, err := sql.Open("libsql", os.Getenv("LIBSQL_URL")) if err != nil { fmt.Fprintf(os.Stderr, "Failed to open DB: %v\n", err) os.Exit(1) } // Ping the database to verify the connection err = db.Ping() if err != nil { fmt.Fprintf(os.Stderr, "Failed to ping DB: %v\n", err) os.Exit(1) } fmt.Println("Successfully connected to Turso!") // Example query: Create a table if it doesn't exist _, err = db.Exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)") if err != nil { fmt.Fprintf(os.Stderr, "Failed to create table: %v\n", err) os.Exit(1) } // Example query: Insert data _, err = db.Exec("INSERT INTO users (name) VALUES (?)", "Alice") if err != nil { fmt.Fprintf(os.Stderr, "Failed to insert data: %v\n", err) os.Exit(1) } // Example query: Select data rows, err := db.Query("SELECT id, name FROM users") if err != nil { fmt.Fprintf(os.Stderr, "Failed to select data: %v\n", err) os.Exit(1) } defer rows.Close() for rows.Next() { var id int var name string if err := rows.Scan(&id, &name); err != nil { fmt.Fprintf(os.Stderr, "Failed to scan row: %v\n", err) os.Exit(1) } fmt.Printf("ID: %d, Name: %s\n", id, name) } if err = rows.Err(); err != nil { fmt.Fprintf(os.Stderr, "Error iterating rows: %v\n", err) os.Exit(1) } } ``` -------------------------------- ### Get Database Performance Metrics Source: https://docs.turso.tech/sdk/http/reference Example of an HTTP request to retrieve performance metrics for a specific database. This can help in monitoring and optimization. ```http GET /v2/databases/my-db-name/metrics HTTP/1.1 Host: Authorization: Bearer ``` -------------------------------- ### Go: Basic Database Connection and Query Source: https://docs.turso.tech/sdk/go Demonstrates how to establish a connection to a Turso database and execute a simple query. Ensure you have the libsql-client-go library installed. ```go package main import ( _ "database/sql" "fmt" os _ "github.com/tursodatabase/libsql-client-go/libsql" ) func main() { url := os.Getenv("LIBSQL_URL") authToken := os.Getenv("LIBSQL_AUTH_TOKEN") db, err := sql.Open("libsql", fmt.Sprintf("libsql://%s", url)) if err != nil { fmt.Printf("failed to open db: %v\n", err) } var version string err = db.QueryRow("SELECT version()").Scan(&version) if err != nil { fmt.Printf("failed to query version: %v\n", err) } fmt.Printf("Turso version: %s\n", version) } ``` -------------------------------- ### Rust Example: Building a Database Connection Source: https://docs.turso.tech/features/embedded-replicas/introduction Shows how to use the ` libsql::Builder` to construct a database connection in Rust, including setting the database URL from environment variables. ```rust use libsql::Builder use bytes::Bytes let url = env::var("TURSO_URL").expect("TURSO_URL not set") let db = Builder::new_remote_url(url, "your-auth-token").build().await.unwrap() ``` -------------------------------- ### Using `turso` with `diesel` Source: https://docs.turso.tech/sdk/rust/quickstart Integrate the `turso` crate with the `diesel` ORM for database interactions in Rust. This example outlines the setup process. ```rust // Add diesel and turso to your Cargo.toml // diesel = { version = "2.0", features = ["sqlite"] } // turso = "0.1" // Example setup (requires diesel CLI setup for schema management) // See Diesel documentation for detailed setup instructions. // #[macro_use] extern crate diesel; // use diesel::prelude::*; // use diesel::sqlite::SqliteConnection; // fn establish_connection() -> SqliteConnection { // SqliteConnection::establish("my-db.sqlite") // .expect("Error connecting to my-db.sqlite") // } // fn main() { // let connection = establish_connection(); // println!("Connected to database using diesel!"); // // Your diesel operations here // } ``` -------------------------------- ### Example of Invalidating Tokens Source: https://docs.turso.tech/sdk/authorization/tokens This snippet demonstrates how to invalidate an existing authorization token. Ensure you have the necessary client setup before calling this function. ```javascript await client.auth.tokens.invalidate("some-token-id"); ``` -------------------------------- ### Create a Token with Go Source: https://docs.turso.tech/api-reference/databases/create-token Shows how to generate a JWT token for a Turso database using the Go SDK. You can install it with `go get github.com/turso/turso-go`. ```go package main import ( "fmt" "log" "github.com/turso/turso-go" ) func main() { client := turso.NewClient() token, err := client.Databases.CreateToken( "", turso.WithExpiresIn("30d"), // Optional: default is "30d" ) if err != nil { log.Fatalf("Failed to create token: %v", err) } fmt.Println(token) } ``` -------------------------------- ### Turso SQL BEGIN Statement Example Source: https://docs.turso.tech/sql-reference/statements/transactions Use BEGIN to start a new transaction. All subsequent statements until COMMIT or ROLLBACK are part of this transaction. ```sql BEGIN; INSERT INTO accounts (id, name, balance) VALUES (1, 'Alice', 100); UPDATE accounts SET balance = balance - 10 WHERE name = 'Alice'; ``` -------------------------------- ### Turso CLI - Managing Database Migrations Source: https://docs.turso.tech/cli This example shows how to run database migrations using the Turso CLI. Migrations help manage schema changes over time. ```bash turso migrate apply --db my-db ``` -------------------------------- ### Turso CLI - Managing Database Table Extensions (List All Dependencies) Source: https://docs.turso.tech/cli This example shows how to list the dependencies for all extensions in a Turso database. This helps in understanding the overall extension ecosystem. ```bash turso db extensions dependencies-all --db my-db ``` -------------------------------- ### Extracting Vector Dimensions Source: https://docs.turso.tech/sql-reference/functions/vector Use `vector_extract` to get specific dimensions from a vector. This example shows how to extract the first 4 dimensions of an embedding. ```sql SELECT vector_extract(embedding, 0, 4) FROM articles WHERE id = 1; SELECT vector_extract(embedding, 0, 4) FROM articles WHERE id = 2; -- Extract the first 4 dimensions of an embedding ``` -------------------------------- ### Initialize Turso Go SDK Source: https://docs.turso.tech/sdk/go/reference This snippet shows how to initialize the Turso Go SDK by specifying the database name, primary URL, and authentication token. It also demonstrates creating a temporary directory for the database file. ```go package main import ( "log" "os" "github.com/tursodatabase/go-libsql" ) func main() { dbName := "local.db" primaryUrl := "libsql://[DATABASE].turso.io" authToken := "..." dir, err := os.MkdirTemp("", "libsql-*") if err != nil { log.Fatal(err) } // ... rest of the code } ``` -------------------------------- ### generate_series Examples Source: https://docs.turso.tech/llms-full.txt Illustrates practical usage of the generate_series function with different start, stop, and step values. Shows the resulting integer sequences. ```sql SELECT value FROM generate_series(1, 5); -- 1, 2, 3, 4, 5 SELECT value FROM generate_series(0, 10, 2); -- 0, 2, 4, 6, 8, 10 SELECT value FROM generate_series(10, 1, -3); -- 10, 7, 4, 1 ``` -------------------------------- ### Get Database Usage Statistics Source: https://docs.turso.tech/sdk/http/reference Example of an HTTP request to retrieve usage statistics for a specific database, such as storage used and query counts. ```http GET /v2/databases/my-db-name/stats HTTP/1.1 Host: Authorization: Bearer ``` -------------------------------- ### Initialize the SDK and Connect to a Database Source: https://docs.turso.tech/sdk/python/quickstart Initialize the Turso client with your database URL and authentication token. This is the first step before performing any database operations. ```python from turso import client # Replace with your database URL and token db_url = "file://./my_db.sqlite" auth_token = "YOUR_AUTH_TOKEN" client = client.Client(url=db_url, token=auth_token) ``` -------------------------------- ### Execute Query with Turso Python SDK Source: https://docs.turso.tech/sdk/python/reference Execute a SQL query using the connected database. This example shows the start of a query execution. ```python conn.execute(" ``` -------------------------------- ### Install libsql-client-go Source: https://docs.turso.tech/sdk/go/reference Install the libsql-client-go package to connect to remote Turso databases. ```go go get github.com/chiselstrike/go-libsql ``` -------------------------------- ### Create JWT Token (Python) Source: https://docs.turso.tech/api-reference/tokens/create Example of creating a JWT token using Python with the Turso SDK. This requires the `turso` package to be installed. ```python from libsql_experimental import Client client = Client(token=os.environ.get("TURSO_AUTH_TOKEN")) res = client.execute("SELECT * FROM users WHERE id = ?", (1,)) print(res) ``` -------------------------------- ### Create JWT Token (JavaScript) Source: https://docs.turso.tech/api-reference/tokens/create Example of creating a JWT token using JavaScript with the Turso SDK. Ensure you have the SDK installed and configured. ```javascript import { createClient } from '@libsql/client/web'; const client = createClient({ url: `file:./dev.db`, authToken: process.env.TURSO_AUTH_TOKEN, }); async function createToken() { const res = await client.execute({ sql: 'SELECT * FROM users WHERE id = ?', args: [1], }); console.log(res); } createToken(); ``` -------------------------------- ### Initialize a Turso project with JavaScript Source: https://docs.turso.tech/quickstart Set up a new JavaScript project to interact with Turso. Requires installing the Turso SDK. ```bash npm create turso-app@latest my-turso-app cd my-turso-app npm install ``` -------------------------------- ### Create Table Example Source: https://docs.turso.tech/sync/usage Example of creating a table if it doesn't exist using SQL. ```javascript if (err != nil) { return err } _ , err = conn.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS notes(id TEXT PRIMARY KEY, body TEXT)") if err != nil { return err } ``` -------------------------------- ### Turso Rust Quickstart Source: https://docs.turso.tech/sdk/rust/quickstart This snippet is part of the Rust quickstart guide, discussing the use of the `turso` crate for new projects requiring synchronization. It mentions local reads and writes with explicit sync using `push()` or `pull()`, and the logical change-data-capture wire format. ```rust use libsql_client::anyhow::Result; use libsql_client::turso::Turso; #[tokio::main] async fn main() -> Result<()> { let db = Turso::new("file.db").await?; db.execute( "CREATE TABLE IF NOT EXISTS counters ( id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER )", [], ).await?; db.execute( "INSERT INTO counters (value) VALUES (0)", [], ).await?; let mut cursor = db.execute("SELECT * FROM counters", []).await?; while let Some(row) = cursor.next()? { println!("Row: {:?}", row); } Ok(()) } ``` -------------------------------- ### Querying a View Source: https://docs.turso.tech/sql-reference/statements/create-view Demonstrates how to query the 'active_users' view to retrieve data. This example filters the view results to find users whose names start with 'A'. ```sql SELECT * FROM active_users WHERE name LIKE 'A'; ``` -------------------------------- ### Initialize libSQL and Connect to Embedded Replica Database Source: https://docs.turso.tech/llms-full.txt Initialize libSQL, set up configuration, and establish a connection to an embedded replica database. Requires database path, URL, and auth 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); ``` -------------------------------- ### Count rows with COUNT() Source: https://docs.turso.tech/sql-reference/functions/aggregate Use COUNT() to get the number of rows that match a condition. This example counts rows where the 'name' column is 'North' or 'South'. ```sql SELECT COUNT(*) FROM users WHERE name = 'North' OR name = 'South'; ```