Skip to content

Commit

Permalink
Change db self check, make it check for database creation permissions…
Browse files Browse the repository at this point in the history
… instead
  • Loading branch information
mbr committed Apr 1, 2024
1 parent b432e08 commit 33a2d9d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
5 changes: 2 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
23 changes: 19 additions & 4 deletions src/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand Down Expand Up @@ -33,17 +37,28 @@ pub(crate) struct PostgresConnection {
}

impl PostgresConnection {
pub(crate) async fn run_self_check(&self) -> Result<bool, Error> {
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(())
}
}

0 comments on commit 33a2d9d

Please sign in to comment.