feat(testing): (re)create postgresql database for test and dev

This commit is contained in:
2024-02-03 20:45:00 -05:00
parent 7cfd05dd96
commit 627f104101
5 changed files with 161 additions and 4 deletions

View File

@@ -0,0 +1,83 @@
import os
from urllib.parse import urlparse
import psycopg
from psycopg import sql
def recreate_db() -> None:
"""
(Re)create the PostgreSQL database
Watch for PostgreSQL version changes
"""
url_parts = urlparse(os.environ["TODO_DB_DATABASE_URL"])
# Extract connection parameters
dbname = url_parts.path[1:]
user_name = url_parts.username
password = url_parts.password
host = url_parts.hostname
port = url_parts.port
print(
f"The database name is {dbname}, the username is {user_name}, the password is {password}, the host is {host}, the port is {port}"
)
with psycopg.connect(
dbname="postgres", user="postgres", password=password, host=host, port=port
) as conn:
with conn.cursor() as cur:
conn._set_autocommit(True)
cur.execute(
sql.SQL("DROP OWNED BY {}").format(
sql.Identifier(user_name) # type: ignore
)
)
# drop the database if exists
cur.execute(
sql.SQL("DROP DATABASE IF EXISTS {dbname}").format(
dbname=sql.Identifier(dbname),
)
)
# Drop the user if it exists
cur.execute(
sql.SQL("DROP USER IF EXISTS {}").format(
sql.Identifier(user_name), # type: ignore
)
)
# Create a new database
cur.execute(
sql.SQL("CREATE DATABASE {dbname}").format(
dbname=sql.Identifier(dbname),
)
)
# Create a new user
cur.execute(
sql.SQL("CREATE USER {} WITH PASSWORD {}").format(
sql.Identifier(user_name), password # type: ignore
)
)
# Grant necessary privileges to the new user
cur.execute(
sql.SQL(
"GRANT ALL PRIVILEGES ON DATABASE {dbname} TO {user_name}"
).format(
dbname=sql.Identifier(dbname),
user_name=sql.Identifier(user_name), # type: ignore
)
)
# Commit the changes
conn.commit()
print("Finished PostgreSQL (re)creatation")
if __name__ == "__main__":
recreate_db()