sqlx-turso-driver 0.0.1

An asynchronous SQLx driver for embedded Turso databases
use crate::{Turso, TursoConnectOptions};
use sqlx::{Error, pool::PoolOptions};
use std::sync::{Arc, atomic::AtomicBool};

/// SQLx pool for local Turso connections.
///
/// Use [`connect_pool`] for memory databases; arbitrary SQLx pool construction
/// does not enforce the single-connection memory policy.
pub type TursoPool = sqlx::Pool<Turso>;

/// Open a bounded file pool or a single-physical-connection memory pool.
///
/// Zero capacity is rejected. Memory capacity must be exactly one. Memory
/// connections are never automatically recycled for age/idleness; if the sole
/// connection is lost or explicitly closed, subsequent acquisition returns an
/// error rather than silently creating a new empty database. Open a new pool
/// explicitly to start over. SQLx's finite default acquire timeout is retained.
pub async fn connect_pool(
    mut options: TursoConnectOptions,
    max_connections: u32,
) -> Result<TursoPool, Error> {
    if max_connections == 0 || (options.path.is_none() && max_connections != 1) {
        return Err(Error::Configuration(
            "sqlx-turso: capacity must be positive; memory pools require capacity 1".into(),
        ));
    }
    let mut pool = PoolOptions::<Turso>::new().max_connections(max_connections);
    if options.path.is_none() {
        options.memory_pool_opened = Some(Arc::new(AtomicBool::new(false)));
        // Recycling the only physical connection would destroy memory state.
        pool = pool.idle_timeout(None).max_lifetime(None);
    }
    pool.connect_with(options).await
}