Skip to content

Commit

Permalink
@pcrespov review: remove match and use a mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
sanderegg committed Dec 2, 2024
1 parent af515c5 commit 0fe3496
Showing 1 changed file with 22 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
import logging
from typing import Any
from typing import Any, Final

import arrow
import sqlalchemy as sa
Expand All @@ -20,7 +20,6 @@
ClusterNotFoundError,
ComputationalRunNotFoundError,
DirectorError,
ProjectNotFoundError,
UserNotFoundError,
)
from ....models.comp_runs import CompRunsAtDB, RunMetadataDict
Expand All @@ -30,6 +29,20 @@

logger = logging.getLogger(__name__)

_POSTGRES_ERROR_TO_ERROR_MAP: Final[
dict[tuple[str, ...], tuple[type[DirectorError], tuple[str, ...]]]
] = {
("users", "user_id"): (UserNotFoundError, ("users", "user_id")),
("projects", "project_uuid"): (
UserNotFoundError,
("projects", "project_id"),
),
("clusters", "cluster_id"): (
ClusterNotFoundError,
("clusters", "cluster_id"),
),
}


class CompRunsRepository(BaseRepository):
async def get(
Expand Down Expand Up @@ -173,15 +186,13 @@ async def create(
return CompRunsAtDB.model_validate(row)
except ForeignKeyViolation as exc:
message = exc.args[0]
match message:
case s if "users" in s and "user_id" in s:
raise UserNotFoundError(user_id=user_id) from exc
case s if "projects" in s and "project_uuid" in s:
raise ProjectNotFoundError(project_id=project_id) from exc
case s if "clusters" in s and "cluster_id" in s:
raise ClusterNotFoundError(cluster_id=cluster_id) from exc
case _:
raise DirectorError from exc

for pg_keys, (exc_type, exc_keys) in _POSTGRES_ERROR_TO_ERROR_MAP.items():
if all(k in message for k in pg_keys):
raise exc_type(
**{f"{k}": locals().get(k) for k in exc_keys}
) from exc
raise DirectorError from exc

async def update(
self, user_id: UserID, project_id: ProjectID, iteration: PositiveInt, **values
Expand Down

0 comments on commit 0fe3496

Please sign in to comment.