lyrs/src/database.rs

42 lines
1.2 KiB
Rust
Raw Normal View History

2023-11-12 11:15:14 -06:00
use deadpool_diesel::sqlite::{Manager, Pool, Runtime};
use diesel::sqlite::Sqlite;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use tracing::info;
pub struct Database {
pub pool: Pool,
}
const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
impl Database {
// TODO: database seeding?
fn run_migrations(
connection: &mut impl MigrationHarness<Sqlite>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
// This will run the necessary migrations.
//
// See the documentation for `MigrationHarness` for
// all available methods.
connection.run_pending_migrations(MIGRATIONS)?;
Ok(())
}
// TODO: make an actual error type
pub async fn new<T: AsRef<str>>(database_url: T) -> Result<Self, anyhow::Error> {
let manager = Manager::new(database_url.as_ref(), Runtime::Tokio1);
let pool = Pool::builder(manager).max_size(8).build().unwrap();
let conn = pool.get().await?;
let _ = conn
.interact(|c| Self::run_migrations(c))
.await
.expect("Failed to run migrations");
info!("Migrations completed!");
return Ok(Database { pool });
}
}