W↓
All docs
🔑
Sign Up/Sign In
docs.turso.tech/sdk/rust/
Public Link
Apr 6, 2025, 5:08:09 PM - complete - 10.7 kB
Starting URLs:
https://docs.turso.tech/sdk/rust/
## Page: https://docs.turso.tech/sdk/rust/ In this Rust quickstart we will learn how to: * Retrieve database credentials * Install the Rust libSQL crate * Connect to a local or remote Turso database * Execute a query using SQL * Sync changes to local database (optional) 1 Retrieve database credentials You will need an existing database to continue. If you don’t have one, create one. Get the database URL: turso db show --url <database-name> Get the database authentication token: turso db tokens create <database-name> Assign credentials to the environment variables inside `.env`. TURSO_DATABASE_URL= TURSO_AUTH_TOKEN= You will want to store these as environment variables. 2 Install First begin by installing the `libsql` crate: cargo add libsql 3 Connect You must first create a `Database` object and then open a `Connection` to it: use libsql::Builder; let url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set"); let db = Builder::new_remote_replica("local.db", url, token) .build() .await?; let conn = db.connect()?; use libsql::Builder; let db = Builder::new_local("local.db").build().await?; let conn = db.connect()?; use libsql::Builder; let url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set"); let db = Builder::new_remote(url, token) .build() .await?; let conn = db.connect()?; 4 Execute You can execute a SQL query against your existing database by calling `execute()`: conn.execute("SELECT * FROM users", ()).await?; If you need to use placeholders for values, you can do that: conn.execute("SELECT * FROM users WHERE id = ?1", libsql::params![1]).await?; To retrieve results from a query, you can use the `query()` method: 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); } 5 Sync (Embedded Replicas only) When using embedded replicas you should call `sync()` on the database type to sync your local database with the primary database: db.sync().await.unwrap(); You can also set up automatic periodic syncing when creating the database: use std::time::Duration; let db = Builder::new_remote_replica("local.db", url, token) .sync_interval(Duration::from_secs(60)) .build() .await?; This will automatically sync the database every 60 seconds. --- ## Page: https://docs.turso.tech/sdk/rust/quickstart In this Rust quickstart we will learn how to: * Retrieve database credentials * Install the Rust libSQL crate * Connect to a local or remote Turso database * Execute a query using SQL * Sync changes to local database (optional) 1 Retrieve database credentials You will need an existing database to continue. If you don’t have one, create one. Get the database URL: turso db show --url <database-name> Get the database authentication token: turso db tokens create <database-name> Assign credentials to the environment variables inside `.env`. TURSO_DATABASE_URL= TURSO_AUTH_TOKEN= You will want to store these as environment variables. 2 Install First begin by installing the `libsql` crate: cargo add libsql 3 Connect You must first create a `Database` object and then open a `Connection` to it: use libsql::Builder; let url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set"); let db = Builder::new_remote_replica("local.db", url, token) .build() .await?; let conn = db.connect()?; use libsql::Builder; let db = Builder::new_local("local.db").build().await?; let conn = db.connect()?; use libsql::Builder; let url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set"); let db = Builder::new_remote(url, token) .build() .await?; let conn = db.connect()?; 4 Execute You can execute a SQL query against your existing database by calling `execute()`: conn.execute("SELECT * FROM users", ()).await?; If you need to use placeholders for values, you can do that: conn.execute("SELECT * FROM users WHERE id = ?1", libsql::params![1]).await?; To retrieve results from a query, you can use the `query()` method: 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); } 5 Sync (Embedded Replicas only) When using embedded replicas you should call `sync()` on the database type to sync your local database with the primary database: db.sync().await.unwrap(); You can also set up automatic periodic syncing when creating the database: use std::time::Duration; let db = Builder::new_remote_replica("local.db", url, token) .sync_interval(Duration::from_secs(60)) .build() .await?; This will automatically sync the database every 60 seconds. --- ## Page: https://docs.turso.tech/sdk/rust/reference The libSQL Rust crate contains everything you need to work with Turso and works flawlessly with popular async runtimes like `tokio`. ## Installing Install the crate in your project using the following command: ### Conditional compilation The libsql rust client supports conditionally compiling certain features to reduce compile times depending on what features you would like to use. The following features are available: | Feature | Description | | --- | --- | | `remote` | Enables the HTTP-only client, allowing communication with a remote sqld server using pure Rust. Does not require compiling C code for SQLite. Suitable for projects that only need to interact with a remote database. | | `core` | Enables the local database only, incorporating the C SQLite3 code into the build. This is the foundation for local database operations but does not include additional features like replication or encryption. | | `replication` | Combines core with additional code required for replication, enabling the embedded replica features. | | `encryption` | Enables encryption at rest support, adding the necessary code to compile encryption capabilities and expose functions for configuring it. **This is optional and not enabled by default**, catering to projects that require enhanced data security. | ## Initializing Make sure add the crate to your project at the top of your file: ## In-Memory Databases libSQL supports connecting to in-memory databases for cases where you don’t require persistence: ## Local Development You can work locally using an SQLite file using `new_local`: ## Embedded Replicas You can work with embedded replicas using `new_remote_replica` that can sync from the remote URL and delegate writes to the remote primary database: ### Manual Sync The `sync` function allows you to sync manually the local database with the remote counterpart: ### Sync Interval The `sync_interval` function allows you to set an interval for automatic synchronization of the database in the background: ### Read Your Own Writes The `read_your_writes` function configures the database connection to ensure that writes are immediately visible to subsequent read operations initiated by the same connection. This is **enabled by default**, and is particularly important in distributed systems to ensure consistency from the perspective of the writing process. You can disable this behavior by passing `false` to the function: ## Encryption To enable encryption on a SQLite file (`new_local` or `new_remote_replica`), make sure you have the `encryption` feature enabled, and pass the `encryption_config`: Rust ## Simple query You can pass a string to `execute()` to invoke a SQL statement, as well as optional arguments: ## Prepared Statements You can prepare a cached statement using `prepare()` and then execute it with `query()`: ## Placeholders libSQL supports the use of positional and named placeholders within SQL statements: ## Deserialization You can use the `de::from_row` function to deserialize a row into a struct: ## Batch Transactions A batch consists of multiple SQL statements executed sequentially within an implicit transaction. The backend handles the transaction: success commits all changes, while any failure results in a full rollback with no modifications. ## Interactive Transactions Interactive transactions in SQLite ensure the consistency of a series of read and write operations within a transaction’s scope. These transactions give you control over when to commit or roll back changes, isolating them from other client activity. * `transaction()` — with default transaction behavior (`DEFFERED`) * `transaction_with_behavior()` — with custom transaction behavior --- ## Page: https://docs.turso.tech/sdk/rust/examples * * GitHub Copilot Write better code with AI * GitHub Advanced Security Find and fix vulnerabilities * Actions Automate any workflow * Codespaces Instant dev environments * Issues Plan and track work * Code Review Manage code changes * Discussions Collaborate outside of code * Code Search Find more, search less * Explore * Learning Pathways * Events & Webinars * Ebooks & Whitepapers * Customer Stories * Partners * Executive Insights * * GitHub Sponsors Fund open source developers * The ReadME Project GitHub community articles * * Enterprise platform AI-powered developer platform * Pricing ## Provide feedback ## Saved searches ## Use saved searches to filter your results more quickly Sign up