ORM-06: Add Database connection management (ambient connection) #6

Closed
opened 2026-10-13 12:49:38 +01:00 by NoctisWolfshadow · 0 comments
Owner

Depends on: #5

Context

Models should be used without passing a connection around (User::find(1)), like Eloquent. rusqlite's Connection is Send but not Sync, so the design is: config is process-wide, the connection is per thread. Database::with is the single choke point that every model and query call goes through.

Tasks

  • Database::connect(config) -> Result<()> opens one connection to fail early and stores the config in a OnceLock. A second call returns Error::AlreadyConnected.
  • A thread_local! slot holds Option<Connection>. The first with on a thread opens a connection from the global config.
  • Database::connect_thread(config) opens a connection immediately and stores it in the calling thread's slot, never touching the global config. Database::disconnect_thread() clears the slot. Tests use this.
  • Database::with(f) hands f a shared &Connection so nested calls work, and returns Error::NotConnected when nothing is configured.
  • Docs: :memory: databases are per connection, so multi-threaded apps need a file; never hold a transaction across an .await; calling connect_thread inside a with closure panics.

Example

impl Database {
    pub fn connect(config: Config) -> Result<()>;
    pub fn connect_thread(config: Config) -> Result<()>;
    pub fn disconnect_thread();

    /// The closure may return a rusqlite or a tessera result.
    pub fn with<T, E>(f: impl FnOnce(&Connection) -> std::result::Result<T, E>) -> Result<T>
    where
        Error: From<E>;
}
// application code
fn main() -> tessera_orm::Result<()> {
    Database::connect(Config::file("app.db"))?;
    let user = User::find(1)?; // runs on this thread's connection
    Ok(())
}
// tests/database.rs  (never calls the global `connect`)
#[test]
fn with_before_connect_is_an_error() {
    let r = Database::with(|_conn| Ok::<_, Error>(()));
    assert!(matches!(r, Err(Error::NotConnected)));
}

#[test]
fn threads_do_not_share_in_memory_databases() {
    Database::connect_thread(Config::memory()).unwrap();
    Database::with(|c| c.execute_batch("CREATE TABLE t (id INTEGER)")).unwrap();

    std::thread::spawn(|| {
        Database::connect_thread(Config::memory()).unwrap();
        assert!(Database::with(|c| c.execute_batch("SELECT * FROM t")).is_err());
    })
    .join()
    .unwrap();
}

#[test]
fn nested_with_does_not_panic() {
    Database::connect_thread(Config::memory()).unwrap();
    Database::with(|_| Database::with(|_| Ok::<_, Error>(()))).unwrap();
}
// tests/database_global.rs
// A OnceLock can be set once per test binary, so this file has exactly one test.
#[test]
fn global_config_gives_each_thread_its_own_connection() {
    let dir = tempfile::tempdir().unwrap();
    Database::connect(Config::file(dir.path().join("app.db"))).unwrap();
    assert!(matches!(Database::connect(Config::memory()), Err(Error::AlreadyConnected)));

    Database::with(|c| c.execute_batch("CREATE TABLE t (id INTEGER)")).unwrap();
    std::thread::spawn(|| {
        // another thread: another connection, same file
        Database::with(|c| c.execute_batch("INSERT INTO t VALUES (1)")).unwrap();
    })
    .join()
    .unwrap();
}

Acceptance criteria

  • The tests above pass, including when run in parallel.
  • Docs cover the :memory: and .await caveats.
**Depends on:** #5 ## Context Models should be used without passing a connection around (`User::find(1)`), like Eloquent. rusqlite's `Connection` is `Send` but not `Sync`, so the design is: **config is process-wide, the connection is per thread**. `Database::with` is the single choke point that every model and query call goes through. ## Tasks - [x] `Database::connect(config) -> Result<()>` opens one connection to fail early and stores the config in a `OnceLock`. A second call returns `Error::AlreadyConnected`. - [x] A `thread_local!` slot holds `Option<Connection>`. The first `with` on a thread opens a connection from the global config. - [x] `Database::connect_thread(config)` opens a connection immediately and stores it in the calling thread's slot, never touching the global config. `Database::disconnect_thread()` clears the slot. Tests use this. - [x] `Database::with(f)` hands `f` a shared `&Connection` so nested calls work, and returns `Error::NotConnected` when nothing is configured. - [x] Docs: `:memory:` databases are per connection, so multi-threaded apps need a file; never hold a transaction across an `.await`; calling `connect_thread` inside a `with` closure panics. ## Example ```rust impl Database { pub fn connect(config: Config) -> Result<()>; pub fn connect_thread(config: Config) -> Result<()>; pub fn disconnect_thread(); /// The closure may return a rusqlite or a tessera result. pub fn with<T, E>(f: impl FnOnce(&Connection) -> std::result::Result<T, E>) -> Result<T> where Error: From<E>; } ``` ```rust // application code fn main() -> tessera_orm::Result<()> { Database::connect(Config::file("app.db"))?; let user = User::find(1)?; // runs on this thread's connection Ok(()) } ``` ```rust // tests/database.rs (never calls the global `connect`) #[test] fn with_before_connect_is_an_error() { let r = Database::with(|_conn| Ok::<_, Error>(())); assert!(matches!(r, Err(Error::NotConnected))); } #[test] fn threads_do_not_share_in_memory_databases() { Database::connect_thread(Config::memory()).unwrap(); Database::with(|c| c.execute_batch("CREATE TABLE t (id INTEGER)")).unwrap(); std::thread::spawn(|| { Database::connect_thread(Config::memory()).unwrap(); assert!(Database::with(|c| c.execute_batch("SELECT * FROM t")).is_err()); }) .join() .unwrap(); } #[test] fn nested_with_does_not_panic() { Database::connect_thread(Config::memory()).unwrap(); Database::with(|_| Database::with(|_| Ok::<_, Error>(()))).unwrap(); } ``` ```rust // tests/database_global.rs // A OnceLock can be set once per test binary, so this file has exactly one test. #[test] fn global_config_gives_each_thread_its_own_connection() { let dir = tempfile::tempdir().unwrap(); Database::connect(Config::file(dir.path().join("app.db"))).unwrap(); assert!(matches!(Database::connect(Config::memory()), Err(Error::AlreadyConnected))); Database::with(|c| c.execute_batch("CREATE TABLE t (id INTEGER)")).unwrap(); std::thread::spawn(|| { // another thread: another connection, same file Database::with(|c| c.execute_batch("INSERT INTO t VALUES (1)")).unwrap(); }) .join() .unwrap(); } ``` ## Acceptance criteria - [x] The tests above pass, including when run in parallel. - [x] Docs cover the `:memory:` and `.await` caveats.
Sign in to join this conversation.
No description provided.