Skip to content

Commit

Permalink
Cleanup code for instance creation
Browse files Browse the repository at this point in the history
  • Loading branch information
mbr committed Apr 9, 2024
1 parent dfb7962 commit 1eaa467
Showing 1 changed file with 31 additions and 7 deletions.
38 changes: 31 additions & 7 deletions src/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,32 @@ impl PostgresConnection {
assert_valid_ident(db_name)?;

// Create role if it does not exist yet.
if self.client.query_opt("SELECT usename FROM pg_user WHERE usename = $1;", &[&role_name]).await?.is_none() {
if self
.client
.query_opt(
"SELECT usename FROM pg_user WHERE usename = $1;",
&[&role_name],
)
.await?
.is_none()
{
// User does not exist, ensure we create it.
let create_role_sql = format!("CREATE ROLE {} NOCREATEDB NOCREATEROLE NOINHERIT LOGIN NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 8 PASSWORD $1;", role_name);
self.client.execute(&create_role_sql, &[&role_name, &role_password]).await?;
self.client
.execute(&create_role_sql, &[&role_name, &role_password])
.await?;
};

// Same for database, only create if not existent yet.
if self.client.query_opt("SELECT datname FROM pg_database WHERE datname = $1", &[&db_name]).await?.is_none() {
if self
.client
.query_opt(
"SELECT datname FROM pg_database WHERE datname = $1",
&[&db_name],
)
.await?
.is_none()
{
let create_db_sql = format!("CREATE DATABASE {} WITH OWNER = {};", db_name, role_name);
self.client.execute(&create_db_sql, &[]).await?;
}
Expand All @@ -110,19 +128,25 @@ impl PostgresConnection {
}

fn valid_ident(input: &str) -> bool {
let Some(first) = input.chars().next() else { return false; }
let Some(first) = input.chars().next() else {
return false;
};

if !first.is_alphabetic() {
return false;
}

input.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
input
.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}

fn assert_valid_ident(input: &str) -> Result<(), Error> {
if !valid_ident(input) {
Err(Error::InvalidIdent(input.to_owned()))
} else {Ok(())}
Err(Error::InvalidIdent(input.to_owned()))
} else {
Ok(())
}
}

#[cfg(test)]
Expand Down

0 comments on commit 1eaa467

Please sign in to comment.