Improved Turso (libsql) ergonomics in Rust
14 min readSep 30, 2024
Not a Medium member? Read the post here for free.
I recently started using Turso, which is a great database option for serverless as well as to keep costs low. Its pricing is more than competitive with something like AWS DynamoDB, which is quite interesting as a alternative to it.
One problem though, there’s no support by any good ORMs or similar in the Rust ecosystem for Turso.
Instead, I was currently writing something like this, just to get a User
out from the database via their session:
let database_context = ctx.data::<DatabaseContext>().expect("Missing database context");
let conn = database_context.users.get().expect("No connection to users database");
let mut stmt = conn
.prepare(
"SELECT users.user_id, users.first_name, users.last_name, users.country, users.onboarding_step, users.demo_user
FROM auth_sessions AS sessions
LEFT JOIN users AS users ON users.user_id = sessions.user_id
WHERE sessions.session_id = :session",
)
.await
.expect("Failed to create the prepared statement to query sessions table");
let row = stmt
.query(libsql::named_params! { ":session": auth_session.session.clone() })
.await
.expect("Failed to query sessions table");
.next()
.await
.expect("Failed to get the first row of the sessions table");
if let Some(row) = row {
let user: User = de::from_row::<lib_database::User>(&row)
.expect("Failed to deserialize user")
.into();
}