diff --git a/src/main.rs b/src/main.rs index d2778af..b633022 100644 --- a/src/main.rs +++ b/src/main.rs @@ -88,9 +88,8 @@ async fn main() -> anyhow::Result<()> { if let Some(uri) = cfg.postgres.uri { let pg = postgres::PostgresDb::new(uri); let con = pg.connect().await?; - if !con.run_self_check().await? { - info!("postgres database is not yet initializing, doing so"); - }; + con.run_self_check().await?; + info!("successfully connected to postgres database"); } let app = Router::new() diff --git a/src/postgres.rs b/src/postgres.rs index a770fed..d76eace 100644 --- a/src/postgres.rs +++ b/src/postgres.rs @@ -2,6 +2,10 @@ use thiserror::Error; #[derive(Debug, Error)] pub(crate) enum Error { + #[error("self-check failed")] + SelfCheckFailed, + #[error("user does not have permission `rolcreatedb`")] + NoRolCreateDb, #[error(transparent)] PostgresError(#[from] tokio_postgres::Error), } @@ -33,17 +37,28 @@ pub(crate) struct PostgresConnection { } impl PostgresConnection { - pub(crate) async fn run_self_check(&self) -> Result { + pub(crate) async fn run_self_check(&self) -> Result<(), Error> { + let row = self.client.query_one("SELECT 1;", &[]).await?; + + let result: i32 = row.get(0); + + if result != 1 { + return Err(Error::SelfCheckFailed); + } + let row = self .client .query_one( - "SELECT COUNT(*) FROM pg_namespace WHERE nspname = 'rockslide'", + "SELECT rolcreatedb from pg_authid where rolname = current_user;", &[], ) .await?; + let can_create_db: bool = row.get(0); - let count: i64 = row.get(0); + if !can_create_db { + return Err(Error::NoRolCreateDb); + } - Ok(count > 0) + Ok(()) } }