refactor: enhance database schema creation and add documentation for test database URL

This commit is contained in:
grillazz
2025-12-28 18:35:19 +01:00
parent 242ea2ab9a
commit 1fe0faa5c9
2 changed files with 17 additions and 3 deletions

View File

@@ -85,6 +85,19 @@ class Settings(BaseSettings):
@computed_field @computed_field
@property @property
def test_asyncpg_url(self) -> PostgresDsn: def test_asyncpg_url(self) -> PostgresDsn:
"""
This is a computed field that generates a PostgresDsn URL for the test database using asyncpg.
The URL is built using the MultiHostUrl.build method, which takes the following parameters:
- scheme: The scheme of the URL. In this case, it is "postgresql+asyncpg".
- username: The username for the Postgres database, retrieved from the POSTGRES_USER environment variable.
- password: The password for the Postgres database, retrieved from the POSTGRES_PASSWORD environment variable.
- host: The host of the Postgres database, retrieved from the POSTGRES_HOST environment variable.
- path: The path of the Postgres test database, retrieved from the POSTGRES_TEST_DB environment variable.
Returns:
PostgresDsn: The constructed PostgresDsn URL for the test database with asyncpg.
"""
return MultiHostUrl.build( return MultiHostUrl.build(
scheme="postgresql+asyncpg", scheme="postgresql+asyncpg",
username=self.POSTGRES_USER, username=self.POSTGRES_USER,
@@ -93,6 +106,7 @@ class Settings(BaseSettings):
path=self.POSTGRES_TEST_DB, path=self.POSTGRES_TEST_DB,
) )
@computed_field @computed_field
@property @property
def postgres_url(self) -> PostgresDsn: def postgres_url(self) -> PostgresDsn:

View File

@@ -35,8 +35,9 @@ def _create_db(conn) -> None:
def _create_db_schema(conn) -> None: def _create_db_schema(conn) -> None:
"""Create a database schema if it doesn't exist.""" """Create a database schema if it doesn't exist."""
try: try:
conn.execute(text("CREATE SCHEMA happy_hog")) """Create a database schema if it doesn't exist."""
conn.execute(text("CREATE SCHEMA shakespeare")) conn.execute(text("CREATE SCHEMA IF NOT EXISTS happy_hog"))
conn.execute(text("CREATE SCHEMA IF NOT EXISTS shakespeare"))
except ProgrammingError: except ProgrammingError:
# This might be raised by databases that don't support `IF NOT EXISTS` # This might be raised by databases that don't support `IF NOT EXISTS`
# and the schema already exists. You can choose to ignore it. # and the schema already exists. You can choose to ignore it.
@@ -54,7 +55,6 @@ async def start_db():
# Now, connect to the newly created `testdb` with `test_engine` # Now, connect to the newly created `testdb` with `test_engine`
async with test_engine.begin() as conn: async with test_engine.begin() as conn:
await conn.run_sync(_create_db_schema) await conn.run_sync(_create_db_schema)
await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all) await conn.run_sync(Base.metadata.create_all)