diff --git a/lib/src/database.rs b/lib/src/database.rs index 97fcbe7..c3ba445 100644 --- a/lib/src/database.rs +++ b/lib/src/database.rs @@ -1,16 +1,49 @@ +/* + TIN - Time Tracking Application + Copyright (C) 2021 Julio Biason + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +use std::path::Path; + +use directories::ProjectDirs; use sqlx::sqlite::Sqlite; use sqlx::sqlite::SqliteConnectOptions; use sqlx::sqlite::SqlitePoolOptions; use sqlx::Pool; async fn connect() -> Result, sqlx::Error> { + connect_with(&default_filename()).await +} + +async fn connect_with(filename: &Path) -> Result, sqlx::Error> { let pool = SqlitePoolOptions::new() .connect_with( SqliteConnectOptions::new() - .filename("testing.sqlite") + .filename(filename) .create_if_missing(true), ) .await?; - sqlx::migrate("migrations").run(&pool).await?; + sqlx::migrate!("./migrations").run(&pool).await?; Ok(pool) } + +/// Return the default filename for the database. +fn default_filename() -> Path { + match ProjectDirs::from("me", "JulioBiason", "tin.sqlite3") { + Some(project_dir) => Path(project_dir.config_dir()), + None => Path("tin.sqlite3"), + } +}