anvilsign in

collin/anvil

1//! Database connection and schema setup via Toasty.
2
3use std::path::Path;
4
5use crate::error::Result;
6use crate::models::{
7 CiRun,
8 Repository,
9 Session,
10 SshKey,
11 User,
12};
13
14/// Open (creating if necessary) the SQLite database at `path`, creating the
15/// schema on first run.
16///
17/// Note: Toasty 0.7's `push_schema` emits plain `CREATE TABLE` (no
18/// `IF NOT EXISTS`) for model tables, so it is *not* idempotent — calling it on
19/// an existing database errors. We therefore only push the schema when the
20/// database file does not yet exist. Skipping it on an existing database issues
21/// no DDL, so data is never touched. Schema evolution will move to Toasty's
22/// migration system when models start changing.
23pub async fn connect(path: impl AsRef<Path>) -> Result<toasty::Db> {
24 let path = path.as_ref();
25 let fresh = !path.exists();
26 let url = format!("sqlite:{}", path.display());
27
28 let db = toasty::Db::builder()
29 .models(toasty::models!(User, Repository, SshKey, Session, CiRun))
30 .connect(&url)
31 .await?;
32
33 if fresh {
34 db.push_schema().await?;
35 }
36 Ok(db)
37}