Actix banner

Prerequisites

Before you start, make sure you:

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

Add the libsql crate to the project

cargo add libsql

Optionally, you can add a package such as dotenvy to help you work with .env files:

cargo add dotenvy
3

Execute SQL

#[tokio::main]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/", web::get().to(index)).route("/items", web::get().to(get_items)))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

async fn get_items() -> Result<HttpResponse, Error> {
    dotenv().expect(".env file not found");

    let db_url = env::var("TURSO_DATABASE_URL").unwrap();
    let auth_token = env::var("TURSO_AUTH_TOKEN").unwrap();
    let db_file = env::var("LOCAL_DB").unwrap();

    let db = Builder::new_remote_replica(db_file, url, auth_token)
    .read_your_writes(true)
    .build()
    .await
    .unwrap();

    let conn = db.connect().unwrap();

    let mut results = conn.query("SELECT * FROM items", ()).await.unwrap();

    let mut items: Vec<T> = Vec::new();

    while let Some(row) = results.next().await.unwrap() {
        let item: Item = Item {
            task: row.get(0).unwrap(),
        };
        items.push(item);
    }

    Ok(HttpResponse::Ok().json(items))
}

Examples