diff --git a/src/app.rs b/src/app.rs index 83dc378..3e91995 100644 --- a/src/app.rs +++ b/src/app.rs @@ -15,6 +15,5 @@ struct IndexTemplate<'a> { } async fn root<'a>(State(database): State) -> IndexTemplate<'a> { - println!("Found {} users", database.log_num_users().await); IndexTemplate { title: "LocalHub" } } diff --git a/src/db.rs b/src/db.rs index 0d6b085..f03e09e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -5,27 +5,52 @@ use { }; #[derive(Error, Debug)] -pub enum Error { +pub enum InitialisationError { #[error("Could not initialize DB connection pool.")] ConnectionPoolError(#[from] CreatePoolError), } +#[derive(Error, Debug)] +pub enum Error { + #[error("")] + PoolError(#[from] deadpool_postgres::PoolError), + #[error("")] + DbError(#[from] tokio_postgres::Error) +} + #[derive(Clone)] pub struct Database { - pg_pool: Pool, + connection_pool: Pool, } impl Database { - pub fn create_pool(connection_url: &str) -> Result { + pub fn create_pool(connection_url: &str) -> Result { let mut config = deadpool_postgres::Config::new(); config.url = Some(connection_url.to_string()); let pg_pool = config.create_pool(Some(Runtime::Tokio1), NoTls)?; - Ok(Database { pg_pool }) + Ok(Database { connection_pool: pg_pool }) } - pub async fn log_num_users(&self) -> usize { - let client = self.pg_pool.get().await.unwrap(); - let results = client.query("SELECT * FROM users;", &[]).await.unwrap(); - results.len() + pub async fn get_db_version(&self) -> Result { + let client = self.connection_pool.get().await?; + client.execute(r#" + DO $$BEGIN + IF NOT EXISTS + ( SELECT 1 + FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name = 'migration_info' + ) + THEN + CREATE TABLE migration_info ( + onerow_id bool PRIMARY KEY DEFAULT true, + migration_version INTEGER, + CONSTRAINT onerow_unique CHECK (onerow_id)); + INSERT + INTO migration_info (migration_version) + VALUES (-1); + END IF; + END$$;"#, &[]).await?; + Ok(client.query_one(r#"SELECT migration_version FROM migration_info;"#, &[]).await?.get(0)) } } diff --git a/src/main.rs b/src/main.rs index 928765a..55145c8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,7 @@ pub enum Error { MissingConfigError(#[from] config::Error), #[error("Database error: {0}")] - DatabaseError(#[from] db::Error), + DatabaseError(#[from] db::InitialisationError), #[error("{0}")] IOError(#[from] std::io::Error), @@ -35,6 +35,8 @@ async fn localhub_main() -> Result<(), Error> { let db_pool = Database::create_pool(&config.database_url)?; + dbg!(db_pool.get_db_version().await.unwrap()); + let app = app::routes() .with_state(db_pool) .nest_service("/static", ServeDir::new(&config.static_file_path));